title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Python - Convert List to Single valued Lists in Tuple - GeeksforGeeks
10 Jul, 2020 Conversion of data types is the most common problem across CS domain nowdays. One such problem can be converting List elements to single values lists in tuples. This can have application in data preprocessing domain. Let’s discuss certain ways in which this task can be performed. Input : test_list = [1, 3, 5, 6, 7, 9]Output : ([1], [3], [5], [6], [7], [9]) Input : test_list = [1]Output : ([1]) Method #1 : Using list comprehension + tuple()This is one of the ways in which this task can be performed. In this, we construct and iterate the list using list comprehension and finally convert the result list to tuple using tuple(). # Python3 code to demonstrate working of # Convert List to Single valued Lists in Tuple# Using list comprehension + tuple() # initializing liststest_list = [6, 8, 4, 9, 10, 2] # printing original listprint("The original list is : " + str(test_list)) # Convert List to Single valued Lists in Tuple# Using list comprehension + tuple()res = tuple([ele] for ele in test_list) # printing result print("Tuple after conversion : " + str(res)) The original list is : [6, 8, 4, 9, 10, 2] Tuple after conversion : ([6], [8], [4], [9], [10], [2]) Method #2 : Using map() + list() + zip() + tuple()The combination of above functions can be used to solve this problem. In this, we perform task of extending logic of conversion to each element using map(), and list conversion to each element using zip(). At end, the result is converted back to tuple using tuple(). # Python3 code to demonstrate working of # Convert List to Single valued Lists in Tuple# Using map() + list() + zip() + tuple() # initializing liststest_list = [6, 8, 4, 9, 10, 2] # printing original listprint("The original list is : " + str(test_list)) # Convert List to Single valued Lists in Tuple# Using map() + list() + zip() + tuple()res = tuple(map(list, zip(test_list))) # printing result print("Tuple after conversion : " + str(res)) The original list is : [6, 8, 4, 9, 10, 2] Tuple after conversion : ([6], [8], [4], [9], [10], [2]) Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Defaultdict in Python Python | Get dictionary keys as a list Python program to check whether a number is Prime or not Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 24113, "s": 24085, "text": "\n10 Jul, 2020" }, { "code": null, "e": 24394, "s": 24113, "text": "Conversion of data types is the most common problem across CS domain nowdays. One such problem can be converting List elements to single values lists in tuples. This can have application in data preprocessing domain. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 24472, "s": 24394, "text": "Input : test_list = [1, 3, 5, 6, 7, 9]Output : ([1], [3], [5], [6], [7], [9])" }, { "code": null, "e": 24510, "s": 24472, "text": "Input : test_list = [1]Output : ([1])" }, { "code": null, "e": 24745, "s": 24510, "text": "Method #1 : Using list comprehension + tuple()This is one of the ways in which this task can be performed. In this, we construct and iterate the list using list comprehension and finally convert the result list to tuple using tuple()." }, { "code": "# Python3 code to demonstrate working of # Convert List to Single valued Lists in Tuple# Using list comprehension + tuple() # initializing liststest_list = [6, 8, 4, 9, 10, 2] # printing original listprint(\"The original list is : \" + str(test_list)) # Convert List to Single valued Lists in Tuple# Using list comprehension + tuple()res = tuple([ele] for ele in test_list) # printing result print(\"Tuple after conversion : \" + str(res)) ", "e": 25186, "s": 24745, "text": null }, { "code": null, "e": 25287, "s": 25186, "text": "The original list is : [6, 8, 4, 9, 10, 2]\nTuple after conversion : ([6], [8], [4], [9], [10], [2])\n" }, { "code": null, "e": 25606, "s": 25289, "text": "Method #2 : Using map() + list() + zip() + tuple()The combination of above functions can be used to solve this problem. In this, we perform task of extending logic of conversion to each element using map(), and list conversion to each element using zip(). At end, the result is converted back to tuple using tuple()." }, { "code": "# Python3 code to demonstrate working of # Convert List to Single valued Lists in Tuple# Using map() + list() + zip() + tuple() # initializing liststest_list = [6, 8, 4, 9, 10, 2] # printing original listprint(\"The original list is : \" + str(test_list)) # Convert List to Single valued Lists in Tuple# Using map() + list() + zip() + tuple()res = tuple(map(list, zip(test_list))) # printing result print(\"Tuple after conversion : \" + str(res)) ", "e": 26054, "s": 25606, "text": null }, { "code": null, "e": 26155, "s": 26054, "text": "The original list is : [6, 8, 4, 9, 10, 2]\nTuple after conversion : ([6], [8], [4], [9], [10], [2])\n" }, { "code": null, "e": 26176, "s": 26155, "text": "Python list-programs" }, { "code": null, "e": 26183, "s": 26176, "text": "Python" }, { "code": null, "e": 26199, "s": 26183, "text": "Python Programs" }, { "code": null, "e": 26297, "s": 26199, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26306, "s": 26297, "text": "Comments" }, { "code": null, "e": 26319, "s": 26306, "text": "Old Comments" }, { "code": null, "e": 26337, "s": 26319, "text": "Python Dictionary" }, { "code": null, "e": 26359, "s": 26337, "text": "Enumerate() in Python" }, { "code": null, "e": 26391, "s": 26359, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26433, "s": 26391, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26459, "s": 26433, "text": "Python String | replace()" }, { "code": null, "e": 26481, "s": 26459, "text": "Defaultdict in Python" }, { "code": null, "e": 26520, "s": 26481, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26577, "s": 26520, "text": "Python program to check whether a number is Prime or not" }, { "code": null, "e": 26615, "s": 26577, "text": "Python | Convert a list to dictionary" } ]
Complementing Machine Learning Algorithms with Image Processing | by Rafael Madrigal | Towards Data Science
Pics, or it did not happen. Taking photos of everyday moments has become today’s default. Last year, Keypoint Intelligence projected that humanity would generate 1,436,300,000,000 images. Mylio, an image organization solutions provider, even forecasted this number to hit 1.6 Trillion in 2022. Wow. That’s a lot of photos! As a data scientist, learning to process and extract information from these images is crucial, especially in computer vision tasks like object detection, image segmentation, and self-driving cars. Several image processing libraries in Python like scikit-image, OpenCV, and Pillow/ PIL allow us to do precisely that. We usually read and clean digital images using our preferred image processing library and extract useful features that can be used by machine learning algorithms. In the sample pipeline above, we carved out each leaf from the source image. We applied image enhancements (i.e., white balancing, thresholding/ morphology, and histogram equalization). After that, we also measured each leaf’s geometric features such as convex area, perimeter, major and minor axes lengths, and eccentricity, which form our features table. Finally, we used these features as inputs to a classification algorithm and produced an acceptable F-1 score. We can mirror the last two steps to the popular iris dataset, but we generated the measurements ourselves this time. Isn’t that nice? We can represent digital images as a 3-D function F(x, y, z) where x, y, and z refer to spatial coordinates. In contrast, F refers to the intensity of the image (usually from 0 to 255) at that specific point. In Python (and in Linear Algebra), we can represent this function as a NumPy array with three dimensions (a tensor). The z-axis can be interpreted as image channels (e.g., RGB for Red, Green, and Blue). There are several color models available for images; Mathworks provides a good discussion of the different color spaces here. Our image processing libraries allow us to convert from one color space to another with a single code line. from skimage.color import rgb2hsv, rgb2grayfrom skimage.data import coffeeim = coffee() # shape : (400, 600, 3); range from 0 to 255hsv = rgb2hsv(im) # shape : (400, 600, 3); range from 0 to 255gry = rgb2gray(im) # shape : (400, 600, 1); range from 0 to 255bin = gry > 0.5 # shape : (400, 600, 1); composed of 0 AND 1 only Image Enhancements. In neural network applications, we flip, rotate, upsample, downsample, and apply shear to images to augment the existing dataset. Sometimes, we want to correct the contrast and white balance of an image to accentuate the desired object or region. In the example below, we enhance the dark image using a linear function, allowing us to see the things that were not visible in the original image. def apply_histogram_correction(im, target_dist, target_bins=range(256): """Apply a histogram correction to an image `im` using a target distribution `target_dist`. The correction is applied at every pixel intensity bin `target_bins`.""" freq, bins = cumulative_distribution(im) corrected = np.interp(freq, target_dist, target_bins) return img_as_ubyte(corrected[im].astype(int)) Morphological Filtering. In morphological filtering, we use a structuring element or kernel that inhibits or enhances regions of interest in a pixel neighborhood. Some common morphological operations include erosion, dilation, opening, closing, skeletonizing, and removing small holes. from skimage.morphology import (erosion, dilation, opening, closing, skeletonize, remove_small_holes)from skimage.morphology import diskfrom skimage.date import shepp_logan_phantofrom skimage.util import img_as_ubyteim = img_as_ubyte(shepp_logan_phantom()) # Original Imageim_open = im.copy()im_open[10:30, 200:210] = 0selem = disk(6) # Structuring element# Morphological Transformationseroded = erosion(im, selem)dilated = dilation(im, selem)opened = opening(im, selem)closed = closing(im_open, selem)skeleton = skeletonize(im==0)no_holes = remove_small_holes(im, area_threshold=64) Blob Detection. In image processing, blobs are defined as bright on dark or dark on bright regions in an image. Detected blobs usually signal an object or parts of an object in an image that helps object recognition and/or objects tracking. The three most common algorithms for blob detection are Laplacian of Gaussian, Difference of Gaussian, and Determinant of Hessian. All of which are based on derivatives of the function with the position. from skimage.data import hubble_deep_fieldfrom skimage.feature import blob_dog, blob_log, blob_dohfrom skimage.color import rgb2grayimport mathim = hubble_deep_field()[:500, :500]im_gry = rgb2gray(im)# Laplacian of Gaussianblobs_log = blob_log(im_gry, max_sigma=30, num_sigma=10, threshold=.1)blob_log[:, 2] = blobs_log[:, 2] * math.sqrt(2)# Difference of Gaussianblobs_dog = blob_dog(im_gry, max_sigma=30, num_sigma=10, threshold=.1)blob_dog[:, 2] = blobs_dog[:, 2] * math.sqrt(2)# Determinant of Hessianblobs_doh = blob_doh(im_gry, max_sigma=30, threshold=0.01) Feature Extraction. Feature extraction takes advantage of connected components in the image. In the leaf classification example above, we isolated each leaf. We computed for each leaf’s area, perimeter, and eccentricity, among others. We use these measurements as inputs to our machine learning algorithm. Features can be quickly extracted using the ‘regionprops’ module in scikit-image. from skimage.measure import label, regionpropsfrom skimage.color import rgba2grayfrom skimage.io import imreadim = rgba2gray('candies.png') im_bw = im < 0.5im_clean = morphological_ops(im_bw)im_label = label(im_clean)props = regionprops(im_label)props[0].area ### Output: 4453 Refers to the Area of the image with label==0 Image Segmentation. In image segmentation, we want to isolate some of the images through several thresholding operations. An example of this is binarizing a grayscale image using a > or < operator to generate a boolean mask. In some cases, we can use other color spaces like HSV or RGB in generating a threshold that will isolate an object of interest. In the example below, we generated a mask to isolate all the grapes in the fruit basket. from scipy.ndimage import median_filterfrom skimage.color import rgb2hsvfrom skimage.io import imreadfruits = imread('fruits.jpg)fruits_hsv = rgb2hsv(fruits)hmask = fruits_hsv[:, :, 0] > 0.7 # Hue Filterhmask1 = fruits_hsv[:, :, 0] < 0.9 # Hue Filtersmask = fruits_hsv[:, :, 2] > 0.3 # Saturation Filtermask = median_filter(smask*hmask*hmask1, size=25) This article discussed how we could incorporate image processing in the machine learning pipeline and showcased the different image processing algorithms commonly used in the field. In the next set of articles, we will be diving deeper into each of the common algorithms I shared here and discussed the concepts behind them.
[ { "code": null, "e": 494, "s": 171, "text": "Pics, or it did not happen. Taking photos of everyday moments has become today’s default. Last year, Keypoint Intelligence projected that humanity would generate 1,436,300,000,000 images. Mylio, an image organization solutions provider, even forecasted this number to hit 1.6 Trillion in 2022. Wow. That’s a lot of photos!" }, { "code": null, "e": 810, "s": 494, "text": "As a data scientist, learning to process and extract information from these images is crucial, especially in computer vision tasks like object detection, image segmentation, and self-driving cars. Several image processing libraries in Python like scikit-image, OpenCV, and Pillow/ PIL allow us to do precisely that." }, { "code": null, "e": 973, "s": 810, "text": "We usually read and clean digital images using our preferred image processing library and extract useful features that can be used by machine learning algorithms." }, { "code": null, "e": 1574, "s": 973, "text": "In the sample pipeline above, we carved out each leaf from the source image. We applied image enhancements (i.e., white balancing, thresholding/ morphology, and histogram equalization). After that, we also measured each leaf’s geometric features such as convex area, perimeter, major and minor axes lengths, and eccentricity, which form our features table. Finally, we used these features as inputs to a classification algorithm and produced an acceptable F-1 score. We can mirror the last two steps to the popular iris dataset, but we generated the measurements ourselves this time. Isn’t that nice?" }, { "code": null, "e": 1986, "s": 1574, "text": "We can represent digital images as a 3-D function F(x, y, z) where x, y, and z refer to spatial coordinates. In contrast, F refers to the intensity of the image (usually from 0 to 255) at that specific point. In Python (and in Linear Algebra), we can represent this function as a NumPy array with three dimensions (a tensor). The z-axis can be interpreted as image channels (e.g., RGB for Red, Green, and Blue)." }, { "code": null, "e": 2220, "s": 1986, "text": "There are several color models available for images; Mathworks provides a good discussion of the different color spaces here. Our image processing libraries allow us to convert from one color space to another with a single code line." }, { "code": null, "e": 2552, "s": 2220, "text": "from skimage.color import rgb2hsv, rgb2grayfrom skimage.data import coffeeim = coffee() # shape : (400, 600, 3); range from 0 to 255hsv = rgb2hsv(im) # shape : (400, 600, 3); range from 0 to 255gry = rgb2gray(im) # shape : (400, 600, 1); range from 0 to 255bin = gry > 0.5 # shape : (400, 600, 1); composed of 0 AND 1 only" }, { "code": null, "e": 2967, "s": 2552, "text": "Image Enhancements. In neural network applications, we flip, rotate, upsample, downsample, and apply shear to images to augment the existing dataset. Sometimes, we want to correct the contrast and white balance of an image to accentuate the desired object or region. In the example below, we enhance the dark image using a linear function, allowing us to see the things that were not visible in the original image." }, { "code": null, "e": 3405, "s": 2967, "text": "def apply_histogram_correction(im, target_dist, target_bins=range(256): \"\"\"Apply a histogram correction to an image `im` using a target distribution `target_dist`. The correction is applied at every pixel intensity bin `target_bins`.\"\"\" freq, bins = cumulative_distribution(im) corrected = np.interp(freq, target_dist, target_bins) return img_as_ubyte(corrected[im].astype(int))" }, { "code": null, "e": 3691, "s": 3405, "text": "Morphological Filtering. In morphological filtering, we use a structuring element or kernel that inhibits or enhances regions of interest in a pixel neighborhood. Some common morphological operations include erosion, dilation, opening, closing, skeletonizing, and removing small holes." }, { "code": null, "e": 4338, "s": 3691, "text": "from skimage.morphology import (erosion, dilation, opening, closing, skeletonize, remove_small_holes)from skimage.morphology import diskfrom skimage.date import shepp_logan_phantofrom skimage.util import img_as_ubyteim = img_as_ubyte(shepp_logan_phantom()) # Original Imageim_open = im.copy()im_open[10:30, 200:210] = 0selem = disk(6) # Structuring element# Morphological Transformationseroded = erosion(im, selem)dilated = dilation(im, selem)opened = opening(im, selem)closed = closing(im_open, selem)skeleton = skeletonize(im==0)no_holes = remove_small_holes(im, area_threshold=64)" }, { "code": null, "e": 4783, "s": 4338, "text": "Blob Detection. In image processing, blobs are defined as bright on dark or dark on bright regions in an image. Detected blobs usually signal an object or parts of an object in an image that helps object recognition and/or objects tracking. The three most common algorithms for blob detection are Laplacian of Gaussian, Difference of Gaussian, and Determinant of Hessian. All of which are based on derivatives of the function with the position." }, { "code": null, "e": 5347, "s": 4783, "text": "from skimage.data import hubble_deep_fieldfrom skimage.feature import blob_dog, blob_log, blob_dohfrom skimage.color import rgb2grayimport mathim = hubble_deep_field()[:500, :500]im_gry = rgb2gray(im)# Laplacian of Gaussianblobs_log = blob_log(im_gry, max_sigma=30, num_sigma=10, threshold=.1)blob_log[:, 2] = blobs_log[:, 2] * math.sqrt(2)# Difference of Gaussianblobs_dog = blob_dog(im_gry, max_sigma=30, num_sigma=10, threshold=.1)blob_dog[:, 2] = blobs_dog[:, 2] * math.sqrt(2)# Determinant of Hessianblobs_doh = blob_doh(im_gry, max_sigma=30, threshold=0.01)" }, { "code": null, "e": 5735, "s": 5347, "text": "Feature Extraction. Feature extraction takes advantage of connected components in the image. In the leaf classification example above, we isolated each leaf. We computed for each leaf’s area, perimeter, and eccentricity, among others. We use these measurements as inputs to our machine learning algorithm. Features can be quickly extracted using the ‘regionprops’ module in scikit-image." }, { "code": null, "e": 6071, "s": 5735, "text": "from skimage.measure import label, regionpropsfrom skimage.color import rgba2grayfrom skimage.io import imreadim = rgba2gray('candies.png') im_bw = im < 0.5im_clean = morphological_ops(im_bw)im_label = label(im_clean)props = regionprops(im_label)props[0].area ### Output: 4453 Refers to the Area of the image with label==0" }, { "code": null, "e": 6513, "s": 6071, "text": "Image Segmentation. In image segmentation, we want to isolate some of the images through several thresholding operations. An example of this is binarizing a grayscale image using a > or < operator to generate a boolean mask. In some cases, we can use other color spaces like HSV or RGB in generating a threshold that will isolate an object of interest. In the example below, we generated a mask to isolate all the grapes in the fruit basket." }, { "code": null, "e": 6871, "s": 6513, "text": "from scipy.ndimage import median_filterfrom skimage.color import rgb2hsvfrom skimage.io import imreadfruits = imread('fruits.jpg)fruits_hsv = rgb2hsv(fruits)hmask = fruits_hsv[:, :, 0] > 0.7 # Hue Filterhmask1 = fruits_hsv[:, :, 0] < 0.9 # Hue Filtersmask = fruits_hsv[:, :, 2] > 0.3 # Saturation Filtermask = median_filter(smask*hmask*hmask1, size=25)" } ]
React Suite SelectPicker Component - GeeksforGeeks
11 Apr, 2022 React Suite is a popular front-end library with a set of React components that are designed for the middle platform and back-end products. SelectPicker component allows the users to select a single piece of data. This component also supports grouping. We can use the following approach in ReactJS to use the React Suite SelectPicker Component. SelectPicker Props: appearance: It is used for the appearance of the component. block: It is used to block an entire row. classPrefix: It is used to denote the prefix of the component CSS class. cleanable: It is used to indicate whether the option can be emptied or not. container: It is used to set the rendering container. creatable: The settings can create new options. data: It is used to denote the selectable data. defaultValue: It is used to denote the default value. disabled: It is used to indicate whether the component is disabled or not. disabledItemValues: It is used to disable optional. groupBy: It is used to set the grouping criteria ‘key’ in ‘data’. labelKey: It is used to set the options to display the ‘key’ in ‘data’. listProps: It is used to denote the list-related properties in react-virtualized. maxHeight: It is used to set the max height of the Dropdown. menuClassName: It is used to denote a CSS class to apply to the Menu DOM node. menuStyle: It is used to denote a style to apply to the Menu DOM node. onChange: It is a callback function that is triggered when value changes. onClean: It is a callback function that is triggered when value clean. onClose: It is a callback function that is triggered on a close event. onEnter: It is a callback function that is triggered before the overlay transitions in. onEntered: It is a callback function that is triggered after the overlay finishes transitioning in. onEntering: It is a callback function that is triggered as the overlay begins to transition in. onExit: It is a callback function that is triggered right before the overlay transitions out. onExited: It is a callback function that is triggered after the overlay finishes transitioning out. onExiting: It is a callback function that is triggered as the overlay begins to transition out. onGroupTitleClick: Click the callback function for the group header. onOpen: It is a callback function that is triggered on open of the component. onSearch: It is a callback function for the search. onSelect: It is a callback function that is triggered on the selection of an option. placeholder: It is used to denote the placeholder. placement: It is used for the placement of component. preventOverflow: It is used to prevent floating element overflow. renderExtraFooter: It is used for the custom render extra footer. renderMenu: It is used for customizing the Rendering Menu list. renderMenuGroup: It is used for the custom Render Options Group. renderMenuItem: It is used for the custom Render Options. renderValue: It is used for the custom Render selected options. searchBy: It is used for the custom search rules. searchable: It is used to indicate whether you can search for options or not. size: It is used to denote the picker size. sort: It is used for the sort options. toggleComponentClass: It can be used for the custom element for this component. value: It is used to denote the value (Controlled). valueKey: It is used to set the option value ‘key’ in ‘data’. virtualized: It is used to indicate whether using Virtualized List 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 rsuite Step 3: After creating the ReactJS application, Install the required module using the following command: npm install rsuite Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react'import 'rsuite/dist/styles/rsuite-default.css';import { SelectPicker } from 'rsuite'; export default function App() { // Sample data const options = [{ "label": "Monday", "value": "Monday", "role": "Master", }, { "label": "Tuesday", "value": "Tuesday", "role": "Master", }, { "label": "Wednesday", "value": "Wednesday", "role": "Master", }, { "label": "Thursday", "value": "Thursday", "role": "Master", }, { "label": "Friday", "value": "Friday", "role": "Master", }, { "label": "Saturday", "value": "Saturday", "role": "Master", }, { "label": "Sunday", "value": "Sunday", "role": "Master", }] return ( <div style={{ display: 'block', width: 600, paddingLeft: 30 }}> <h4>React Suite SelectPicker Component</h4> <SelectPicker placeholder="Please Select Weekday" data={options} /> </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://rsuitejs.com/components/select-picker/ React-Suite React-Suite Components React-Suite Data Entry 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 How to get character array from string in JavaScript? Remove elements from a JavaScript Array 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": "\n11 Apr, 2022" }, { "code": null, "e": 25265, "s": 24921, "text": "React Suite is a popular front-end library with a set of React components that are designed for the middle platform and back-end products. SelectPicker component allows the users to select a single piece of data. This component also supports grouping. We can use the following approach in ReactJS to use the React Suite SelectPicker Component." }, { "code": null, "e": 25285, "s": 25265, "text": "SelectPicker Props:" }, { "code": null, "e": 25346, "s": 25285, "text": "appearance: It is used for the appearance of the component. " }, { "code": null, "e": 25388, "s": 25346, "text": "block: It is used to block an entire row." }, { "code": null, "e": 25461, "s": 25388, "text": "classPrefix: It is used to denote the prefix of the component CSS class." }, { "code": null, "e": 25537, "s": 25461, "text": "cleanable: It is used to indicate whether the option can be emptied or not." }, { "code": null, "e": 25591, "s": 25537, "text": "container: It is used to set the rendering container." }, { "code": null, "e": 25639, "s": 25591, "text": "creatable: The settings can create new options." }, { "code": null, "e": 25687, "s": 25639, "text": "data: It is used to denote the selectable data." }, { "code": null, "e": 25741, "s": 25687, "text": "defaultValue: It is used to denote the default value." }, { "code": null, "e": 25816, "s": 25741, "text": "disabled: It is used to indicate whether the component is disabled or not." }, { "code": null, "e": 25868, "s": 25816, "text": "disabledItemValues: It is used to disable optional." }, { "code": null, "e": 25934, "s": 25868, "text": "groupBy: It is used to set the grouping criteria ‘key’ in ‘data’." }, { "code": null, "e": 26006, "s": 25934, "text": "labelKey: It is used to set the options to display the ‘key’ in ‘data’." }, { "code": null, "e": 26088, "s": 26006, "text": "listProps: It is used to denote the list-related properties in react-virtualized." }, { "code": null, "e": 26149, "s": 26088, "text": "maxHeight: It is used to set the max height of the Dropdown." }, { "code": null, "e": 26228, "s": 26149, "text": "menuClassName: It is used to denote a CSS class to apply to the Menu DOM node." }, { "code": null, "e": 26299, "s": 26228, "text": "menuStyle: It is used to denote a style to apply to the Menu DOM node." }, { "code": null, "e": 26373, "s": 26299, "text": "onChange: It is a callback function that is triggered when value changes." }, { "code": null, "e": 26444, "s": 26373, "text": "onClean: It is a callback function that is triggered when value clean." }, { "code": null, "e": 26515, "s": 26444, "text": "onClose: It is a callback function that is triggered on a close event." }, { "code": null, "e": 26603, "s": 26515, "text": "onEnter: It is a callback function that is triggered before the overlay transitions in." }, { "code": null, "e": 26703, "s": 26603, "text": "onEntered: It is a callback function that is triggered after the overlay finishes transitioning in." }, { "code": null, "e": 26799, "s": 26703, "text": "onEntering: It is a callback function that is triggered as the overlay begins to transition in." }, { "code": null, "e": 26893, "s": 26799, "text": "onExit: It is a callback function that is triggered right before the overlay transitions out." }, { "code": null, "e": 26993, "s": 26893, "text": "onExited: It is a callback function that is triggered after the overlay finishes transitioning out." }, { "code": null, "e": 27089, "s": 26993, "text": "onExiting: It is a callback function that is triggered as the overlay begins to transition out." }, { "code": null, "e": 27158, "s": 27089, "text": "onGroupTitleClick: Click the callback function for the group header." }, { "code": null, "e": 27236, "s": 27158, "text": "onOpen: It is a callback function that is triggered on open of the component." }, { "code": null, "e": 27288, "s": 27236, "text": "onSearch: It is a callback function for the search." }, { "code": null, "e": 27373, "s": 27288, "text": "onSelect: It is a callback function that is triggered on the selection of an option." }, { "code": null, "e": 27424, "s": 27373, "text": "placeholder: It is used to denote the placeholder." }, { "code": null, "e": 27478, "s": 27424, "text": "placement: It is used for the placement of component." }, { "code": null, "e": 27544, "s": 27478, "text": "preventOverflow: It is used to prevent floating element overflow." }, { "code": null, "e": 27610, "s": 27544, "text": "renderExtraFooter: It is used for the custom render extra footer." }, { "code": null, "e": 27674, "s": 27610, "text": "renderMenu: It is used for customizing the Rendering Menu list." }, { "code": null, "e": 27739, "s": 27674, "text": "renderMenuGroup: It is used for the custom Render Options Group." }, { "code": null, "e": 27797, "s": 27739, "text": "renderMenuItem: It is used for the custom Render Options." }, { "code": null, "e": 27861, "s": 27797, "text": "renderValue: It is used for the custom Render selected options." }, { "code": null, "e": 27911, "s": 27861, "text": "searchBy: It is used for the custom search rules." }, { "code": null, "e": 27989, "s": 27911, "text": "searchable: It is used to indicate whether you can search for options or not." }, { "code": null, "e": 28033, "s": 27989, "text": "size: It is used to denote the picker size." }, { "code": null, "e": 28072, "s": 28033, "text": "sort: It is used for the sort options." }, { "code": null, "e": 28152, "s": 28072, "text": "toggleComponentClass: It can be used for the custom element for this component." }, { "code": null, "e": 28204, "s": 28152, "text": "value: It is used to denote the value (Controlled)." }, { "code": null, "e": 28266, "s": 28204, "text": "valueKey: It is used to set the option value ‘key’ in ‘data’." }, { "code": null, "e": 28341, "s": 28266, "text": "virtualized: It is used to indicate whether using Virtualized List or not." }, { "code": null, "e": 28391, "s": 28341, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 28487, "s": 28391, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername " }, { "code": null, "e": 28551, "s": 28487, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 28583, "s": 28551, "text": "npx create-react-app foldername" }, { "code": null, "e": 28698, "s": 28585, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 28798, "s": 28698, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 28812, "s": 28798, "text": "cd foldername" }, { "code": null, "e": 28935, "s": 28812, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install rsuite" }, { "code": null, "e": 29040, "s": 28935, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 29059, "s": 29040, "text": "npm install rsuite" }, { "code": null, "e": 29111, "s": 29059, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 29129, "s": 29111, "text": "Project Structure" }, { "code": null, "e": 29259, "s": 29129, "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": 29266, "s": 29259, "text": "App.js" }, { "code": "import React from 'react'import 'rsuite/dist/styles/rsuite-default.css';import { SelectPicker } from 'rsuite'; export default function App() { // Sample data const options = [{ \"label\": \"Monday\", \"value\": \"Monday\", \"role\": \"Master\", }, { \"label\": \"Tuesday\", \"value\": \"Tuesday\", \"role\": \"Master\", }, { \"label\": \"Wednesday\", \"value\": \"Wednesday\", \"role\": \"Master\", }, { \"label\": \"Thursday\", \"value\": \"Thursday\", \"role\": \"Master\", }, { \"label\": \"Friday\", \"value\": \"Friday\", \"role\": \"Master\", }, { \"label\": \"Saturday\", \"value\": \"Saturday\", \"role\": \"Master\", }, { \"label\": \"Sunday\", \"value\": \"Sunday\", \"role\": \"Master\", }] return ( <div style={{ display: 'block', width: 600, paddingLeft: 30 }}> <h4>React Suite SelectPicker Component</h4> <SelectPicker placeholder=\"Please Select Weekday\" data={options} /> </div> );}", "e": 30190, "s": 29266, "text": null }, { "code": null, "e": 30303, "s": 30190, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 30313, "s": 30303, "text": "npm start" }, { "code": null, "e": 30412, "s": 30313, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 30470, "s": 30412, "text": "Reference: https://rsuitejs.com/components/select-picker/" }, { "code": null, "e": 30482, "s": 30470, "text": "React-Suite" }, { "code": null, "e": 30505, "s": 30482, "text": "React-Suite Components" }, { "code": null, "e": 30528, "s": 30505, "text": "React-Suite Data Entry" }, { "code": null, "e": 30539, "s": 30528, "text": "JavaScript" }, { "code": null, "e": 30547, "s": 30539, "text": "ReactJS" }, { "code": null, "e": 30564, "s": 30547, "text": "Web Technologies" }, { "code": null, "e": 30662, "s": 30564, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30671, "s": 30662, "text": "Comments" }, { "code": null, "e": 30684, "s": 30671, "text": "Old Comments" }, { "code": null, "e": 30745, "s": 30684, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30786, "s": 30745, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30840, "s": 30786, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 30880, "s": 30840, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30942, "s": 30880, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 30985, "s": 30942, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31030, "s": 30985, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 31095, "s": 31030, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 31163, "s": 31095, "text": "How to pass data from one component to other component in ReactJS ?" } ]
CSS | stroke-dasharray Property - GeeksforGeeks
21 Nov, 2019 The stroke-dasharray property is used to set the pattern of dashes and gaps used in the stroke of SVG shapes. A larger value indicates a larger number of dashes. Different values can be specified in the array parameter to change the pattern. Syntax: stroke-dasharray: <dasharray> | none Property Values: dasharray: It is used to set the pattern with a list of values separated by commas or white space. The values can be both in terms of length units or percentages that specify the dashes and gaps in the pattern.Example 1: Setting the density of the dashes in lines.<!DOCTYPE html><html><head> <title> CSS | stroke-dasharray property </title> <style> .stroke1 { stroke-dasharray: 20; stroke: green; stroke-width: 20; } .stroke2 { stroke-dasharray: 40; stroke: red; stroke-width: 20; } .stroke3 { stroke-dasharray: 80; stroke: orange; stroke-width: 20; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | stroke-dasharray </b> <div class="container"> <svg height="250px" width="500px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <line class="stroke1" x1="0" x2="350" y1="20" y2="20" /> <line class="stroke2" x1="0" x2="350" y1="70" y2="70" /> <line class="stroke3" x1="0" x2="350" y1="120" y2="120" /> </svg> </div></body></html> Output:Example 2: Setting the density of the dashes in circles.<!DOCTYPE html><html><head> <title> CSS | stroke-dasharray property </title> <style> .stroke1 { stroke-dasharray: 10; stroke: green; stroke-width: 20; } .stroke2 { stroke-dasharray: 20; stroke: red; stroke-width: 20; } .stroke3 { stroke-dasharray: 40; stroke: orange; stroke-width: 20; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | stroke-dasharray </b> <div class="container"> <svg height="250px" width="500px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <circle class="stroke1" cx="100" cy="100" r="50"/> <circle class="stroke2" cx="250" cy="100" r="50"/> <circle class="stroke3" cx="400" cy="100" r="50"/> </svg> </div></body></html>Output:Example 3: Setting the pattern of the dashes.<!DOCTYPE html><html><head> <title> CSS | stroke-dasharray property </title> <style> .stroke1 { stroke-dasharray: 20; stroke: green; stroke-width: 20; } .stroke2 { /* pattern with even number of values */ stroke-dasharray: 40 20; stroke: red; stroke-width: 20; } .stroke3 { /* pattern with odd number of values */ stroke-dasharray: 80 40 20; stroke: orange; stroke-width: 20; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | stroke-dasharray </b> <div class="container"> <svg height="250px" width="500px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <line class="stroke1" x1="0" x2="350" y1="20" y2="20" /> <line class="stroke2" x1="0" x2="350" y1="70" y2="70" /> <line class="stroke3" x1="0" x2="350" y1="120" y2="120" /> </svg> </div></body></html>Output: Example 1: Setting the density of the dashes in lines. <!DOCTYPE html><html><head> <title> CSS | stroke-dasharray property </title> <style> .stroke1 { stroke-dasharray: 20; stroke: green; stroke-width: 20; } .stroke2 { stroke-dasharray: 40; stroke: red; stroke-width: 20; } .stroke3 { stroke-dasharray: 80; stroke: orange; stroke-width: 20; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | stroke-dasharray </b> <div class="container"> <svg height="250px" width="500px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <line class="stroke1" x1="0" x2="350" y1="20" y2="20" /> <line class="stroke2" x1="0" x2="350" y1="70" y2="70" /> <line class="stroke3" x1="0" x2="350" y1="120" y2="120" /> </svg> </div></body></html> Output: Example 2: Setting the density of the dashes in circles. <!DOCTYPE html><html><head> <title> CSS | stroke-dasharray property </title> <style> .stroke1 { stroke-dasharray: 10; stroke: green; stroke-width: 20; } .stroke2 { stroke-dasharray: 20; stroke: red; stroke-width: 20; } .stroke3 { stroke-dasharray: 40; stroke: orange; stroke-width: 20; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | stroke-dasharray </b> <div class="container"> <svg height="250px" width="500px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <circle class="stroke1" cx="100" cy="100" r="50"/> <circle class="stroke2" cx="250" cy="100" r="50"/> <circle class="stroke3" cx="400" cy="100" r="50"/> </svg> </div></body></html> Output: Example 3: Setting the pattern of the dashes. <!DOCTYPE html><html><head> <title> CSS | stroke-dasharray property </title> <style> .stroke1 { stroke-dasharray: 20; stroke: green; stroke-width: 20; } .stroke2 { /* pattern with even number of values */ stroke-dasharray: 40 20; stroke: red; stroke-width: 20; } .stroke3 { /* pattern with odd number of values */ stroke-dasharray: 80 40 20; stroke: orange; stroke-width: 20; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | stroke-dasharray </b> <div class="container"> <svg height="250px" width="500px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <line class="stroke1" x1="0" x2="350" y1="20" y2="20" /> <line class="stroke2" x1="0" x2="350" y1="70" y2="70" /> <line class="stroke3" x1="0" x2="350" y1="120" y2="120" /> </svg> </div></body></html> Output: none: It is used to specify that no pattern would be used. It is the default value. Supported Browsers: The browsers supported by stroke-dasharray property are listed below: Chrome Firefox Safari Opera Internet Explorer 9 CSS-Properties Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox 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": 24985, "s": 24957, "text": "\n21 Nov, 2019" }, { "code": null, "e": 25227, "s": 24985, "text": "The stroke-dasharray property is used to set the pattern of dashes and gaps used in the stroke of SVG shapes. A larger value indicates a larger number of dashes. Different values can be specified in the array parameter to change the pattern." }, { "code": null, "e": 25235, "s": 25227, "text": "Syntax:" }, { "code": null, "e": 25272, "s": 25235, "text": "stroke-dasharray: <dasharray> | none" }, { "code": null, "e": 25289, "s": 25272, "text": "Property Values:" }, { "code": null, "e": 28293, "s": 25289, "text": "dasharray: It is used to set the pattern with a list of values separated by commas or white space. The values can be both in terms of length units or percentages that specify the dashes and gaps in the pattern.Example 1: Setting the density of the dashes in lines.<!DOCTYPE html><html><head> <title> CSS | stroke-dasharray property </title> <style> .stroke1 { stroke-dasharray: 20; stroke: green; stroke-width: 20; } .stroke2 { stroke-dasharray: 40; stroke: red; stroke-width: 20; } .stroke3 { stroke-dasharray: 80; stroke: orange; stroke-width: 20; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | stroke-dasharray </b> <div class=\"container\"> <svg height=\"250px\" width=\"500px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <line class=\"stroke1\" x1=\"0\" x2=\"350\" y1=\"20\" y2=\"20\" /> <line class=\"stroke2\" x1=\"0\" x2=\"350\" y1=\"70\" y2=\"70\" /> <line class=\"stroke3\" x1=\"0\" x2=\"350\" y1=\"120\" y2=\"120\" /> </svg> </div></body></html> Output:Example 2: Setting the density of the dashes in circles.<!DOCTYPE html><html><head> <title> CSS | stroke-dasharray property </title> <style> .stroke1 { stroke-dasharray: 10; stroke: green; stroke-width: 20; } .stroke2 { stroke-dasharray: 20; stroke: red; stroke-width: 20; } .stroke3 { stroke-dasharray: 40; stroke: orange; stroke-width: 20; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | stroke-dasharray </b> <div class=\"container\"> <svg height=\"250px\" width=\"500px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <circle class=\"stroke1\" cx=\"100\" cy=\"100\" r=\"50\"/> <circle class=\"stroke2\" cx=\"250\" cy=\"100\" r=\"50\"/> <circle class=\"stroke3\" cx=\"400\" cy=\"100\" r=\"50\"/> </svg> </div></body></html>Output:Example 3: Setting the pattern of the dashes.<!DOCTYPE html><html><head> <title> CSS | stroke-dasharray property </title> <style> .stroke1 { stroke-dasharray: 20; stroke: green; stroke-width: 20; } .stroke2 { /* pattern with even number of values */ stroke-dasharray: 40 20; stroke: red; stroke-width: 20; } .stroke3 { /* pattern with odd number of values */ stroke-dasharray: 80 40 20; stroke: orange; stroke-width: 20; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | stroke-dasharray </b> <div class=\"container\"> <svg height=\"250px\" width=\"500px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <line class=\"stroke1\" x1=\"0\" x2=\"350\" y1=\"20\" y2=\"20\" /> <line class=\"stroke2\" x1=\"0\" x2=\"350\" y1=\"70\" y2=\"70\" /> <line class=\"stroke3\" x1=\"0\" x2=\"350\" y1=\"120\" y2=\"120\" /> </svg> </div></body></html>Output:" }, { "code": null, "e": 28348, "s": 28293, "text": "Example 1: Setting the density of the dashes in lines." }, { "code": "<!DOCTYPE html><html><head> <title> CSS | stroke-dasharray property </title> <style> .stroke1 { stroke-dasharray: 20; stroke: green; stroke-width: 20; } .stroke2 { stroke-dasharray: 40; stroke: red; stroke-width: 20; } .stroke3 { stroke-dasharray: 80; stroke: orange; stroke-width: 20; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | stroke-dasharray </b> <div class=\"container\"> <svg height=\"250px\" width=\"500px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <line class=\"stroke1\" x1=\"0\" x2=\"350\" y1=\"20\" y2=\"20\" /> <line class=\"stroke2\" x1=\"0\" x2=\"350\" y1=\"70\" y2=\"70\" /> <line class=\"stroke3\" x1=\"0\" x2=\"350\" y1=\"120\" y2=\"120\" /> </svg> </div></body></html> ", "e": 29192, "s": 28348, "text": null }, { "code": null, "e": 29200, "s": 29192, "text": "Output:" }, { "code": null, "e": 29257, "s": 29200, "text": "Example 2: Setting the density of the dashes in circles." }, { "code": "<!DOCTYPE html><html><head> <title> CSS | stroke-dasharray property </title> <style> .stroke1 { stroke-dasharray: 10; stroke: green; stroke-width: 20; } .stroke2 { stroke-dasharray: 20; stroke: red; stroke-width: 20; } .stroke3 { stroke-dasharray: 40; stroke: orange; stroke-width: 20; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | stroke-dasharray </b> <div class=\"container\"> <svg height=\"250px\" width=\"500px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <circle class=\"stroke1\" cx=\"100\" cy=\"100\" r=\"50\"/> <circle class=\"stroke2\" cx=\"250\" cy=\"100\" r=\"50\"/> <circle class=\"stroke3\" cx=\"400\" cy=\"100\" r=\"50\"/> </svg> </div></body></html>", "e": 30076, "s": 29257, "text": null }, { "code": null, "e": 30084, "s": 30076, "text": "Output:" }, { "code": null, "e": 30130, "s": 30084, "text": "Example 3: Setting the pattern of the dashes." }, { "code": "<!DOCTYPE html><html><head> <title> CSS | stroke-dasharray property </title> <style> .stroke1 { stroke-dasharray: 20; stroke: green; stroke-width: 20; } .stroke2 { /* pattern with even number of values */ stroke-dasharray: 40 20; stroke: red; stroke-width: 20; } .stroke3 { /* pattern with odd number of values */ stroke-dasharray: 80 40 20; stroke: orange; stroke-width: 20; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | stroke-dasharray </b> <div class=\"container\"> <svg height=\"250px\" width=\"500px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <line class=\"stroke1\" x1=\"0\" x2=\"350\" y1=\"20\" y2=\"20\" /> <line class=\"stroke2\" x1=\"0\" x2=\"350\" y1=\"70\" y2=\"70\" /> <line class=\"stroke3\" x1=\"0\" x2=\"350\" y1=\"120\" y2=\"120\" /> </svg> </div></body></html>", "e": 31087, "s": 30130, "text": null }, { "code": null, "e": 31095, "s": 31087, "text": "Output:" }, { "code": null, "e": 31179, "s": 31095, "text": "none: It is used to specify that no pattern would be used. It is the default value." }, { "code": null, "e": 31269, "s": 31179, "text": "Supported Browsers: The browsers supported by stroke-dasharray property are listed below:" }, { "code": null, "e": 31276, "s": 31269, "text": "Chrome" }, { "code": null, "e": 31284, "s": 31276, "text": "Firefox" }, { "code": null, "e": 31291, "s": 31284, "text": "Safari" }, { "code": null, "e": 31297, "s": 31291, "text": "Opera" }, { "code": null, "e": 31317, "s": 31297, "text": "Internet Explorer 9" }, { "code": null, "e": 31332, "s": 31317, "text": "CSS-Properties" }, { "code": null, "e": 31339, "s": 31332, "text": "Picked" }, { "code": null, "e": 31343, "s": 31339, "text": "CSS" }, { "code": null, "e": 31360, "s": 31343, "text": "Web Technologies" }, { "code": null, "e": 31458, "s": 31360, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31467, "s": 31458, "text": "Comments" }, { "code": null, "e": 31480, "s": 31467, "text": "Old Comments" }, { "code": null, "e": 31517, "s": 31480, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 31546, "s": 31517, "text": "Form validation using jQuery" }, { "code": null, "e": 31585, "s": 31546, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 31627, "s": 31585, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 31662, "s": 31627, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 31718, "s": 31662, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 31751, "s": 31718, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31794, "s": 31751, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31855, "s": 31794, "text": "Difference between var, let and const keywords in JavaScript" } ]
HTML | DOM Input Radio required Property - GeeksforGeeks
25 Mar, 2019 The DOM Input Radio required Property in HTML DOM is used to set or return whether Input Radio Field should be checked or not when submitting the form. This property is used to reflect the HTML required attribute. Syntax: It returns the Input Radio required property.radioObject.required radioObject.required It is used to set the Input Radio required property.radioObject.required = true|false radioObject.required = true|false Property Values: true: It specifies that the Radio field must be checked out before submitting the form. false: It is the default value. It specifies that the Radio field must not be checked out before submitting the form. Return Value: It returns a Boolean value which represents that the Radio Field must be checked or not before submitting the form. Example-1: This example illustrates how to return Input Radio required property. <!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <h2> HTML DOM Input Radio required Property </h2> Radio Button: <input type="radio" checked=true id="radioID" value="Geeks_radio" required> <br> <br> <button onclick="GFG()"> Click! </button> <p id="GFG" style="font-size:25px; color:green;"> </p> <script> function GFG() { // Accessing input element // type="radio" var x = document.getElementById( "radioID").required; document.getElementById( "GFG").innerHTML = x; } </script> </body> </html> Output:Before Clicking On Button: After Clicking On Button: Example-2: This Example illustrates how to set the Input Radio required Property. <!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <h2> HTML DOM Input Radio required Property </h2> Radio Button: <input type="radio" checked=true id="radioID" value="Geeks_radio" required> <br> <br> <button onclick="GFG()"> Click! </button> <p id="GFG" style="font-size:25px; color:green;"> </p> <script> function GFG() { // Accessing input element // type="radio" var x = document.getElementById( "radioID").required = "false"; document.getElementById( "GFG").innerHTML = x; } </script> </body> </html> Output:Before Clicking On Button: After Clicking On Button: Supported Browsers: The browser supported by DOM input Radio required Property are listed below: Google Chrome Internet Explorer 10.0 + 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. HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form REST API (Introduction) 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": 25018, "s": 24990, "text": "\n25 Mar, 2019" }, { "code": null, "e": 25232, "s": 25018, "text": "The DOM Input Radio required Property in HTML DOM is used to set or return whether Input Radio Field should be checked or not when submitting the form. This property is used to reflect the HTML required attribute." }, { "code": null, "e": 25240, "s": 25232, "text": "Syntax:" }, { "code": null, "e": 25306, "s": 25240, "text": "It returns the Input Radio required property.radioObject.required" }, { "code": null, "e": 25327, "s": 25306, "text": "radioObject.required" }, { "code": null, "e": 25413, "s": 25327, "text": "It is used to set the Input Radio required property.radioObject.required = true|false" }, { "code": null, "e": 25447, "s": 25413, "text": "radioObject.required = true|false" }, { "code": null, "e": 25464, "s": 25447, "text": "Property Values:" }, { "code": null, "e": 25552, "s": 25464, "text": "true: It specifies that the Radio field must be checked out before submitting the form." }, { "code": null, "e": 25670, "s": 25552, "text": "false: It is the default value. It specifies that the Radio field must not be checked out before submitting the form." }, { "code": null, "e": 25800, "s": 25670, "text": "Return Value: It returns a Boolean value which represents that the Radio Field must be checked or not before submitting the form." }, { "code": null, "e": 25881, "s": 25800, "text": "Example-1: This example illustrates how to return Input Radio required property." }, { "code": "<!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <h2> HTML DOM Input Radio required Property </h2> Radio Button: <input type=\"radio\" checked=true id=\"radioID\" value=\"Geeks_radio\" required> <br> <br> <button onclick=\"GFG()\"> Click! </button> <p id=\"GFG\" style=\"font-size:25px; color:green;\"> </p> <script> function GFG() { // Accessing input element // type=\"radio\" var x = document.getElementById( \"radioID\").required; document.getElementById( \"GFG\").innerHTML = x; } </script> </body> </html>", "e": 26765, "s": 25881, "text": null }, { "code": null, "e": 26799, "s": 26765, "text": "Output:Before Clicking On Button:" }, { "code": null, "e": 26825, "s": 26799, "text": "After Clicking On Button:" }, { "code": null, "e": 26907, "s": 26825, "text": "Example-2: This Example illustrates how to set the Input Radio required Property." }, { "code": "<!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <h2> HTML DOM Input Radio required Property </h2> Radio Button: <input type=\"radio\" checked=true id=\"radioID\" value=\"Geeks_radio\" required> <br> <br> <button onclick=\"GFG()\"> Click! </button> <p id=\"GFG\" style=\"font-size:25px; color:green;\"> </p> <script> function GFG() { // Accessing input element // type=\"radio\" var x = document.getElementById( \"radioID\").required = \"false\"; document.getElementById( \"GFG\").innerHTML = x; } </script> </body> </html>", "e": 27800, "s": 26907, "text": null }, { "code": null, "e": 27834, "s": 27800, "text": "Output:Before Clicking On Button:" }, { "code": null, "e": 27860, "s": 27834, "text": "After Clicking On Button:" }, { "code": null, "e": 27957, "s": 27860, "text": "Supported Browsers: The browser supported by DOM input Radio required Property are listed below:" }, { "code": null, "e": 27971, "s": 27957, "text": "Google Chrome" }, { "code": null, "e": 27996, "s": 27971, "text": "Internet Explorer 10.0 +" }, { "code": null, "e": 28004, "s": 27996, "text": "Firefox" }, { "code": null, "e": 28010, "s": 28004, "text": "Opera" }, { "code": null, "e": 28017, "s": 28010, "text": "Safari" }, { "code": null, "e": 28154, "s": 28017, "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": 28163, "s": 28154, "text": "HTML-DOM" }, { "code": null, "e": 28168, "s": 28163, "text": "HTML" }, { "code": null, "e": 28185, "s": 28168, "text": "Web Technologies" }, { "code": null, "e": 28190, "s": 28185, "text": "HTML" }, { "code": null, "e": 28288, "s": 28190, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28297, "s": 28288, "text": "Comments" }, { "code": null, "e": 28310, "s": 28297, "text": "Old Comments" }, { "code": null, "e": 28358, "s": 28310, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28395, "s": 28358, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28445, "s": 28395, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28495, "s": 28445, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 28519, "s": 28495, "text": "REST API (Introduction)" }, { "code": null, "e": 28575, "s": 28519, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28608, "s": 28575, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28651, "s": 28608, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28712, "s": 28651, "text": "Difference between var, let and const keywords in JavaScript" } ]
C# | Jump Statements (Break, Continue, Goto, Return and Throw) - GeeksforGeeks
09 Feb, 2022 In C#, Jump statements are used to transfer control from one point to another point in the program due to some specified code while executing the program. There are five keywords in the Jump Statements: break continue goto return throw The break statement is used to terminate the loop or statement in which it present. After that, the control will pass to the statements that present after the break statement, if available. If the break statement present in the nested loop, then it terminates only those loops which contains break statement. Flowchart: Example: CSharp // C# program to illustrate the// use of break statementusing System; class Geeks { // Main Method static public void Main() { // GeeksforGeeks is printed only 2 times // because of break statement for (int i = 1; i < 4; i++) { if (i == 3) break; Console.WriteLine("GeeksforGeeks"); } }} GeeksforGeeks GeeksforGeeks This statement is used to skip over the execution part of the loop on a certain condition. After that, it transfers the control to the beginning of the loop. Basically, it skips its following statements and continues with the next iteration of the loop. Example: CSharp // C# program to illustrate the// use of continue statementusing System; class Geeks { // Main Method public static void Main() { // This will skip 4 to print for (int i = 1; i <= 10; i++) { // if the value of i becomes 4 then // it will skip 4 and send the // transfer to the for loop and // continue with 5 if (i == 4) continue; Console.WriteLine(i); } }} 1 2 3 5 6 7 8 9 10 This statement is used to transfer control to the labeled statement in the program. The label is the valid identifier and placed just before the statement from where the control is transferred. Example: CSharp // C# program to illustrate the// use of goto statementusing System; class Geeks { // Main Method static public void Main() { int number = 20; switch (number) { case 5: Console.WriteLine("case 5"); break; case 10: Console.WriteLine("case 10"); break; case 20: Console.WriteLine("case 20"); // goto statement transfer // the control to case 5 goto case 5; default: Console.WriteLine("No match found"); break; } }} case 20 case 5 This statement terminates the execution of the method and returns the control to the calling method. It returns an optional value. If the type of method is void, then the return statement can be excluded.Example: CSharp // C# program to illustrate the// use of return statementusing System; class Geeks { // creating simple addition function static int Addition(int a) { // add two value and // return the result of addition int add = a + a; // using return statement return add; } // Main Method static public void Main() { int number = 2; // calling addition function int result = Addition(number); Console.WriteLine("The addition is {0}", result); }} The addition is 4 This is used to create an object of any valid exception class with the help of new keyword manually. The valid exception must be derived from the Exception class.Example: CSharp // C# Program to illustrate the use// of throw keywordusing System; class Geeks { // taking null in the string static string sub = null; // method to display subject name static void displaysubject(string sub1) { if (sub1 == null) throw new NullReferenceException("Exception Message"); } // Main Method static void Main(string[] args){ // using try catch block to // handle the Exception try { // calling the static method displaysubject(sub); } catch(Exception exp) { Console.WriteLine(exp.Message ); } } } Exception Message shubham_singh vishalkumar14 CSharp-Basics CSharp-Decision Making C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Abstract Class and Interface in C# C# | IsNullOrEmpty() Method C# | How to check whether a List contains a specified element String.Split() Method in C# with Examples C# | Arrays of Strings Extension Method in C# C# | Delegates C# | String.IndexOf( ) Method | Set - 1 Difference between Ref and Out keywords in C# Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework
[ { "code": null, "e": 25224, "s": 25196, "text": "\n09 Feb, 2022" }, { "code": null, "e": 25427, "s": 25224, "text": "In C#, Jump statements are used to transfer control from one point to another point in the program due to some specified code while executing the program. There are five keywords in the Jump Statements:" }, { "code": null, "e": 25433, "s": 25427, "text": "break" }, { "code": null, "e": 25442, "s": 25433, "text": "continue" }, { "code": null, "e": 25447, "s": 25442, "text": "goto" }, { "code": null, "e": 25454, "s": 25447, "text": "return" }, { "code": null, "e": 25461, "s": 25454, "text": "throw " }, { "code": null, "e": 25782, "s": 25461, "text": "The break statement is used to terminate the loop or statement in which it present. After that, the control will pass to the statements that present after the break statement, if available. If the break statement present in the nested loop, then it terminates only those loops which contains break statement. Flowchart: " }, { "code": null, "e": 25792, "s": 25782, "text": "Example: " }, { "code": null, "e": 25799, "s": 25792, "text": "CSharp" }, { "code": "// C# program to illustrate the// use of break statementusing System; class Geeks { // Main Method static public void Main() { // GeeksforGeeks is printed only 2 times // because of break statement for (int i = 1; i < 4; i++) { if (i == 3) break; Console.WriteLine(\"GeeksforGeeks\"); } }}", "e": 26174, "s": 25799, "text": null }, { "code": null, "e": 26202, "s": 26174, "text": "GeeksforGeeks\nGeeksforGeeks" }, { "code": null, "e": 26459, "s": 26204, "text": "This statement is used to skip over the execution part of the loop on a certain condition. After that, it transfers the control to the beginning of the loop. Basically, it skips its following statements and continues with the next iteration of the loop. " }, { "code": null, "e": 26469, "s": 26459, "text": "Example: " }, { "code": null, "e": 26476, "s": 26469, "text": "CSharp" }, { "code": "// C# program to illustrate the// use of continue statementusing System; class Geeks { // Main Method public static void Main() { // This will skip 4 to print for (int i = 1; i <= 10; i++) { // if the value of i becomes 4 then // it will skip 4 and send the // transfer to the for loop and // continue with 5 if (i == 4) continue; Console.WriteLine(i); } }}", "e": 26960, "s": 26476, "text": null }, { "code": null, "e": 26979, "s": 26960, "text": "1\n2\n3\n5\n6\n7\n8\n9\n10" }, { "code": null, "e": 27176, "s": 26981, "text": "This statement is used to transfer control to the labeled statement in the program. The label is the valid identifier and placed just before the statement from where the control is transferred. " }, { "code": null, "e": 27186, "s": 27176, "text": "Example: " }, { "code": null, "e": 27193, "s": 27186, "text": "CSharp" }, { "code": "// C# program to illustrate the// use of goto statementusing System; class Geeks { // Main Method static public void Main() { int number = 20; switch (number) { case 5: Console.WriteLine(\"case 5\"); break; case 10: Console.WriteLine(\"case 10\"); break; case 20: Console.WriteLine(\"case 20\"); // goto statement transfer // the control to case 5 goto case 5; default: Console.WriteLine(\"No match found\"); break; } }}", "e": 27781, "s": 27193, "text": null }, { "code": null, "e": 27796, "s": 27781, "text": "case 20\ncase 5" }, { "code": null, "e": 28012, "s": 27798, "text": "This statement terminates the execution of the method and returns the control to the calling method. It returns an optional value. If the type of method is void, then the return statement can be excluded.Example: " }, { "code": null, "e": 28019, "s": 28012, "text": "CSharp" }, { "code": "// C# program to illustrate the// use of return statementusing System; class Geeks { // creating simple addition function static int Addition(int a) { // add two value and // return the result of addition int add = a + a; // using return statement return add; } // Main Method static public void Main() { int number = 2; // calling addition function int result = Addition(number); Console.WriteLine(\"The addition is {0}\", result); }}", "e": 28552, "s": 28019, "text": null }, { "code": null, "e": 28570, "s": 28552, "text": "The addition is 4" }, { "code": null, "e": 28744, "s": 28572, "text": "This is used to create an object of any valid exception class with the help of new keyword manually. The valid exception must be derived from the Exception class.Example: " }, { "code": null, "e": 28751, "s": 28744, "text": "CSharp" }, { "code": "// C# Program to illustrate the use// of throw keywordusing System; class Geeks { // taking null in the string static string sub = null; // method to display subject name static void displaysubject(string sub1) { if (sub1 == null) throw new NullReferenceException(\"Exception Message\"); } // Main Method static void Main(string[] args){ // using try catch block to // handle the Exception try { // calling the static method displaysubject(sub); } catch(Exception exp) { Console.WriteLine(exp.Message ); } } }", "e": 29413, "s": 28751, "text": null }, { "code": null, "e": 29431, "s": 29413, "text": "Exception Message" }, { "code": null, "e": 29447, "s": 29433, "text": "shubham_singh" }, { "code": null, "e": 29461, "s": 29447, "text": "vishalkumar14" }, { "code": null, "e": 29475, "s": 29461, "text": "CSharp-Basics" }, { "code": null, "e": 29498, "s": 29475, "text": "CSharp-Decision Making" }, { "code": null, "e": 29501, "s": 29498, "text": "C#" }, { "code": null, "e": 29599, "s": 29501, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29608, "s": 29599, "text": "Comments" }, { "code": null, "e": 29621, "s": 29608, "text": "Old Comments" }, { "code": null, "e": 29675, "s": 29621, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 29703, "s": 29675, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 29765, "s": 29703, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 29807, "s": 29765, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 29830, "s": 29807, "text": "C# | Arrays of Strings" }, { "code": null, "e": 29853, "s": 29830, "text": "Extension Method in C#" }, { "code": null, "e": 29868, "s": 29853, "text": "C# | Delegates" }, { "code": null, "e": 29908, "s": 29868, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 29954, "s": 29908, "text": "Difference between Ref and Out keywords in C#" } ]
Logistic Regression and Decision Boundary | by Anuradha Wickramarachchi | Towards Data Science
The fundamental application of logistic regression is to determine a decision boundary for a binary classification problem. Although the baseline is to identify a binary decision boundary, the approach can be very well applied for scenarios with multiple classification classes or multi-class classification. In the above diagram, the dashed line can be identified as the decision boundary since we will observe instances of a different class on each side of the boundary. Our intention in logistic regression would be to decide on a proper fit to the decision boundary so that we will be able to predict which class a new feature set might correspond to. The interesting fact about logistic regression is the utilization of the sigmoid function as the target class estimator. Let us have a look at the intuition behind this decision. The sigmoid function for parameter z can be represented as follows. Note that the function always lies in the range of 0 to 1, boundaries being asymptotic. This gives us a perfect output representation of probabilities too. Now that we know our sigmoid function lies between 0 and 1 we can represent the class probabilities as follows. Here θ stands for the estimated parameter vector and X is the vector of variables considered. X = X0, X1 ... Xn <- n Features and X0=1θ = θ0, θ1 ... θn <- Parameters to be estimated Now that we are aware of a function estimate for our probabilities we shall come up with a way to estimate the parameters represented by θ vector. For this exercise let us consider the following example. We have a dataset with two features and two classes. Our objective is to discover the proper values of θ for the two features. This can be modelled as follows. h(θ) is the probability estimation or the hypothesis function. For a moment let’s assume that we can use the root mean squared error (RMS), similar to linear regression. You may refer to the following article for more insights. towardsdatascience.com For simplicity, I will plot the variation of cost function against θ[0] which is biased of our estimator. This is based on the representation of our target variable y to be as follows; We can see that there are two local optima. This is unexpected and is caused by the behaviour of our sigmoid function. Therefore, the cost function is represented as follows which matches our expectations perfectly. This is a piece-wise function that has different definitions at different values of y. The idea is to penalize the wrong classification exponentially. For example, for label y=1 if the model predicts h(x)=0, we will have the first equation reaching infinity and vice versa. Now that we have a better loss function at hand, let us see how we can estimate the parameter vector θ for this dataset. Since we know the loss function, we need to compute the derivative of the loss function in order to update our gradients. It can be done as follows. This whole operation becomes extremely simple given the nature of the derivate of the sigmoid function. It will leave us with the following loss function. Note that this is the exact linear regression loss/cost function we discussed in the above article that I have cited. Since I have already implemented the algorithm, in this article let us use the python sklearn package’s logistic regressor. The usage is pretty straightforward. However, it is important that we understand the estimated parameters. The model fitting can be done as follows. Here X is a 2-dimensional vector and y is a binary vector. from sklearn.linear_model import LogisticRegressionclf = LogisticRegression(random_state=0).fit(X, y) Estimated parameters can be determined as follows. print(clf.coef_)print(clf.intercept_)>>> [[-3.36656909 0.12308678]]>>> [-0.13931403] Coefficients are the multipliers of the features. We represented them in our θ vector in indices 1 and 2. Intercept is the bias value of the model. Usage of the logistic regression after fitting can be done as follows. clf.predict_proba([[ 0.8780991 , 0.89551051]])>>> array([[0.95190421, 0.04809579]]) This is the prediction for each class. Note that the total probability is equal to one. The same can be achieved using the following implementation. h(theta, xi) is the hypothesis function using learned theta parameters. def h(theta, xi): return 1/(1 + np.exp(-1*np.dot(xi, theta))) Note that I have used np.dot() to obtain the matrix or vector multiplication which is far more efficient than using a forloop. This is also called vectorization. We can obtain our p(y=1) estimate using the following function call. h([-0.13931403, -3.36656909, 0.12308678], [1, 0.8780991 , 0.89551051]) Note that I have used our intercept value as the first element of theta parameter and the rest in order. I have prepended an additional 1 for the feature vector which corresponds to the learned bias. Finally, we can plot our boundary as follows. Logistic regression can easily be extended to predict more than 2 classes. However, you will have to build k classifiers to predict each of the k many classes and train them using i vs other k-1 classes for each class. Logistic regression is a fast machine learning techniqueMost of the implementations use faster optimizers apart from the simple gradient descent we discussedIt is always wise to check for the existence of a decision boundary. You might require a technique like PCA or t-SNE. Logistic regression is a fast machine learning technique Most of the implementations use faster optimizers apart from the simple gradient descent we discussed It is always wise to check for the existence of a decision boundary. You might require a technique like PCA or t-SNE. I hope you enjoyed reading this article on Logistic Regression. You can find the Jupyer notebook here. Some interesting reading for the curious;
[ { "code": null, "e": 481, "s": 172, "text": "The fundamental application of logistic regression is to determine a decision boundary for a binary classification problem. Although the baseline is to identify a binary decision boundary, the approach can be very well applied for scenarios with multiple classification classes or multi-class classification." }, { "code": null, "e": 1007, "s": 481, "text": "In the above diagram, the dashed line can be identified as the decision boundary since we will observe instances of a different class on each side of the boundary. Our intention in logistic regression would be to decide on a proper fit to the decision boundary so that we will be able to predict which class a new feature set might correspond to. The interesting fact about logistic regression is the utilization of the sigmoid function as the target class estimator. Let us have a look at the intuition behind this decision." }, { "code": null, "e": 1231, "s": 1007, "text": "The sigmoid function for parameter z can be represented as follows. Note that the function always lies in the range of 0 to 1, boundaries being asymptotic. This gives us a perfect output representation of probabilities too." }, { "code": null, "e": 1343, "s": 1231, "text": "Now that we know our sigmoid function lies between 0 and 1 we can represent the class probabilities as follows." }, { "code": null, "e": 1437, "s": 1343, "text": "Here θ stands for the estimated parameter vector and X is the vector of variables considered." }, { "code": null, "e": 1531, "s": 1437, "text": "X = X0, X1 ... Xn <- n Features and X0=1θ = θ0, θ1 ... θn <- Parameters to be estimated" }, { "code": null, "e": 1735, "s": 1531, "text": "Now that we are aware of a function estimate for our probabilities we shall come up with a way to estimate the parameters represented by θ vector. For this exercise let us consider the following example." }, { "code": null, "e": 1895, "s": 1735, "text": "We have a dataset with two features and two classes. Our objective is to discover the proper values of θ for the two features. This can be modelled as follows." }, { "code": null, "e": 1958, "s": 1895, "text": "h(θ) is the probability estimation or the hypothesis function." }, { "code": null, "e": 2123, "s": 1958, "text": "For a moment let’s assume that we can use the root mean squared error (RMS), similar to linear regression. You may refer to the following article for more insights." }, { "code": null, "e": 2146, "s": 2123, "text": "towardsdatascience.com" }, { "code": null, "e": 2331, "s": 2146, "text": "For simplicity, I will plot the variation of cost function against θ[0] which is biased of our estimator. This is based on the representation of our target variable y to be as follows;" }, { "code": null, "e": 2547, "s": 2331, "text": "We can see that there are two local optima. This is unexpected and is caused by the behaviour of our sigmoid function. Therefore, the cost function is represented as follows which matches our expectations perfectly." }, { "code": null, "e": 2821, "s": 2547, "text": "This is a piece-wise function that has different definitions at different values of y. The idea is to penalize the wrong classification exponentially. For example, for label y=1 if the model predicts h(x)=0, we will have the first equation reaching infinity and vice versa." }, { "code": null, "e": 2942, "s": 2821, "text": "Now that we have a better loss function at hand, let us see how we can estimate the parameter vector θ for this dataset." }, { "code": null, "e": 3246, "s": 2942, "text": "Since we know the loss function, we need to compute the derivative of the loss function in order to update our gradients. It can be done as follows. This whole operation becomes extremely simple given the nature of the derivate of the sigmoid function. It will leave us with the following loss function." }, { "code": null, "e": 3488, "s": 3246, "text": "Note that this is the exact linear regression loss/cost function we discussed in the above article that I have cited. Since I have already implemented the algorithm, in this article let us use the python sklearn package’s logistic regressor." }, { "code": null, "e": 3696, "s": 3488, "text": "The usage is pretty straightforward. However, it is important that we understand the estimated parameters. The model fitting can be done as follows. Here X is a 2-dimensional vector and y is a binary vector." }, { "code": null, "e": 3798, "s": 3696, "text": "from sklearn.linear_model import LogisticRegressionclf = LogisticRegression(random_state=0).fit(X, y)" }, { "code": null, "e": 3849, "s": 3798, "text": "Estimated parameters can be determined as follows." }, { "code": null, "e": 3935, "s": 3849, "text": "print(clf.coef_)print(clf.intercept_)>>> [[-3.36656909 0.12308678]]>>> [-0.13931403]" }, { "code": null, "e": 4083, "s": 3935, "text": "Coefficients are the multipliers of the features. We represented them in our θ vector in indices 1 and 2. Intercept is the bias value of the model." }, { "code": null, "e": 4154, "s": 4083, "text": "Usage of the logistic regression after fitting can be done as follows." }, { "code": null, "e": 4239, "s": 4154, "text": "clf.predict_proba([[ 0.8780991 , 0.89551051]])>>> array([[0.95190421, 0.04809579]])" }, { "code": null, "e": 4460, "s": 4239, "text": "This is the prediction for each class. Note that the total probability is equal to one. The same can be achieved using the following implementation. h(theta, xi) is the hypothesis function using learned theta parameters." }, { "code": null, "e": 4525, "s": 4460, "text": "def h(theta, xi): return 1/(1 + np.exp(-1*np.dot(xi, theta)))" }, { "code": null, "e": 4756, "s": 4525, "text": "Note that I have used np.dot() to obtain the matrix or vector multiplication which is far more efficient than using a forloop. This is also called vectorization. We can obtain our p(y=1) estimate using the following function call." }, { "code": null, "e": 4829, "s": 4756, "text": "h([-0.13931403, -3.36656909, 0.12308678], [1, 0.8780991 , 0.89551051])" }, { "code": null, "e": 5029, "s": 4829, "text": "Note that I have used our intercept value as the first element of theta parameter and the rest in order. I have prepended an additional 1 for the feature vector which corresponds to the learned bias." }, { "code": null, "e": 5075, "s": 5029, "text": "Finally, we can plot our boundary as follows." }, { "code": null, "e": 5294, "s": 5075, "text": "Logistic regression can easily be extended to predict more than 2 classes. However, you will have to build k classifiers to predict each of the k many classes and train them using i vs other k-1 classes for each class." }, { "code": null, "e": 5569, "s": 5294, "text": "Logistic regression is a fast machine learning techniqueMost of the implementations use faster optimizers apart from the simple gradient descent we discussedIt is always wise to check for the existence of a decision boundary. You might require a technique like PCA or t-SNE." }, { "code": null, "e": 5626, "s": 5569, "text": "Logistic regression is a fast machine learning technique" }, { "code": null, "e": 5728, "s": 5626, "text": "Most of the implementations use faster optimizers apart from the simple gradient descent we discussed" }, { "code": null, "e": 5846, "s": 5728, "text": "It is always wise to check for the existence of a decision boundary. You might require a technique like PCA or t-SNE." }, { "code": null, "e": 5949, "s": 5846, "text": "I hope you enjoyed reading this article on Logistic Regression. You can find the Jupyer notebook here." } ]
Minimum cost to convert string into palindrome - GeeksforGeeks
21 May, 2021 Convert string S into a palindrome string. You can only replace a character with any other character. When you replace character ‘a’ with any other character, it costs 1 unit, similarly for ‘b’ it is 2 units ..... and for ‘z’, it is 26 units. Find the minimum cost required to convert string S into palindrome string.Examples : Input : abcdef Output : 6 Explanation: replace 'a', 'b' and 'c' => cost= 1 + 2 + 3 = 6 Input : aba Output : 0 The idea is to start comparing from the two ends of string. Let i be initialized as 0 index and j initialized as length – 1. If characters at two indices are not same, a cost will apply. To make the cost minimum replace the character which is smaller. Then increment i by 1 and decrement j by 1. Iterate till i less than j. C++ Java Python3 C# PHP Javascript // CPP program to find minimum cost to make// a palindrome.#include <bits/stdc++.h>using namespace std; // Function to return costint cost(string str){ // length of string int len = str.length(); // Iterate from both sides of string. // If not equal, a cost will be there int res = 0; for (int i=0, j=len-1; i < j; i++, j--) if (str[i] != str[j]) res += min(str[i], str[j]) - 'a' + 1; return res;} // Driver codeint main(){ string str = "abcdef"; cout << cost(str) << endl; return 0;} // Java program to find minimum cost to make// a palindrome.import java.io.*; class GFG{ // Function to return cost static int cost(String str) { // length of string int len = str.length(); // Iterate from both sides of string. // If not equal, a cost will be there int res = 0; for (int i = 0, j = len - 1; i < j; i++, j--) if (str.charAt(i) != str.charAt(j)) res += Math.min(str.charAt(i), str.charAt(j)) - 'a' + 1; return res; } // Driver code public static void main (String[] args) { String str = "abcdef"; System.out.println(cost(str)); }} // This code is contributed by vt_m. # python program to find minimum# cost to make a palindrome. # Function to return costdef cost(st): # length of string l = len(st) # Iterate from both sides # of string. If not equal, # a cost will be there res = 0 j = l - 1 i = 0 while(i < j): if (st[i] != st[j]): res += (min(ord(st[i]), ord(st[j])) - ord('a') + 1) i = i + 1 j = j - 1 return res # Driver codest = "abcdef";print(cost(st)) # This code is contributed by# Sam007 // C# program to find minimum cost// to make a palindrome.using System; class GFG{ // Function to return cost static int cost(String str) { // length of string int len = str.Length; // Iterate from both sides of string. // If not equal, a cost will be there int res = 0; for (int i = 0, j = len - 1; i < j; i++, j--) if (str[i] != str[j]) res += Math.Min(str[i], str[j]) - 'a' + 1; return res; } // Driver code public static void Main () { string str = "abcdef"; Console.WriteLine(cost(str)); }} // This code is contributed by vt_m. <?php// PHP program to find minimum// cost to make a palindrome. // Function to return costfunction cost($str){ // length of string $len = strlen($str); // Iterate from both sides // of string. If not equal, // a cost will be there $res = 0; for ($i = 0, $j = $len - 1; $i < $j; $i++, $j--) if ($str[$i] != $str[$j]) $res += (min(ord($str[$i]), ord($str[$j])) - ord('a') + 1 ); return $res;} // Driver code$str = "abcdef";echo cost($str); // This code is contributed by Sam007?> <script> // Javascript program to find minimum cost // to make a palindrome. // Function to return cost function cost(str) { // length of string let len = str.length; // Iterate from both sides of string. // If not equal, a cost will be there let res = 0; for (let i = 0, j = len - 1; i < j; i++, j--) { if (str[i] != str[j]) { res += Math.min(str[i].charCodeAt(), str[j].charCodeAt()) - 'a'.charCodeAt() + 1; } } return res; } let str = "abcdef"; document.write(cost(str)); </script> Output : 6 vt_m Sam007 divyesh072019 palindrome Strings Strings palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python program to check if a string is palindrome or not Check for Balanced Brackets in an expression (well-formedness) using Stack Different methods to reverse a string in C/C++ KMP Algorithm for Pattern Searching Convert string to char array in C++ Array of Strings in C++ (5 Different Ways to Create) Reverse words in a given string Caesar Cipher in Cryptography Length of the longest substring without repeating characters Check whether two strings are anagram of each other
[ { "code": null, "e": 24471, "s": 24443, "text": "\n21 May, 2021" }, { "code": null, "e": 24801, "s": 24471, "text": "Convert string S into a palindrome string. You can only replace a character with any other character. When you replace character ‘a’ with any other character, it costs 1 unit, similarly for ‘b’ it is 2 units ..... and for ‘z’, it is 26 units. Find the minimum cost required to convert string S into palindrome string.Examples : " }, { "code": null, "e": 24914, "s": 24801, "text": "Input : abcdef\nOutput : 6\nExplanation: replace 'a', 'b' and \n'c' => cost= 1 + 2 + 3 = 6 \n\nInput : aba\nOutput : 0" }, { "code": null, "e": 25242, "s": 24916, "text": "The idea is to start comparing from the two ends of string. Let i be initialized as 0 index and j initialized as length – 1. If characters at two indices are not same, a cost will apply. To make the cost minimum replace the character which is smaller. Then increment i by 1 and decrement j by 1. Iterate till i less than j. " }, { "code": null, "e": 25246, "s": 25242, "text": "C++" }, { "code": null, "e": 25251, "s": 25246, "text": "Java" }, { "code": null, "e": 25259, "s": 25251, "text": "Python3" }, { "code": null, "e": 25262, "s": 25259, "text": "C#" }, { "code": null, "e": 25266, "s": 25262, "text": "PHP" }, { "code": null, "e": 25277, "s": 25266, "text": "Javascript" }, { "code": "// CPP program to find minimum cost to make// a palindrome.#include <bits/stdc++.h>using namespace std; // Function to return costint cost(string str){ // length of string int len = str.length(); // Iterate from both sides of string. // If not equal, a cost will be there int res = 0; for (int i=0, j=len-1; i < j; i++, j--) if (str[i] != str[j]) res += min(str[i], str[j]) - 'a' + 1; return res;} // Driver codeint main(){ string str = \"abcdef\"; cout << cost(str) << endl; return 0;}", "e": 25841, "s": 25277, "text": null }, { "code": "// Java program to find minimum cost to make// a palindrome.import java.io.*; class GFG{ // Function to return cost static int cost(String str) { // length of string int len = str.length(); // Iterate from both sides of string. // If not equal, a cost will be there int res = 0; for (int i = 0, j = len - 1; i < j; i++, j--) if (str.charAt(i) != str.charAt(j)) res += Math.min(str.charAt(i), str.charAt(j)) - 'a' + 1; return res; } // Driver code public static void main (String[] args) { String str = \"abcdef\"; System.out.println(cost(str)); }} // This code is contributed by vt_m.", "e": 26599, "s": 25841, "text": null }, { "code": "# python program to find minimum# cost to make a palindrome. # Function to return costdef cost(st): # length of string l = len(st) # Iterate from both sides # of string. If not equal, # a cost will be there res = 0 j = l - 1 i = 0 while(i < j): if (st[i] != st[j]): res += (min(ord(st[i]), ord(st[j])) - ord('a') + 1) i = i + 1 j = j - 1 return res # Driver codest = \"abcdef\";print(cost(st)) # This code is contributed by# Sam007", "e": 27174, "s": 26599, "text": null }, { "code": "// C# program to find minimum cost// to make a palindrome.using System; class GFG{ // Function to return cost static int cost(String str) { // length of string int len = str.Length; // Iterate from both sides of string. // If not equal, a cost will be there int res = 0; for (int i = 0, j = len - 1; i < j; i++, j--) if (str[i] != str[j]) res += Math.Min(str[i], str[j]) - 'a' + 1; return res; } // Driver code public static void Main () { string str = \"abcdef\"; Console.WriteLine(cost(str)); }} // This code is contributed by vt_m.", "e": 27883, "s": 27174, "text": null }, { "code": "<?php// PHP program to find minimum// cost to make a palindrome. // Function to return costfunction cost($str){ // length of string $len = strlen($str); // Iterate from both sides // of string. If not equal, // a cost will be there $res = 0; for ($i = 0, $j = $len - 1; $i < $j; $i++, $j--) if ($str[$i] != $str[$j]) $res += (min(ord($str[$i]), ord($str[$j])) - ord('a') + 1 ); return $res;} // Driver code$str = \"abcdef\";echo cost($str); // This code is contributed by Sam007?>", "e": 28489, "s": 27883, "text": null }, { "code": "<script> // Javascript program to find minimum cost // to make a palindrome. // Function to return cost function cost(str) { // length of string let len = str.length; // Iterate from both sides of string. // If not equal, a cost will be there let res = 0; for (let i = 0, j = len - 1; i < j; i++, j--) { if (str[i] != str[j]) { res += Math.min(str[i].charCodeAt(), str[j].charCodeAt()) - 'a'.charCodeAt() + 1; } } return res; } let str = \"abcdef\"; document.write(cost(str)); </script>", "e": 29156, "s": 28489, "text": null }, { "code": null, "e": 29167, "s": 29156, "text": "Output : " }, { "code": null, "e": 29169, "s": 29167, "text": "6" }, { "code": null, "e": 29176, "s": 29171, "text": "vt_m" }, { "code": null, "e": 29183, "s": 29176, "text": "Sam007" }, { "code": null, "e": 29197, "s": 29183, "text": "divyesh072019" }, { "code": null, "e": 29208, "s": 29197, "text": "palindrome" }, { "code": null, "e": 29216, "s": 29208, "text": "Strings" }, { "code": null, "e": 29224, "s": 29216, "text": "Strings" }, { "code": null, "e": 29235, "s": 29224, "text": "palindrome" }, { "code": null, "e": 29333, "s": 29235, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29342, "s": 29333, "text": "Comments" }, { "code": null, "e": 29355, "s": 29342, "text": "Old Comments" }, { "code": null, "e": 29412, "s": 29355, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 29487, "s": 29412, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 29534, "s": 29487, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 29570, "s": 29534, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 29606, "s": 29570, "text": "Convert string to char array in C++" }, { "code": null, "e": 29659, "s": 29606, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 29691, "s": 29659, "text": "Reverse words in a given string" }, { "code": null, "e": 29721, "s": 29691, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 29782, "s": 29721, "text": "Length of the longest substring without repeating characters" } ]
How to scrape any website with Python and Beautiful Soup (dynamic web) | by Patrick Collins | Towards Data Science
Note: This is a purely technical tutorial. Please check with the policies of the website before engaging in any scraping. In the example I use, it’s not legal to scrape the site: https://gitcoin.co//legal/terms. Please do not use. For those who want to see it done in front of your eyes, check out my YouTube video at the bottom of the page. Now if you didn’t read my part one, go back and read it! This is building on the concepts learnt there. And remember, the documentation for this is very strong, so be sure to check it out after this tutorial! We are now going to learn how to deal with dynamic web pages or web pages that have a lot going on and are more than just HTML/CSS. These pages are tricker to scrape with beautifulsoup, because sometimes, code happens on the server side, and beautifulsoup needs to let a browser run it. Wouldn’t it be nice if there was a way for us to code and have our code pretend it was a browser?... Well it just so happens that’s exactly what this article is about! Now, I first read about this in this article, and I’ve kept this article more focused on the exact implementation, so for more details, be sure to check it out! These are the only two I know of at the moment that have this functionality, so be sure to use one of them. For this article, we are using Firefox. The web driver we will be using is geckodriver, and you can find all the downloads at the bottom of that link. After you download it, extract the file from your downloads (just double click the zip file). Web drivers are a little finicky, and don’t play so well with operating systems, so we need to:Move geckodriver to where a path executable is. Please check this article for how to do it with windows. We can find out where our executable path is by running: echo $PATH And then we can either: cp the geckodriver file from the zip into one of the locations your $PATH variable tells you (after running echo $PATH)Add a new $PATH location to your $PATH environment variable, and put the executable geckodriver in there. You can see how to do this here. cp the geckodriver file from the zip into one of the locations your $PATH variable tells you (after running echo $PATH) Add a new $PATH location to your $PATH environment variable, and put the executable geckodriver in there. You can see how to do this here. Then restart your terminal for the changes to take affect. You may also need to notarize the application if you’re using MacOS (which I am). You can do that by running: xattr -r -d com.apple.quarantine geckodriver After running:pip install selenium , you can now start using the web driver! Instead of pulling the dynamic web page URL with requests.get you’ll pull it with driver.get , like this: from selenium import webdriverfrom selenium.webdriver.firefox.options import Optionsfrom bs4 import BeautifulSoupoptions = Options()# Make it go faster by running headless# This will remove the web browser GUI from popping upoptions.headless = Truedriver = webdriver.Firefox(options=options)# Enter whatever URL you likedriver.get("https://gitcoin.co/{}".format(link.attrs['href']))# Let the code on their end runtime.sleep(20)# Save it to a variablehtml = driver.page_sourcedriver.quit()# And then just paste it right back into beautifulsoup!projects_soup = BeautifulSoup(html, 'lxml') You can see a full code example located at the Alpha Chain demos repo, a full scale example at my hackathon-scraper project, and a video that shows you how to do it all right here. And remember, you can always fast forward :)
[ { "code": null, "e": 402, "s": 171, "text": "Note: This is a purely technical tutorial. Please check with the policies of the website before engaging in any scraping. In the example I use, it’s not legal to scrape the site: https://gitcoin.co//legal/terms. Please do not use." }, { "code": null, "e": 513, "s": 402, "text": "For those who want to see it done in front of your eyes, check out my YouTube video at the bottom of the page." }, { "code": null, "e": 722, "s": 513, "text": "Now if you didn’t read my part one, go back and read it! This is building on the concepts learnt there. And remember, the documentation for this is very strong, so be sure to check it out after this tutorial!" }, { "code": null, "e": 1009, "s": 722, "text": "We are now going to learn how to deal with dynamic web pages or web pages that have a lot going on and are more than just HTML/CSS. These pages are tricker to scrape with beautifulsoup, because sometimes, code happens on the server side, and beautifulsoup needs to let a browser run it." }, { "code": null, "e": 1177, "s": 1009, "text": "Wouldn’t it be nice if there was a way for us to code and have our code pretend it was a browser?... Well it just so happens that’s exactly what this article is about!" }, { "code": null, "e": 1338, "s": 1177, "text": "Now, I first read about this in this article, and I’ve kept this article more focused on the exact implementation, so for more details, be sure to check it out!" }, { "code": null, "e": 1486, "s": 1338, "text": "These are the only two I know of at the moment that have this functionality, so be sure to use one of them. For this article, we are using Firefox." }, { "code": null, "e": 1691, "s": 1486, "text": "The web driver we will be using is geckodriver, and you can find all the downloads at the bottom of that link. After you download it, extract the file from your downloads (just double click the zip file)." }, { "code": null, "e": 1891, "s": 1691, "text": "Web drivers are a little finicky, and don’t play so well with operating systems, so we need to:Move geckodriver to where a path executable is. Please check this article for how to do it with windows." }, { "code": null, "e": 1948, "s": 1891, "text": "We can find out where our executable path is by running:" }, { "code": null, "e": 1959, "s": 1948, "text": "echo $PATH" }, { "code": null, "e": 1983, "s": 1959, "text": "And then we can either:" }, { "code": null, "e": 2241, "s": 1983, "text": "cp the geckodriver file from the zip into one of the locations your $PATH variable tells you (after running echo $PATH)Add a new $PATH location to your $PATH environment variable, and put the executable geckodriver in there. You can see how to do this here." }, { "code": null, "e": 2361, "s": 2241, "text": "cp the geckodriver file from the zip into one of the locations your $PATH variable tells you (after running echo $PATH)" }, { "code": null, "e": 2500, "s": 2361, "text": "Add a new $PATH location to your $PATH environment variable, and put the executable geckodriver in there. You can see how to do this here." }, { "code": null, "e": 2669, "s": 2500, "text": "Then restart your terminal for the changes to take affect. You may also need to notarize the application if you’re using MacOS (which I am). You can do that by running:" }, { "code": null, "e": 2714, "s": 2669, "text": "xattr -r -d com.apple.quarantine geckodriver" }, { "code": null, "e": 2897, "s": 2714, "text": "After running:pip install selenium , you can now start using the web driver! Instead of pulling the dynamic web page URL with requests.get you’ll pull it with driver.get , like this:" }, { "code": null, "e": 3484, "s": 2897, "text": "from selenium import webdriverfrom selenium.webdriver.firefox.options import Optionsfrom bs4 import BeautifulSoupoptions = Options()# Make it go faster by running headless# This will remove the web browser GUI from popping upoptions.headless = Truedriver = webdriver.Firefox(options=options)# Enter whatever URL you likedriver.get(\"https://gitcoin.co/{}\".format(link.attrs['href']))# Let the code on their end runtime.sleep(20)# Save it to a variablehtml = driver.page_sourcedriver.quit()# And then just paste it right back into beautifulsoup!projects_soup = BeautifulSoup(html, 'lxml')" }, { "code": null, "e": 3665, "s": 3484, "text": "You can see a full code example located at the Alpha Chain demos repo, a full scale example at my hackathon-scraper project, and a video that shows you how to do it all right here." } ]
JSON - DataTypes
JSON format supports the following data types − Number double- precision floating-point format in JavaScript String double-quoted Unicode with backslash escaping Boolean true or false Array an ordered sequence of values Value it can be a string, a number, true or false, null etc Object an unordered collection of key:value pairs Whitespace can be used between any pair of tokens null empty It is a double precision floating-point format in JavaScript and it depends on implementation. It is a double precision floating-point format in JavaScript and it depends on implementation. Octal and hexadecimal formats are not used. Octal and hexadecimal formats are not used. No NaN or Infinity is used in Number. No NaN or Infinity is used in Number. The following table shows the number types − Integer Digits 1-9, 0 and positive or negative Fraction Fractions like .3, .9 Exponent Exponent like e, e+, e-, E, E+, E- var json-object-name = { string : number_value, .......} Example showing Number Datatype, value should not be quoted − var obj = {marks: 97} It is a sequence of zero or more double quoted Unicode characters with backslash escaping. It is a sequence of zero or more double quoted Unicode characters with backslash escaping. Character is a single character string i.e. a string with length 1. Character is a single character string i.e. a string with length 1. The table shows various special characters that you can use in strings of a JSON document − " double quotation \ backslash / forward slash b backspace f form feed n new line r carriage return t horizontal tab u four hexadecimal digits var json-object-name = { string : "string value", .......} Example showing String Datatype − var obj = {name: 'Amit'} It includes true or false values. var json-object-name = { string : true/false, .......} var obj = {name: 'Amit', marks: 97, distinction: true} It is an ordered collection of values. It is an ordered collection of values. These are enclosed in square brackets which means that array begins with .[. and ends with .].. These are enclosed in square brackets which means that array begins with .[. and ends with .].. The values are separated by , (comma). The values are separated by , (comma). Array indexing can be started at 0 or 1. Array indexing can be started at 0 or 1. Arrays should be used when the key names are sequential integers. Arrays should be used when the key names are sequential integers. [ value, .......] Example showing array containing multiple objects − { "books": [ { "language":"Java" , "edition":"second" }, { "language":"C++" , "lastName":"fifth" }, { "language":"C" , "lastName":"third" } ] } It is an unordered set of name/value pairs. It is an unordered set of name/value pairs. Objects are enclosed in curly braces that is, it starts with '{' and ends with '}'. Objects are enclosed in curly braces that is, it starts with '{' and ends with '}'. Each name is followed by ':'(colon) and the key/value pairs are separated by , (comma). Each name is followed by ':'(colon) and the key/value pairs are separated by , (comma). The keys must be strings and should be different from each other. The keys must be strings and should be different from each other. Objects should be used when the key names are arbitrary strings. Objects should be used when the key names are arbitrary strings. { string : value, .......} Example showing Object − { "id": "011A", "language": "JAVA", "price": 500, } It can be inserted between any pair of tokens. It can be added to make a code more readable. Example shows declaration with and without whitespace − {string:" ",....} var obj1 = {"name": "Sachin Tendulkar"} var obj2 = {"name": "SauravGanguly"} It means empty type. null var i = null; if(i == 1) { document.write("<h1>value is 1</h1>"); } else { document.write("<h1>value is null</h1>"); } It includes − number (integer or floating point) string boolean array object null String | Number | Object | Array | TRUE | FALSE | NULL var i = 1; var j = "sachin"; var k = null; 20 Lectures 1 hours Laurence Svekis 16 Lectures 1 hours Laurence Svekis 10 Lectures 1 hours Laurence Svekis 23 Lectures 2.5 hours Laurence Svekis 9 Lectures 48 mins Nilay Mehta 18 Lectures 2.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 1828, "s": 1780, "text": "JSON format supports the following data types −" }, { "code": null, "e": 1835, "s": 1828, "text": "Number" }, { "code": null, "e": 1889, "s": 1835, "text": "double- precision floating-point format in JavaScript" }, { "code": null, "e": 1896, "s": 1889, "text": "String" }, { "code": null, "e": 1942, "s": 1896, "text": "double-quoted Unicode with backslash escaping" }, { "code": null, "e": 1950, "s": 1942, "text": "Boolean" }, { "code": null, "e": 1964, "s": 1950, "text": "true or false" }, { "code": null, "e": 1970, "s": 1964, "text": "Array" }, { "code": null, "e": 2000, "s": 1970, "text": "an ordered sequence of values" }, { "code": null, "e": 2006, "s": 2000, "text": "Value" }, { "code": null, "e": 2060, "s": 2006, "text": "it can be a string, a number, true or false, null etc" }, { "code": null, "e": 2067, "s": 2060, "text": "Object" }, { "code": null, "e": 2110, "s": 2067, "text": "an unordered collection of key:value pairs" }, { "code": null, "e": 2121, "s": 2110, "text": "Whitespace" }, { "code": null, "e": 2160, "s": 2121, "text": "can be used between any pair of tokens" }, { "code": null, "e": 2165, "s": 2160, "text": "null" }, { "code": null, "e": 2171, "s": 2165, "text": "empty" }, { "code": null, "e": 2266, "s": 2171, "text": "It is a double precision floating-point format in JavaScript and it depends on implementation." }, { "code": null, "e": 2361, "s": 2266, "text": "It is a double precision floating-point format in JavaScript and it depends on implementation." }, { "code": null, "e": 2405, "s": 2361, "text": "Octal and hexadecimal formats are not used." }, { "code": null, "e": 2449, "s": 2405, "text": "Octal and hexadecimal formats are not used." }, { "code": null, "e": 2487, "s": 2449, "text": "No NaN or Infinity is used in Number." }, { "code": null, "e": 2525, "s": 2487, "text": "No NaN or Infinity is used in Number." }, { "code": null, "e": 2570, "s": 2525, "text": "The following table shows the number types −" }, { "code": null, "e": 2578, "s": 2570, "text": "Integer" }, { "code": null, "e": 2617, "s": 2578, "text": "Digits 1-9, 0 and positive or negative" }, { "code": null, "e": 2626, "s": 2617, "text": "Fraction" }, { "code": null, "e": 2648, "s": 2626, "text": "Fractions like .3, .9" }, { "code": null, "e": 2657, "s": 2648, "text": "Exponent" }, { "code": null, "e": 2692, "s": 2657, "text": "Exponent like e, e+, e-, E, E+, E-" }, { "code": null, "e": 2750, "s": 2692, "text": "var json-object-name = { string : number_value, .......}\n" }, { "code": null, "e": 2812, "s": 2750, "text": "Example showing Number Datatype, value should not be quoted −" }, { "code": null, "e": 2834, "s": 2812, "text": "var obj = {marks: 97}" }, { "code": null, "e": 2925, "s": 2834, "text": "It is a sequence of zero or more double quoted Unicode characters with backslash escaping." }, { "code": null, "e": 3016, "s": 2925, "text": "It is a sequence of zero or more double quoted Unicode characters with backslash escaping." }, { "code": null, "e": 3084, "s": 3016, "text": "Character is a single character string i.e. a string with length 1." }, { "code": null, "e": 3152, "s": 3084, "text": "Character is a single character string i.e. a string with length 1." }, { "code": null, "e": 3244, "s": 3152, "text": "The table shows various special characters that you can use in strings of a JSON document −" }, { "code": null, "e": 3246, "s": 3244, "text": "\"" }, { "code": null, "e": 3263, "s": 3246, "text": "double quotation" }, { "code": null, "e": 3265, "s": 3263, "text": "\\" }, { "code": null, "e": 3275, "s": 3265, "text": "backslash" }, { "code": null, "e": 3277, "s": 3275, "text": "/" }, { "code": null, "e": 3291, "s": 3277, "text": "forward slash" }, { "code": null, "e": 3293, "s": 3291, "text": "b" }, { "code": null, "e": 3303, "s": 3293, "text": "backspace" }, { "code": null, "e": 3305, "s": 3303, "text": "f" }, { "code": null, "e": 3315, "s": 3305, "text": "form feed" }, { "code": null, "e": 3317, "s": 3315, "text": "n" }, { "code": null, "e": 3326, "s": 3317, "text": "new line" }, { "code": null, "e": 3328, "s": 3326, "text": "r" }, { "code": null, "e": 3344, "s": 3328, "text": "carriage return" }, { "code": null, "e": 3346, "s": 3344, "text": "t" }, { "code": null, "e": 3361, "s": 3346, "text": "horizontal tab" }, { "code": null, "e": 3363, "s": 3361, "text": "u" }, { "code": null, "e": 3387, "s": 3363, "text": "four hexadecimal digits" }, { "code": null, "e": 3447, "s": 3387, "text": "var json-object-name = { string : \"string value\", .......}\n" }, { "code": null, "e": 3481, "s": 3447, "text": "Example showing String Datatype −" }, { "code": null, "e": 3506, "s": 3481, "text": "var obj = {name: 'Amit'}" }, { "code": null, "e": 3540, "s": 3506, "text": "It includes true or false values." }, { "code": null, "e": 3596, "s": 3540, "text": "var json-object-name = { string : true/false, .......}\n" }, { "code": null, "e": 3651, "s": 3596, "text": "var obj = {name: 'Amit', marks: 97, distinction: true}" }, { "code": null, "e": 3690, "s": 3651, "text": "It is an ordered collection of values." }, { "code": null, "e": 3729, "s": 3690, "text": "It is an ordered collection of values." }, { "code": null, "e": 3825, "s": 3729, "text": "These are enclosed in square brackets which means that array begins with .[. and ends with .].." }, { "code": null, "e": 3921, "s": 3825, "text": "These are enclosed in square brackets which means that array begins with .[. and ends with .].." }, { "code": null, "e": 3960, "s": 3921, "text": "The values are separated by , (comma)." }, { "code": null, "e": 3999, "s": 3960, "text": "The values are separated by , (comma)." }, { "code": null, "e": 4040, "s": 3999, "text": "Array indexing can be started at 0 or 1." }, { "code": null, "e": 4081, "s": 4040, "text": "Array indexing can be started at 0 or 1." }, { "code": null, "e": 4147, "s": 4081, "text": "Arrays should be used when the key names are sequential integers." }, { "code": null, "e": 4213, "s": 4147, "text": "Arrays should be used when the key names are sequential integers." }, { "code": null, "e": 4232, "s": 4213, "text": "[ value, .......]\n" }, { "code": null, "e": 4284, "s": 4232, "text": "Example showing array containing multiple objects −" }, { "code": null, "e": 4452, "s": 4284, "text": "{\n \"books\": [\n { \"language\":\"Java\" , \"edition\":\"second\" },\n { \"language\":\"C++\" , \"lastName\":\"fifth\" },\n { \"language\":\"C\" , \"lastName\":\"third\" }\n ]\n}" }, { "code": null, "e": 4496, "s": 4452, "text": "It is an unordered set of name/value pairs." }, { "code": null, "e": 4540, "s": 4496, "text": "It is an unordered set of name/value pairs." }, { "code": null, "e": 4624, "s": 4540, "text": "Objects are enclosed in curly braces that is, it starts with '{' and ends with '}'." }, { "code": null, "e": 4708, "s": 4624, "text": "Objects are enclosed in curly braces that is, it starts with '{' and ends with '}'." }, { "code": null, "e": 4796, "s": 4708, "text": "Each name is followed by ':'(colon) and the key/value pairs are separated by , (comma)." }, { "code": null, "e": 4884, "s": 4796, "text": "Each name is followed by ':'(colon) and the key/value pairs are separated by , (comma)." }, { "code": null, "e": 4950, "s": 4884, "text": "The keys must be strings and should be different from each other." }, { "code": null, "e": 5016, "s": 4950, "text": "The keys must be strings and should be different from each other." }, { "code": null, "e": 5081, "s": 5016, "text": "Objects should be used when the key names are arbitrary strings." }, { "code": null, "e": 5146, "s": 5081, "text": "Objects should be used when the key names are arbitrary strings." }, { "code": null, "e": 5174, "s": 5146, "text": "{ string : value, .......}\n" }, { "code": null, "e": 5199, "s": 5174, "text": "Example showing Object −" }, { "code": null, "e": 5260, "s": 5199, "text": "{\n \"id\": \"011A\",\n \"language\": \"JAVA\",\n \"price\": 500,\n}" }, { "code": null, "e": 5409, "s": 5260, "text": "It can be inserted between any pair of tokens. It can be added to make a code more readable. Example shows declaration with and without whitespace −" }, { "code": null, "e": 5428, "s": 5409, "text": "{string:\" \",....}\n" }, { "code": null, "e": 5505, "s": 5428, "text": "var obj1 = {\"name\": \"Sachin Tendulkar\"}\nvar obj2 = {\"name\": \"SauravGanguly\"}" }, { "code": null, "e": 5526, "s": 5505, "text": "It means empty type." }, { "code": null, "e": 5532, "s": 5526, "text": "null\n" }, { "code": null, "e": 5658, "s": 5532, "text": "var i = null;\n\nif(i == 1) {\n document.write(\"<h1>value is 1</h1>\");\n} else {\n document.write(\"<h1>value is null</h1>\");\n}" }, { "code": null, "e": 5672, "s": 5658, "text": "It includes −" }, { "code": null, "e": 5707, "s": 5672, "text": "number (integer or floating point)" }, { "code": null, "e": 5714, "s": 5707, "text": "string" }, { "code": null, "e": 5722, "s": 5714, "text": "boolean" }, { "code": null, "e": 5728, "s": 5722, "text": "array" }, { "code": null, "e": 5735, "s": 5728, "text": "object" }, { "code": null, "e": 5740, "s": 5735, "text": "null" }, { "code": null, "e": 5796, "s": 5740, "text": "String | Number | Object | Array | TRUE | FALSE | NULL\n" }, { "code": null, "e": 5839, "s": 5796, "text": "var i = 1;\nvar j = \"sachin\";\nvar k = null;" }, { "code": null, "e": 5872, "s": 5839, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 5889, "s": 5872, "text": " Laurence Svekis" }, { "code": null, "e": 5922, "s": 5889, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 5939, "s": 5922, "text": " Laurence Svekis" }, { "code": null, "e": 5972, "s": 5939, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 5989, "s": 5972, "text": " Laurence Svekis" }, { "code": null, "e": 6024, "s": 5989, "text": "\n 23 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6041, "s": 6024, "text": " Laurence Svekis" }, { "code": null, "e": 6072, "s": 6041, "text": "\n 9 Lectures \n 48 mins\n" }, { "code": null, "e": 6085, "s": 6072, "text": " Nilay Mehta" }, { "code": null, "e": 6120, "s": 6085, "text": "\n 18 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6143, "s": 6120, "text": " Stone River ELearning" }, { "code": null, "e": 6150, "s": 6143, "text": " Print" }, { "code": null, "e": 6161, "s": 6150, "text": " Add Notes" } ]
NLG for Fun — Automated Headlines Generator | by AbdulMajedRaja RS | Towards Data Science
Natural Language Generation is a very important area to be explored in our time. It forms the basis of how a bot would communicate with — not like how literates write books but like how we talk. In this Kernel, I’d like to show you a very simple but powerful Python module that does a similar exercise in (literally) a couple of lines of code. Module: Markovify The Py module we use here is markovify. Descrption of Markovify: Markovify is a simple, extensible Markov chain generator. Right now, its main use is for building Markov models of large corpora of text, and generating random sentences from that. But, in theory, it could be used for other applications. About the Dataset: This includes the entire corpus of articles published by the ABC website in the given time range. With a volume of 200 articles per day and a good focus on international news, we can be fairly certain that every event of significance has been captured here. This dataset can be downloaded from Kaggle Datasets. Markov chains, named after Andrey Markov, are mathematical systems that hop from one “state” (a situation or set of values) to another. For example, if you made a Markov chain model of a baby’s behavior, you might include “playing,” “eating”, “sleeping,” and “crying” as states, which together with other behaviors could form a ‘state space’: a list of all possible states. In addition, on top of the state space, a Markov chain tells you the probabilitiy of hopping, or “transitioning,” from one state to any other state — -e.g., the chance that a baby currently playing will fall asleep in the next five minutes without crying first. Read more about how Markov Chain works in this interactive article by Victor Powell import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)import markovify #Markov Chain Generator# Any results you write to the current directory are saved as output. inp = pd.read_csv('../input/abcnews-date-text.csv')inp.head(3)publish_date headline_text020030219 aba decides against community broadcasting lic...120030219 act fire witnesses must be aware of defamation220030219a g calls for infrastructure protection summit text_model = markovify.NewlineText(inp.headline_text, state_size = 2) # Print five randomly-generated sentencesfor i in range(5): print(text_model.make_sentence())iron magnate poised to storm cleanupmeet the png government defends stockdale appointmentthe twitter exec charged with animal cruelty trialpm denies role in pregnancyshoalhaven business boosts hunter Now, this text could become input for a Twitter Bot, Slack Bot or even a Parody Blog. And that’s the point. References: Github RepoKaggle KernelMarkov Chains explained VisuallyInput Dataset Github Repo Kaggle Kernel Markov Chains explained Visually
[ { "code": null, "e": 515, "s": 171, "text": "Natural Language Generation is a very important area to be explored in our time. It forms the basis of how a bot would communicate with — not like how literates write books but like how we talk. In this Kernel, I’d like to show you a very simple but powerful Python module that does a similar exercise in (literally) a couple of lines of code." }, { "code": null, "e": 533, "s": 515, "text": "Module: Markovify" }, { "code": null, "e": 573, "s": 533, "text": "The Py module we use here is markovify." }, { "code": null, "e": 598, "s": 573, "text": "Descrption of Markovify:" }, { "code": null, "e": 836, "s": 598, "text": "Markovify is a simple, extensible Markov chain generator. Right now, its main use is for building Markov models of large corpora of text, and generating random sentences from that. But, in theory, it could be used for other applications." }, { "code": null, "e": 855, "s": 836, "text": "About the Dataset:" }, { "code": null, "e": 1166, "s": 855, "text": "This includes the entire corpus of articles published by the ABC website in the given time range. With a volume of 200 articles per day and a good focus on international news, we can be fairly certain that every event of significance has been captured here. This dataset can be downloaded from Kaggle Datasets." }, { "code": null, "e": 1802, "s": 1166, "text": "Markov chains, named after Andrey Markov, are mathematical systems that hop from one “state” (a situation or set of values) to another. For example, if you made a Markov chain model of a baby’s behavior, you might include “playing,” “eating”, “sleeping,” and “crying” as states, which together with other behaviors could form a ‘state space’: a list of all possible states. In addition, on top of the state space, a Markov chain tells you the probabilitiy of hopping, or “transitioning,” from one state to any other state — -e.g., the chance that a baby currently playing will fall asleep in the next five minutes without crying first." }, { "code": null, "e": 1886, "s": 1802, "text": "Read more about how Markov Chain works in this interactive article by Victor Powell" }, { "code": null, "e": 2066, "s": 1886, "text": "import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)import markovify #Markov Chain Generator# Any results you write to the current directory are saved as output." }, { "code": null, "e": 2325, "s": 2066, "text": "inp = pd.read_csv('../input/abcnews-date-text.csv')inp.head(3)publish_date headline_text020030219 aba decides against community broadcasting lic...120030219 act fire witnesses must be aware of defamation220030219a g calls for infrastructure protection summit" }, { "code": null, "e": 2395, "s": 2325, "text": "text_model = markovify.NewlineText(inp.headline_text, state_size = 2)" }, { "code": null, "e": 2691, "s": 2395, "text": "# Print five randomly-generated sentencesfor i in range(5): print(text_model.make_sentence())iron magnate poised to storm cleanupmeet the png government defends stockdale appointmentthe twitter exec charged with animal cruelty trialpm denies role in pregnancyshoalhaven business boosts hunter" }, { "code": null, "e": 2799, "s": 2691, "text": "Now, this text could become input for a Twitter Bot, Slack Bot or even a Parody Blog. And that’s the point." }, { "code": null, "e": 2811, "s": 2799, "text": "References:" }, { "code": null, "e": 2881, "s": 2811, "text": "Github RepoKaggle KernelMarkov Chains explained VisuallyInput Dataset" }, { "code": null, "e": 2893, "s": 2881, "text": "Github Repo" }, { "code": null, "e": 2907, "s": 2893, "text": "Kaggle Kernel" } ]
JavaScript program to retrieve clients IP address
Following is the code for retrieving clients IP address − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-weight: 500; font-size: 18px; color: blueviolet; } </style> </head> <body> <h1>Retrieve clients IP address</h1> <div class="result"></div> <script type="application/javascript"> let resEle = document.querySelector(".result"); function showIP(json) { resEle.innerHTML = "My public IP address is: " + json.ip; } </script> <script type="application/javascript" src="http://ipinfo.io/?format=jsonp&callback=showIP"></script> </body> </html>
[ { "code": null, "e": 1120, "s": 1062, "text": "Following is the code for retrieving clients IP address −" }, { "code": null, "e": 1131, "s": 1120, "text": " Live Demo" }, { "code": null, "e": 1875, "s": 1131, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-weight: 500;\n font-size: 18px;\n color: blueviolet;\n }\n</style>\n</head>\n<body>\n<h1>Retrieve clients IP address</h1>\n<div class=\"result\"></div>\n<script type=\"application/javascript\">\n let resEle = document.querySelector(\".result\");\n function showIP(json) {\n resEle.innerHTML = \"My public IP address is: \" + json.ip;\n }\n</script>\n<script type=\"application/javascript\" src=\"http://ipinfo.io/?format=jsonp&callback=showIP\"></script>\n</body>\n</html>" } ]
Kotlin Tail Recursion - GeeksforGeeks
28 Mar, 2022 In traditional recursion call, we perform our recursive call first, and then we take the return value of the recursive call and calculate the result. But in tail recursion, we perform the calculation first, and then we execute the recursive call, passing the results of the current step to the next recursive call. In the end, both recursion and tail recursion gives same output. The must follow rule for the tail recursion is that recursive call should be the last call of the method. In tail recursion, function call is the last thing executed by the function and nothing left in the current function to execute. So, there is no need to save current function call in stack memory and compiler can re-use that stack space for next recursive call.In tail recursion, we do not get the StackOverflowError during the execution of program. In tail recursion, function call is the last thing executed by the function and nothing left in the current function to execute. So, there is no need to save current function call in stack memory and compiler can re-use that stack space for next recursive call. In tail recursion, we do not get the StackOverflowError during the execution of program. Example 1: Find the factorial of a number using tail-recursion. Kotlin // Kotlin program of factorial using tail-recursionfun Fact(num: Int, x:Int):Long{ return if(num==1) // terminate condition x.toLong() else Fact(num-1,x*num) //tail recursion}fun main() { var n = 1 var result = Fact(5,n) println("Factorial of 5 is: $result")} Output: Factorial of 5 is: 120 Working of the above program-Example 2: Find the sum of elements of an array using tail-recursion Kotlin // two parameters passed an array and size of arrayfun sum(args: Array<Int> , index:Int, s : Int = 0 ):Int{ return if(index<=0) s else sum(args ,index-1, s + args[index-1]) // tail-recursion} fun main() { // array initialization val array = arrayOf(1,2,3,4,5,6,7,8,9,10) // size of array val n = array.size val result = sum(array,n) // normal function call println("The sum of array elements is: $result")} Output: The sum of array elements is: 55 Explanation: Here, we have passed the array as an argument along with two other parameters in sum() function. The default value of (s) parameter is equal to zero. We are calculating the sum of elements, from the last index of the array, with each recursive call. With the last recursive call, we will have the sum of all elements in s and return it when condition satisfies. ayushpandey3july Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Android RecyclerView in Kotlin Retrofit with Kotlin Coroutine in Android Android Menus MVP (Model View Presenter) Architecture Pattern in Android with Example Kotlin Android Tutorial How to Build a Weather App in Android? MVC (Model View Controller) Architecture Pattern in Android with Example How to Get Current Location in Android? Kotlin when expression How to Convert Kotlin Code to Java Code in Android Studio?
[ { "code": null, "e": 24168, "s": 24140, "text": "\n28 Mar, 2022" }, { "code": null, "e": 24654, "s": 24168, "text": "In traditional recursion call, we perform our recursive call first, and then we take the return value of the recursive call and calculate the result. But in tail recursion, we perform the calculation first, and then we execute the recursive call, passing the results of the current step to the next recursive call. In the end, both recursion and tail recursion gives same output. The must follow rule for the tail recursion is that recursive call should be the last call of the method." }, { "code": null, "e": 25004, "s": 24654, "text": "In tail recursion, function call is the last thing executed by the function and nothing left in the current function to execute. So, there is no need to save current function call in stack memory and compiler can re-use that stack space for next recursive call.In tail recursion, we do not get the StackOverflowError during the execution of program." }, { "code": null, "e": 25266, "s": 25004, "text": "In tail recursion, function call is the last thing executed by the function and nothing left in the current function to execute. So, there is no need to save current function call in stack memory and compiler can re-use that stack space for next recursive call." }, { "code": null, "e": 25355, "s": 25266, "text": "In tail recursion, we do not get the StackOverflowError during the execution of program." }, { "code": null, "e": 25420, "s": 25355, "text": "Example 1: Find the factorial of a number using tail-recursion. " }, { "code": null, "e": 25427, "s": 25420, "text": "Kotlin" }, { "code": "// Kotlin program of factorial using tail-recursionfun Fact(num: Int, x:Int):Long{ return if(num==1) // terminate condition x.toLong() else Fact(num-1,x*num) //tail recursion}fun main() { var n = 1 var result = Fact(5,n) println(\"Factorial of 5 is: $result\")}", "e": 25721, "s": 25427, "text": null }, { "code": null, "e": 25729, "s": 25721, "text": "Output:" }, { "code": null, "e": 25752, "s": 25729, "text": "Factorial of 5 is: 120" }, { "code": null, "e": 25851, "s": 25752, "text": "Working of the above program-Example 2: Find the sum of elements of an array using tail-recursion " }, { "code": null, "e": 25858, "s": 25851, "text": "Kotlin" }, { "code": "// two parameters passed an array and size of arrayfun sum(args: Array<Int> , index:Int, s : Int = 0 ):Int{ return if(index<=0) s else sum(args ,index-1, s + args[index-1]) // tail-recursion} fun main() { // array initialization val array = arrayOf(1,2,3,4,5,6,7,8,9,10) // size of array val n = array.size val result = sum(array,n) // normal function call println(\"The sum of array elements is: $result\")}", "e": 26305, "s": 25858, "text": null }, { "code": null, "e": 26313, "s": 26305, "text": "Output:" }, { "code": null, "e": 26346, "s": 26313, "text": "The sum of array elements is: 55" }, { "code": null, "e": 26721, "s": 26346, "text": "Explanation: Here, we have passed the array as an argument along with two other parameters in sum() function. The default value of (s) parameter is equal to zero. We are calculating the sum of elements, from the last index of the array, with each recursive call. With the last recursive call, we will have the sum of all elements in s and return it when condition satisfies." }, { "code": null, "e": 26738, "s": 26721, "text": "ayushpandey3july" }, { "code": null, "e": 26745, "s": 26738, "text": "Kotlin" }, { "code": null, "e": 26843, "s": 26745, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26852, "s": 26843, "text": "Comments" }, { "code": null, "e": 26865, "s": 26852, "text": "Old Comments" }, { "code": null, "e": 26896, "s": 26865, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 26938, "s": 26896, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 26952, "s": 26938, "text": "Android Menus" }, { "code": null, "e": 27024, "s": 26952, "text": "MVP (Model View Presenter) Architecture Pattern in Android with Example" }, { "code": null, "e": 27048, "s": 27024, "text": "Kotlin Android Tutorial" }, { "code": null, "e": 27087, "s": 27048, "text": "How to Build a Weather App in Android?" }, { "code": null, "e": 27160, "s": 27087, "text": "MVC (Model View Controller) Architecture Pattern in Android with Example" }, { "code": null, "e": 27200, "s": 27160, "text": "How to Get Current Location in Android?" }, { "code": null, "e": 27223, "s": 27200, "text": "Kotlin when expression" } ]
SQL Interview Questions You Must Prepare: The Ultimate Guide | by Nathan Rosidi | Towards Data Science
SQL is a must have tool in the arsenal of any aspiring data scientist. In this article we provide an outline to learn, prepare and ace your next SQL Interview for a Data Science role. We will explore why SQL is so widely used, then provide you a breakdown of SQL skills needed by each role viz — Data Analyst, Data Scientist, Machine Learning Engineer, etc. Further, we provide you with real interview examples from the StrataScratch Platform illustrating a few of these skills and provide you with a step-by-step learning guide to become proficient with SQL even if you are not too familiar with SQL concepts and get your dream job. So let us start off with why SQL is so widely used in the Data Science World. One of the biggest reasons for the popularity of SQL is the tabular format for storage of data. It is easy to visualize databases as large spreadsheets with millions and millions of rows and columns. SQL allows users to quickly manipulate these tables to access information and present the results in the most common formats, tables and associated graphs and visualizations. While No-SQL databases like MongoDB, Cassandra, etc have gained traction with the requirements of Big-Data and real time applications and increasing prevalence of unstructured data, SQL databases still hold the top seven positions of the top ten most popular database engines. In fact No-SQL databases have positioned themselves as No just SQL to highlight their support for SQL so as to help increase their acceptance in organizations where traditional SQL based databases are already used. Another reason for the popularity of SQL is the ease of use. The syntax is very easy to understand, and anyone can pick it up very quickly. It is very easy to comprehend what the below statements do. SELECT name FROM EMPLOYEES;SELECT name FROM EMPLOYEES WHERE age >= 35;SELECT state, AVG(age) as average_age FROM EMPLOYEES WHERE age >= 35 GROUP BY state; It is pretty easy to learn SQL and a convenient yet powerful tool for the hiring managers to evaluate reasoning, coding and data science aptitudes of potential employees. Our analysis of 903 data science interview questions showed the most prominent interview question category is coding. It comprises almost a third of all the interview questions, since more often than not, the most prominent concept tested in the coding segment was writing SQL queries. There are more SQL based interview questions asked than those on Python or R at these top companies. With increasing focus on Data management skills, you cannot go wrong with learning SQL. So what should one concentrate on while building up their SQL skills for Data Science and Allied Positions? Not every position in Data Science uses the same SQL concepts. While some roles will focus heavily on queries and query optimization, others will tend towards data architecture and ETL processes. One can divide SQL Commands asked in Data Science Interviews into the following categories. Data Definition Language (DDL)- CREATE- ALTER- DROP- RENAME- TRUNCATE- COMMENT Data Query Language (DQL)- SELECT Data Manipulation Language (DML)- INSERT- UPDATE- DELETE- MERGE- CALL- EXPLAIN PLAN- LOCK TABLE Data Control Language (DCL)- GRANT- REVOKE A Data Analyst or a Data Scientist will be expected to mostly be working with the SELECT statement and associated advanced level concepts like subqueries, Grouping / Rollups, Window Functions and CTEs. If you work as an analyst, you probably already use SQL. It does not matter if you are a data analyst, reporting analyst, product analyst, or even financial analyst. Your position generally requires handling the raw data and using your skills to provide the management and other stakeholders with the decision-making insight. Data engineers work closely with data scientists and data analysts. Their main task is building and maintaining the data architecture and creating algorithms to allow data scientists and analysts easier access to data. By doing their job, they are helping data scientists to do their job too. What you cannot avoid as a data engineer is knowing SQL, often on an advanced level compared to data analysts and scientists. To be a good data engineer, you need to be an SQL master. That is why some questions you will be asked are the same as with data analysts and scientists. Besides the DQL commands, you are expected to be proficient in database modeling as well, hence you should know the DDL, DML and DCL commands in detail as well. Machine learning engineers are hybrid experts who are bridging the gap between data scientists and software engineers. As they serve as a bridge between those two positions, they need to have a certain set of skills from both worlds. They use those skills to design, build, and maintain the machine learning systems. To achieve that, they usually use several sets of skills: statistics mathematics data mining data analysis predictive analytics Machine learning engineers usually need to know Python and/or R. However, since machine learning engineers and data scientists have some skills in common (data mining, data analysis), it is quite often required from the machine learning engineers to know SQL as well. That way, they are able to make their own analyses and use the data according to their needs. They do not need some intermediary who’ll pull out the data and analyze it for them. For example, here is a question from Uber on creating a Naive Forecasting Model. ​ Develop a naive forecast for a new metric: “distance per dollar”. Distance Per Dollar is defined as the (distance_to_travel/monetary_cost) in our dataset. Calculate the metric and measure its accuracy. Algorithm Outline: Sum the “distance to travel” and “monetary cost” values at a monthly level and calculate “distance per dollar”. This is the actual value for the current month.Next, populate the forecasted value for each month. To achieve this, take the previous month’s value.Now, we have actual and forecasted values. This is our naive forecast. Now evaluate our model by calculating the root mean squared error (RMSE). RMSE is the square root of the difference mean squared differences between the actual and the forecast values. Report the RMSE rounded to the 2nd decimal place. SQL interviews for software engineers are also usually at an intersection of various skill sets, such as computer science, engineering, and mathematics. They use those different disciplines to design, write, test, and maintain the software. Like the machine learning engineers, they will also need to work with various departments and clients. That is why they too need a high level of business and technical skills, even though their primary task is not data analysis. Why is that? When they build the interface, they have to lean on the database(s) that run in the background. They need to use those databases and analyze data during the implementation of new software. You can refer to this excellent article on the various roles and responsibilities in Data Science to learn more. The article breaks down the most common requirements for each role that you can expect on a daily basis. Let us look at the most frequent SQL areas tested in Data Science Interviews. Since SQL roles differ widely, the testing areas vary quite a bit as well. Depending on the type of role that you are applying for and the organization, you can expect one or more of these SQL Data Science Interview Question types Fundamental SQL concepts SQL basics interview questions SQL aggregation interview questions Open Ended SQL interview questions Data Transformation interview questions Database Modeling interview questions Software Engineering SQL Interview questions Let us look at these SQL interview question types individually to understand the similarities and distinctions among them. The emphasis of these questions is on your understanding and knowledge of basic database and SQL terminology. One is not required to write any code. These are the broad concepts and some example questions that one should be familiar with. General information about SQL- What is SQL?- What are the different flavors of SQL?- What is a primary key? Relational Databases and how they work?- What are the top RDBMS engines?- How is an RDBMS different from a No-SQL database? SQL sublanguages and their main keywords- What do DDL, DCL, and DML stand for?- Give examples of commands for each. Data types and how SQL handles it (including blanks and NULLs)- What are the common data types in SQL?- Does an SQLite database support date time objects? Attribute constraints- What are attribute constraints, and explain them? types of JOINs- What is the difference between inner join and left outer join?- What is the difference between UNION and UNION ALL? Aggregation and Rollup functions- When should one use a CTE over a subquery?- What are window functions? Knowledge of various SQL functions- What is the difference between WHERE and HAVING? Examples of where one should use one over the other- What does the COALESCE function do? While one may not find them in the interviews initially, these questions might be asked as follow up questions to the coding solutions submitted by you. For example, if you used an inner join in your solution, you might be asked why you did not use a left join or what would have happened if you did? The SQL basics interview questions will require you to put some of the above theoretical concepts into practice. That doesn’t necessarily mean that these questions have to be coding questions. They can be descriptive too. But they usually cover concepts you will need to know if you want to write a code. Those concepts are: using SUM(), COUNT(), AVG(), MIN(), MAX() and other aggregate functions GROUP BY CASE WHEN statement WHERE and HAVING JOINs UNION and UNION all Questions Example Here is an example from a Postmates SQL Data Science Interview ​ “How many customers placed an order and what is the average order amount?” Solution: To answer this SQL interview question you’ll have to use the table postmates_orders. SELECT count(DISTINCT customer_id), avg(amount) FROM postmates_orders As one can see, this is really an easy one. It tests the aggregate functions COUNT() and AVG(), and it also requires the knowledge of how to use the DISTINCT clause. Here’s another one, this time from Credit Karma: “Write a query that returns the user ID of all users that have created at least one ‘Refinance’ submission and at least one ‘InSchool’ submission.” Solution: To answer this SQL interview question you’ll have to use the table loans. SELECT user_idFROM loansWHERE TYPE in ('Refinance', 'InSchool')GROUP BY user_idHAVING count(DISTINCT TYPE) =2 The code selects the column user_id from the table loans where the value equals one of the two values: “Refinance” and “InSchool”. Since we need to ensure that there are submissions in each type, we need to use the DISTINCT clause. One also needs to appreciate the difference between WHERE and HAVING. Since we are using the DISTINCT clause in the aggregate function, we have used HAVING instead of WHERE here. Aggregation functions are widely used for reporting metrics and evaluating summary results. Something Data Analysts and Data Scientists must do a lot. The purpose of aggregation is to transform data into information. This information is presented in the form of reports, dashboards, and charts. What you report are different metrics that need to be monitored. So, basically, your two main tasks will be aggregating and filtering data and performing various calculations on that data. While strictly speaking, the data analysts and data scientists are not reporting but analyzing the data, there are a lot of instances where one needs to monitor and report metrics on a regular basis. If you are interviewing for an SQL Data Analyst or Data Scientist position, you are expected to be familiar with these concepts: subqueries joins and self-joins window functions CTEs GROUP BY extensions (ROLLUP, CUBE, GROUPING SETS) Questions Example This is a moderate SQL interview question from Zillow that tests your understanding of aggregations functions “Write a query that identifies cities with higher than average home prices when compared to the national average. Output the city names.” Solution: To answer this question you’ll have to use the table zillow_transactions. SELECT cityFROM zillow_transactions aGROUP BY cityHAVING avg(a.mkt_price) > (SELECT avg(mkt_price) FROM zillow_transactions)ORDER BY city ASC To answer this SQL interview question, we write a subquery in the HAVING clause. The inner query calculates the overall average market price of all the transactions. The main query then filters only those cities where the average market price is greater than the overall average market price. Since we need to report only the cities in the final output, only those metrics are reported. Here is another one. This one is a little more complex from Lyft. “Find the top 10 users that have traveled the greatest distance. Output their names and total distance traveled.” Solution: To answer this question you will have to use the tables lyft_rides_log, lyft_users. SELECT name, traveled_distanceFROM (SELECT lu.name, SUM(lr.distance) AS traveled_distance, rank () over (order by SUM(lr.distance) desc) as rank FROM lyft_users AS lu INNER JOIN lyft_rides_log AS lr ON lu.id = lr.user_id GROUP BY lu.name ORDER BY traveled_distance DESC ) sqWHERE rank <= 10 This SQL interview question tests subqueries, window functions, and joins. We start off by joining the two tables with an inner join as we need those users who have used the services and remove the rides with incomplete user information. We then proceed to rank the sum of the total distances travelled by these users. We finally select the top 10 users by rank and output their names and total distances traveled. To improve your coding skills for SQL Data Science Interviews, you can refer to this video where we discuss some top data science interview questions, how to solve them and avoid common mistakes. You will encounter these types of questions in Data Analyst or Data Scientist positions that require some work experience. The greatest challenge in these questions is the lack of any specified metric that needs to be calculated as in the case of SQL Aggregation Interview Questions. You will still be required to write an SQL query that will return some metric(s) as a result. However, there is one big difference. In the Open-Ended SQL Interview questions, you will be asked to find the insight. It is entirely up to you to understand your data and what calculation answers what you are being asked. For example, you will have to find out if some product launch campaign succeeded, or new calling procedure saves the costs, or if new vehicles improved the users’ satisfaction. You will have to come up with metrics to define “success”, “saving”, or “improvement”. Compared to the SQL Aggregation questions, these questions have this extra dimension designed to test your thinking in solving the problem. Regarding the coding part of the Open-Ended SQL interview questions, they test all the concepts you will use in the basic level and the SQL Aggregation type questions. Questions Example Have a look at a question asked by Facebook: “Facebook has developed a search algorithm that will parse through user comments and present the results of the search to a user. To evaluate the performance of the algorithm, we are given a table that consists of the search result the user clicked on (‘notes’ column), the user’s search query, and the resulting search position that was returned for the specific comment.The higher the position, the better, since these comments were exactly what the user was searching for. Write a query that evaluates the performance of the search algorithm against each user query.” Solution: To answer this question we must use the table fb_search_results. SELECT t.result_id, t.query, CASE WHEN t.check = FALSE THEN 1 WHEN t.check = TRUE AND t.position >= 11 THEN 2 WHEN t.check = TRUE AND (t.position BETWEEN 6 AND 10) THEN 3 WHEN t.check = TRUE AND (t.position BETWEEN 4 AND 5) THEN 4 WHEN t.check = TRUE AND t.position <=3 THEN 5 END AS ratingFROM (SELECT query, result_id, position, notes, (regexp_replace(notes, '[^\w]+',' ','g') ilike concat('% ', query,' %')) AS check FROM fb_search_results ) t In order to solve this problem, we first need to define the criteria for evaluation. We define the rating of the match between the user’s search query and the search result returned by the algorithm (5 being the highest and 1 the lowest) as follows. If there is no match, a rating of 1 is given.If the match happens after the first 10 characters of the query, then the rating is 2.If the match happens between the 6 to 10 characters, then the rating is 3.If the match is within the first five characters, but not in the first three characters, then a rating of 4 is givenIf the match is in the first three characters, then the highest possible rating of 5 is given. If there is no match, a rating of 1 is given. If the match happens after the first 10 characters of the query, then the rating is 2. If the match happens between the 6 to 10 characters, then the rating is 3. If the match is within the first five characters, but not in the first three characters, then a rating of 4 is given If the match is in the first three characters, then the highest possible rating of 5 is given. Based on these ratings, we evaluate each search string. To match the search query and the result, we use the regular expression matching function in SQL. The main query uses this check column in the CASE WHEN statements. This is an open-ended SQL interview question because you were not given the metrics which would differentiate excellent performance from not-so-great one. Therefore, you had to decide on your scale that would show how the performance was. Your scale could be different from the one in the solution above. However, it is important that you explain your assumptions and why you decided to go with a certain evaluation scale. These are questions that one can expect to be asked very frequently for a Data Engineer or a Machine Learning Engineer position. Though it might not be out of place in a Data Scientist Interview for positions that require some experience. Data Transformation or more generally ETL (Extract, Transform and Load) is a process used to collect data from various sources (extract), changing it according to the business rules (transform), and then loading such extracted and transformed data into a database. When the data is extracted, it is done so from various data sources that, more often than not, store data in completely different formats. By transformation, the data takes the format appropriate for reporting and analysis. The data is transformed via data aggregation, filtering, sorting, joining, a calculation based on the rules set for business needs, etc. Such data is loaded into another database or table that the analysts or any other users might use. The ETL is heavily used in data warehouses, which serves as the central source of the integrated data, with data flowing into it from one or more separate sources. If you want to perform well at the SQL job interview, these are the concepts you need to know: Data Definition Language (DDL) keywords Data Manipulation Language (DML) keywords Data Control Language (DCL) keywords Transaction Control Language (TCL) keywords SQL constraints JOINs indexes transactions views user-defined functions stored procedures triggers variables query optimization Question Examples This is one of the easiest and yet frequently asked questions from the Southwest Airlines Data Science SQL Interview: “What is the difference between DELETE and TRUNCATE?” Answer: DELETE is a DML statement. TRUNCATE is a DDL statement. The DELETE statement can be used to delete all rows or only some rows. To delete some rows, you’ll have to use the WHERE clause. While doing this, every row removed will be logged as an activity by the database. On the other hand, TRUNCATE is used only for deleting the whole table, which will be logged as only one action. That’s why TRUNCATE is faster than DELETE, which shows when deleting a table with a huge amount of data. Also, you can’t use TRUNCATE if there’s a foreign key in the table. Another common question to appear is “How do you change a column name by writing a query in SQL?” Answer: Assuming you are using PostgreSQL. For a hypothetical table say product, one of the columns is named year, but I want to rename it to description. The query that will do that is: ALTER TABLE productRENAME year TO description; Another example of Data Transformation SQL Interview question will be: “How do you create a stored procedure?” Answer: We will solve this for Microsoft SQL Server. For example, if you are using a table named employee. Your procedure should help you get the employees that work in a certain department. The code would be CREATE PROCEDURE employee_deparment @deparment nvarchar(50)ASSELECT * FROM employees WHERE department = @departmentGO; Once the procedure is created, I can invoke it in the following manner: EXEC employee_deparment @department = 'Accounting'; These questions are designed to test how good you are at database design or database modeling. What is meant by that? You need to show the ability to design and build the database from scratch according to the business processes and business needs. This requires a high level of both technical and business knowledge. You will be working with both technical and non-technical colleagues. So, you need to understand both the business side of their requirement and how to, in the soundest way, technically cater to their business needs regarding the data. Generally, this is a process that goes through these steps (at least in the ideal world): defining the database purposecollecting and defining users’ requirementscreating a conceptual modelcreating the logical modelcreating the physical model defining the database purpose collecting and defining users’ requirements creating a conceptual model creating the logical model creating the physical model Question Examples One of the typical questions that occur in the SQL interviews is this one by Audible: “Can you walk us through how you would build a recommendation system?” Answer: Since there is a wide variety of approaches to answer this question, we will leave you to come up with your own way of building one. The database design question can also include SQL coding, such as this one from Facebook: “Write a SQL query to compute a frequency table of a certain attribute involving two joins. What if you want to GROUP or ORDER BY some attribute? What changes would you need to make? How would you account for NULLs?” Answer: Due to the nature of the question, we will let you answer this one on your own. These are questions that require SQL knowledge, but usually, what is being asked may not be widely applicable in practice. These questions come up during the interview because even though as a software engineer, you might not be writing SQL codes every day, you still need to interact with your peers who use SQL daily and follow what they are trying to achieve and implement their needs and SQL logic into the software development. These questions test your logical skills more than coding skills. One such question that could be asked during your interview could be Imagine you’re working with two tables. The one is the product table, which has the following data: id product_name manufacturer_id The second table is manufacturer with the following data: id manufacturer There are 8 records in the first table and 4 in the second one. How many rows will the following SQL code return: SELECT *FROM product, manufacturer Answer: The query will return 32 rows. Whenever the WHERE clause is omitted, the default result is CROSS JOIN or a Cartesian product. This means the query will return every combination of rows from the first table with every combination of rows from the second table. FAANG is an acronym for the five most famous tech companies: Facebook, Amazon, Apple, Netflix, and Google. Why would you specially prepare for the questions asked by those companies, except being in awe of the possibility of working for them? They might seem or even be attractive, but that is not the main reason why you would pay special attention if you want to work at those companies. The main reason is their SQL interview questions are a bit different. As tech companies, their business heavily relies on data. And where there is data, there is SQL which the FAANG companies often use. Hence they want to be absolutely certain that their employees know SQL in depth. You will always get SQL interview questions with a little twist. The twist being their questions are more practical and concerning a case study with real problems and data a certain company is facing in their everyday business. These are arguably the next level of the Open Ended SQL Interview Questions that we saw earlier. Have a look at this example from Google: “Find the email activity rank for each user. Email activity rank is defined by the total number of emails sent. The user with the highest number of emails sent will have a rank of 1, and so on. Output the user, total emails, and their activity rank. Order records by the total emails in descending order. Sort users with the same rank score in alphabetical order.In your rankings, return a unique value (i.e., a unique percentile) even if multiple users have the same number of emails.” Solution: To answer this question, you’ll need to use the google_gmail_emails table. SELECT from_user, count(*) as total_emails, row_number() OVER ( order by count(*) desc) FROM google_gmail_emails GROUP BY from_user order by 3, 1 As you can see, this question tests your aggregate functions and window functions knowledge, along with the GROUP BY and ORDER BY clauses. But they also do that on real-life problems you’ll probably have to work on if you get a job. Here is another example of such question, this time from Netflix: “Find the nominee who has won the most Oscars.Output the nominee’s name alongside the result.Order the result based on the number of wins in descending order.” Solution: To answer this question, you will need to use the oscar_nominees table. SELECT nominee, count(winner) AS n_times_wonFROM oscar_nomineesWHERE winner = trueGROUP BY nomineeORDER BY n_times_won DESC Again, this question tests some usual concepts. But the problem set is something that you expect to work on a daily basis. If you work at Netflix on an SQL job, you will for sure analyze some data that contains some Oscar nominations and winners. You would have probably noticed that the technical SQL interview questions overlap with other SQL questions. That is because one does not work without the other. There is no point in knowing the theory without being able to put it into practice, i.e., the SQL code. Conversely, you need to describe the technical concepts behind the code that you wrote. While the SQL concepts you should know depend on your position, years of experience, and the company you want to work at, we have looked at some concepts that are useful across roles. While this is not an exhaustive list, it is definitely something that you are expected to know if you are attending an SQL Data Science Interview. SQL definition SQL stands for “Structured Query Language”. It is a programming language used for creating database structure, retrieving and manipulating data in it. Types of the SQL commands Relational database Data Definition Language (DDL)- CREATE- ALTER- DROP- RENAME- TRUNCATE- COMMENT Data Query Language (DQL)- SELECT Data Manipulation Language (DML)- INSERT- UPDATE- DELETE- MERGE- CALL- EXPLAIN PLAN- LOCK TABLE Data Control Language (DCL)- GRANT- REVOKE Relational database A relational database is one based on the relational data model. This means the database is a collection of relations. Those relations are shown as tables, which consist of columns, rows, and values. The relational database aims to minimize or completely avoid data redundancy, leading to data integrity and speeding up its retrieval. Relationships in the database The relationship defines the type of connection between the tables in the database. There are three main types of relationships: one-to-one relationship (1:1) one-to-many relationship (1:N) or many-to-one relationship (N:1) many-to-many relationship (M:N) Database normalization Database normalization is a process of organizing data in the database to achieve its purpose: data integrity, its non-redundancy, and speed of retrieval. Constraints The constraints are the rules that define what type of data can and can’t be entered as a value in the database. The most common attributes are: NOT NULL CHECK UNIQUE PRIMARY KEY FOREIGN KEY Indexes The indexes are structures in the databases created to tune the database performance. They are used to speed up data retrieval. The types of indexes are: clustered index non-clustered index unique index filtered index columnstore index hash index View A view is a virtual table containing data from one or more tables resulting from a SQL statement. Stored procedure A stored procedure is an SQL code consisting of one or several SQL statements that are saved and can be called and executed whenever required. Trigger A trigger is a special type of a stored procedure. It is automatically executed (triggered) whenever some special event occurs in the database. Inner join An Inner join returns only those rows where the data from one table matches the data from the second table. Left outer join The left join is a table join that will retrieve all the rows from the left table and only the matching rows from the right table. Right outer join This join is the one that returns all the rows from the right table and only the matching rows from the left table. Full outer join The full outer join will join the data so that the result will include all the rows from one table and all the rows from the second table. Cross join This results in a Cartesian product. This means it will return all the combinations of rows from one table with all the combinations of rows from the other table. Union This is an SQL command that will combine the result of one query with the result of another query. Therefore, it will show only unique records. Union all This one also combines the results from two or more queries. The difference between UNION and UNION ALL is it will also include duplicates. Aggregate functions The aggregate functions perform a calculation on a data set and return a single value as a result. Example of the aggregate functions are: COUNT() SUM() MIN() MAX() AVG() STDEV() VAR() GROUP BY clause The GROUP BY clause allows you to group data according to the defined (one or more) criteria. DISTINCT clause The DISTINCT clause is a clause that will return only distinct or unique values, i.e., there will be no duplicate values in the result. WHERE clause The WHERE clause is used to filter data according to the specified criteria. HAVING clause The HAVING clause also filters data according to the specified criteria. The difference compared to the WHERE clause is that the HAVING clause works with the aggregate functions. Therefore, if used, it always follows the GROUP BY clause and precedes the ORDER BY clause. ORDER BY clause The ORDER BY clause is used to order the query result according to a certain data column. CASE statement The CASE statement returns a defined value based on certain criteria. It is the SQL statement that allows you to apply the IF-THEN logic. Instead of IF, you use WHEN. And for THEN, you use THEN. Subquery A subquery is a query found within the query. It can occur in a SELECT clause, FROM clause, or WHERE clause. CTE A CTE or a Common Table Expression is a temporary result set returned by a query and used by another query. In that way, it’s similar to subquery. But the main difference is CTE can be named and can reference itself. Window functions The window functions are SQL functions performing calculations over the defined set of rows (a window). Compared to the aggregate functions, which return a single value as a result, the window functions allow you to add the aggregated value to each row in a separate column. This means the rows are not grouped and all the rows are kept as a query result. The window functions are: row_number() rank() dense_rank() percent_rank() cume_dist() lead() lag() ntile() first_value() last_value() nth_value() avg() count() min() max() sum() Being good at SQL is the prerequisite to do well at the job interview. However, it is not the only skill. Questions can be tricky, designed to put you off or doubt your knowledge by being seemingly too complicated or too simple. That’s why it’s important to have a clear strategy on what to do in certain situations. If you don’t understand what the question is and what is expected from you, you will likely get the wrong answer. To avoid that, make sure you understand what is asked of you. Repeat the requirements out loud and ask the interviewer to confirm you understood the question correctly. Don’t be afraid to do that. The interviewers are people too. They can also unintentionally be unclear, make a mistake, or forget to give you enough details for you to answer correctly. Before you start answering, especially if you are writing SQL code, outlay your approach. That way, you will be able to find the solution faster and or find the holes in the code you intended to write. You should do that to allow the interviewer to lead you through in case you missed the point of the question. It is always better to be corrected before presenting the final solution. This is something that can help you in writing the problem-solving code. Sometimes, when you clarify how the output should look and compare it with initial data, the approach and the solution reveal themselves. At some point, you will need to start writing the code. As we discussed, you should not jump headfirst into it. But you cannot keep procrastinating on the best approach to write it. After you have gone through all those previous steps, and you are still not sure if you have the right solution, simply start writing the code. One of the reasons is, sometimes there is no solution at all. Meaning the question is too complex to be solved in the time you’re being given. In such cases, the interviewer is not interested in your solution. Instead, he or she is interested in your way of thinking and how you approach the problem. There are usually multiple ways to use SQL for problem-solving, and this is what some interviewers are interested in: the process, not the goal. When you’re writing the code, pay attention to its structure. Divide the code into logical parts. That way, you will make your code easier to read, which is also one of the requirements to get the job. There is no point in writing a correct code that is a mess, and nobody can read it and understand it after you write it. Not even you!! If your code is divided into logical parts, it will be easier for you to explain to the interviewer what you did. It is also important to have the code optimization in mind. If your code is complex, of course, you are not going to be able to optimize it as you write. But you should pay attention to some general optimization guidelines, so your code is reasonably optimized. You can also discuss with the interviewer what other steps you will have to take to optimize your code in the aftermath. This is also the job requirement, similarly to the previous point. There is no point writing the code that will get you the required result, but takes forever to execute. Even if you did not get the required answer, it does not mean you failed the interview. That is why you should always know why you did something and explain why you did it. Maybe you did not get the answer to the question they asked, but you did get the answer to some questions. So make sure that you state your assumption and explain why you did what you did. Again, they may be looking exactly for that: the right reasoning in line with assumptions, even though the assumptions were wrong. That also shows you know what you are doing, even if it is not what they asked. Also, one of the reasons for explaining the assumptions is there may be a loophole in the question. So imagine pointing at it right there at the interview by simply explaining why you did something while you thought you were all wrong. Here is the video where Nate from StrataScratch shares some tips on how to organize your SQL interview solution: Here are some additional tips that might help you to be a success at the upcoming SQL interview. This is important in general, not only for the SQL part of the interview. It is important to be informed about your future employer, their products, and their industry. It is especially important when the SQL questions are regarded. Why is that? As we discussed earlier, the FAANG companies will usually ask you very practical SQL coding questions that will have you use the same data and solve the same problems as you would have to when you get employed. The FAANG companies are not the only ones who do that. So when you prepare for the interview, try to think which data is important to this company, how their database could look like, etc. When you practice the SQL questions, try to find the real questions from the companies you are interested in or at least from their competitors. If the companies are in the same industry, it’s quite likely the data they use will be more or less the same. It is quite usual to be asked to write SQL code on a whiteboard. It can be shocking to some people, which is understandable. You are probably used to writing code in a real RDBMS, on real data, which allows you to regularly check if the query works. Not even the greatest masters of SQL can write a code without running it to see if it works at all or if it returns the desired result. However, in the SQL interview, the criteria are a little higher. While it can be scary, it is also understandable. Writing the code on a whiteboard shows that you know how to write your code. Reading your (or someone else’s code) is also important. This is the skill that is also tested on a whiteboard. If you can read a code and say if it will give you the desired result without relying on the database to tell you that, then working with a real database and SQL environment will be easier for you. We are not talking about your handwriting. There is not much you can do if your handwriting is messy. But that does not mean your code has to be unreadable. When you write a code, try to format it so that it is easier for you and the interviewers to read it and check your solution. Code is read more often than it is written. Code should always be written in a way that promotes readability. - Guido Van Rossum, the creator of Python Regularly use spacing and line breaks to make your code easier to read. If you need to (re)name tables and columns, be consistent with the naming convention you choose. Add comments whenever needed. Try to use aliases whenever possible, but try to make them sound logical and not some random decision when you do. Here are also some useful tips from Nate on how to organize lengthy SQL codes. If you have experience with multiple SQL databases (Oracle, PostgreSQL, Microsoft SQL Server, MySQL), try to adapt and write in a dialect of the database that is used at your future employer. That would be nice and could show your versatility, especially if you know what dialect they prefer. However, if you are familiar with only one dialect, do not think that it is the end of the interview. For example, if you were using only PostgreSQL and the company is using Microsoft SQL Server, there may be different keywords for the same command in those two databases. It is also possible that PostgreSQL has some functions that aren’t allowed in Microsoft SQL Server and vice versa. Ask the interviewer if it is possible to write a code in, say, PostgreSQL instead of Microsoft SQL Server since you are more familiar with it. It is always better if you know several dialects. But it is also better if you write in a familiar dialect, even though “the wrong one”, than mess up the code just because you were too afraid to ask if you can write in a dialect you are comfortable with. The differences between the dialects are not that huge. So if you know SQL, you’ll easily and quickly adapt to a new database. While the interview is evaluating you, there are other things that employers look for in an employee besides just coding ability. You will be working as a part of a team and hence your ability to confidently put across your ideas, be open to positive feedback about your codes and ability to work as a team is equally important. Employers try to gage these even during something as technical as coding. It is vital that you ask for help in case you are stuck. Asking for help shows confidence and is not a sign of weakness. Keep the interviewer in the loop regarding what your thought process is so that she might be able to help you in case you are stuck or omitted some information unintentionally. Listen to any explanations provided to ensure that you have taken care of all the edge cases that might arise. These are skills that every Data Scientist must possess and unfortunately not a lot of candidates focus on them. An interviewer is more likely to hire a Data Scientist with sound basic understanding of SQL and willing to adapt to changes and pick up additional skills on the way over a prodigious but rigid one. The employer is looking at the potential for a long term relationship. If you give the right signals, you might just land your dream job. Check out these 5 tips on how to prepare for a Data Science interview. We have also gathered some advanced level SQL questions asked by real companies in 2021 that you can find in our Advanced SQL Interview Questions You Must Know How to Answer article. In this article, we looked at the various aspects of an SQL Data Science Interview. We started off by understanding why SQL is so popular in the Data Science world and the different roles that are available in the industry. We then provided a detailed overview of the type of questions that you can expect for each position and what to learn for your becoming proficient with SQL for Data Science Interviews. Even if you have just started with SQL, all that it takes to become interview ready is persistence, patience and lots of practice. If you do not have much real-life experience with SQL, it is very important that you practice writing SQL codes. Do it a lot, and regularly. Continuity is very important. Try to answer as many as possible SQL interview questions, be it hypothetical or, even better, the real ones from the company you want to work at. Only by writing a lot of code, you’ll gain experience, grasp some typical problems that need to be solved by SQL, and the syntax will become like second nature. Even if you are vastly experienced in SQL and use it in a business environment, it is always good to prepare for an interview and brush up your skills. Nobody knows everything about SQL. Generally, people know what they need, what they regularly use every day. So it is possible that after several years at your job, you became a master of a certain aspect of SQL. Do not let it make you think you know it all. It could be that your new job will be asking you to know some different SQL functions and possibilities, the ones you are not exactly versed at. Originally published at https://www.stratascratch.com.
[ { "code": null, "e": 806, "s": 172, "text": "SQL is a must have tool in the arsenal of any aspiring data scientist. In this article we provide an outline to learn, prepare and ace your next SQL Interview for a Data Science role. We will explore why SQL is so widely used, then provide you a breakdown of SQL skills needed by each role viz — Data Analyst, Data Scientist, Machine Learning Engineer, etc. Further, we provide you with real interview examples from the StrataScratch Platform illustrating a few of these skills and provide you with a step-by-step learning guide to become proficient with SQL even if you are not too familiar with SQL concepts and get your dream job." }, { "code": null, "e": 884, "s": 806, "text": "So let us start off with why SQL is so widely used in the Data Science World." }, { "code": null, "e": 1259, "s": 884, "text": "One of the biggest reasons for the popularity of SQL is the tabular format for storage of data. It is easy to visualize databases as large spreadsheets with millions and millions of rows and columns. SQL allows users to quickly manipulate these tables to access information and present the results in the most common formats, tables and associated graphs and visualizations." }, { "code": null, "e": 1751, "s": 1259, "text": "While No-SQL databases like MongoDB, Cassandra, etc have gained traction with the requirements of Big-Data and real time applications and increasing prevalence of unstructured data, SQL databases still hold the top seven positions of the top ten most popular database engines. In fact No-SQL databases have positioned themselves as No just SQL to highlight their support for SQL so as to help increase their acceptance in organizations where traditional SQL based databases are already used." }, { "code": null, "e": 1951, "s": 1751, "text": "Another reason for the popularity of SQL is the ease of use. The syntax is very easy to understand, and anyone can pick it up very quickly. It is very easy to comprehend what the below statements do." }, { "code": null, "e": 2118, "s": 1951, "text": "SELECT name FROM EMPLOYEES;SELECT name FROM EMPLOYEES WHERE age >= 35;SELECT state, AVG(age) as average_age FROM EMPLOYEES WHERE age >= 35 GROUP BY state;" }, { "code": null, "e": 2575, "s": 2118, "text": "It is pretty easy to learn SQL and a convenient yet powerful tool for the hiring managers to evaluate reasoning, coding and data science aptitudes of potential employees. Our analysis of 903 data science interview questions showed the most prominent interview question category is coding. It comprises almost a third of all the interview questions, since more often than not, the most prominent concept tested in the coding segment was writing SQL queries." }, { "code": null, "e": 2872, "s": 2575, "text": "There are more SQL based interview questions asked than those on Python or R at these top companies. With increasing focus on Data management skills, you cannot go wrong with learning SQL. So what should one concentrate on while building up their SQL skills for Data Science and Allied Positions?" }, { "code": null, "e": 3160, "s": 2872, "text": "Not every position in Data Science uses the same SQL concepts. While some roles will focus heavily on queries and query optimization, others will tend towards data architecture and ETL processes. One can divide SQL Commands asked in Data Science Interviews into the following categories." }, { "code": null, "e": 3239, "s": 3160, "text": "Data Definition Language (DDL)- CREATE- ALTER- DROP- RENAME- TRUNCATE- COMMENT" }, { "code": null, "e": 3273, "s": 3239, "text": "Data Query Language (DQL)- SELECT" }, { "code": null, "e": 3369, "s": 3273, "text": "Data Manipulation Language (DML)- INSERT- UPDATE- DELETE- MERGE- CALL- EXPLAIN PLAN- LOCK TABLE" }, { "code": null, "e": 3412, "s": 3369, "text": "Data Control Language (DCL)- GRANT- REVOKE" }, { "code": null, "e": 3940, "s": 3412, "text": "A Data Analyst or a Data Scientist will be expected to mostly be working with the SELECT statement and associated advanced level concepts like subqueries, Grouping / Rollups, Window Functions and CTEs. If you work as an analyst, you probably already use SQL. It does not matter if you are a data analyst, reporting analyst, product analyst, or even financial analyst. Your position generally requires handling the raw data and using your skills to provide the management and other stakeholders with the decision-making insight." }, { "code": null, "e": 4674, "s": 3940, "text": "Data engineers work closely with data scientists and data analysts. Their main task is building and maintaining the data architecture and creating algorithms to allow data scientists and analysts easier access to data. By doing their job, they are helping data scientists to do their job too. What you cannot avoid as a data engineer is knowing SQL, often on an advanced level compared to data analysts and scientists. To be a good data engineer, you need to be an SQL master. That is why some questions you will be asked are the same as with data analysts and scientists. Besides the DQL commands, you are expected to be proficient in database modeling as well, hence you should know the DDL, DML and DCL commands in detail as well." }, { "code": null, "e": 5049, "s": 4674, "text": "Machine learning engineers are hybrid experts who are bridging the gap between data scientists and software engineers. As they serve as a bridge between those two positions, they need to have a certain set of skills from both worlds. They use those skills to design, build, and maintain the machine learning systems. To achieve that, they usually use several sets of skills:" }, { "code": null, "e": 5060, "s": 5049, "text": "statistics" }, { "code": null, "e": 5072, "s": 5060, "text": "mathematics" }, { "code": null, "e": 5084, "s": 5072, "text": "data mining" }, { "code": null, "e": 5098, "s": 5084, "text": "data analysis" }, { "code": null, "e": 5119, "s": 5098, "text": "predictive analytics" }, { "code": null, "e": 5649, "s": 5119, "text": "Machine learning engineers usually need to know Python and/or R. However, since machine learning engineers and data scientists have some skills in common (data mining, data analysis), it is quite often required from the machine learning engineers to know SQL as well. That way, they are able to make their own analyses and use the data according to their needs. They do not need some intermediary who’ll pull out the data and analyze it for them. For example, here is a question from Uber on creating a Naive Forecasting Model. ​" }, { "code": null, "e": 5851, "s": 5649, "text": "Develop a naive forecast for a new metric: “distance per dollar”. Distance Per Dollar is defined as the (distance_to_travel/monetary_cost) in our dataset. Calculate the metric and measure its accuracy." }, { "code": null, "e": 5870, "s": 5851, "text": "Algorithm Outline:" }, { "code": null, "e": 6436, "s": 5870, "text": "Sum the “distance to travel” and “monetary cost” values at a monthly level and calculate “distance per dollar”. This is the actual value for the current month.Next, populate the forecasted value for each month. To achieve this, take the previous month’s value.Now, we have actual and forecasted values. This is our naive forecast. Now evaluate our model by calculating the root mean squared error (RMSE). RMSE is the square root of the difference mean squared differences between the actual and the forecast values. Report the RMSE rounded to the 2nd decimal place." }, { "code": null, "e": 7108, "s": 6436, "text": "SQL interviews for software engineers are also usually at an intersection of various skill sets, such as computer science, engineering, and mathematics. They use those different disciplines to design, write, test, and maintain the software. Like the machine learning engineers, they will also need to work with various departments and clients. That is why they too need a high level of business and technical skills, even though their primary task is not data analysis. Why is that? When they build the interface, they have to lean on the database(s) that run in the background. They need to use those databases and analyze data during the implementation of new software." }, { "code": null, "e": 7326, "s": 7108, "text": "You can refer to this excellent article on the various roles and responsibilities in Data Science to learn more. The article breaks down the most common requirements for each role that you can expect on a daily basis." }, { "code": null, "e": 7404, "s": 7326, "text": "Let us look at the most frequent SQL areas tested in Data Science Interviews." }, { "code": null, "e": 7635, "s": 7404, "text": "Since SQL roles differ widely, the testing areas vary quite a bit as well. Depending on the type of role that you are applying for and the organization, you can expect one or more of these SQL Data Science Interview Question types" }, { "code": null, "e": 7660, "s": 7635, "text": "Fundamental SQL concepts" }, { "code": null, "e": 7691, "s": 7660, "text": "SQL basics interview questions" }, { "code": null, "e": 7727, "s": 7691, "text": "SQL aggregation interview questions" }, { "code": null, "e": 7762, "s": 7727, "text": "Open Ended SQL interview questions" }, { "code": null, "e": 7802, "s": 7762, "text": "Data Transformation interview questions" }, { "code": null, "e": 7840, "s": 7802, "text": "Database Modeling interview questions" }, { "code": null, "e": 7885, "s": 7840, "text": "Software Engineering SQL Interview questions" }, { "code": null, "e": 8008, "s": 7885, "text": "Let us look at these SQL interview question types individually to understand the similarities and distinctions among them." }, { "code": null, "e": 8247, "s": 8008, "text": "The emphasis of these questions is on your understanding and knowledge of basic database and SQL terminology. One is not required to write any code. These are the broad concepts and some example questions that one should be familiar with." }, { "code": null, "e": 8355, "s": 8247, "text": "General information about SQL- What is SQL?- What are the different flavors of SQL?- What is a primary key?" }, { "code": null, "e": 8479, "s": 8355, "text": "Relational Databases and how they work?- What are the top RDBMS engines?- How is an RDBMS different from a No-SQL database?" }, { "code": null, "e": 8595, "s": 8479, "text": "SQL sublanguages and their main keywords- What do DDL, DCL, and DML stand for?- Give examples of commands for each." }, { "code": null, "e": 8750, "s": 8595, "text": "Data types and how SQL handles it (including blanks and NULLs)- What are the common data types in SQL?- Does an SQLite database support date time objects?" }, { "code": null, "e": 8823, "s": 8750, "text": "Attribute constraints- What are attribute constraints, and explain them?" }, { "code": null, "e": 8955, "s": 8823, "text": "types of JOINs- What is the difference between inner join and left outer join?- What is the difference between UNION and UNION ALL?" }, { "code": null, "e": 9060, "s": 8955, "text": "Aggregation and Rollup functions- When should one use a CTE over a subquery?- What are window functions?" }, { "code": null, "e": 9234, "s": 9060, "text": "Knowledge of various SQL functions- What is the difference between WHERE and HAVING? Examples of where one should use one over the other- What does the COALESCE function do?" }, { "code": null, "e": 9535, "s": 9234, "text": "While one may not find them in the interviews initially, these questions might be asked as follow up questions to the coding solutions submitted by you. For example, if you used an inner join in your solution, you might be asked why you did not use a left join or what would have happened if you did?" }, { "code": null, "e": 9860, "s": 9535, "text": "The SQL basics interview questions will require you to put some of the above theoretical concepts into practice. That doesn’t necessarily mean that these questions have to be coding questions. They can be descriptive too. But they usually cover concepts you will need to know if you want to write a code. Those concepts are:" }, { "code": null, "e": 9932, "s": 9860, "text": "using SUM(), COUNT(), AVG(), MIN(), MAX() and other aggregate functions" }, { "code": null, "e": 9941, "s": 9932, "text": "GROUP BY" }, { "code": null, "e": 9961, "s": 9941, "text": "CASE WHEN statement" }, { "code": null, "e": 9978, "s": 9961, "text": "WHERE and HAVING" }, { "code": null, "e": 9984, "s": 9978, "text": "JOINs" }, { "code": null, "e": 10004, "s": 9984, "text": "UNION and UNION all" }, { "code": null, "e": 10022, "s": 10004, "text": "Questions Example" }, { "code": null, "e": 10087, "s": 10022, "text": "Here is an example from a Postmates SQL Data Science Interview ​" }, { "code": null, "e": 10162, "s": 10087, "text": "“How many customers placed an order and what is the average order amount?”" }, { "code": null, "e": 10257, "s": 10162, "text": "Solution: To answer this SQL interview question you’ll have to use the table postmates_orders." }, { "code": null, "e": 10327, "s": 10257, "text": "SELECT count(DISTINCT customer_id), avg(amount) FROM postmates_orders" }, { "code": null, "e": 10493, "s": 10327, "text": "As one can see, this is really an easy one. It tests the aggregate functions COUNT() and AVG(), and it also requires the knowledge of how to use the DISTINCT clause." }, { "code": null, "e": 10542, "s": 10493, "text": "Here’s another one, this time from Credit Karma:" }, { "code": null, "e": 10690, "s": 10542, "text": "“Write a query that returns the user ID of all users that have created at least one ‘Refinance’ submission and at least one ‘InSchool’ submission.”" }, { "code": null, "e": 10774, "s": 10690, "text": "Solution: To answer this SQL interview question you’ll have to use the table loans." }, { "code": null, "e": 10884, "s": 10774, "text": "SELECT user_idFROM loansWHERE TYPE in ('Refinance', 'InSchool')GROUP BY user_idHAVING count(DISTINCT TYPE) =2" }, { "code": null, "e": 11295, "s": 10884, "text": "The code selects the column user_id from the table loans where the value equals one of the two values: “Refinance” and “InSchool”. Since we need to ensure that there are submissions in each type, we need to use the DISTINCT clause. One also needs to appreciate the difference between WHERE and HAVING. Since we are using the DISTINCT clause in the aggregate function, we have used HAVING instead of WHERE here." }, { "code": null, "e": 11779, "s": 11295, "text": "Aggregation functions are widely used for reporting metrics and evaluating summary results. Something Data Analysts and Data Scientists must do a lot. The purpose of aggregation is to transform data into information. This information is presented in the form of reports, dashboards, and charts. What you report are different metrics that need to be monitored. So, basically, your two main tasks will be aggregating and filtering data and performing various calculations on that data." }, { "code": null, "e": 12108, "s": 11779, "text": "While strictly speaking, the data analysts and data scientists are not reporting but analyzing the data, there are a lot of instances where one needs to monitor and report metrics on a regular basis. If you are interviewing for an SQL Data Analyst or Data Scientist position, you are expected to be familiar with these concepts:" }, { "code": null, "e": 12119, "s": 12108, "text": "subqueries" }, { "code": null, "e": 12140, "s": 12119, "text": "joins and self-joins" }, { "code": null, "e": 12157, "s": 12140, "text": "window functions" }, { "code": null, "e": 12162, "s": 12157, "text": "CTEs" }, { "code": null, "e": 12212, "s": 12162, "text": "GROUP BY extensions (ROLLUP, CUBE, GROUPING SETS)" }, { "code": null, "e": 12230, "s": 12212, "text": "Questions Example" }, { "code": null, "e": 12340, "s": 12230, "text": "This is a moderate SQL interview question from Zillow that tests your understanding of aggregations functions" }, { "code": null, "e": 12478, "s": 12340, "text": "“Write a query that identifies cities with higher than average home prices when compared to the national average. Output the city names.”" }, { "code": null, "e": 12562, "s": 12478, "text": "Solution: To answer this question you’ll have to use the table zillow_transactions." }, { "code": null, "e": 12707, "s": 12562, "text": "SELECT cityFROM zillow_transactions aGROUP BY cityHAVING avg(a.mkt_price) > (SELECT avg(mkt_price) FROM zillow_transactions)ORDER BY city ASC" }, { "code": null, "e": 13094, "s": 12707, "text": "To answer this SQL interview question, we write a subquery in the HAVING clause. The inner query calculates the overall average market price of all the transactions. The main query then filters only those cities where the average market price is greater than the overall average market price. Since we need to report only the cities in the final output, only those metrics are reported." }, { "code": null, "e": 13160, "s": 13094, "text": "Here is another one. This one is a little more complex from Lyft." }, { "code": null, "e": 13274, "s": 13160, "text": "“Find the top 10 users that have traveled the greatest distance. Output their names and total distance traveled.”" }, { "code": null, "e": 13368, "s": 13274, "text": "Solution: To answer this question you will have to use the tables lyft_rides_log, lyft_users." }, { "code": null, "e": 13697, "s": 13368, "text": "SELECT name, traveled_distanceFROM (SELECT lu.name, SUM(lr.distance) AS traveled_distance, rank () over (order by SUM(lr.distance) desc) as rank FROM lyft_users AS lu INNER JOIN lyft_rides_log AS lr ON lu.id = lr.user_id GROUP BY lu.name ORDER BY traveled_distance DESC ) sqWHERE rank <= 10" }, { "code": null, "e": 14112, "s": 13697, "text": "This SQL interview question tests subqueries, window functions, and joins. We start off by joining the two tables with an inner join as we need those users who have used the services and remove the rides with incomplete user information. We then proceed to rank the sum of the total distances travelled by these users. We finally select the top 10 users by rank and output their names and total distances traveled." }, { "code": null, "e": 14308, "s": 14112, "text": "To improve your coding skills for SQL Data Science Interviews, you can refer to this video where we discuss some top data science interview questions, how to solve them and avoid common mistakes." }, { "code": null, "e": 14806, "s": 14308, "text": "You will encounter these types of questions in Data Analyst or Data Scientist positions that require some work experience. The greatest challenge in these questions is the lack of any specified metric that needs to be calculated as in the case of SQL Aggregation Interview Questions. You will still be required to write an SQL query that will return some metric(s) as a result. However, there is one big difference. In the Open-Ended SQL Interview questions, you will be asked to find the insight." }, { "code": null, "e": 15174, "s": 14806, "text": "It is entirely up to you to understand your data and what calculation answers what you are being asked. For example, you will have to find out if some product launch campaign succeeded, or new calling procedure saves the costs, or if new vehicles improved the users’ satisfaction. You will have to come up with metrics to define “success”, “saving”, or “improvement”." }, { "code": null, "e": 15482, "s": 15174, "text": "Compared to the SQL Aggregation questions, these questions have this extra dimension designed to test your thinking in solving the problem. Regarding the coding part of the Open-Ended SQL interview questions, they test all the concepts you will use in the basic level and the SQL Aggregation type questions." }, { "code": null, "e": 15500, "s": 15482, "text": "Questions Example" }, { "code": null, "e": 15545, "s": 15500, "text": "Have a look at a question asked by Facebook:" }, { "code": null, "e": 16116, "s": 15545, "text": "“Facebook has developed a search algorithm that will parse through user comments and present the results of the search to a user. To evaluate the performance of the algorithm, we are given a table that consists of the search result the user clicked on (‘notes’ column), the user’s search query, and the resulting search position that was returned for the specific comment.The higher the position, the better, since these comments were exactly what the user was searching for. Write a query that evaluates the performance of the search algorithm against each user query.”" }, { "code": null, "e": 16191, "s": 16116, "text": "Solution: To answer this question we must use the table fb_search_results." }, { "code": null, "e": 16803, "s": 16191, "text": "SELECT t.result_id, t.query, CASE WHEN t.check = FALSE THEN 1 WHEN t.check = TRUE AND t.position >= 11 THEN 2 WHEN t.check = TRUE AND (t.position BETWEEN 6 AND 10) THEN 3 WHEN t.check = TRUE AND (t.position BETWEEN 4 AND 5) THEN 4 WHEN t.check = TRUE AND t.position <=3 THEN 5 END AS ratingFROM (SELECT query, \tresult_id, \tposition, \t notes, \t(regexp_replace(notes, '[^\\w]+',' ','g') ilike concat('% ', query,' %')) AS check FROM fb_search_results ) t" }, { "code": null, "e": 17053, "s": 16803, "text": "In order to solve this problem, we first need to define the criteria for evaluation. We define the rating of the match between the user’s search query and the search result returned by the algorithm (5 being the highest and 1 the lowest) as follows." }, { "code": null, "e": 17469, "s": 17053, "text": "If there is no match, a rating of 1 is given.If the match happens after the first 10 characters of the query, then the rating is 2.If the match happens between the 6 to 10 characters, then the rating is 3.If the match is within the first five characters, but not in the first three characters, then a rating of 4 is givenIf the match is in the first three characters, then the highest possible rating of 5 is given." }, { "code": null, "e": 17515, "s": 17469, "text": "If there is no match, a rating of 1 is given." }, { "code": null, "e": 17602, "s": 17515, "text": "If the match happens after the first 10 characters of the query, then the rating is 2." }, { "code": null, "e": 17677, "s": 17602, "text": "If the match happens between the 6 to 10 characters, then the rating is 3." }, { "code": null, "e": 17794, "s": 17677, "text": "If the match is within the first five characters, but not in the first three characters, then a rating of 4 is given" }, { "code": null, "e": 17889, "s": 17794, "text": "If the match is in the first three characters, then the highest possible rating of 5 is given." }, { "code": null, "e": 18533, "s": 17889, "text": "Based on these ratings, we evaluate each search string. To match the search query and the result, we use the regular expression matching function in SQL. The main query uses this check column in the CASE WHEN statements. This is an open-ended SQL interview question because you were not given the metrics which would differentiate excellent performance from not-so-great one. Therefore, you had to decide on your scale that would show how the performance was. Your scale could be different from the one in the solution above. However, it is important that you explain your assumptions and why you decided to go with a certain evaluation scale." }, { "code": null, "e": 19037, "s": 18533, "text": "These are questions that one can expect to be asked very frequently for a Data Engineer or a Machine Learning Engineer position. Though it might not be out of place in a Data Scientist Interview for positions that require some experience. Data Transformation or more generally ETL (Extract, Transform and Load) is a process used to collect data from various sources (extract), changing it according to the business rules (transform), and then loading such extracted and transformed data into a database." }, { "code": null, "e": 19176, "s": 19037, "text": "When the data is extracted, it is done so from various data sources that, more often than not, store data in completely different formats." }, { "code": null, "e": 19398, "s": 19176, "text": "By transformation, the data takes the format appropriate for reporting and analysis. The data is transformed via data aggregation, filtering, sorting, joining, a calculation based on the rules set for business needs, etc." }, { "code": null, "e": 19497, "s": 19398, "text": "Such data is loaded into another database or table that the analysts or any other users might use." }, { "code": null, "e": 19756, "s": 19497, "text": "The ETL is heavily used in data warehouses, which serves as the central source of the integrated data, with data flowing into it from one or more separate sources. If you want to perform well at the SQL job interview, these are the concepts you need to know:" }, { "code": null, "e": 19796, "s": 19756, "text": "Data Definition Language (DDL) keywords" }, { "code": null, "e": 19838, "s": 19796, "text": "Data Manipulation Language (DML) keywords" }, { "code": null, "e": 19875, "s": 19838, "text": "Data Control Language (DCL) keywords" }, { "code": null, "e": 19919, "s": 19875, "text": "Transaction Control Language (TCL) keywords" }, { "code": null, "e": 19935, "s": 19919, "text": "SQL constraints" }, { "code": null, "e": 19941, "s": 19935, "text": "JOINs" }, { "code": null, "e": 19949, "s": 19941, "text": "indexes" }, { "code": null, "e": 19962, "s": 19949, "text": "transactions" }, { "code": null, "e": 19968, "s": 19962, "text": "views" }, { "code": null, "e": 19991, "s": 19968, "text": "user-defined functions" }, { "code": null, "e": 20009, "s": 19991, "text": "stored procedures" }, { "code": null, "e": 20018, "s": 20009, "text": "triggers" }, { "code": null, "e": 20028, "s": 20018, "text": "variables" }, { "code": null, "e": 20047, "s": 20028, "text": "query optimization" }, { "code": null, "e": 20065, "s": 20047, "text": "Question Examples" }, { "code": null, "e": 20183, "s": 20065, "text": "This is one of the easiest and yet frequently asked questions from the Southwest Airlines Data Science SQL Interview:" }, { "code": null, "e": 20237, "s": 20183, "text": "“What is the difference between DELETE and TRUNCATE?”" }, { "code": null, "e": 20245, "s": 20237, "text": "Answer:" }, { "code": null, "e": 20798, "s": 20245, "text": "DELETE is a DML statement. TRUNCATE is a DDL statement. The DELETE statement can be used to delete all rows or only some rows. To delete some rows, you’ll have to use the WHERE clause. While doing this, every row removed will be logged as an activity by the database. On the other hand, TRUNCATE is used only for deleting the whole table, which will be logged as only one action. That’s why TRUNCATE is faster than DELETE, which shows when deleting a table with a huge amount of data. Also, you can’t use TRUNCATE if there’s a foreign key in the table." }, { "code": null, "e": 20835, "s": 20798, "text": "Another common question to appear is" }, { "code": null, "e": 20896, "s": 20835, "text": "“How do you change a column name by writing a query in SQL?”" }, { "code": null, "e": 21083, "s": 20896, "text": "Answer: Assuming you are using PostgreSQL. For a hypothetical table say product, one of the columns is named year, but I want to rename it to description. The query that will do that is:" }, { "code": null, "e": 21130, "s": 21083, "text": "ALTER TABLE productRENAME year TO description;" }, { "code": null, "e": 21201, "s": 21130, "text": "Another example of Data Transformation SQL Interview question will be:" }, { "code": null, "e": 21241, "s": 21201, "text": "“How do you create a stored procedure?”" }, { "code": null, "e": 21450, "s": 21241, "text": "Answer: We will solve this for Microsoft SQL Server. For example, if you are using a table named employee. Your procedure should help you get the employees that work in a certain department. The code would be" }, { "code": null, "e": 21569, "s": 21450, "text": "CREATE PROCEDURE employee_deparment @deparment nvarchar(50)ASSELECT * FROM employees WHERE department = @departmentGO;" }, { "code": null, "e": 21641, "s": 21569, "text": "Once the procedure is created, I can invoke it in the following manner:" }, { "code": null, "e": 21693, "s": 21641, "text": "EXEC employee_deparment @department = 'Accounting';" }, { "code": null, "e": 22337, "s": 21693, "text": "These questions are designed to test how good you are at database design or database modeling. What is meant by that? You need to show the ability to design and build the database from scratch according to the business processes and business needs. This requires a high level of both technical and business knowledge. You will be working with both technical and non-technical colleagues. So, you need to understand both the business side of their requirement and how to, in the soundest way, technically cater to their business needs regarding the data. Generally, this is a process that goes through these steps (at least in the ideal world):" }, { "code": null, "e": 22490, "s": 22337, "text": "defining the database purposecollecting and defining users’ requirementscreating a conceptual modelcreating the logical modelcreating the physical model" }, { "code": null, "e": 22520, "s": 22490, "text": "defining the database purpose" }, { "code": null, "e": 22564, "s": 22520, "text": "collecting and defining users’ requirements" }, { "code": null, "e": 22592, "s": 22564, "text": "creating a conceptual model" }, { "code": null, "e": 22619, "s": 22592, "text": "creating the logical model" }, { "code": null, "e": 22647, "s": 22619, "text": "creating the physical model" }, { "code": null, "e": 22665, "s": 22647, "text": "Question Examples" }, { "code": null, "e": 22751, "s": 22665, "text": "One of the typical questions that occur in the SQL interviews is this one by Audible:" }, { "code": null, "e": 22822, "s": 22751, "text": "“Can you walk us through how you would build a recommendation system?”" }, { "code": null, "e": 22963, "s": 22822, "text": "Answer: Since there is a wide variety of approaches to answer this question, we will leave you to come up with your own way of building one." }, { "code": null, "e": 23053, "s": 22963, "text": "The database design question can also include SQL coding, such as this one from Facebook:" }, { "code": null, "e": 23270, "s": 23053, "text": "“Write a SQL query to compute a frequency table of a certain attribute involving two joins. What if you want to GROUP or ORDER BY some attribute? What changes would you need to make? How would you account for NULLs?”" }, { "code": null, "e": 23358, "s": 23270, "text": "Answer: Due to the nature of the question, we will let you answer this one on your own." }, { "code": null, "e": 23926, "s": 23358, "text": "These are questions that require SQL knowledge, but usually, what is being asked may not be widely applicable in practice. These questions come up during the interview because even though as a software engineer, you might not be writing SQL codes every day, you still need to interact with your peers who use SQL daily and follow what they are trying to achieve and implement their needs and SQL logic into the software development. These questions test your logical skills more than coding skills. One such question that could be asked during your interview could be" }, { "code": null, "e": 24026, "s": 23926, "text": "Imagine you’re working with two tables. The one is the product table, which has the following data:" }, { "code": null, "e": 24029, "s": 24026, "text": "id" }, { "code": null, "e": 24042, "s": 24029, "text": "product_name" }, { "code": null, "e": 24058, "s": 24042, "text": "manufacturer_id" }, { "code": null, "e": 24116, "s": 24058, "text": "The second table is manufacturer with the following data:" }, { "code": null, "e": 24119, "s": 24116, "text": "id" }, { "code": null, "e": 24132, "s": 24119, "text": "manufacturer" }, { "code": null, "e": 24196, "s": 24132, "text": "There are 8 records in the first table and 4 in the second one." }, { "code": null, "e": 24246, "s": 24196, "text": "How many rows will the following SQL code return:" }, { "code": null, "e": 24281, "s": 24246, "text": "SELECT *FROM product, manufacturer" }, { "code": null, "e": 24549, "s": 24281, "text": "Answer: The query will return 32 rows. Whenever the WHERE clause is omitted, the default result is CROSS JOIN or a Cartesian product. This means the query will return every combination of rows from the first table with every combination of rows from the second table." }, { "code": null, "e": 24939, "s": 24549, "text": "FAANG is an acronym for the five most famous tech companies: Facebook, Amazon, Apple, Netflix, and Google. Why would you specially prepare for the questions asked by those companies, except being in awe of the possibility of working for them? They might seem or even be attractive, but that is not the main reason why you would pay special attention if you want to work at those companies." }, { "code": null, "e": 25548, "s": 24939, "text": "The main reason is their SQL interview questions are a bit different. As tech companies, their business heavily relies on data. And where there is data, there is SQL which the FAANG companies often use. Hence they want to be absolutely certain that their employees know SQL in depth. You will always get SQL interview questions with a little twist. The twist being their questions are more practical and concerning a case study with real problems and data a certain company is facing in their everyday business. These are arguably the next level of the Open Ended SQL Interview Questions that we saw earlier." }, { "code": null, "e": 25589, "s": 25548, "text": "Have a look at this example from Google:" }, { "code": null, "e": 26076, "s": 25589, "text": "“Find the email activity rank for each user. Email activity rank is defined by the total number of emails sent. The user with the highest number of emails sent will have a rank of 1, and so on. Output the user, total emails, and their activity rank. Order records by the total emails in descending order. Sort users with the same rank score in alphabetical order.In your rankings, return a unique value (i.e., a unique percentile) even if multiple users have the same number of emails.”" }, { "code": null, "e": 26161, "s": 26076, "text": "Solution: To answer this question, you’ll need to use the google_gmail_emails table." }, { "code": null, "e": 26334, "s": 26161, "text": "SELECT from_user, count(*) as total_emails, row_number() OVER ( order by count(*) desc) FROM google_gmail_emails GROUP BY from_user order by 3, 1" }, { "code": null, "e": 26567, "s": 26334, "text": "As you can see, this question tests your aggregate functions and window functions knowledge, along with the GROUP BY and ORDER BY clauses. But they also do that on real-life problems you’ll probably have to work on if you get a job." }, { "code": null, "e": 26633, "s": 26567, "text": "Here is another example of such question, this time from Netflix:" }, { "code": null, "e": 26793, "s": 26633, "text": "“Find the nominee who has won the most Oscars.Output the nominee’s name alongside the result.Order the result based on the number of wins in descending order.”" }, { "code": null, "e": 26875, "s": 26793, "text": "Solution: To answer this question, you will need to use the oscar_nominees table." }, { "code": null, "e": 27016, "s": 26875, "text": "SELECT nominee, count(winner) AS n_times_wonFROM oscar_nomineesWHERE winner = trueGROUP BY nomineeORDER BY n_times_won DESC" }, { "code": null, "e": 27263, "s": 27016, "text": "Again, this question tests some usual concepts. But the problem set is something that you expect to work on a daily basis. If you work at Netflix on an SQL job, you will for sure analyze some data that contains some Oscar nominations and winners." }, { "code": null, "e": 27948, "s": 27263, "text": "You would have probably noticed that the technical SQL interview questions overlap with other SQL questions. That is because one does not work without the other. There is no point in knowing the theory without being able to put it into practice, i.e., the SQL code. Conversely, you need to describe the technical concepts behind the code that you wrote. While the SQL concepts you should know depend on your position, years of experience, and the company you want to work at, we have looked at some concepts that are useful across roles. While this is not an exhaustive list, it is definitely something that you are expected to know if you are attending an SQL Data Science Interview." }, { "code": null, "e": 27963, "s": 27948, "text": "SQL definition" }, { "code": null, "e": 28114, "s": 27963, "text": "SQL stands for “Structured Query Language”. It is a programming language used for creating database structure, retrieving and manipulating data in it." }, { "code": null, "e": 28160, "s": 28114, "text": "Types of the SQL commands Relational database" }, { "code": null, "e": 28239, "s": 28160, "text": "Data Definition Language (DDL)- CREATE- ALTER- DROP- RENAME- TRUNCATE- COMMENT" }, { "code": null, "e": 28273, "s": 28239, "text": "Data Query Language (DQL)- SELECT" }, { "code": null, "e": 28369, "s": 28273, "text": "Data Manipulation Language (DML)- INSERT- UPDATE- DELETE- MERGE- CALL- EXPLAIN PLAN- LOCK TABLE" }, { "code": null, "e": 28412, "s": 28369, "text": "Data Control Language (DCL)- GRANT- REVOKE" }, { "code": null, "e": 28432, "s": 28412, "text": "Relational database" }, { "code": null, "e": 28767, "s": 28432, "text": "A relational database is one based on the relational data model. This means the database is a collection of relations. Those relations are shown as tables, which consist of columns, rows, and values. The relational database aims to minimize or completely avoid data redundancy, leading to data integrity and speeding up its retrieval." }, { "code": null, "e": 28797, "s": 28767, "text": "Relationships in the database" }, { "code": null, "e": 28926, "s": 28797, "text": "The relationship defines the type of connection between the tables in the database. There are three main types of relationships:" }, { "code": null, "e": 28956, "s": 28926, "text": "one-to-one relationship (1:1)" }, { "code": null, "e": 29021, "s": 28956, "text": "one-to-many relationship (1:N) or many-to-one relationship (N:1)" }, { "code": null, "e": 29053, "s": 29021, "text": "many-to-many relationship (M:N)" }, { "code": null, "e": 29076, "s": 29053, "text": "Database normalization" }, { "code": null, "e": 29231, "s": 29076, "text": "Database normalization is a process of organizing data in the database to achieve its purpose: data integrity, its non-redundancy, and speed of retrieval." }, { "code": null, "e": 29243, "s": 29231, "text": "Constraints" }, { "code": null, "e": 29388, "s": 29243, "text": "The constraints are the rules that define what type of data can and can’t be entered as a value in the database. The most common attributes are:" }, { "code": null, "e": 29397, "s": 29388, "text": "NOT NULL" }, { "code": null, "e": 29403, "s": 29397, "text": "CHECK" }, { "code": null, "e": 29410, "s": 29403, "text": "UNIQUE" }, { "code": null, "e": 29422, "s": 29410, "text": "PRIMARY KEY" }, { "code": null, "e": 29434, "s": 29422, "text": "FOREIGN KEY" }, { "code": null, "e": 29442, "s": 29434, "text": "Indexes" }, { "code": null, "e": 29596, "s": 29442, "text": "The indexes are structures in the databases created to tune the database performance. They are used to speed up data retrieval. The types of indexes are:" }, { "code": null, "e": 29612, "s": 29596, "text": "clustered index" }, { "code": null, "e": 29632, "s": 29612, "text": "non-clustered index" }, { "code": null, "e": 29645, "s": 29632, "text": "unique index" }, { "code": null, "e": 29660, "s": 29645, "text": "filtered index" }, { "code": null, "e": 29678, "s": 29660, "text": "columnstore index" }, { "code": null, "e": 29689, "s": 29678, "text": "hash index" }, { "code": null, "e": 29694, "s": 29689, "text": "View" }, { "code": null, "e": 29792, "s": 29694, "text": "A view is a virtual table containing data from one or more tables resulting from a SQL statement." }, { "code": null, "e": 29809, "s": 29792, "text": "Stored procedure" }, { "code": null, "e": 29952, "s": 29809, "text": "A stored procedure is an SQL code consisting of one or several SQL statements that are saved and can be called and executed whenever required." }, { "code": null, "e": 29960, "s": 29952, "text": "Trigger" }, { "code": null, "e": 30104, "s": 29960, "text": "A trigger is a special type of a stored procedure. It is automatically executed (triggered) whenever some special event occurs in the database." }, { "code": null, "e": 30115, "s": 30104, "text": "Inner join" }, { "code": null, "e": 30223, "s": 30115, "text": "An Inner join returns only those rows where the data from one table matches the data from the second table." }, { "code": null, "e": 30239, "s": 30223, "text": "Left outer join" }, { "code": null, "e": 30370, "s": 30239, "text": "The left join is a table join that will retrieve all the rows from the left table and only the matching rows from the right table." }, { "code": null, "e": 30387, "s": 30370, "text": "Right outer join" }, { "code": null, "e": 30503, "s": 30387, "text": "This join is the one that returns all the rows from the right table and only the matching rows from the left table." }, { "code": null, "e": 30519, "s": 30503, "text": "Full outer join" }, { "code": null, "e": 30658, "s": 30519, "text": "The full outer join will join the data so that the result will include all the rows from one table and all the rows from the second table." }, { "code": null, "e": 30669, "s": 30658, "text": "Cross join" }, { "code": null, "e": 30832, "s": 30669, "text": "This results in a Cartesian product. This means it will return all the combinations of rows from one table with all the combinations of rows from the other table." }, { "code": null, "e": 30838, "s": 30832, "text": "Union" }, { "code": null, "e": 30982, "s": 30838, "text": "This is an SQL command that will combine the result of one query with the result of another query. Therefore, it will show only unique records." }, { "code": null, "e": 30992, "s": 30982, "text": "Union all" }, { "code": null, "e": 31132, "s": 30992, "text": "This one also combines the results from two or more queries. The difference between UNION and UNION ALL is it will also include duplicates." }, { "code": null, "e": 31152, "s": 31132, "text": "Aggregate functions" }, { "code": null, "e": 31291, "s": 31152, "text": "The aggregate functions perform a calculation on a data set and return a single value as a result. Example of the aggregate functions are:" }, { "code": null, "e": 31299, "s": 31291, "text": "COUNT()" }, { "code": null, "e": 31305, "s": 31299, "text": "SUM()" }, { "code": null, "e": 31311, "s": 31305, "text": "MIN()" }, { "code": null, "e": 31317, "s": 31311, "text": "MAX()" }, { "code": null, "e": 31323, "s": 31317, "text": "AVG()" }, { "code": null, "e": 31331, "s": 31323, "text": "STDEV()" }, { "code": null, "e": 31337, "s": 31331, "text": "VAR()" }, { "code": null, "e": 31353, "s": 31337, "text": "GROUP BY clause" }, { "code": null, "e": 31447, "s": 31353, "text": "The GROUP BY clause allows you to group data according to the defined (one or more) criteria." }, { "code": null, "e": 31463, "s": 31447, "text": "DISTINCT clause" }, { "code": null, "e": 31599, "s": 31463, "text": "The DISTINCT clause is a clause that will return only distinct or unique values, i.e., there will be no duplicate values in the result." }, { "code": null, "e": 31612, "s": 31599, "text": "WHERE clause" }, { "code": null, "e": 31689, "s": 31612, "text": "The WHERE clause is used to filter data according to the specified criteria." }, { "code": null, "e": 31703, "s": 31689, "text": "HAVING clause" }, { "code": null, "e": 31974, "s": 31703, "text": "The HAVING clause also filters data according to the specified criteria. The difference compared to the WHERE clause is that the HAVING clause works with the aggregate functions. Therefore, if used, it always follows the GROUP BY clause and precedes the ORDER BY clause." }, { "code": null, "e": 31990, "s": 31974, "text": "ORDER BY clause" }, { "code": null, "e": 32080, "s": 31990, "text": "The ORDER BY clause is used to order the query result according to a certain data column." }, { "code": null, "e": 32095, "s": 32080, "text": "CASE statement" }, { "code": null, "e": 32290, "s": 32095, "text": "The CASE statement returns a defined value based on certain criteria. It is the SQL statement that allows you to apply the IF-THEN logic. Instead of IF, you use WHEN. And for THEN, you use THEN." }, { "code": null, "e": 32299, "s": 32290, "text": "Subquery" }, { "code": null, "e": 32408, "s": 32299, "text": "A subquery is a query found within the query. It can occur in a SELECT clause, FROM clause, or WHERE clause." }, { "code": null, "e": 32412, "s": 32408, "text": "CTE" }, { "code": null, "e": 32629, "s": 32412, "text": "A CTE or a Common Table Expression is a temporary result set returned by a query and used by another query. In that way, it’s similar to subquery. But the main difference is CTE can be named and can reference itself." }, { "code": null, "e": 32646, "s": 32629, "text": "Window functions" }, { "code": null, "e": 33028, "s": 32646, "text": "The window functions are SQL functions performing calculations over the defined set of rows (a window). Compared to the aggregate functions, which return a single value as a result, the window functions allow you to add the aggregated value to each row in a separate column. This means the rows are not grouped and all the rows are kept as a query result. The window functions are:" }, { "code": null, "e": 33041, "s": 33028, "text": "row_number()" }, { "code": null, "e": 33048, "s": 33041, "text": "rank()" }, { "code": null, "e": 33061, "s": 33048, "text": "dense_rank()" }, { "code": null, "e": 33076, "s": 33061, "text": "percent_rank()" }, { "code": null, "e": 33088, "s": 33076, "text": "cume_dist()" }, { "code": null, "e": 33095, "s": 33088, "text": "lead()" }, { "code": null, "e": 33101, "s": 33095, "text": "lag()" }, { "code": null, "e": 33109, "s": 33101, "text": "ntile()" }, { "code": null, "e": 33123, "s": 33109, "text": "first_value()" }, { "code": null, "e": 33136, "s": 33123, "text": "last_value()" }, { "code": null, "e": 33148, "s": 33136, "text": "nth_value()" }, { "code": null, "e": 33154, "s": 33148, "text": "avg()" }, { "code": null, "e": 33162, "s": 33154, "text": "count()" }, { "code": null, "e": 33168, "s": 33162, "text": "min()" }, { "code": null, "e": 33174, "s": 33168, "text": "max()" }, { "code": null, "e": 33180, "s": 33174, "text": "sum()" }, { "code": null, "e": 33497, "s": 33180, "text": "Being good at SQL is the prerequisite to do well at the job interview. However, it is not the only skill. Questions can be tricky, designed to put you off or doubt your knowledge by being seemingly too complicated or too simple. That’s why it’s important to have a clear strategy on what to do in certain situations." }, { "code": null, "e": 33965, "s": 33497, "text": "If you don’t understand what the question is and what is expected from you, you will likely get the wrong answer. To avoid that, make sure you understand what is asked of you. Repeat the requirements out loud and ask the interviewer to confirm you understood the question correctly. Don’t be afraid to do that. The interviewers are people too. They can also unintentionally be unclear, make a mistake, or forget to give you enough details for you to answer correctly." }, { "code": null, "e": 34351, "s": 33965, "text": "Before you start answering, especially if you are writing SQL code, outlay your approach. That way, you will be able to find the solution faster and or find the holes in the code you intended to write. You should do that to allow the interviewer to lead you through in case you missed the point of the question. It is always better to be corrected before presenting the final solution." }, { "code": null, "e": 34562, "s": 34351, "text": "This is something that can help you in writing the problem-solving code. Sometimes, when you clarify how the output should look and compare it with initial data, the approach and the solution reveal themselves." }, { "code": null, "e": 34888, "s": 34562, "text": "At some point, you will need to start writing the code. As we discussed, you should not jump headfirst into it. But you cannot keep procrastinating on the best approach to write it. After you have gone through all those previous steps, and you are still not sure if you have the right solution, simply start writing the code." }, { "code": null, "e": 35334, "s": 34888, "text": "One of the reasons is, sometimes there is no solution at all. Meaning the question is too complex to be solved in the time you’re being given. In such cases, the interviewer is not interested in your solution. Instead, he or she is interested in your way of thinking and how you approach the problem. There are usually multiple ways to use SQL for problem-solving, and this is what some interviewers are interested in: the process, not the goal." }, { "code": null, "e": 35786, "s": 35334, "text": "When you’re writing the code, pay attention to its structure. Divide the code into logical parts. That way, you will make your code easier to read, which is also one of the requirements to get the job. There is no point in writing a correct code that is a mess, and nobody can read it and understand it after you write it. Not even you!! If your code is divided into logical parts, it will be easier for you to explain to the interviewer what you did." }, { "code": null, "e": 36340, "s": 35786, "text": "It is also important to have the code optimization in mind. If your code is complex, of course, you are not going to be able to optimize it as you write. But you should pay attention to some general optimization guidelines, so your code is reasonably optimized. You can also discuss with the interviewer what other steps you will have to take to optimize your code in the aftermath. This is also the job requirement, similarly to the previous point. There is no point writing the code that will get you the required result, but takes forever to execute." }, { "code": null, "e": 36913, "s": 36340, "text": "Even if you did not get the required answer, it does not mean you failed the interview. That is why you should always know why you did something and explain why you did it. Maybe you did not get the answer to the question they asked, but you did get the answer to some questions. So make sure that you state your assumption and explain why you did what you did. Again, they may be looking exactly for that: the right reasoning in line with assumptions, even though the assumptions were wrong. That also shows you know what you are doing, even if it is not what they asked." }, { "code": null, "e": 37149, "s": 36913, "text": "Also, one of the reasons for explaining the assumptions is there may be a loophole in the question. So imagine pointing at it right there at the interview by simply explaining why you did something while you thought you were all wrong." }, { "code": null, "e": 37262, "s": 37149, "text": "Here is the video where Nate from StrataScratch shares some tips on how to organize your SQL interview solution:" }, { "code": null, "e": 37359, "s": 37262, "text": "Here are some additional tips that might help you to be a success at the upcoming SQL interview." }, { "code": null, "e": 37605, "s": 37359, "text": "This is important in general, not only for the SQL part of the interview. It is important to be informed about your future employer, their products, and their industry. It is especially important when the SQL questions are regarded. Why is that?" }, { "code": null, "e": 38260, "s": 37605, "text": "As we discussed earlier, the FAANG companies will usually ask you very practical SQL coding questions that will have you use the same data and solve the same problems as you would have to when you get employed. The FAANG companies are not the only ones who do that. So when you prepare for the interview, try to think which data is important to this company, how their database could look like, etc. When you practice the SQL questions, try to find the real questions from the companies you are interested in or at least from their competitors. If the companies are in the same industry, it’s quite likely the data they use will be more or less the same." }, { "code": null, "e": 38711, "s": 38260, "text": "It is quite usual to be asked to write SQL code on a whiteboard. It can be shocking to some people, which is understandable. You are probably used to writing code in a real RDBMS, on real data, which allows you to regularly check if the query works. Not even the greatest masters of SQL can write a code without running it to see if it works at all or if it returns the desired result. However, in the SQL interview, the criteria are a little higher." }, { "code": null, "e": 39148, "s": 38711, "text": "While it can be scary, it is also understandable. Writing the code on a whiteboard shows that you know how to write your code. Reading your (or someone else’s code) is also important. This is the skill that is also tested on a whiteboard. If you can read a code and say if it will give you the desired result without relying on the database to tell you that, then working with a real database and SQL environment will be easier for you." }, { "code": null, "e": 39431, "s": 39148, "text": "We are not talking about your handwriting. There is not much you can do if your handwriting is messy. But that does not mean your code has to be unreadable. When you write a code, try to format it so that it is easier for you and the interviewers to read it and check your solution." }, { "code": null, "e": 39583, "s": 39431, "text": "Code is read more often than it is written. Code should always be written in a way that promotes readability. - Guido Van Rossum, the creator of Python" }, { "code": null, "e": 39897, "s": 39583, "text": "Regularly use spacing and line breaks to make your code easier to read. If you need to (re)name tables and columns, be consistent with the naming convention you choose. Add comments whenever needed. Try to use aliases whenever possible, but try to make them sound logical and not some random decision when you do." }, { "code": null, "e": 39976, "s": 39897, "text": "Here are also some useful tips from Nate on how to organize lengthy SQL codes." }, { "code": null, "e": 40657, "s": 39976, "text": "If you have experience with multiple SQL databases (Oracle, PostgreSQL, Microsoft SQL Server, MySQL), try to adapt and write in a dialect of the database that is used at your future employer. That would be nice and could show your versatility, especially if you know what dialect they prefer. However, if you are familiar with only one dialect, do not think that it is the end of the interview. For example, if you were using only PostgreSQL and the company is using Microsoft SQL Server, there may be different keywords for the same command in those two databases. It is also possible that PostgreSQL has some functions that aren’t allowed in Microsoft SQL Server and vice versa." }, { "code": null, "e": 41182, "s": 40657, "text": "Ask the interviewer if it is possible to write a code in, say, PostgreSQL instead of Microsoft SQL Server since you are more familiar with it. It is always better if you know several dialects. But it is also better if you write in a familiar dialect, even though “the wrong one”, than mess up the code just because you were too afraid to ask if you can write in a dialect you are comfortable with. The differences between the dialects are not that huge. So if you know SQL, you’ll easily and quickly adapt to a new database." }, { "code": null, "e": 41585, "s": 41182, "text": "While the interview is evaluating you, there are other things that employers look for in an employee besides just coding ability. You will be working as a part of a team and hence your ability to confidently put across your ideas, be open to positive feedback about your codes and ability to work as a team is equally important. Employers try to gage these even during something as technical as coding." }, { "code": null, "e": 41994, "s": 41585, "text": "It is vital that you ask for help in case you are stuck. Asking for help shows confidence and is not a sign of weakness. Keep the interviewer in the loop regarding what your thought process is so that she might be able to help you in case you are stuck or omitted some information unintentionally. Listen to any explanations provided to ensure that you have taken care of all the edge cases that might arise." }, { "code": null, "e": 42444, "s": 41994, "text": "These are skills that every Data Scientist must possess and unfortunately not a lot of candidates focus on them. An interviewer is more likely to hire a Data Scientist with sound basic understanding of SQL and willing to adapt to changes and pick up additional skills on the way over a prodigious but rigid one. The employer is looking at the potential for a long term relationship. If you give the right signals, you might just land your dream job." }, { "code": null, "e": 42515, "s": 42444, "text": "Check out these 5 tips on how to prepare for a Data Science interview." }, { "code": null, "e": 42698, "s": 42515, "text": "We have also gathered some advanced level SQL questions asked by real companies in 2021 that you can find in our Advanced SQL Interview Questions You Must Know How to Answer article." }, { "code": null, "e": 43107, "s": 42698, "text": "In this article, we looked at the various aspects of an SQL Data Science Interview. We started off by understanding why SQL is so popular in the Data Science world and the different roles that are available in the industry. We then provided a detailed overview of the type of questions that you can expect for each position and what to learn for your becoming proficient with SQL for Data Science Interviews." }, { "code": null, "e": 43717, "s": 43107, "text": "Even if you have just started with SQL, all that it takes to become interview ready is persistence, patience and lots of practice. If you do not have much real-life experience with SQL, it is very important that you practice writing SQL codes. Do it a lot, and regularly. Continuity is very important. Try to answer as many as possible SQL interview questions, be it hypothetical or, even better, the real ones from the company you want to work at. Only by writing a lot of code, you’ll gain experience, grasp some typical problems that need to be solved by SQL, and the syntax will become like second nature." }, { "code": null, "e": 44273, "s": 43717, "text": "Even if you are vastly experienced in SQL and use it in a business environment, it is always good to prepare for an interview and brush up your skills. Nobody knows everything about SQL. Generally, people know what they need, what they regularly use every day. So it is possible that after several years at your job, you became a master of a certain aspect of SQL. Do not let it make you think you know it all. It could be that your new job will be asking you to know some different SQL functions and possibilities, the ones you are not exactly versed at." } ]
Difference between List and Set in Java
List and Set both interface belongs to the Collection framework. Both interfaces extend the Collection interface. They both are used to store a collection of objects as a single unit. Before jdk1.2, we used to use Arrays, Vectors, and Hashtable for grouping objects as a single unit. import java.util.List; import java.util.ArrayList; import java.util.LinkedList; public class ListExample { public static void main(String[] args) { List<String> al = new ArrayList<String>(); al.add("BMW"); al.add("Audi"); al.add("BMW"); System.out.println("List Elements: "); System.out.print(al); } } List Elements: [BMW, Audi, BMW] import java.util.Set; import java.util.HashSet; import java.util.TreeSet; public class SetExample { public static void main(String args[]) { int count[] = {2, 4, 3, 5}; Set<Integer> hset = new HashSet<Integer>(); try{ for(int i = 0; i<4; i++){ hset.add(count[i]); } System.out.println(hset); } catch(Exception e){ e.printStackTrace(); } } } [2, 4, 3, 5]
[ { "code": null, "e": 1247, "s": 1062, "text": "List and Set both interface belongs to the Collection framework. Both interfaces extend the Collection interface. They both are used to store a collection of objects as a single unit. " }, { "code": null, "e": 1348, "s": 1247, "text": "Before jdk1.2, we used to use Arrays, Vectors, and Hashtable for grouping objects as a single unit. " }, { "code": null, "e": 1692, "s": 1348, "text": "import java.util.List;\nimport java.util.ArrayList;\nimport java.util.LinkedList;\npublic class ListExample {\n public static void main(String[] args) {\n List<String> al = new ArrayList<String>();\n al.add(\"BMW\");\n al.add(\"Audi\");\n al.add(\"BMW\");\n System.out.println(\"List Elements: \");\n System.out.print(al);\n }\n}" }, { "code": null, "e": 1724, "s": 1692, "text": "List Elements:\n[BMW, Audi, BMW]" }, { "code": null, "e": 2155, "s": 1724, "text": "import java.util.Set;\nimport java.util.HashSet;\nimport java.util.TreeSet;\npublic class SetExample {\n public static void main(String args[]) {\n int count[] = {2, 4, 3, 5};\n Set<Integer> hset = new HashSet<Integer>();\n try{\n for(int i = 0; i<4; i++){\n hset.add(count[i]);\n }\n System.out.println(hset);\n }\n catch(Exception e){\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 2168, "s": 2155, "text": "[2, 4, 3, 5]" } ]
How to set sql_mode permanently in MySQL?
If you are using Windows Operating System, check your directory my.cnf or my.ini file. mysql> select @@datadir; The following is the output +---------------------------------------------+ | @@datadir | +---------------------------------------------+ | C:\ProgramData\MySQL\MySQL Server 8.0\Data\ | +---------------------------------------------+ 1 row in set (0.00 sec) Reach the above location ‘C:\ProgramData\MySQL\MySQL Server 8.0\Data\”. The screenshot is as follows for my.cnf file Open the my.cnf file and write the sql_mode="TRADITIONAL". The syntax is as follows sql_mode="TRADITIONAL". After that start your server once again.
[ { "code": null, "e": 1149, "s": 1062, "text": "If you are using Windows Operating System, check your directory my.cnf or my.ini file." }, { "code": null, "e": 1174, "s": 1149, "text": "mysql> select @@datadir;" }, { "code": null, "e": 1202, "s": 1174, "text": "The following is the output" }, { "code": null, "e": 1466, "s": 1202, "text": "+---------------------------------------------+\n| @@datadir |\n+---------------------------------------------+\n| C:\\ProgramData\\MySQL\\MySQL Server 8.0\\Data\\ |\n+---------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1583, "s": 1466, "text": "Reach the above location ‘C:\\ProgramData\\MySQL\\MySQL Server 8.0\\Data\\”. The screenshot is as follows for my.cnf file" }, { "code": null, "e": 1667, "s": 1583, "text": "Open the my.cnf file and write the sql_mode=\"TRADITIONAL\". The syntax is as follows" }, { "code": null, "e": 1691, "s": 1667, "text": "sql_mode=\"TRADITIONAL\"." }, { "code": null, "e": 1732, "s": 1691, "text": "After that start your server once again." } ]
Rexx - reverse String
This method returns the characters in a reverse format. reverse(str) str − The source string str − The source string This method returns the characters in a reverse format. /* Main program */ a = "Hello World" say reverse(a) When we run the above program we will get the following result. dlroW olleH Print Add Notes Bookmark this page
[ { "code": null, "e": 2395, "s": 2339, "text": "This method returns the characters in a reverse format." }, { "code": null, "e": 2410, "s": 2395, "text": "reverse(str) \n" }, { "code": null, "e": 2434, "s": 2410, "text": "str − The source string" }, { "code": null, "e": 2458, "s": 2434, "text": "str − The source string" }, { "code": null, "e": 2514, "s": 2458, "text": "This method returns the characters in a reverse format." }, { "code": null, "e": 2569, "s": 2514, "text": "/* Main program */ \na = \"Hello World\" \nsay reverse(a) " }, { "code": null, "e": 2633, "s": 2569, "text": "When we run the above program we will get the following result." }, { "code": null, "e": 2648, "s": 2633, "text": "dlroW olleH \n" }, { "code": null, "e": 2655, "s": 2648, "text": " Print" }, { "code": null, "e": 2666, "s": 2655, "text": " Add Notes" } ]
Learning One-Hot Encoding in Python the Easy Way | by Tanu N Prabhu | Towards Data Science
Let’s understand the situation first and then define one-hot encoding. Sometimes solving a problem is one of the fastest ways to understand the concepts. Alright, let's create a situation first (I just made up the situation). Just a heads up the entire code can be found in my GitHub Repository given below: github.com Let’s say you are solving a simple data science problem. Now, it doesn’t matter what the actual problem is about but you are caught up in a situation where you have a tiny data set which has 7 instances and each of this instance has 4 features. In lame words, the data set has 7 rows and 4 columns. Out of which the three columns are of type object meaning those columns comprise string values. The other column is of type int meaning it has only integer values. Now enough talk, let’s practically see how the data set looks like. Rather than showing you the raw data (.CSV format). I formatted it into a data frame using the pandas library. To be on the safer side, let’s see the data types of the columns. Now the actual situation starts since some learning algorithms work only with numeric data you have to somehow deal with this object data. There are two options to deal with this situation: Delete all the three columns and then go to sleep Read this tutorial and implement one-hot encoding I know option 1 works well, but sometimes you have to focus and work hard for a living. Now the solution to this situation is to convert this object type of data into several binary ones. What I mean by this is look at the data set very closely. The column Favourite Color has 6 unique values such as Red, Orange, Yellow, Green, Purple, and Blue. Now we can transform this feature into a vector of six numerical values as shown below: Similarly don’t you think we can transform the Favourite Day column into a vector of six numerical values too? Because there are 7 unique days in this column such as Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday. Now you might be thinking what about the Attitude column can we not do the same. But the catch point here is no. Don’t do the same. Here we shall learn a new concept called order. Since there are decent, good, better, best and excellent. We shall order them as {decent, good, better, best, excellent} as {1, 2, 3, 4, 5} or {0, 1, 2, 3, 4}. This is because when the ordering of some values matters we can replace those values by keeping only one variable. Remember this technique does not work in all the cases. For example, some of you might think that can’t we use the same technique to fill the values for the other two columns too. By doing so you will certainly decrease the dimensions of the feature vector but it implies that there is an order among the values in that category and it will often confuse the learning algorithm. The learning algorithm will try to find a state or regularity when there is no one and the algorithm will most likely overfit. So think and use this technique wisely. Use this only when the order of the values is important. This technique can be used in the cases of quality of an article, user reviews of a product, taste of food, etc. So knowingly or unknowingly you have learned and mastered the concept of One-hot encoding, and where to use it. This is how you convert the categorical or object type data into numeric type data. Let us see how we can actually code this and come out of this situation. As mentioned earlier, this is a made-up dataset. Created for this tutorial. Nothing personal. import pandas as pd# Creating a list with some values studentID = [1000, 1001, 1002, 1003, 1004, 1005, 1006]color = ['Red', 'Orange', "Yellow", 'Green', 'Yellow', 'Purple', 'Blue']DaysOfTheWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']Attitude = ['Best', 'Decent', 'Better', 'Excellent', 'Excellent', 'Good', 'Best'] Now that we have the list let’s convert this into a data frame. To do this we need to zip all the list values and then store it. # Converting the list into a data frame and simultaneously renaming the columns.df = pd.DataFrame(list(zip(studentID, color, DaysOfTheWeek, Attitude)), columns =['Student ID', 'Favourite Color', 'Favourite Day', 'Attitude'])print(df) This is because in most cases you might get a categorical type of data. But in this, all the three as seen above is of an object type. If this is the case with you then you need to manually convert them to categorical type. # Converting the object type data into categorical data columnfor col in ['Favourite Color','Favourite Day', 'Attitude']: df[col] = df[col].astype('category')print(df.dtypes) As discussed we will be transforming only the Favourite Color and Favourite Day columns to its binary value columns. Rather than manually doing this we can use the pandas get_dummies method. # Assigning the binary values for Favourite Day and Favourite Color columnsdf = pd.get_dummies(data=df,columns=['Favourite Color','Favourite Day'])print(df) By doing so you will obviously increase the dimension of your data set, but your learning algorithm will perform a lot more better. There are two ways you can do this: Manually assigning values using a dictionary. Using LabelEncoder method Option 1 is just of no use because what if you have more than 1000 unique values then you might use a looping statement and make your life complicated. It’s 2020 think smart and use the sklearn library to do this. # Assigning order to the categorical column from sklearn.preprocessing import LabelEncoder# Initializing an object of class LabelEncoderlabelencoder = LabelEncoder() df['Attitude'] = labelencoder.fit_transform(df['Attitude'])print(df) There you go, now you can use your favorite learning algorithm and then tell fit(X, y) or whatever and sleep happily. Alright, guys, I hope you have learned something new today. This is really a very important concept and feature engineering technique that you will come across. This is one of the most commonly asked questions during data science interviews. If you have any doubts regarding this tutorial then the comment section is all yours. Until then stay safe, goodbye. I will see you next time.
[ { "code": null, "e": 480, "s": 172, "text": "Let’s understand the situation first and then define one-hot encoding. Sometimes solving a problem is one of the fastest ways to understand the concepts. Alright, let's create a situation first (I just made up the situation). Just a heads up the entire code can be found in my GitHub Repository given below:" }, { "code": null, "e": 491, "s": 480, "text": "github.com" }, { "code": null, "e": 1133, "s": 491, "text": "Let’s say you are solving a simple data science problem. Now, it doesn’t matter what the actual problem is about but you are caught up in a situation where you have a tiny data set which has 7 instances and each of this instance has 4 features. In lame words, the data set has 7 rows and 4 columns. Out of which the three columns are of type object meaning those columns comprise string values. The other column is of type int meaning it has only integer values. Now enough talk, let’s practically see how the data set looks like. Rather than showing you the raw data (.CSV format). I formatted it into a data frame using the pandas library." }, { "code": null, "e": 1199, "s": 1133, "text": "To be on the safer side, let’s see the data types of the columns." }, { "code": null, "e": 1389, "s": 1199, "text": "Now the actual situation starts since some learning algorithms work only with numeric data you have to somehow deal with this object data. There are two options to deal with this situation:" }, { "code": null, "e": 1439, "s": 1389, "text": "Delete all the three columns and then go to sleep" }, { "code": null, "e": 1489, "s": 1439, "text": "Read this tutorial and implement one-hot encoding" }, { "code": null, "e": 1924, "s": 1489, "text": "I know option 1 works well, but sometimes you have to focus and work hard for a living. Now the solution to this situation is to convert this object type of data into several binary ones. What I mean by this is look at the data set very closely. The column Favourite Color has 6 unique values such as Red, Orange, Yellow, Green, Purple, and Blue. Now we can transform this feature into a vector of six numerical values as shown below:" }, { "code": null, "e": 2158, "s": 1924, "text": "Similarly don’t you think we can transform the Favourite Day column into a vector of six numerical values too? Because there are 7 unique days in this column such as Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday." }, { "code": null, "e": 2498, "s": 2158, "text": "Now you might be thinking what about the Attitude column can we not do the same. But the catch point here is no. Don’t do the same. Here we shall learn a new concept called order. Since there are decent, good, better, best and excellent. We shall order them as {decent, good, better, best, excellent} as {1, 2, 3, 4, 5} or {0, 1, 2, 3, 4}." }, { "code": null, "e": 2613, "s": 2498, "text": "This is because when the ordering of some values matters we can replace those values by keeping only one variable." }, { "code": null, "e": 3329, "s": 2613, "text": "Remember this technique does not work in all the cases. For example, some of you might think that can’t we use the same technique to fill the values for the other two columns too. By doing so you will certainly decrease the dimensions of the feature vector but it implies that there is an order among the values in that category and it will often confuse the learning algorithm. The learning algorithm will try to find a state or regularity when there is no one and the algorithm will most likely overfit. So think and use this technique wisely. Use this only when the order of the values is important. This technique can be used in the cases of quality of an article, user reviews of a product, taste of food, etc." }, { "code": null, "e": 3598, "s": 3329, "text": "So knowingly or unknowingly you have learned and mastered the concept of One-hot encoding, and where to use it. This is how you convert the categorical or object type data into numeric type data. Let us see how we can actually code this and come out of this situation." }, { "code": null, "e": 3692, "s": 3598, "text": "As mentioned earlier, this is a made-up dataset. Created for this tutorial. Nothing personal." }, { "code": null, "e": 4048, "s": 3692, "text": "import pandas as pd# Creating a list with some values studentID = [1000, 1001, 1002, 1003, 1004, 1005, 1006]color = ['Red', 'Orange', \"Yellow\", 'Green', 'Yellow', 'Purple', 'Blue']DaysOfTheWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']Attitude = ['Best', 'Decent', 'Better', 'Excellent', 'Excellent', 'Good', 'Best']" }, { "code": null, "e": 4177, "s": 4048, "text": "Now that we have the list let’s convert this into a data frame. To do this we need to zip all the list values and then store it." }, { "code": null, "e": 4411, "s": 4177, "text": "# Converting the list into a data frame and simultaneously renaming the columns.df = pd.DataFrame(list(zip(studentID, color, DaysOfTheWeek, Attitude)), columns =['Student ID', 'Favourite Color', 'Favourite Day', 'Attitude'])print(df)" }, { "code": null, "e": 4635, "s": 4411, "text": "This is because in most cases you might get a categorical type of data. But in this, all the three as seen above is of an object type. If this is the case with you then you need to manually convert them to categorical type." }, { "code": null, "e": 4813, "s": 4635, "text": "# Converting the object type data into categorical data columnfor col in ['Favourite Color','Favourite Day', 'Attitude']: df[col] = df[col].astype('category')print(df.dtypes)" }, { "code": null, "e": 5004, "s": 4813, "text": "As discussed we will be transforming only the Favourite Color and Favourite Day columns to its binary value columns. Rather than manually doing this we can use the pandas get_dummies method." }, { "code": null, "e": 5161, "s": 5004, "text": "# Assigning the binary values for Favourite Day and Favourite Color columnsdf = pd.get_dummies(data=df,columns=['Favourite Color','Favourite Day'])print(df)" }, { "code": null, "e": 5293, "s": 5161, "text": "By doing so you will obviously increase the dimension of your data set, but your learning algorithm will perform a lot more better." }, { "code": null, "e": 5329, "s": 5293, "text": "There are two ways you can do this:" }, { "code": null, "e": 5375, "s": 5329, "text": "Manually assigning values using a dictionary." }, { "code": null, "e": 5401, "s": 5375, "text": "Using LabelEncoder method" }, { "code": null, "e": 5615, "s": 5401, "text": "Option 1 is just of no use because what if you have more than 1000 unique values then you might use a looping statement and make your life complicated. It’s 2020 think smart and use the sklearn library to do this." }, { "code": null, "e": 5850, "s": 5615, "text": "# Assigning order to the categorical column from sklearn.preprocessing import LabelEncoder# Initializing an object of class LabelEncoderlabelencoder = LabelEncoder() df['Attitude'] = labelencoder.fit_transform(df['Attitude'])print(df)" }, { "code": null, "e": 5968, "s": 5850, "text": "There you go, now you can use your favorite learning algorithm and then tell fit(X, y) or whatever and sleep happily." } ]
Angular PrimeNG Paginator Component - GeeksforGeeks
03 Oct, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Paginator component in Angular PrimeNG. We will also learn about the properties, events & styling along with their syntaxes that will be used in the code. Paginator component: It is used to display content in paged format. Properties: totalRecords: It is the total number of total records pages to be shown. It is of number datatype, the default value is 0. rows: It is the data count to display per page. It is of number datatype, the default value is 0. first: It is the zero-relative number of the first row to be displayed. It is of number datatype, the default value is 0. pageLinkSize: It sets the number of page links to display. It is of number datatype, the default value is 5. rowsPerPageOptions: It is the array of integer/object values to display inside rows per page dropdown. It is of array data type, the default value is null. style: It is an inline style of the component. It is of string data type, the default value is null. styleClass: It is the style class of the component. It is of string data type, the default value is null. alwaysShow: It specifies whether to show it even there is only one page. It is of boolean data type, the default value is true. showFirstLastIcon: It shows that the icons are displayed on the paginator to go first and the last page. It is of boolean data type, the default value is true. templateLeft: It is the template instance to inject into the left side of the paginator. It is of TemplateRef data type, the default value is null. templateRight: It is the template instance to inject into the right side of the paginator. It is of TemplateRef data type, the default value is null. dropdownItemTemplate: It is the template instance to inject into the dropdown item inside the paginator. It is of TemplateRef data type, the default value is null. dropdownAppendTo: It is the target element to attach the dropdown overlay. It can accept any type of data & the default value is null. dropdownScrollHeight: It is the dropdown height of the viewport in pixels, a scrollbar is defined if the height of the list exceeds this value. It is of string data type, the default value is 200px. currentPageReportTemplate: It is the template of the current page report element. It is of string data type, the default value is ({currentPage} of {totalPages}). showCurrentPageReport: It specifies whether to display the current page report. It is of boolean data type, the default value is false. showJumpToPageDropdown: It specifies whether to display a dropdown to navigate to any page. It is of boolean data type, the default value is false. showPageLinks: It specifies whether to show page links. It is of boolean data type, the default value is true. Events: onPageChange: It is a callback that is fired when the page changes in the element. Styling: p-paginator: It is the Container element. p-paginator-first: It is the first-page element. p-paginator-prev: It is the previous page element. p-paginator-pages: It is the container of page links. p-paginator-page: It is the page link. p-paginator-next: It is the next page element. p-paginator-last: It is the last page element. p-paginator-rpp-options: It is the rows per page dropdown. p-paginator-page-options: It is the jump to per page dropdown. Creating Angular application & module installation: Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: It will look like the following: Example 1: This is the basic example that illustrates how to use the Paginator component. We have used row & totalRecord property that will give the information about data count to be rendered per page & a total number of records respectively. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG Paginator Component</h5><p-paginator [rows]="1" [totalRecords]="15"></p-paginator> app.component.ts import { Component } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.scss"],})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { PaginatorModule } from "primeng/paginator"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, PaginatorModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Example 2: In this example, we will use the pageLinkSize property in the paginator Component with rowsPerPageOptions dropdown. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG Paginator Component</h5><p-paginator [pageLinkSize]="10" [rows]="1" [totalRecords]="25" [rowsPerPageOptions]="[10,20,30]"></p-paginator> app.component.ts import { Component } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.scss"],})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { PaginatorModule } from "primeng/paginator"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, PaginatorModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Reference: https://primefaces.org/primeng/showcase/#/paginator Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Angular Libraries For Web Developers How to use <mat-chip-list> and <mat-chip> in Angular Material ? How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular 10 (blur) Event Angular PrimeNG Dropdown Component Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25109, "s": 25081, "text": "\n03 Oct, 2021" }, { "code": null, "e": 25509, "s": 25109, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Paginator component in Angular PrimeNG. We will also learn about the properties, events & styling along with their syntaxes that will be used in the code." }, { "code": null, "e": 25577, "s": 25509, "text": "Paginator component: It is used to display content in paged format." }, { "code": null, "e": 25589, "s": 25577, "text": "Properties:" }, { "code": null, "e": 25712, "s": 25589, "text": "totalRecords: It is the total number of total records pages to be shown. It is of number datatype, the default value is 0." }, { "code": null, "e": 25810, "s": 25712, "text": "rows: It is the data count to display per page. It is of number datatype, the default value is 0." }, { "code": null, "e": 25932, "s": 25810, "text": "first: It is the zero-relative number of the first row to be displayed. It is of number datatype, the default value is 0." }, { "code": null, "e": 26041, "s": 25932, "text": "pageLinkSize: It sets the number of page links to display. It is of number datatype, the default value is 5." }, { "code": null, "e": 26197, "s": 26041, "text": "rowsPerPageOptions: It is the array of integer/object values to display inside rows per page dropdown. It is of array data type, the default value is null." }, { "code": null, "e": 26298, "s": 26197, "text": "style: It is an inline style of the component. It is of string data type, the default value is null." }, { "code": null, "e": 26404, "s": 26298, "text": "styleClass: It is the style class of the component. It is of string data type, the default value is null." }, { "code": null, "e": 26532, "s": 26404, "text": "alwaysShow: It specifies whether to show it even there is only one page. It is of boolean data type, the default value is true." }, { "code": null, "e": 26692, "s": 26532, "text": "showFirstLastIcon: It shows that the icons are displayed on the paginator to go first and the last page. It is of boolean data type, the default value is true." }, { "code": null, "e": 26840, "s": 26692, "text": "templateLeft: It is the template instance to inject into the left side of the paginator. It is of TemplateRef data type, the default value is null." }, { "code": null, "e": 26990, "s": 26840, "text": "templateRight: It is the template instance to inject into the right side of the paginator. It is of TemplateRef data type, the default value is null." }, { "code": null, "e": 27154, "s": 26990, "text": "dropdownItemTemplate: It is the template instance to inject into the dropdown item inside the paginator. It is of TemplateRef data type, the default value is null." }, { "code": null, "e": 27289, "s": 27154, "text": "dropdownAppendTo: It is the target element to attach the dropdown overlay. It can accept any type of data & the default value is null." }, { "code": null, "e": 27488, "s": 27289, "text": "dropdownScrollHeight: It is the dropdown height of the viewport in pixels, a scrollbar is defined if the height of the list exceeds this value. It is of string data type, the default value is 200px." }, { "code": null, "e": 27651, "s": 27488, "text": "currentPageReportTemplate: It is the template of the current page report element. It is of string data type, the default value is ({currentPage} of {totalPages})." }, { "code": null, "e": 27787, "s": 27651, "text": "showCurrentPageReport: It specifies whether to display the current page report. It is of boolean data type, the default value is false." }, { "code": null, "e": 27935, "s": 27787, "text": "showJumpToPageDropdown: It specifies whether to display a dropdown to navigate to any page. It is of boolean data type, the default value is false." }, { "code": null, "e": 28046, "s": 27935, "text": "showPageLinks: It specifies whether to show page links. It is of boolean data type, the default value is true." }, { "code": null, "e": 28054, "s": 28046, "text": "Events:" }, { "code": null, "e": 28137, "s": 28054, "text": "onPageChange: It is a callback that is fired when the page changes in the element." }, { "code": null, "e": 28148, "s": 28139, "text": "Styling:" }, { "code": null, "e": 28190, "s": 28148, "text": "p-paginator: It is the Container element." }, { "code": null, "e": 28239, "s": 28190, "text": "p-paginator-first: It is the first-page element." }, { "code": null, "e": 28290, "s": 28239, "text": "p-paginator-prev: It is the previous page element." }, { "code": null, "e": 28344, "s": 28290, "text": "p-paginator-pages: It is the container of page links." }, { "code": null, "e": 28383, "s": 28344, "text": "p-paginator-page: It is the page link." }, { "code": null, "e": 28430, "s": 28383, "text": "p-paginator-next: It is the next page element." }, { "code": null, "e": 28477, "s": 28430, "text": "p-paginator-last: It is the last page element." }, { "code": null, "e": 28536, "s": 28477, "text": "p-paginator-rpp-options: It is the rows per page dropdown." }, { "code": null, "e": 28599, "s": 28536, "text": "p-paginator-page-options: It is the jump to per page dropdown." }, { "code": null, "e": 28651, "s": 28599, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 28718, "s": 28651, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 28733, "s": 28718, "text": "ng new appname" }, { "code": null, "e": 28830, "s": 28733, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 28841, "s": 28830, "text": "cd appname" }, { "code": null, "e": 28890, "s": 28841, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 28947, "s": 28890, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 28999, "s": 28947, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 29244, "s": 28999, "text": "Example 1: This is the basic example that illustrates how to use the Paginator component. We have used row & totalRecord property that will give the information about data count to be rendered per page & a total number of records respectively. " }, { "code": null, "e": 29263, "s": 29244, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Paginator Component</h5><p-paginator [rows]=\"1\" [totalRecords]=\"15\"></p-paginator>", "e": 29380, "s": 29263, "text": null }, { "code": null, "e": 29397, "s": 29380, "text": "app.component.ts" }, { "code": "import { Component } from \"@angular/core\"; @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\", styleUrls: [\"./app.component.scss\"],})export class AppComponent {}", "e": 29581, "s": 29397, "text": null }, { "code": null, "e": 29595, "s": 29581, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { PaginatorModule } from \"primeng/paginator\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, PaginatorModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 30121, "s": 29595, "text": null }, { "code": null, "e": 30129, "s": 30121, "text": "Output:" }, { "code": null, "e": 30256, "s": 30129, "text": "Example 2: In this example, we will use the pageLinkSize property in the paginator Component with rowsPerPageOptions dropdown." }, { "code": null, "e": 30275, "s": 30256, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Paginator Component</h5><p-paginator [pageLinkSize]=\"10\" [rows]=\"1\" [totalRecords]=\"25\" [rowsPerPageOptions]=\"[10,20,30]\"></p-paginator>", "e": 30450, "s": 30275, "text": null }, { "code": null, "e": 30467, "s": 30450, "text": "app.component.ts" }, { "code": "import { Component } from \"@angular/core\"; @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\", styleUrls: [\"./app.component.scss\"],})export class AppComponent {}", "e": 30651, "s": 30467, "text": null }, { "code": null, "e": 30665, "s": 30651, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { PaginatorModule } from \"primeng/paginator\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, PaginatorModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 31191, "s": 30665, "text": null }, { "code": null, "e": 31199, "s": 31191, "text": "Output:" }, { "code": null, "e": 31262, "s": 31199, "text": "Reference: https://primefaces.org/primeng/showcase/#/paginator" }, { "code": null, "e": 31278, "s": 31262, "text": "Angular-PrimeNG" }, { "code": null, "e": 31288, "s": 31278, "text": "AngularJS" }, { "code": null, "e": 31305, "s": 31288, "text": "Web Technologies" }, { "code": null, "e": 31403, "s": 31305, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31412, "s": 31403, "text": "Comments" }, { "code": null, "e": 31425, "s": 31412, "text": "Old Comments" }, { "code": null, "e": 31469, "s": 31425, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 31533, "s": 31469, "text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?" }, { "code": null, "e": 31586, "s": 31533, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 31610, "s": 31586, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 31645, "s": 31610, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 31687, "s": 31645, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 31720, "s": 31687, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31763, "s": 31720, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31825, "s": 31763, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Encryption of files
In Python, it is possible to encrypt and decrypt files before transmitting to a communication channel. For this, you will have to use the plugin PyCrypto. You can installation this plugin using the command given below. pip install pycrypto The program code for encrypting the file with password protector is mentioned below − # =================Other Configuration================ # Usages : usage = "usage: %prog [options] " # Version Version="%prog 0.0.1" # ==================================================== # Import Modules import optparse, sys,os from toolkit import processor as ps def main(): parser = optparse.OptionParser(usage = usage,version = Version) parser.add_option( '-i','--input',type = 'string',dest = 'inputfile', help = "File Input Path For Encryption", default = None) parser.add_option( '-o','--output',type = "string",dest = 'outputfile', help = "File Output Path For Saving Encrypter Cipher",default = ".") parser.add_option( '-p','--password',type = "string",dest = 'password', help = "Provide Password For Encrypting File",default = None) parser.add_option( '-p','--password',type = "string",dest = 'password', help = "Provide Password For Encrypting File",default = None) (options, args)= parser.parse_args() # Input Conditions Checkings if not options.inputfile or not os.path.isfile(options.inputfile): print " [Error] Please Specify Input File Path" exit(0) if not options.outputfile or not os.path.isdir(options.outputfile): print " [Error] Please Specify Output Path" exit(0) if not options.password: print " [Error] No Password Input" exit(0) inputfile = options.inputfile outputfile = os.path.join( options.outputfile,os.path.basename(options.inputfile).split('.')[0]+'.ssb') password = options.password base = os.path.basename(inputfile).split('.')[1] work = "E" ps.FileCipher(inputfile,outputfile,password,work) return if __name__ == '__main__': main() You can use the following command to execute the encryption process along with password − python pyfilecipher-encrypt.py -i file_path_for_encryption -o output_path -p password You can observe the following output when you execute the code given above − The passwords are generated using MD5 hash algorithm and the values are stored in simply safe backup files in Windows system, which includes the values as displayed below − 10 Lectures 2 hours Total Seminars 10 Lectures 2 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2511, "s": 2292, "text": "In Python, it is possible to encrypt and decrypt files before transmitting to a communication channel. For this, you will have to use the plugin PyCrypto. You can installation this plugin using the command given below." }, { "code": null, "e": 2533, "s": 2511, "text": "pip install pycrypto\n" }, { "code": null, "e": 2619, "s": 2533, "text": "The program code for encrypting the file with password protector is mentioned below −" }, { "code": null, "e": 4347, "s": 2619, "text": "# =================Other Configuration================\n# Usages :\nusage = \"usage: %prog [options] \"\n# Version\nVersion=\"%prog 0.0.1\"\n# ====================================================\n# Import Modules\nimport optparse, sys,os\nfrom toolkit import processor as ps\ndef main():\n parser = optparse.OptionParser(usage = usage,version = Version)\n parser.add_option(\n '-i','--input',type = 'string',dest = 'inputfile',\n help = \"File Input Path For Encryption\", default = None)\n \n parser.add_option(\n '-o','--output',type = \"string\",dest = 'outputfile',\n help = \"File Output Path For Saving Encrypter Cipher\",default = \".\")\n\t\n parser.add_option(\n '-p','--password',type = \"string\",dest = 'password',\n help = \"Provide Password For Encrypting File\",default = None)\n\t\n parser.add_option(\n '-p','--password',type = \"string\",dest = 'password',\n help = \"Provide Password For Encrypting File\",default = None)\n\t\n (options, args)= parser.parse_args()\n\t\n # Input Conditions Checkings\n if not options.inputfile or not os.path.isfile(options.inputfile):\n print \" [Error] Please Specify Input File Path\"\n exit(0)\n if not options.outputfile or not os.path.isdir(options.outputfile):\n print \" [Error] Please Specify Output Path\"\n exit(0)\n if not options.password:\n print \" [Error] No Password Input\"\n exit(0)\n inputfile = options.inputfile\n\n outputfile = os.path.join(\n options.outputfile,os.path.basename(options.inputfile).split('.')[0]+'.ssb')\n password = options.password\n base = os.path.basename(inputfile).split('.')[1]\n work = \"E\"\n\n ps.FileCipher(inputfile,outputfile,password,work)\n return\n\n if __name__ == '__main__':\n main()" }, { "code": null, "e": 4437, "s": 4347, "text": "You can use the following command to execute the encryption process along with password −" }, { "code": null, "e": 4524, "s": 4437, "text": "python pyfilecipher-encrypt.py -i file_path_for_encryption -o output_path -p password\n" }, { "code": null, "e": 4601, "s": 4524, "text": "You can observe the following output when you execute the code given above −" }, { "code": null, "e": 4774, "s": 4601, "text": "The passwords are generated using MD5 hash algorithm and the values are stored in simply safe backup files in Windows system, which includes the values as displayed below −" }, { "code": null, "e": 4807, "s": 4774, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4823, "s": 4807, "text": " Total Seminars" }, { "code": null, "e": 4856, "s": 4823, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4879, "s": 4856, "text": " Stone River ELearning" }, { "code": null, "e": 4886, "s": 4879, "text": " Print" }, { "code": null, "e": 4897, "s": 4886, "text": " Add Notes" } ]
Scrapy - Sending an E-mail
Scrapy can send e-mails using its own facility called as Twisted non-blocking IO which keeps away from non-blocking IO of the crawler. You can configure the few settings of sending emails and provide simple API for sending attachments. There are two ways to instantiate the MailSender as shown in the following table − The following line sends an e-mail without attachments − mailer.send(to = ["receiver@example.com"], subject = "subject data", body = "body data", cc = ["list@example.com"]) The MailSender class uses Twisted non-blocking IO for sending e-mails from Scrapy. class scrapy.mail.MailSender(smtphost = None, mailfrom = None, smtpuser = None, smtppass = None, smtpport = None) The following table shows the parameters used in MailSender class − smtphost (str) The SMTP host is used for sending the emails. If not, then MAIL_HOST setting will be used. mailfrom (str) The address of receiver is used to send the emails. If not, then MAIL_FROM setting will be used. smtpuser It specifies the SMTP user. If it is not used, then MAIL_USER setting will be used and there will be no SMTP validation if is not mentioned. smtppass (str) It specifies the SMTP pass for validation. smtpport (int) It specifies the SMTP port for connection. smtptls (boolean) It implements using the SMTP STARTTLS. smtpssl (boolean) It administers using a safe SSL connection. Following two methods are there in the MailSender class reference as specified. First method, classmethod from_settings(settings) It incorporates by using the Scrapy settings object. It contains the following parameter − settings (scrapy.settings.Settings object) − It is treated as e-mail receiver. Another method, send(to, subject, body, cc = None, attachs = (), mimetype = 'text/plain', charset = None) The following table contains the parameters of the above method − to (list) It refers to the email receiver. subject (str) It specifies the subject of the email. cc (list) It refers to the list of receivers. body (str) It refers to email body data. attachs (iterable) It refers to the email's attachment, mimetype of the attachment and name of the attachment. mimetype (str) It represents the MIME type of the e-mail. charset (str) It specifies the character encoding used for email contents. The following settings ensure that without writing any code, we can configure an e-mail using the MailSender class in the project. MAIL_FROM It refers to sender email for sending emails. MAIL_HOST It refers to SMTP host used for sending emails. MAIL_PORT It specifies SMTP port to be used for sending emails. MAIL_USER It refers to SMTP validation. There will be no validation, if this setting is set to disable. MAIL_PASS It provides the password used for SMTP validation. MAIL_TLS It provides the method of upgrading an insecure connection to a secure connection using SSL/TLS. MAIL_SSL It implements the connection using a SSL encrypted connection. 27 Lectures 3.5 hours Attreya Bhatt Print Add Notes Bookmark this page
[ { "code": null, "e": 2473, "s": 2237, "text": "Scrapy can send e-mails using its own facility called as Twisted non-blocking IO which keeps away from non-blocking IO of the crawler. You can configure the few settings of sending emails and provide simple API for sending attachments." }, { "code": null, "e": 2556, "s": 2473, "text": "There are two ways to instantiate the MailSender as shown in the following table −" }, { "code": null, "e": 2613, "s": 2556, "text": "The following line sends an e-mail without attachments −" }, { "code": null, "e": 2733, "s": 2613, "text": "mailer.send(to = [\"receiver@example.com\"], subject = \"subject data\", body = \"body data\", \n cc = [\"list@example.com\"])" }, { "code": null, "e": 2816, "s": 2733, "text": "The MailSender class uses Twisted non-blocking IO for sending e-mails from Scrapy." }, { "code": null, "e": 2934, "s": 2816, "text": "class scrapy.mail.MailSender(smtphost = None, mailfrom = None, smtpuser = None, \n smtppass = None, smtpport = None)" }, { "code": null, "e": 3002, "s": 2934, "text": "The following table shows the parameters used in MailSender class −" }, { "code": null, "e": 3017, "s": 3002, "text": "smtphost (str)" }, { "code": null, "e": 3108, "s": 3017, "text": "The SMTP host is used for sending the emails. If not, then MAIL_HOST setting will be used." }, { "code": null, "e": 3123, "s": 3108, "text": "mailfrom (str)" }, { "code": null, "e": 3220, "s": 3123, "text": "The address of receiver is used to send the emails. If not, then MAIL_FROM setting will be used." }, { "code": null, "e": 3229, "s": 3220, "text": "smtpuser" }, { "code": null, "e": 3370, "s": 3229, "text": "It specifies the SMTP user. If it is not used, then MAIL_USER setting will be used and there will be no SMTP validation if is not mentioned." }, { "code": null, "e": 3385, "s": 3370, "text": "smtppass (str)" }, { "code": null, "e": 3428, "s": 3385, "text": "It specifies the SMTP pass for validation." }, { "code": null, "e": 3443, "s": 3428, "text": "smtpport (int)" }, { "code": null, "e": 3486, "s": 3443, "text": "It specifies the SMTP port for connection." }, { "code": null, "e": 3504, "s": 3486, "text": "smtptls (boolean)" }, { "code": null, "e": 3543, "s": 3504, "text": "It implements using the SMTP STARTTLS." }, { "code": null, "e": 3561, "s": 3543, "text": "smtpssl (boolean)" }, { "code": null, "e": 3605, "s": 3561, "text": "It administers using a safe SSL connection." }, { "code": null, "e": 3699, "s": 3605, "text": "Following two methods are there in the MailSender class reference as specified. First method," }, { "code": null, "e": 3735, "s": 3699, "text": "classmethod from_settings(settings)" }, { "code": null, "e": 3826, "s": 3735, "text": "It incorporates by using the Scrapy settings object. It contains the following parameter −" }, { "code": null, "e": 3905, "s": 3826, "text": "settings (scrapy.settings.Settings object) − It is treated as e-mail receiver." }, { "code": null, "e": 3921, "s": 3905, "text": "Another method," }, { "code": null, "e": 4011, "s": 3921, "text": "send(to, subject, body, cc = None, attachs = (), mimetype = 'text/plain', charset = None)" }, { "code": null, "e": 4077, "s": 4011, "text": "The following table contains the parameters of the above method −" }, { "code": null, "e": 4087, "s": 4077, "text": "to (list)" }, { "code": null, "e": 4120, "s": 4087, "text": "It refers to the email receiver." }, { "code": null, "e": 4134, "s": 4120, "text": "subject (str)" }, { "code": null, "e": 4173, "s": 4134, "text": "It specifies the subject of the email." }, { "code": null, "e": 4183, "s": 4173, "text": "cc (list)" }, { "code": null, "e": 4219, "s": 4183, "text": "It refers to the list of receivers." }, { "code": null, "e": 4230, "s": 4219, "text": "body (str)" }, { "code": null, "e": 4260, "s": 4230, "text": "It refers to email body data." }, { "code": null, "e": 4279, "s": 4260, "text": "attachs (iterable)" }, { "code": null, "e": 4371, "s": 4279, "text": "It refers to the email's attachment, mimetype of the attachment and name of the attachment." }, { "code": null, "e": 4386, "s": 4371, "text": "mimetype (str)" }, { "code": null, "e": 4429, "s": 4386, "text": "It represents the MIME type of the e-mail." }, { "code": null, "e": 4443, "s": 4429, "text": "charset (str)" }, { "code": null, "e": 4504, "s": 4443, "text": "It specifies the character encoding used for email contents." }, { "code": null, "e": 4635, "s": 4504, "text": "The following settings ensure that without writing any code, we can configure an e-mail using the MailSender class in the project." }, { "code": null, "e": 4645, "s": 4635, "text": "MAIL_FROM" }, { "code": null, "e": 4691, "s": 4645, "text": "It refers to sender email for sending emails." }, { "code": null, "e": 4701, "s": 4691, "text": "MAIL_HOST" }, { "code": null, "e": 4749, "s": 4701, "text": "It refers to SMTP host used for sending emails." }, { "code": null, "e": 4759, "s": 4749, "text": "MAIL_PORT" }, { "code": null, "e": 4813, "s": 4759, "text": "It specifies SMTP port to be used for sending emails." }, { "code": null, "e": 4823, "s": 4813, "text": "MAIL_USER" }, { "code": null, "e": 4917, "s": 4823, "text": "It refers to SMTP validation. There will be no validation, if this setting is set to disable." }, { "code": null, "e": 4927, "s": 4917, "text": "MAIL_PASS" }, { "code": null, "e": 4978, "s": 4927, "text": "It provides the password used for SMTP validation." }, { "code": null, "e": 4987, "s": 4978, "text": "MAIL_TLS" }, { "code": null, "e": 5084, "s": 4987, "text": "It provides the method of upgrading an insecure connection to a secure connection using SSL/TLS." }, { "code": null, "e": 5093, "s": 5084, "text": "MAIL_SSL" }, { "code": null, "e": 5156, "s": 5093, "text": "It implements the connection using a SSL encrypted connection." }, { "code": null, "e": 5191, "s": 5156, "text": "\n 27 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5206, "s": 5191, "text": " Attreya Bhatt" }, { "code": null, "e": 5213, "s": 5206, "text": " Print" }, { "code": null, "e": 5224, "s": 5213, "text": " Add Notes" } ]
JavaScript - The Strings Object
The String object lets you work with a series of characters; it wraps Javascript's string primitive data type with a number of helper methods. As JavaScript automatically converts between string primitives and String objects, you can call any of the helper methods of the String object on a string primitive. Use the following syntax to create a String object − var val = new String(string); The String parameter is a series of characters that has been properly encoded. Here is a list of the properties of String object and their description. Returns a reference to the String function that created the object. Returns the length of the string. The prototype property allows you to add properties and methods to an object. In the following sections, we will have a few examples to demonstrate the usage of String properties. Here is a list of the methods available in String object along with their description. Returns the character at the specified index. Returns a number indicating the Unicode value of the character at the given index. Combines the text of two strings and returns a new string. Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found. Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found. Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. Used to match a regular expression against a string. Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring. Executes the search for a match between a regular expression and a specified string. Extracts a section of a string and returns a new string. Splits a String object into an array of strings by separating the string into substrings. Returns the characters in a string beginning at the specified location through the specified number of characters. Returns the characters in a string between two indexes into the string. The characters within a string are converted to lower case while respecting the current locale. The characters within a string are converted to upper case while respecting the current locale. Returns the calling string value converted to lower case. Returns a string representing the specified object. Returns the calling string value converted to uppercase. Returns the primitive value of the specified object. Here is a list of the methods that return a copy of the string wrapped inside an appropriate HTML tag. Creates an HTML anchor that is used as a hypertext target. Creates a string to be displayed in a big font as if it were in a <big> tag. Creates a string to blink as if it were in a <blink> tag. Creates a string to be displayed as bold as if it were in a <b> tag. Causes a string to be displayed in fixed-pitch font as if it were in a <tt> tag Causes a string to be displayed in the specified color as if it were in a <font color="color"> tag. Causes a string to be displayed in the specified font size as if it were in a <font size="size"> tag. Causes a string to be italic, as if it were in an <i> tag. Creates an HTML hypertext link that requests another URL. Causes a string to be displayed in a small font, as if it were in a <small> tag. Causes a string to be displayed as struck-out text, as if it were in a <strike> tag. Causes a string to be displayed as a subscript, as if it were in a <sub> tag Causes a string to be displayed as a superscript, as if it were in a <sup> tag In the following sections, we will have a few examples to demonstrate the usage of String methods. 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2609, "s": 2466, "text": "The String object lets you work with a series of characters; it wraps Javascript's string primitive data type with a number of helper methods." }, { "code": null, "e": 2775, "s": 2609, "text": "As JavaScript automatically converts between string primitives and String objects, you can call any of the helper methods of the String object on a string primitive." }, { "code": null, "e": 2828, "s": 2775, "text": "Use the following syntax to create a String object −" }, { "code": null, "e": 2859, "s": 2828, "text": "var val = new String(string);\n" }, { "code": null, "e": 2938, "s": 2859, "text": "The String parameter is a series of characters that has been properly encoded." }, { "code": null, "e": 3011, "s": 2938, "text": "Here is a list of the properties of String object and their description." }, { "code": null, "e": 3079, "s": 3011, "text": "Returns a reference to the String function that created the object." }, { "code": null, "e": 3113, "s": 3079, "text": "Returns the length of the string." }, { "code": null, "e": 3191, "s": 3113, "text": "The prototype property allows you to add properties and methods to an object." }, { "code": null, "e": 3293, "s": 3191, "text": "In the following sections, we will have a few examples to demonstrate the usage of String properties." }, { "code": null, "e": 3380, "s": 3293, "text": "Here is a list of the methods available in String object along with their description." }, { "code": null, "e": 3426, "s": 3380, "text": "Returns the character at the specified index." }, { "code": null, "e": 3509, "s": 3426, "text": "Returns a number indicating the Unicode value of the character at the given index." }, { "code": null, "e": 3568, "s": 3509, "text": "Combines the text of two strings and returns a new string." }, { "code": null, "e": 3687, "s": 3568, "text": "Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found." }, { "code": null, "e": 3805, "s": 3687, "text": "Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found." }, { "code": null, "e": 3932, "s": 3805, "text": "Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order." }, { "code": null, "e": 3985, "s": 3932, "text": "Used to match a regular expression against a string." }, { "code": null, "e": 4108, "s": 3985, "text": "Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring." }, { "code": null, "e": 4193, "s": 4108, "text": "Executes the search for a match between a regular expression and a specified string." }, { "code": null, "e": 4250, "s": 4193, "text": "Extracts a section of a string and returns a new string." }, { "code": null, "e": 4340, "s": 4250, "text": "Splits a String object into an array of strings by separating the string into substrings." }, { "code": null, "e": 4455, "s": 4340, "text": "Returns the characters in a string beginning at the specified location through the specified number of characters." }, { "code": null, "e": 4527, "s": 4455, "text": "Returns the characters in a string between two indexes into the string." }, { "code": null, "e": 4623, "s": 4527, "text": "The characters within a string are converted to lower case while respecting the current locale." }, { "code": null, "e": 4719, "s": 4623, "text": "The characters within a string are converted to upper case while respecting the current locale." }, { "code": null, "e": 4777, "s": 4719, "text": "Returns the calling string value converted to lower case." }, { "code": null, "e": 4829, "s": 4777, "text": "Returns a string representing the specified object." }, { "code": null, "e": 4886, "s": 4829, "text": "Returns the calling string value converted to uppercase." }, { "code": null, "e": 4939, "s": 4886, "text": "Returns the primitive value of the specified object." }, { "code": null, "e": 5042, "s": 4939, "text": "Here is a list of the methods that return a copy of the string wrapped inside an appropriate HTML tag." }, { "code": null, "e": 5101, "s": 5042, "text": "Creates an HTML anchor that is used as a hypertext target." }, { "code": null, "e": 5178, "s": 5101, "text": "Creates a string to be displayed in a big font as if it were in a <big> tag." }, { "code": null, "e": 5236, "s": 5178, "text": "Creates a string to blink as if it were in a <blink> tag." }, { "code": null, "e": 5305, "s": 5236, "text": "Creates a string to be displayed as bold as if it were in a <b> tag." }, { "code": null, "e": 5385, "s": 5305, "text": "Causes a string to be displayed in fixed-pitch font as if it were in a <tt> tag" }, { "code": null, "e": 5485, "s": 5385, "text": "Causes a string to be displayed in the specified color as if it were in a <font color=\"color\"> tag." }, { "code": null, "e": 5587, "s": 5485, "text": "Causes a string to be displayed in the specified font size as if it were in a <font size=\"size\"> tag." }, { "code": null, "e": 5646, "s": 5587, "text": "Causes a string to be italic, as if it were in an <i> tag." }, { "code": null, "e": 5704, "s": 5646, "text": "Creates an HTML hypertext link that requests another URL." }, { "code": null, "e": 5785, "s": 5704, "text": "Causes a string to be displayed in a small font, as if it were in a <small> tag." }, { "code": null, "e": 5870, "s": 5785, "text": "Causes a string to be displayed as struck-out text, as if it were in a <strike> tag." }, { "code": null, "e": 5947, "s": 5870, "text": "Causes a string to be displayed as a subscript, as if it were in a <sub> tag" }, { "code": null, "e": 6026, "s": 5947, "text": "Causes a string to be displayed as a superscript, as if it were in a <sup> tag" }, { "code": null, "e": 6125, "s": 6026, "text": "In the following sections, we will have a few examples to demonstrate the usage of String methods." }, { "code": null, "e": 6160, "s": 6125, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6174, "s": 6160, "text": " Anadi Sharma" }, { "code": null, "e": 6208, "s": 6174, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 6222, "s": 6208, "text": " Lets Kode It" }, { "code": null, "e": 6257, "s": 6222, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6274, "s": 6257, "text": " Frahaan Hussain" }, { "code": null, "e": 6309, "s": 6274, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6326, "s": 6309, "text": " Frahaan Hussain" }, { "code": null, "e": 6359, "s": 6326, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 6387, "s": 6359, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6421, "s": 6387, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 6449, "s": 6421, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6456, "s": 6449, "text": " Print" }, { "code": null, "e": 6467, "s": 6456, "text": " Add Notes" } ]
IPython - Magic Commands
Magic commands or magic functions are one of the important enhancements that IPython offers compared to the standard Python shell. These magic commands are intended to solve common problems in data analysis using Python. In fact, they control the behaviour of IPython itself. Magic commands act as convenient functions where Python syntax is not the most natural one. They are useful to embed invalid python syntax in their work flow. There are two types of magic commands − Line magics Cell magics They are similar to command line calls. They start with % character. Rest of the line is its argument passed without parentheses or quotes. Line magics can be used as expression and their return value can be assigned to variable. They have %% character prefix. Unlike line magic functions, they can operate on multiple lines below their call. They can in fact make arbitrary modifications to the input they receive, which need not even be a valid Python code at all. They receive the whole block as a single string. To know more about magic functions, the built-in magics and their docstrings, use the magic command. Information of a specific magic function is obtained by %magicfunction? Command. Let us now describe some of the built-in line and cell magic commands. %autocall [mode] This magic function makes a function automatically callable without having to use parentheses. It takes three possible mode parameters: 0 (off), 1 (smart) is default or 2 (always on). Magic functions are callable without having to type the initial % if set to 1. Without arguments it toggles on/off. To deactivate, set to 0. The following example shows a magic function %pwd (displays present working directory) being called without leading % when %automagic set to 1 This line magic changes the current directory. This command automatically maintains an internal list of directories you visit during your IPython session, in the variable _dh. You can also do ‘cd -<tab>’ to see directory history conveniently. The %cd command can be used in the following ways − %cd <dir> − Changes current working directory to <dir> %cd <dir> − Changes current working directory to <dir> %cd.. − Changes current directory to parent directory %cd.. − Changes current directory to parent directory %cd − changes to last visited directory. %cd − changes to last visited directory. This magic command prints all directories you have visited in current session. Every time %cd command is used, this list is updated in _dh variable. This magic command calls upon the default text editor of current operating system (Notepad for Windows) for editing a Python script. The script is executed as the editor is closed. This magic command will list all environment variables. It also reads value of particular variable or set the value of environment variable. Usage The %cd command can be used in the following ways − %env − Lists all environment variables %env − Lists all environment variables %env var − Gets value for var %env var − Gets value for var %env var val − Sets value for var %env var val − Sets value for var When used without argument this command enables or disables IPython GUI event loop integration. With GUINAME argument, this magic replaces the default GUI toolkits by the specified one. %gui wx enable wxPython event loop integration %gui qt4|qt enable PyQt4 event loop integration %gui qt5 enable PyQt5 event loop integration %gui gtk enable PyGTK event loop integration %gui gtk3 enable Gtk3 event loop integration %gui tk enable Tk event loop integration %gui osx enable Cocoa event loop integration (requires %matplotlib 1.1) %gui disable all event loop integration Displays all magic functions currently available This function activates matplotlib interactive support during an IPython session. However, it does not import matplotlib library. The matplotlib default GUI toolkit is TkAgg. But you can explicitly request a different GUI backend. You can see a list of the available backends as shown − In [4]: %matplotlib --list Available matplotlib backends: ['osx', 'qt4', 'qt5', 'gtk3', 'notebook', 'wx', 'qt', 'nbagg','gtk', 'tk', 'inline'] The IPython session shown here plots a sine wave using qt toolkit − While using Jupyter notebook, %matplotlib inline directive displays plot output in the browser only. This function converts current IPython history into an IPython notebook file with ipynb extension. The input cells in previous example are saved as sine.ipynb %notebook sine.ipynb This function is similar to object introspection ? character. To obtain information about an object, use the following command − %pinfo object This is synonymous to object? or ?object. This magic function restricts a floating point result to specified digits after decimal. This magic function returns the present working directory. This function populates current IPython session with matplotlib, and numpy libraries. When executed without any parameter, this function executes previous command. Note that in %recall n, number in front of it is input cell number. Hence the command in the nth cell is recalled. You can recall commands in section of cells by using command such as %recall 1-4. Current input cell is populated with recalled cell and the cursor blinks till the enter key is pressed. This command runs a Python script from within IPython shell. This command displays time required by IPython environment to execute a Python expression. This function also displays time required by IPython environment to execute a Python expression. Time execution of a Python statement or expression uses the timeit module. This function can be used both as a line and cell magic as explained here − In line mode you can time a single-line. In line mode you can time a single-line. In cell mode, the statement in the first line is used as setup code and the body of the cell is timed. The cell body has access to any variables created in the setup code. In cell mode, the statement in the first line is used as setup code and the body of the cell is timed. The cell body has access to any variables created in the setup code. This line magic prints all interactive variables, with some minimal formatting. If any arguments are given, only variables whose type matches one of these are printed. IPython’s core library contains register_line_magic decorator. A user defined function is converted into a line magic function using this decorator. 22 Lectures 49 mins Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2936, "s": 2660, "text": "Magic commands or magic functions are one of the important enhancements that IPython offers compared to the standard Python shell. These magic commands are intended to solve common problems in data analysis using Python. In fact, they control the behaviour of IPython itself." }, { "code": null, "e": 3095, "s": 2936, "text": "Magic commands act as convenient functions where Python syntax is not the most natural one. They are useful to embed invalid python syntax in their work flow." }, { "code": null, "e": 3135, "s": 3095, "text": "There are two types of magic commands −" }, { "code": null, "e": 3147, "s": 3135, "text": "Line magics" }, { "code": null, "e": 3159, "s": 3147, "text": "Cell magics" }, { "code": null, "e": 3389, "s": 3159, "text": "They are similar to command line calls. They start with % character. Rest of the line is its argument passed without parentheses or quotes. Line magics can be used as expression and their return value can be assigned to variable." }, { "code": null, "e": 3675, "s": 3389, "text": "They have %% character prefix. Unlike line magic functions, they can operate on multiple lines below their call. They can in fact make arbitrary modifications to the input they receive, which need not even be a valid Python code at all. They receive the whole block as a single string." }, { "code": null, "e": 3928, "s": 3675, "text": "To know more about magic functions, the built-in magics and their docstrings, use the magic command. Information of a specific magic function is obtained by %magicfunction? Command. Let us now describe some of the built-in line and cell magic commands." }, { "code": null, "e": 3946, "s": 3928, "text": "%autocall [mode]\n" }, { "code": null, "e": 4130, "s": 3946, "text": "This magic function makes a function automatically callable without having to use parentheses. It takes three possible mode parameters: 0 (off), 1 (smart) is default or 2 (always on)." }, { "code": null, "e": 4271, "s": 4130, "text": "Magic functions are callable without having to type the initial % if set to 1. Without arguments it toggles on/off. To deactivate, set to 0." }, { "code": null, "e": 4414, "s": 4271, "text": "The following example shows a magic function %pwd (displays present working directory) being called without leading % when %automagic set to 1" }, { "code": null, "e": 4657, "s": 4414, "text": "This line magic changes the current directory. This command automatically maintains an internal list of directories you visit during your IPython session, in the variable _dh. You can also do ‘cd -<tab>’ to see directory history conveniently." }, { "code": null, "e": 4709, "s": 4657, "text": "The %cd command can be used in the following ways −" }, { "code": null, "e": 4764, "s": 4709, "text": "%cd <dir> − Changes current working directory to <dir>" }, { "code": null, "e": 4819, "s": 4764, "text": "%cd <dir> − Changes current working directory to <dir>" }, { "code": null, "e": 4873, "s": 4819, "text": "%cd.. − Changes current directory to parent directory" }, { "code": null, "e": 4927, "s": 4873, "text": "%cd.. − Changes current directory to parent directory" }, { "code": null, "e": 4968, "s": 4927, "text": "%cd − changes to last visited directory." }, { "code": null, "e": 5009, "s": 4968, "text": "%cd − changes to last visited directory." }, { "code": null, "e": 5158, "s": 5009, "text": "This magic command prints all directories you have visited in current session. Every time %cd command is used, this list is updated in _dh variable." }, { "code": null, "e": 5339, "s": 5158, "text": "This magic command calls upon the default text editor of current operating system (Notepad for Windows) for editing a Python script. The script is executed as the editor is closed." }, { "code": null, "e": 5480, "s": 5339, "text": "This magic command will list all environment variables. It also reads value of particular variable or set the value of environment variable." }, { "code": null, "e": 5486, "s": 5480, "text": "Usage" }, { "code": null, "e": 5538, "s": 5486, "text": "The %cd command can be used in the following ways −" }, { "code": null, "e": 5577, "s": 5538, "text": "%env − Lists all environment variables" }, { "code": null, "e": 5616, "s": 5577, "text": "%env − Lists all environment variables" }, { "code": null, "e": 5646, "s": 5616, "text": "%env var − Gets value for var" }, { "code": null, "e": 5676, "s": 5646, "text": "%env var − Gets value for var" }, { "code": null, "e": 5710, "s": 5676, "text": "%env var val − Sets value for var" }, { "code": null, "e": 5744, "s": 5710, "text": "%env var val − Sets value for var" }, { "code": null, "e": 5930, "s": 5744, "text": "When used without argument this command enables or disables IPython GUI event loop integration. With GUINAME argument, this magic replaces the default GUI toolkits by the specified one." }, { "code": null, "e": 5938, "s": 5930, "text": "%gui wx" }, { "code": null, "e": 5977, "s": 5938, "text": "enable wxPython event loop integration" }, { "code": null, "e": 5989, "s": 5977, "text": "%gui qt4|qt" }, { "code": null, "e": 6025, "s": 5989, "text": "enable PyQt4 event loop integration" }, { "code": null, "e": 6034, "s": 6025, "text": "%gui qt5" }, { "code": null, "e": 6070, "s": 6034, "text": "enable PyQt5 event loop integration" }, { "code": null, "e": 6079, "s": 6070, "text": "%gui gtk" }, { "code": null, "e": 6115, "s": 6079, "text": "enable PyGTK event loop integration" }, { "code": null, "e": 6125, "s": 6115, "text": "%gui gtk3" }, { "code": null, "e": 6160, "s": 6125, "text": "enable Gtk3 event loop integration" }, { "code": null, "e": 6168, "s": 6160, "text": "%gui tk" }, { "code": null, "e": 6201, "s": 6168, "text": "enable Tk event loop integration" }, { "code": null, "e": 6210, "s": 6201, "text": "%gui osx" }, { "code": null, "e": 6246, "s": 6210, "text": "enable Cocoa event loop integration" }, { "code": null, "e": 6273, "s": 6246, "text": "(requires %matplotlib 1.1)" }, { "code": null, "e": 6278, "s": 6273, "text": "%gui" }, { "code": null, "e": 6313, "s": 6278, "text": "disable all event loop integration" }, { "code": null, "e": 6362, "s": 6313, "text": "Displays all magic functions currently available" }, { "code": null, "e": 6649, "s": 6362, "text": "This function activates matplotlib interactive support during an IPython session. However, it does not import matplotlib library. The matplotlib default GUI toolkit is TkAgg. But you can explicitly request a different GUI backend. You can see a list of the available backends as shown −" }, { "code": null, "e": 6794, "s": 6649, "text": "In [4]: %matplotlib --list\nAvailable matplotlib backends: \n['osx', 'qt4', 'qt5', 'gtk3', 'notebook', 'wx', 'qt', 'nbagg','gtk', 'tk', 'inline']\n" }, { "code": null, "e": 6862, "s": 6794, "text": "The IPython session shown here plots a sine wave using qt toolkit −" }, { "code": null, "e": 6963, "s": 6862, "text": "While using Jupyter notebook, %matplotlib inline directive displays plot output in the browser only." }, { "code": null, "e": 7122, "s": 6963, "text": "This function converts current IPython history into an IPython notebook file with ipynb extension. The input cells in previous example are saved as sine.ipynb" }, { "code": null, "e": 7144, "s": 7122, "text": "%notebook sine.ipynb\n" }, { "code": null, "e": 7273, "s": 7144, "text": "This function is similar to object introspection ? character. To obtain information about an object, use the following command −" }, { "code": null, "e": 7288, "s": 7273, "text": "%pinfo object\n" }, { "code": null, "e": 7330, "s": 7288, "text": "This is synonymous to object? or ?object." }, { "code": null, "e": 7419, "s": 7330, "text": "This magic function restricts a floating point result to specified digits after decimal." }, { "code": null, "e": 7478, "s": 7419, "text": "This magic function returns the present working directory." }, { "code": null, "e": 7564, "s": 7478, "text": "This function populates current IPython session with matplotlib, and numpy libraries." }, { "code": null, "e": 7642, "s": 7564, "text": "When executed without any parameter, this function executes previous command." }, { "code": null, "e": 7943, "s": 7642, "text": "Note that in %recall n, number in front of it is input cell number. Hence the command in the nth cell is recalled. You can recall commands in section of cells by using command such as %recall 1-4. Current input cell is populated with recalled cell and the cursor blinks till the enter key is pressed." }, { "code": null, "e": 8004, "s": 7943, "text": "This command runs a Python script from within IPython shell." }, { "code": null, "e": 8095, "s": 8004, "text": "This command displays time required by IPython environment to execute a Python expression." }, { "code": null, "e": 8343, "s": 8095, "text": "This function also displays time required by IPython environment to execute a Python expression. Time execution of a Python statement or expression uses the timeit module. This function can be used both as a line and cell magic as explained here −" }, { "code": null, "e": 8384, "s": 8343, "text": "In line mode you can time a single-line." }, { "code": null, "e": 8425, "s": 8384, "text": "In line mode you can time a single-line." }, { "code": null, "e": 8597, "s": 8425, "text": "In cell mode, the statement in the first line is used as setup code and the body of the cell is timed. The cell body has access to any variables created in the setup code." }, { "code": null, "e": 8769, "s": 8597, "text": "In cell mode, the statement in the first line is used as setup code and the body of the cell is timed. The cell body has access to any variables created in the setup code." }, { "code": null, "e": 8937, "s": 8769, "text": "This line magic prints all interactive variables, with some minimal formatting. If any arguments are given, only variables whose type matches one of these are printed." }, { "code": null, "e": 9086, "s": 8937, "text": "IPython’s core library contains register_line_magic decorator. A user defined function is converted into a line magic function using this decorator." }, { "code": null, "e": 9118, "s": 9086, "text": "\n 22 Lectures \n 49 mins\n" }, { "code": null, "e": 9136, "s": 9118, "text": " Bigdata Engineer" }, { "code": null, "e": 9143, "s": 9136, "text": " Print" }, { "code": null, "e": 9154, "s": 9143, "text": " Add Notes" } ]
Max distance between same elements | Practice | GeeksforGeeks
Given an array with repeated elements, the task is to find the maximum distance between two occurrences of an element. Example 1: Input n= 6 arr = {1, 1, 2, 2, 2, 1} Output 5 Explanation arr[] = {1, 1, 2, 2, 2, 1} Max Distance: 5 Distance for 1 is: 5-0 = 5 Distance for 2 is : 4-2 = 2 Max Distance 5 Example 2: Input n = 12 arr = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2} Output 10 Explanation arr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2} Max Distance 10 maximum distance for 2 is 11-1 = 10 maximum distance for 1 is 4-2 = 2 maximum distance for 4 is 10-5 = 5 Your Task: Complete maxDistance() function which takes both the given array and their size as function arguments and returns the maximum distance between 2 same elements. Expected Time Complexity : O(N) Expected Auxilliary Space : O(N) Constraints: 1<=N<=106 0 subhamsen11 day ago Python code def maxDistance(self, arr, n): # declaure a default dict with list # add the all the index as a list to value of dictionary #now make the dictionary with key as arr elemt and list of indexes as value # traverse the dictionary and add the distance of each element to a result value[-1] last element and [0] first index # from collections import defaultdict new=defaultdict(list) for index,value in enumerate(arr): new[value].append(index) # now lets get the max distance # res=[] for key,value in new.items(): distance=value[-1]-value[0] # calculating distance res.append(distance) # print(max(res)) return max(res) +1 tanashah3 days ago unordered_map<int,int>mp; int max_count=0; for(int i=0;i<n;i++){ if(mp.find(arr[i])==mp.end()){ mp[arr[i]]=i; }else{ max_count=max(max_count,i-mp[arr[i]]); } } return max_count;//T.C O(N) only 0 shailendramaheshwari173 weeks ago int maxDistance(int arr[], int n) { int a[n] , max_d = -1; fill(a,a+n,-1); for(int i=0;i<n;i++) { int temp = arr[i]; if(((arr[0] != arr[1])&&(n==2))|| n==1) return 0; else if(a[temp] >-1) { max_d = max(max_d,i-a[temp]); } else a[temp] = i; } return max_d; } 0 ajayab77991 month ago class Solution { int maxDistance(int arr[], int n) { // Your code here HashMap<Integer,Integer> maxInd = new HashMap<>(); int max = 0; for(int i=0;i<n;i++) { if(maxInd.containsKey(arr[i])) { int j = maxInd.get(arr[i]); // storing previous index of that element max = Math.max(max,i-(maxInd.get(arr[i]))); maxInd.put(arr[i],j); // assigning same previous index } else { maxInd.put(arr[i],i); } } return max; } } 0 vrajeshmodi991 month ago int maxDistance(int arr[], int n){ unordered_map<int,pair<int,int>>mp; for(int i=0;i<n;i++) { if(mp.count(arr[i])){ mp[arr[i]].second = i; } else{ mp[arr[i]] = make_pair(i,i); } } int ans=INT_MIN; for (auto it: mp){ auto ele_pair = it.second; int diff =ele_pair.second-ele_pair.first; ans = max(ans ,diff); } return ans; } 0 aalap02111 month ago JAVA Solution.Using the map to see if the element is already there. If element is three in the map then calculate the the distance. If distance is more than the current max value, change the max value. class Solution{ int maxDistance(int arr[], int n) { Map<Integer,Integer> map = new HashMap<Integer,Integer>(); int maxDistance = 0; for(int i=0;i<n;i++){ if(map.get(arr[i])==null){ map.put(arr[i],i); }else{ int mapValue = map.get(arr[i]); if(maxDistance<(i-mapValue)){ maxDistance = i-mapValue; } } }return maxDistance; }} -1 abhaybaranwal4 This comment has been flagged for violating our community guidelines. -1 abhaybaranwal4 This comment has been flagged for violating our community guidelines. -1 abhaybaranwal4 This comment has been flagged for violating our community guidelines. -1 abhaybaranwal4 This comment has been flagged for violating our community guidelines. 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": 357, "s": 238, "text": "Given an array with repeated elements, the task is to find the maximum distance between two occurrences of an element." }, { "code": null, "e": 368, "s": 357, "text": "Example 1:" }, { "code": null, "e": 540, "s": 368, "text": "Input\nn= 6\narr = {1, 1, 2, 2, 2, 1}\n\nOutput\n5\n\nExplanation\narr[] = {1, 1, 2, 2, 2, 1}\nMax Distance: 5\nDistance for 1 is: 5-0 = 5\nDistance for 2 is : 4-2 = 2\nMax Distance 5" }, { "code": null, "e": 551, "s": 540, "text": "Example 2:" }, { "code": null, "e": 800, "s": 551, "text": "Input\nn = 12\narr = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}\n\nOutput\n10\n\nExplanation\n\n\n\narr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}\nMax Distance 10\nmaximum distance for 2 is 11-1 = 10\nmaximum distance for 1 is 4-2 = 2\nmaximum distance for 4 is 10-5 = 5" }, { "code": null, "e": 972, "s": 800, "text": "Your Task:\nComplete maxDistance() function which takes both the given array and their size as function arguments and returns the maximum distance between 2 same elements. " }, { "code": null, "e": 1038, "s": 972, "text": "\nExpected Time Complexity : O(N)\nExpected Auxilliary Space : O(N)" }, { "code": null, "e": 1051, "s": 1038, "text": "Constraints:" }, { "code": null, "e": 1061, "s": 1051, "text": "1<=N<=106" }, { "code": null, "e": 1067, "s": 1065, "text": "0" }, { "code": null, "e": 1087, "s": 1067, "text": "subhamsen11 day ago" }, { "code": null, "e": 1099, "s": 1087, "text": "Python code" }, { "code": null, "e": 1774, "s": 1099, "text": "def maxDistance(self, arr, n): # declaure a default dict with list # add the all the index as a list to value of dictionary #now make the dictionary with key as arr elemt and list of indexes as value # traverse the dictionary and add the distance of each element to a result value[-1] last element and [0] first index # from collections import defaultdict new=defaultdict(list) for index,value in enumerate(arr): new[value].append(index) # now lets get the max distance # res=[] for key,value in new.items(): distance=value[-1]-value[0] # calculating distance res.append(distance) # print(max(res)) return max(res)" }, { "code": null, "e": 1777, "s": 1774, "text": "+1" }, { "code": null, "e": 1796, "s": 1777, "text": "tanashah3 days ago" }, { "code": null, "e": 2075, "s": 1796, "text": "unordered_map<int,int>mp;\n int max_count=0;\n for(int i=0;i<n;i++){\n if(mp.find(arr[i])==mp.end()){\n mp[arr[i]]=i;\n }else{\n max_count=max(max_count,i-mp[arr[i]]);\n }\n }\n return max_count;//T.C O(N) only" }, { "code": null, "e": 2077, "s": 2075, "text": "0" }, { "code": null, "e": 2111, "s": 2077, "text": "shailendramaheshwari173 weeks ago" }, { "code": null, "e": 2458, "s": 2111, "text": " int maxDistance(int arr[], int n)\n {\n int a[n] , max_d = -1;\n fill(a,a+n,-1);\n for(int i=0;i<n;i++)\n {\n int temp = arr[i];\n if(((arr[0] != arr[1])&&(n==2))|| n==1) return 0;\n else\n if(a[temp] >-1) {\n max_d = max(max_d,i-a[temp]);\n }\n else\n a[temp] = i;\n }\n return max_d;\n }" }, { "code": null, "e": 2460, "s": 2458, "text": "0" }, { "code": null, "e": 2482, "s": 2460, "text": "ajayab77991 month ago" }, { "code": null, "e": 3045, "s": 2482, "text": "class Solution\n{\n int maxDistance(int arr[], int n)\n {\n\t// Your code here\n\t HashMap<Integer,Integer> maxInd = new HashMap<>();\n\t int max = 0;\n\t for(int i=0;i<n;i++)\n\t {\n\t if(maxInd.containsKey(arr[i]))\n\t {\n\t int j = maxInd.get(arr[i]); // storing previous index of that element\n\t max = Math.max(max,i-(maxInd.get(arr[i])));\n\t maxInd.put(arr[i],j); // assigning same previous index\n\t }\n\t else\n\t {\n\t maxInd.put(arr[i],i);\n\t }\n\t }\n return max;\n }\n}" }, { "code": null, "e": 3047, "s": 3045, "text": "0" }, { "code": null, "e": 3072, "s": 3047, "text": "vrajeshmodi991 month ago" }, { "code": null, "e": 3578, "s": 3072, "text": " int maxDistance(int arr[], int n){\n unordered_map<int,pair<int,int>>mp;\n for(int i=0;i<n;i++)\n {\n if(mp.count(arr[i])){\n mp[arr[i]].second = i;\n }\n else{\n mp[arr[i]] = make_pair(i,i); \n }\n }\n int ans=INT_MIN;\n for (auto it: mp){\n auto ele_pair = it.second;\n int diff =ele_pair.second-ele_pair.first;\n ans = max(ans ,diff);\n }\n return ans;\n }" }, { "code": null, "e": 3580, "s": 3578, "text": "0" }, { "code": null, "e": 3601, "s": 3580, "text": "aalap02111 month ago" }, { "code": null, "e": 3803, "s": 3601, "text": "JAVA Solution.Using the map to see if the element is already there. If element is three in the map then calculate the the distance. If distance is more than the current max value, change the max value." }, { "code": null, "e": 4273, "s": 3805, "text": "class Solution{ int maxDistance(int arr[], int n) { Map<Integer,Integer> map = new HashMap<Integer,Integer>(); int maxDistance = 0; for(int i=0;i<n;i++){ if(map.get(arr[i])==null){ map.put(arr[i],i); }else{ int mapValue = map.get(arr[i]); if(maxDistance<(i-mapValue)){ maxDistance = i-mapValue; } } }return maxDistance; }}" }, { "code": null, "e": 4276, "s": 4273, "text": "-1" }, { "code": null, "e": 4291, "s": 4276, "text": "abhaybaranwal4" }, { "code": null, "e": 4361, "s": 4291, "text": "This comment has been flagged for violating our community guidelines." }, { "code": null, "e": 4364, "s": 4361, "text": "-1" }, { "code": null, "e": 4379, "s": 4364, "text": "abhaybaranwal4" }, { "code": null, "e": 4449, "s": 4379, "text": "This comment has been flagged for violating our community guidelines." }, { "code": null, "e": 4452, "s": 4449, "text": "-1" }, { "code": null, "e": 4467, "s": 4452, "text": "abhaybaranwal4" }, { "code": null, "e": 4537, "s": 4467, "text": "This comment has been flagged for violating our community guidelines." }, { "code": null, "e": 4540, "s": 4537, "text": "-1" }, { "code": null, "e": 4555, "s": 4540, "text": "abhaybaranwal4" }, { "code": null, "e": 4625, "s": 4555, "text": "This comment has been flagged for violating our community guidelines." }, { "code": null, "e": 4771, "s": 4625, "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": 4807, "s": 4771, "text": " Login to access your submissions. " }, { "code": null, "e": 4817, "s": 4807, "text": "\nProblem\n" }, { "code": null, "e": 4827, "s": 4817, "text": "\nContest\n" }, { "code": null, "e": 4890, "s": 4827, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5038, "s": 4890, "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": 5246, "s": 5038, "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": 5352, "s": 5246, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Create a Doubly Linked List from a Ternary Tree - GeeksforGeeks
29 Mar, 2022 Given a ternary tree, create a doubly linked list out of it. A ternary tree is just like binary tree but instead of having two nodes, it has three nodes i.e. left, middle, right. The doubly linked list should holds following properties – Left pointer of ternary tree should act as prev pointer of doubly linked list.Middle pointer of ternary tree should not point to anything.Right pointer of ternary tree should act as next pointer of doubly linked list.Each node of ternary tree is inserted into doubly linked list before its subtrees and for any node, its left child will be inserted first, followed by mid and right child (if any). Left pointer of ternary tree should act as prev pointer of doubly linked list. Middle pointer of ternary tree should not point to anything. Right pointer of ternary tree should act as next pointer of doubly linked list. Each node of ternary tree is inserted into doubly linked list before its subtrees and for any node, its left child will be inserted first, followed by mid and right child (if any). For the above example, the linked list formed for below tree should be NULL <- 30 <-> 5 <-> 1 <-> 4 <-> 8 <-> 11 <-> 6 <-> 7 <-> 15 <-> 63 <-> 31 <-> 55 <-> 65 -> NULL We strongly recommend you to minimize your browser and try this yourself first.The idea is to traverse the tree in preorder fashion similar to binary tree preorder traversal. Here, when we visit a node, we will insert it into doubly linked list in the end using a tail pointer. That we use to maintain the required insertion order. We then recursively call for left child, middle child and right child in that order. Below is the implementation of this idea. C++ Java Python3 C# Javascript // C++ program to create a doubly linked list out// of given a ternary tree.#include <bits/stdc++.h>using namespace std; /* A ternary tree */struct Node{ int data; struct Node *left, *middle, *right;}; /* Helper function that allocates a new node with the given data and assign NULL to left, middle and right pointers.*/Node* newNode(int data){ Node* node = new Node; node->data = data; node->left = node->middle = node->right = NULL; return node;} /* Utility function that constructs doubly linked listby inserting current node at the end of the doublylinked list by using a tail pointer */void push(Node** tail_ref, Node* node){ // initialize tail pointer if (*tail_ref == NULL) { *tail_ref = node; // set left, middle and right child to point // to NULL node->left = node->middle = node->right = NULL; return; } // insert node in the end using tail pointer (*tail_ref)->right = node; // set prev of node node->left = (*tail_ref); // set middle and right child to point to NULL node->right = node->middle = NULL; // now tail pointer will point to inserted node (*tail_ref) = node;} /* Create a doubly linked list out of given a ternary tree.by traversing the tree in preorder fashion. */void TernaryTreeToList(Node* root, Node** head_ref){ // Base case if (root == NULL) return; //create a static tail pointer static Node* tail = NULL; // store left, middle and right nodes // for future calls. Node* left = root->left; Node* middle = root->middle; Node* right = root->right; // set head of the doubly linked list // head will be root of the ternary tree if (*head_ref == NULL) *head_ref = root; // push current node in the end of DLL push(&tail, root); //recurse for left, middle and right child TernaryTreeToList(left, head_ref); TernaryTreeToList(middle, head_ref); TernaryTreeToList(right, head_ref);} // Utility function for printing double linked list.void printList(Node* head){ printf("Created Double Linked list is:\n"); while (head) { printf("%d ", head->data); head = head->right; }} // Driver program to test above functionsint main(){ // Constructing ternary tree as shown in above figure Node* root = newNode(30); root->left = newNode(5); root->middle = newNode(11); root->right = newNode(63); root->left->left = newNode(1); root->left->middle = newNode(4); root->left->right = newNode(8); root->middle->left = newNode(6); root->middle->middle = newNode(7); root->middle->right = newNode(15); root->right->left = newNode(31); root->right->middle = newNode(55); root->right->right = newNode(65); Node* head = NULL; TernaryTreeToList(root, &head); printList(head); return 0;} //Java program to create a doubly linked list// from a given ternary tree. //Custom node class.class newNode{ int data; newNode left,middle,right; public newNode(int data) { this.data = data; left = middle = right = null; }} class GFG { //tail of the linked list. static newNode tail; //function to push the node to the tail. public static void push(newNode node) { //to put the node at the end of // the already existing tail. tail.right = node; //to point to the previous node. node.left = tail; // middle pointer should point to // nothing so null. initiate right // pointer to null. node.middle = node.right = null; //update the tail position. tail = node; } /* Create a doubly linked list out of given a ternary tree. by traversing the tree in preorder fashion. */ public static void ternaryTree(newNode node,newNode head) { if(node == null) return; newNode left = node.left; newNode middle = node.middle; newNode right = node.right; if(tail != node) // already root is in the tail so dont push // the node when it was root.In the first // case both node and tail have root in them. push(node); // First the left child is to be taken. // Then middle and then right child. ternaryTree(left,head); ternaryTree(middle,head); ternaryTree(right,head); } //function to initiate the list process. public static newNode startTree(newNode root) { //Initiate the head and tail with root. newNode head = root; tail = root; ternaryTree(root,head); //since the head,root are passed // with reference the changes in // root will be reflected in head. return head; } // Utility function for printing double linked list. public static void printList(newNode head) { System.out.print("Created Double Linked list is:\n"); while(head != null) { System.out.print(head.data + " "); head = head.right; } } // Driver program to test above functions public static void main(String args[]) { // Constructing ternary tree as shown // in above figure newNode root = new newNode(30); root.left = new newNode(5); root.middle = new newNode(11); root.right = new newNode(63); root.left.left = new newNode(1); root.left.middle = new newNode(4); root.left.right = new newNode(8); root.middle.left = new newNode(6); root.middle.middle = new newNode(7); root.middle.right = new newNode(15); root.right.left = new newNode(31); root.right.middle = new newNode(55); root.right.right = new newNode(65); // The function which initiates the list // process returns the head. newNode head = startTree(root); printList(head); }} // This code is contributed by M.V.S.Surya Teja. # Python3 program to create a doubly linked# list out of given a ternary tree. # Custom node class.class newNode: def __init__(self, data): self.data = data self.left = None self.right = None self.middle = None class GFG: def __init__(self): # Tail of the linked list. self.tail = None # Function to push the node to the tail. def push(self, node): # To put the node at the end of # the already existing tail. self.tail.right = node # To point to the previous node. node.left = self.tail # Middle pointer should point to # nothing so null. initiate right # pointer to null. node.middle = node.right = None # Update the tail position. self.tail = node # Create a doubly linked list out of given # a ternary tree By traversing the tree in # preorder fashion. def ternaryTree(self, node, head): if node == None: return left = node.left middle = node.middle right = node.right if self.tail != node: # Already root is in the tail so dont push # the node when it was root.In the first # case both node and tail have root in them. self.push(node) # First the left child is to be taken. # Then middle and then right child. self.ternaryTree(left, head) self.ternaryTree(middle, head) self.ternaryTree(right, head) def startTree(self, root): # Initiate the head and tail with root. head = root self.tail = root self.ternaryTree(root, head) # Since the head,root are passed # with reference the changes in # root will be reflected in head. return head # Utility function for printing double linked list. def printList(self, head): print("Created Double Linked list is:") while head: print(head.data, end = " ") head = head.right # Driver codeif __name__ == '__main__': # Constructing ternary tree as shown # in above figure root = newNode(30) root.left = newNode(5) root.middle = newNode(11) root.right = newNode(63) root.left.left = newNode(1) root.left.middle = newNode(4) root.left.right = newNode(8) root.middle.left = newNode(6) root.middle.middle = newNode(7) root.middle.right = newNode(15) root.right.left = newNode(31) root.right.middle = newNode(55) root.right.right = newNode(65) # The function which initiates the list # process returns the head. head = None gfg = GFG() head = gfg.startTree(root) gfg.printList(head) # This code is contributed by Winston Sebastian Pais // C# program to create a doubly linked// list from a given ternary tree.using System; // Custom node class.public class newNode{ public int data; public newNode left, middle, right; public newNode(int data) { this.data = data; left = middle = right = null; }} class GFG{ // tail of the linked list.public static newNode tail; // function to push the node to the tail.public static void push(newNode node){ // to put the node at the end of // the already existing tail. tail.right = node; // to point to the previous node. node.left = tail; // middle pointer should point to // nothing so null. initiate right // pointer to null. node.middle = node.right = null; // update the tail position. tail = node;} /* Create a doubly linked list outof given a ternary tree. by traversingthe tree in preorder fashion. */public static void ternaryTree(newNode node, newNode head){ if (node == null) { return; } newNode left = node.left; newNode middle = node.middle; newNode right = node.right; if (tail != node) { // already root is in the tail so dont push // the node when it was root.In the first // case both node and tail have root in them. push(node); } // First the left child is to be taken. // Then middle and then right child. ternaryTree(left, head); ternaryTree(middle, head); ternaryTree(right, head);} // function to initiate the list process.public static newNode startTree(newNode root){ // Initiate the head and tail with root. newNode head = root; tail = root; ternaryTree(root,head); // since the head,root are passed // with reference the changes in // root will be reflected in head. return head;} // Utility function for printing// double linked list.public static void printList(newNode head){ Console.Write("Created Double Linked list is:\n"); while (head != null) { Console.Write(head.data + " "); head = head.right; }} // Driver Codepublic static void Main(string[] args){ // Constructing ternary tree as shown // in above figure newNode root = new newNode(30); root.left = new newNode(5); root.middle = new newNode(11); root.right = new newNode(63); root.left.left = new newNode(1); root.left.middle = new newNode(4); root.left.right = new newNode(8); root.middle.left = new newNode(6); root.middle.middle = new newNode(7); root.middle.right = new newNode(15); root.right.left = new newNode(31); root.right.middle = new newNode(55); root.right.right = new newNode(65); // The function which initiates the list // process returns the head. newNode head = startTree(root); printList(head);}} // This code is contributed by Shrikant13 <script>//javascript program to create a doubly linked list// from a given ternary tree. //Custom node class.class newNode { constructor(data) { this.data = data; this.left = null; this.middle = null; this.right = null; }} // tail of the linked list. var tail; // function to push the node to the tail. function push( node) { // to put the node at the end of // the already existing tail. tail.right = node; // to point to the previous node. node.left = tail; // middle pointer should point to // nothing so null. initiate right // pointer to null. node.middle = node.right = null; // update the tail position. tail = node; } /* * Create a doubly linked list out of given a ternary tree. by traversing the * tree in preorder fashion. */ function ternaryTree( node, head) { if (node == null) return; var left = node.left; var middle = node.middle; var right = node.right; if (tail != node) // already root is in the tail so dont push // the node when it was root.In the first // case both node and tail have root in them. push(node); // First the left child is to be taken. // Then middle and then right child. ternaryTree(left, head); ternaryTree(middle, head); ternaryTree(right, head); } // function to initiate the list process. function startTree( root) { // Initiate the head and tail with root. var head = root; tail = root; ternaryTree(root, head); // since the head,root are passed // with reference the changes in // root will be reflected in head. return head; } // Utility function for printing var linked list. function printList( head) { document.write("Created Double Linked list is:<br/>"); while (head != null) { document.write(head.data + " "); head = head.right; } } // Driver program to test above functions // Constructing ternary tree as shown // in above figure root = new newNode(30); root.left = new newNode(5); root.middle = new newNode(11); root.right = new newNode(63); root.left.left = new newNode(1); root.left.middle = new newNode(4); root.left.right = new newNode(8); root.middle.left = new newNode(6); root.middle.middle = new newNode(7); root.middle.right = new newNode(15); root.right.left = new newNode(31); root.right.middle = new newNode(55); root.right.right = new newNode(65); // The function which initiates the list // process returns the head. head = startTree(root); printList(head); // This code contributed by gauravrajput1</script> Output: Created Double Linked list is: 30 5 1 4 8 11 6 7 15 63 31 55 65 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above MvssTeja shrikanth13 winstonpaisarsenal GauravRajput1 anikakapoor kalrap615 simranarora5sos spratik doubly linked list Linked List Tree Linked List Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Swap nodes in a linked list without swapping data Given a linked list which is sorted, how will you insert in sorted way Delete a node in a Doubly Linked List Circular Linked List | Set 2 (Traversal) Circular Singly Linked List | Insertion Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion
[ { "code": null, "e": 24880, "s": 24852, "text": "\n29 Mar, 2022" }, { "code": null, "e": 25059, "s": 24880, "text": "Given a ternary tree, create a doubly linked list out of it. A ternary tree is just like binary tree but instead of having two nodes, it has three nodes i.e. left, middle, right." }, { "code": null, "e": 25120, "s": 25059, "text": "The doubly linked list should holds following properties – " }, { "code": null, "e": 25518, "s": 25120, "text": "Left pointer of ternary tree should act as prev pointer of doubly linked list.Middle pointer of ternary tree should not point to anything.Right pointer of ternary tree should act as next pointer of doubly linked list.Each node of ternary tree is inserted into doubly linked list before its subtrees and for any node, its left child will be inserted first, followed by mid and right child (if any)." }, { "code": null, "e": 25597, "s": 25518, "text": "Left pointer of ternary tree should act as prev pointer of doubly linked list." }, { "code": null, "e": 25658, "s": 25597, "text": "Middle pointer of ternary tree should not point to anything." }, { "code": null, "e": 25738, "s": 25658, "text": "Right pointer of ternary tree should act as next pointer of doubly linked list." }, { "code": null, "e": 25919, "s": 25738, "text": "Each node of ternary tree is inserted into doubly linked list before its subtrees and for any node, its left child will be inserted first, followed by mid and right child (if any)." }, { "code": null, "e": 26089, "s": 25919, "text": "For the above example, the linked list formed for below tree should be NULL <- 30 <-> 5 <-> 1 <-> 4 <-> 8 <-> 11 <-> 6 <-> 7 <-> 15 <-> 63 <-> 31 <-> 55 <-> 65 -> NULL " }, { "code": null, "e": 26506, "s": 26089, "text": "We strongly recommend you to minimize your browser and try this yourself first.The idea is to traverse the tree in preorder fashion similar to binary tree preorder traversal. Here, when we visit a node, we will insert it into doubly linked list in the end using a tail pointer. That we use to maintain the required insertion order. We then recursively call for left child, middle child and right child in that order." }, { "code": null, "e": 26549, "s": 26506, "text": "Below is the implementation of this idea. " }, { "code": null, "e": 26553, "s": 26549, "text": "C++" }, { "code": null, "e": 26558, "s": 26553, "text": "Java" }, { "code": null, "e": 26566, "s": 26558, "text": "Python3" }, { "code": null, "e": 26569, "s": 26566, "text": "C#" }, { "code": null, "e": 26580, "s": 26569, "text": "Javascript" }, { "code": "// C++ program to create a doubly linked list out// of given a ternary tree.#include <bits/stdc++.h>using namespace std; /* A ternary tree */struct Node{ int data; struct Node *left, *middle, *right;}; /* Helper function that allocates a new node with the given data and assign NULL to left, middle and right pointers.*/Node* newNode(int data){ Node* node = new Node; node->data = data; node->left = node->middle = node->right = NULL; return node;} /* Utility function that constructs doubly linked listby inserting current node at the end of the doublylinked list by using a tail pointer */void push(Node** tail_ref, Node* node){ // initialize tail pointer if (*tail_ref == NULL) { *tail_ref = node; // set left, middle and right child to point // to NULL node->left = node->middle = node->right = NULL; return; } // insert node in the end using tail pointer (*tail_ref)->right = node; // set prev of node node->left = (*tail_ref); // set middle and right child to point to NULL node->right = node->middle = NULL; // now tail pointer will point to inserted node (*tail_ref) = node;} /* Create a doubly linked list out of given a ternary tree.by traversing the tree in preorder fashion. */void TernaryTreeToList(Node* root, Node** head_ref){ // Base case if (root == NULL) return; //create a static tail pointer static Node* tail = NULL; // store left, middle and right nodes // for future calls. Node* left = root->left; Node* middle = root->middle; Node* right = root->right; // set head of the doubly linked list // head will be root of the ternary tree if (*head_ref == NULL) *head_ref = root; // push current node in the end of DLL push(&tail, root); //recurse for left, middle and right child TernaryTreeToList(left, head_ref); TernaryTreeToList(middle, head_ref); TernaryTreeToList(right, head_ref);} // Utility function for printing double linked list.void printList(Node* head){ printf(\"Created Double Linked list is:\\n\"); while (head) { printf(\"%d \", head->data); head = head->right; }} // Driver program to test above functionsint main(){ // Constructing ternary tree as shown in above figure Node* root = newNode(30); root->left = newNode(5); root->middle = newNode(11); root->right = newNode(63); root->left->left = newNode(1); root->left->middle = newNode(4); root->left->right = newNode(8); root->middle->left = newNode(6); root->middle->middle = newNode(7); root->middle->right = newNode(15); root->right->left = newNode(31); root->right->middle = newNode(55); root->right->right = newNode(65); Node* head = NULL; TernaryTreeToList(root, &head); printList(head); return 0;}", "e": 29430, "s": 26580, "text": null }, { "code": "//Java program to create a doubly linked list// from a given ternary tree. //Custom node class.class newNode{ int data; newNode left,middle,right; public newNode(int data) { this.data = data; left = middle = right = null; }} class GFG { //tail of the linked list. static newNode tail; //function to push the node to the tail. public static void push(newNode node) { //to put the node at the end of // the already existing tail. tail.right = node; //to point to the previous node. node.left = tail; // middle pointer should point to // nothing so null. initiate right // pointer to null. node.middle = node.right = null; //update the tail position. tail = node; } /* Create a doubly linked list out of given a ternary tree. by traversing the tree in preorder fashion. */ public static void ternaryTree(newNode node,newNode head) { if(node == null) return; newNode left = node.left; newNode middle = node.middle; newNode right = node.right; if(tail != node) // already root is in the tail so dont push // the node when it was root.In the first // case both node and tail have root in them. push(node); // First the left child is to be taken. // Then middle and then right child. ternaryTree(left,head); ternaryTree(middle,head); ternaryTree(right,head); } //function to initiate the list process. public static newNode startTree(newNode root) { //Initiate the head and tail with root. newNode head = root; tail = root; ternaryTree(root,head); //since the head,root are passed // with reference the changes in // root will be reflected in head. return head; } // Utility function for printing double linked list. public static void printList(newNode head) { System.out.print(\"Created Double Linked list is:\\n\"); while(head != null) { System.out.print(head.data + \" \"); head = head.right; } } // Driver program to test above functions public static void main(String args[]) { // Constructing ternary tree as shown // in above figure newNode root = new newNode(30); root.left = new newNode(5); root.middle = new newNode(11); root.right = new newNode(63); root.left.left = new newNode(1); root.left.middle = new newNode(4); root.left.right = new newNode(8); root.middle.left = new newNode(6); root.middle.middle = new newNode(7); root.middle.right = new newNode(15); root.right.left = new newNode(31); root.right.middle = new newNode(55); root.right.right = new newNode(65); // The function which initiates the list // process returns the head. newNode head = startTree(root); printList(head); }} // This code is contributed by M.V.S.Surya Teja.", "e": 32699, "s": 29430, "text": null }, { "code": "# Python3 program to create a doubly linked# list out of given a ternary tree. # Custom node class.class newNode: def __init__(self, data): self.data = data self.left = None self.right = None self.middle = None class GFG: def __init__(self): # Tail of the linked list. self.tail = None # Function to push the node to the tail. def push(self, node): # To put the node at the end of # the already existing tail. self.tail.right = node # To point to the previous node. node.left = self.tail # Middle pointer should point to # nothing so null. initiate right # pointer to null. node.middle = node.right = None # Update the tail position. self.tail = node # Create a doubly linked list out of given # a ternary tree By traversing the tree in # preorder fashion. def ternaryTree(self, node, head): if node == None: return left = node.left middle = node.middle right = node.right if self.tail != node: # Already root is in the tail so dont push # the node when it was root.In the first # case both node and tail have root in them. self.push(node) # First the left child is to be taken. # Then middle and then right child. self.ternaryTree(left, head) self.ternaryTree(middle, head) self.ternaryTree(right, head) def startTree(self, root): # Initiate the head and tail with root. head = root self.tail = root self.ternaryTree(root, head) # Since the head,root are passed # with reference the changes in # root will be reflected in head. return head # Utility function for printing double linked list. def printList(self, head): print(\"Created Double Linked list is:\") while head: print(head.data, end = \" \") head = head.right # Driver codeif __name__ == '__main__': # Constructing ternary tree as shown # in above figure root = newNode(30) root.left = newNode(5) root.middle = newNode(11) root.right = newNode(63) root.left.left = newNode(1) root.left.middle = newNode(4) root.left.right = newNode(8) root.middle.left = newNode(6) root.middle.middle = newNode(7) root.middle.right = newNode(15) root.right.left = newNode(31) root.right.middle = newNode(55) root.right.right = newNode(65) # The function which initiates the list # process returns the head. head = None gfg = GFG() head = gfg.startTree(root) gfg.printList(head) # This code is contributed by Winston Sebastian Pais", "e": 35520, "s": 32699, "text": null }, { "code": "// C# program to create a doubly linked// list from a given ternary tree.using System; // Custom node class.public class newNode{ public int data; public newNode left, middle, right; public newNode(int data) { this.data = data; left = middle = right = null; }} class GFG{ // tail of the linked list.public static newNode tail; // function to push the node to the tail.public static void push(newNode node){ // to put the node at the end of // the already existing tail. tail.right = node; // to point to the previous node. node.left = tail; // middle pointer should point to // nothing so null. initiate right // pointer to null. node.middle = node.right = null; // update the tail position. tail = node;} /* Create a doubly linked list outof given a ternary tree. by traversingthe tree in preorder fashion. */public static void ternaryTree(newNode node, newNode head){ if (node == null) { return; } newNode left = node.left; newNode middle = node.middle; newNode right = node.right; if (tail != node) { // already root is in the tail so dont push // the node when it was root.In the first // case both node and tail have root in them. push(node); } // First the left child is to be taken. // Then middle and then right child. ternaryTree(left, head); ternaryTree(middle, head); ternaryTree(right, head);} // function to initiate the list process.public static newNode startTree(newNode root){ // Initiate the head and tail with root. newNode head = root; tail = root; ternaryTree(root,head); // since the head,root are passed // with reference the changes in // root will be reflected in head. return head;} // Utility function for printing// double linked list.public static void printList(newNode head){ Console.Write(\"Created Double Linked list is:\\n\"); while (head != null) { Console.Write(head.data + \" \"); head = head.right; }} // Driver Codepublic static void Main(string[] args){ // Constructing ternary tree as shown // in above figure newNode root = new newNode(30); root.left = new newNode(5); root.middle = new newNode(11); root.right = new newNode(63); root.left.left = new newNode(1); root.left.middle = new newNode(4); root.left.right = new newNode(8); root.middle.left = new newNode(6); root.middle.middle = new newNode(7); root.middle.right = new newNode(15); root.right.left = new newNode(31); root.right.middle = new newNode(55); root.right.right = new newNode(65); // The function which initiates the list // process returns the head. newNode head = startTree(root); printList(head);}} // This code is contributed by Shrikant13", "e": 38353, "s": 35520, "text": null }, { "code": "<script>//javascript program to create a doubly linked list// from a given ternary tree. //Custom node class.class newNode { constructor(data) { this.data = data; this.left = null; this.middle = null; this.right = null; }} // tail of the linked list. var tail; // function to push the node to the tail. function push( node) { // to put the node at the end of // the already existing tail. tail.right = node; // to point to the previous node. node.left = tail; // middle pointer should point to // nothing so null. initiate right // pointer to null. node.middle = node.right = null; // update the tail position. tail = node; } /* * Create a doubly linked list out of given a ternary tree. by traversing the * tree in preorder fashion. */ function ternaryTree( node, head) { if (node == null) return; var left = node.left; var middle = node.middle; var right = node.right; if (tail != node) // already root is in the tail so dont push // the node when it was root.In the first // case both node and tail have root in them. push(node); // First the left child is to be taken. // Then middle and then right child. ternaryTree(left, head); ternaryTree(middle, head); ternaryTree(right, head); } // function to initiate the list process. function startTree( root) { // Initiate the head and tail with root. var head = root; tail = root; ternaryTree(root, head); // since the head,root are passed // with reference the changes in // root will be reflected in head. return head; } // Utility function for printing var linked list. function printList( head) { document.write(\"Created Double Linked list is:<br/>\"); while (head != null) { document.write(head.data + \" \"); head = head.right; } } // Driver program to test above functions // Constructing ternary tree as shown // in above figure root = new newNode(30); root.left = new newNode(5); root.middle = new newNode(11); root.right = new newNode(63); root.left.left = new newNode(1); root.left.middle = new newNode(4); root.left.right = new newNode(8); root.middle.left = new newNode(6); root.middle.middle = new newNode(7); root.middle.right = new newNode(15); root.right.left = new newNode(31); root.right.middle = new newNode(55); root.right.right = new newNode(65); // The function which initiates the list // process returns the head. head = startTree(root); printList(head); // This code contributed by gauravrajput1</script>", "e": 41285, "s": 38353, "text": null }, { "code": null, "e": 41294, "s": 41285, "text": "Output: " }, { "code": null, "e": 41358, "s": 41294, "text": "Created Double Linked list is:\n30 5 1 4 8 11 6 7 15 63 31 55 65" }, { "code": null, "e": 41748, "s": 41358, "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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 41757, "s": 41748, "text": "MvssTeja" }, { "code": null, "e": 41769, "s": 41757, "text": "shrikanth13" }, { "code": null, "e": 41788, "s": 41769, "text": "winstonpaisarsenal" }, { "code": null, "e": 41802, "s": 41788, "text": "GauravRajput1" }, { "code": null, "e": 41814, "s": 41802, "text": "anikakapoor" }, { "code": null, "e": 41824, "s": 41814, "text": "kalrap615" }, { "code": null, "e": 41840, "s": 41824, "text": "simranarora5sos" }, { "code": null, "e": 41848, "s": 41840, "text": "spratik" }, { "code": null, "e": 41867, "s": 41848, "text": "doubly linked list" }, { "code": null, "e": 41879, "s": 41867, "text": "Linked List" }, { "code": null, "e": 41884, "s": 41879, "text": "Tree" }, { "code": null, "e": 41896, "s": 41884, "text": "Linked List" }, { "code": null, "e": 41901, "s": 41896, "text": "Tree" }, { "code": null, "e": 41999, "s": 41901, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42008, "s": 41999, "text": "Comments" }, { "code": null, "e": 42021, "s": 42008, "text": "Old Comments" }, { "code": null, "e": 42071, "s": 42021, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 42142, "s": 42071, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 42180, "s": 42142, "text": "Delete a node in a Doubly Linked List" }, { "code": null, "e": 42221, "s": 42180, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 42261, "s": 42221, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 42311, "s": 42261, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 42346, "s": 42311, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 42380, "s": 42346, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 42409, "s": 42380, "text": "AVL Tree | Set 1 (Insertion)" } ]
PostgreSQL – REPLACE Function
01 Feb, 2021 In PostgreSQL, the REPLACE function is used to search and replace all occurrences of a string with a new one. Syntax: REPLACE(source, old_text, new_text ); Let’s analyze the above syntax: The source is a string where you want to replace the existing string. The old_text is the string that is to be searched and subsequently replaced. The old_text can occur multiple times and each of them gets replaced on the function is executed. The new_text is the new text string that is suppose to replace the old text ( old_text ). Example 1: The following statement replaces the substring ‘tt’ with ‘xx’ in a URL: SELECT REPLACE ( 'https://www.geeksforgeeks.org', 'tt', 'xx' ); Output: Example 2: The below statement updates the email column to replace the domain ‘sakilacustomer.org’ with ‘geeksforgeek.org’, in the customer table of the sample database, ie, dvdrental: UPDATE customer SET email = REPLACE ( email, 'sakilacustomer.org', 'geeksforgeeks.org' ); To verify it use the below statement: SELECT first_name, last_name, email FROM customer; Output: PostgreSQL-function PostgreSQL-String-function PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - Psql commands PostgreSQL - Change Column Type PostgreSQL - For Loops PostgreSQL - LIMIT with OFFSET clause PostgreSQL - Function Returning A Table PostgreSQL - ARRAY_AGG() Function PostgreSQL - Copy Table PostgreSQL - DROP INDEX How to use PostgreSQL Database in Django? PostgreSQL - Identity Column
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2021" }, { "code": null, "e": 138, "s": 28, "text": "In PostgreSQL, the REPLACE function is used to search and replace all occurrences of a string with a new one." }, { "code": null, "e": 184, "s": 138, "text": "Syntax: REPLACE(source, old_text, new_text );" }, { "code": null, "e": 216, "s": 184, "text": "Let’s analyze the above syntax:" }, { "code": null, "e": 286, "s": 216, "text": "The source is a string where you want to replace the existing string." }, { "code": null, "e": 461, "s": 286, "text": "The old_text is the string that is to be searched and subsequently replaced. The old_text can occur multiple times and each of them gets replaced on the function is executed." }, { "code": null, "e": 551, "s": 461, "text": "The new_text is the new text string that is suppose to replace the old text ( old_text )." }, { "code": null, "e": 562, "s": 551, "text": "Example 1:" }, { "code": null, "e": 636, "s": 562, "text": "The following statement replaces the substring ‘tt’ with ‘xx’ in a URL:" }, { "code": null, "e": 732, "s": 636, "text": "SELECT\n REPLACE (\n 'https://www.geeksforgeeks.org',\n 'tt',\n 'xx'\n );" }, { "code": null, "e": 740, "s": 732, "text": "Output:" }, { "code": null, "e": 751, "s": 740, "text": "Example 2:" }, { "code": null, "e": 925, "s": 751, "text": "The below statement updates the email column to replace the domain ‘sakilacustomer.org’ with ‘geeksforgeek.org’, in the customer table of the sample database, ie, dvdrental:" }, { "code": null, "e": 1040, "s": 925, "text": "UPDATE \n customer\nSET \n email = REPLACE (\n email,\n 'sakilacustomer.org',\n 'geeksforgeeks.org'\n );" }, { "code": null, "e": 1078, "s": 1040, "text": "To verify it use the below statement:" }, { "code": null, "e": 1145, "s": 1078, "text": "SELECT\n first_name,\n last_name,\n email\nFROM\n customer;" }, { "code": null, "e": 1153, "s": 1145, "text": "Output:" }, { "code": null, "e": 1173, "s": 1153, "text": "PostgreSQL-function" }, { "code": null, "e": 1200, "s": 1173, "text": "PostgreSQL-String-function" }, { "code": null, "e": 1211, "s": 1200, "text": "PostgreSQL" }, { "code": null, "e": 1309, "s": 1211, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1336, "s": 1309, "text": "PostgreSQL - Psql commands" }, { "code": null, "e": 1368, "s": 1336, "text": "PostgreSQL - Change Column Type" }, { "code": null, "e": 1391, "s": 1368, "text": "PostgreSQL - For Loops" }, { "code": null, "e": 1429, "s": 1391, "text": "PostgreSQL - LIMIT with OFFSET clause" }, { "code": null, "e": 1469, "s": 1429, "text": "PostgreSQL - Function Returning A Table" }, { "code": null, "e": 1503, "s": 1469, "text": "PostgreSQL - ARRAY_AGG() Function" }, { "code": null, "e": 1527, "s": 1503, "text": "PostgreSQL - Copy Table" }, { "code": null, "e": 1551, "s": 1527, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 1593, "s": 1551, "text": "How to use PostgreSQL Database in Django?" } ]
Jaro and Jaro-Winkler similarity
15 Feb, 2022 Jaro Similarity is the measure of similarity between two strings. The value of Jaro distance ranges from 0 to 1. where 1 means the strings are equal and 0 means no similarity between the two strings. Examples: Input: s1 = “CRATE”, s2 = “TRACE”; Output: Jaro Similarity = 0.733333 Input: s1 = “DwAyNE”, s2 = “DuANE”; Output: Jaro Similarity = 0.822222 Algorithm: The Jaro Similarity is calculated using the following formula where: m is the number of matching characters t is half the number of transpositions where |s1| and |s2| are the lengths of strings s1 and s2 respectively. The characters are said to be matching if they are the same and the characters are not further than Transpositions are half the number of matching characters in both strings but in a different order.Calculation: Let s1=”arnab”, s2=”raanb”, so the maximum distance to which each character is matched is 1. It is evident that both the strings have 5 matching characters, but the order is not the same, so the number of characters that are not in order is 4, so the number of transpositions is 2. Therefore, Jaro similarity can be calculated as follows: Jaro Similarity = (1/3) * {(5/5) + (5/5) + (5-2)/5 } = 0.86667 Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to calculate the// Jaro Similarity of two stringsdouble jaro_distance(string s1, string s2){ // If the strings are equal if (s1 == s2) return 1.0; // Length of two strings int len1 = s1.length(), len2 = s2.length(); // Maximum distance upto which matching // is allowed int max_dist = floor(max(len1, len2) / 2) - 1; // Count of matches int match = 0; // Hash for matches int hash_s1[s1.length()] = { 0 }, hash_s2[s2.length()] = { 0 }; // Traverse through the first string for (int i = 0; i < len1; i++) { // Check if there is any matches for (int j = max(0, i - max_dist); j < min(len2, i + max_dist + 1); j++) // If there is a match if (s1[i] == s2[j] && hash_s2[j] == 0) { hash_s1[i] = 1; hash_s2[j] = 1; match++; break; } } // If there is no match if (match == 0) return 0.0; // Number of transpositions double t = 0; int point = 0; // Count number of occurrences // where two characters match but // there is a third matched character // in between the indices for (int i = 0; i < len1; i++) if (hash_s1[i]) { // Find the next matched character // in second string while (hash_s2[point] == 0) point++; if (s1[i] != s2[point++]) t++; } t /= 2; // Return the Jaro Similarity return (((double)match) / ((double)len1) + ((double)match) / ((double)len2) + ((double)match - t) / ((double)match)) / 3.0;} // Driver codeint main(){ string s1 = "CRATE", s2 = "TRACE"; // Print jaro Similarity of two strings cout << jaro_distance(s1, s2) << endl; return 0;} // Java implementation of above approachclass GFG{ // Function to calculate the// Jaro Similarity of two Stringsstatic double jaro_distance(String s1, String s2){ // If the Strings are equal if (s1 == s2) return 1.0; // Length of two Strings int len1 = s1.length(), len2 = s2.length(); // Maximum distance upto which matching // is allowed int max_dist = (int) (Math.floor(Math.max(len1, len2) / 2) - 1); // Count of matches int match = 0; // Hash for matches int hash_s1[] = new int[s1.length()]; int hash_s2[] = new int[s2.length()]; // Traverse through the first String for (int i = 0; i < len1; i++) { // Check if there is any matches for (int j = Math.max(0, i - max_dist); j < Math.min(len2, i + max_dist + 1); j++) // If there is a match if (s1.charAt(i) == s2.charAt(j) && hash_s2[j] == 0) { hash_s1[i] = 1; hash_s2[j] = 1; match++; break; } } // If there is no match if (match == 0) return 0.0; // Number of transpositions double t = 0; int point = 0; // Count number of occurrences // where two characters match but // there is a third matched character // in between the indices for (int i = 0; i < len1; i++) if (hash_s1[i] == 1) { // Find the next matched character // in second String while (hash_s2[point] == 0) point++; if (s1.charAt(i) != s2.charAt(point++) ) t++; } t /= 2; // Return the Jaro Similarity return (((double)match) / ((double)len1) + ((double)match) / ((double)len2) + ((double)match - t) / ((double)match)) / 3.0;} // Driver codepublic static void main(String[] args){ String s1 = "CRATE", s2 = "TRACE"; // Print jaro Similarity of two Strings System.out.print(jaro_distance(s1, s2) +"\n");}} // This code is contributed by PrinciRaj1992 # Python3 implementation of above approachfrom math import floor, ceil # Function to calculate the# Jaro Similarity of two sdef jaro_distance(s1, s2): # If the s are equal if (s1 == s2): return 1.0 # Length of two s len1 = len(s1) len2 = len(s2) # Maximum distance upto which matching # is allowed max_dist = floor(max(len1, len2) / 2) - 1 # Count of matches match = 0 # Hash for matches hash_s1 = [0] * len(s1) hash_s2 = [0] * len(s2) # Traverse through the first for i in range(len1): # Check if there is any matches for j in range(max(0, i - max_dist), min(len2, i + max_dist + 1)): # If there is a match if (s1[i] == s2[j] and hash_s2[j] == 0): hash_s1[i] = 1 hash_s2[j] = 1 match += 1 break # If there is no match if (match == 0): return 0.0 # Number of transpositions t = 0 point = 0 # Count number of occurrences # where two characters match but # there is a third matched character # in between the indices for i in range(len1): if (hash_s1[i]): # Find the next matched character # in second while (hash_s2[point] == 0): point += 1 if (s1[i] != s2[point]): t += 1 point += 1 t = t//2 # Return the Jaro Similarity return (match/ len1 + match / len2 + (match - t) / match)/ 3.0 # Driver codes1 = "CRATE"s2 = "TRACE" # Prjaro Similarity of two sprint(round(jaro_distance(s1, s2),6)) # This code is contributed by mohit kumar 29 // C# implementation of above approachusing System; class GFG{ // Function to calculate the // Jaro Similarity of two Strings static double jaro_distance(string s1, string s2) { // If the Strings are equal if (s1 == s2) return 1.0; // Length of two Strings int len1 = s1.Length ; int len2 = s2.Length; // Maximum distance upto which matching // is allowed int max_dist = (int)(Math.Floor((double)( (Math.Max(len1, len2) / 2) - 1))); // Count of matches int match = 0; // Hash for matches int []hash_s1 = new int[s1.Length]; int []hash_s2 = new int[s2.Length]; // Traverse through the first String for (int i = 0; i < len1; i++) { // Check if there is any matches for (int j = Math.Max(0, i - max_dist); j < Math.Min(len2, i + max_dist + 1); j++) // If there is a match if (s1[i] == s2[j] && hash_s2[j] == 0) { hash_s1[i] = 1; hash_s2[j] = 1; match++; break; } } // If there is no match if (match == 0) return 0.0; // Number of transpositions double t = 0; int point = 0; // Count number of occurrences // where two characters match but // there is a third matched character // in between the indices for (int i = 0; i < len1; i++) if (hash_s1[i] == 1) { // Find the next matched character // in second String while (hash_s2[point] == 0) point++; if (s1[i] != s2[point++] ) t++; } t /= 2; // Return the Jaro Similarity return (((double)match) / ((double)len1) + ((double)match) / ((double)len2) + ((double)match - t) / ((double)match)) / 3.0; } // Driver code public static void Main() { string s1 = "CRATE", s2 = "TRACE"; // Print jaro Similarity of two Strings Console.WriteLine(jaro_distance(s1, s2)); }} // This code is contributed by AnkitRai01 <script> // Javascript implementation of above approach // Function to calculate the// Jaro Similarity of two stringsfunction jaro_distance(s1, s2){ // If the strings are equal if (s1 == s2) return 1.0; // Length of two strings var len1 = s1.length, len2 = s2.length; // Maximum distance upto which matching // is allowed var max_dist = Math.floor(Math.max(len1, len2) / 2) - 1; // Count of matches var match = 0; // Hash for matches var hash_s1 = Array(s1.length).fill(0); var hash_s2 = Array(s1.length).fill(0); // Traverse through the first string for (var i = 0; i < len1; i++) { // Check if there is any matches for (var j = Math.max(0, i - max_dist); j < Math.min(len2, i + max_dist + 1); j++) // If there is a match if (s1[i] == s2[j] && hash_s2[j] == 0) { hash_s1[i] = 1; hash_s2[j] = 1; match++; break; } } // If there is no match if (match == 0) return 0.0; // Number of transpositions var t = 0; var point = 0; // Count number of occurrences // where two characters match but // there is a third matched character // in between the indices for (var i = 0; i < len1; i++) if (hash_s1[i]) { // Find the next matched character // in second string while (hash_s2[point] == 0) point++; if (s1[i] != s2[point++]) t++; } t /= 2; // Return the Jaro Similarity return ((match) / (len1) + (match) / (len2) + (match - t) / (match)) / 3.0;} // Driver codevar s1 = "CRATE", s2 = "TRACE";// Print jaro Similarity of two stringsdocument.write( jaro_distance(s1, s2).toFixed(5)); </script> 0.733333 Time Complexity: O(N * M), where N is the length of string s1 and M is the length of string s2. Auxiliary Space: O(N + M) The Jaro-Winkler similarity is a string metric measuring edit distance between two strings. Jaro – Winkler Similarity is much similar to Jaro Similarity. They both differ when the prefix of two string match. Jaro – Winkler Similarity uses a prefix scale ‘p’ which gives a more accurate answer when the strings have a common prefix up to a defined maximum length l. Examples: Input: s1 = “DwAyNE”, s2 = “DuANE”; Output: Jaro-Winkler Similarity =0.84 Input: s1=”TRATE”, s2=”TRACE”; Output: Jaro-Winkler similarity = 0.906667 Calculation: Jaro Winkler similarity is defined as follows Sw = Sj + P * L * (1 – Sj) where, Sj, is jaro similaritySw, is jaro- winkler similarityP is the scaling factor (0.1 by default)L is the length of the matching prefix up to a maximum of 4 characters. Sj, is jaro similarity Sw, is jaro- winkler similarity P is the scaling factor (0.1 by default) L is the length of the matching prefix up to a maximum of 4 characters. Let s1=”arnab”, s2=”aranb”. The Jaro similarity of the two strings is 0.933333 (From the above calculation.) The length of the matching prefix is 2 and we take the scaling factor as 0.1. Substituting in the formula; Jaro-Winkler Similarity= 0.9333333 + 0.1 * 2 * (1-0.9333333) = 0.946667 Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to calculate the// Jaro Similarity of two stringsdouble jaro_distance(string s1, string s2){ // If the strings are equal if (s1 == s2) return 1.0; // Length of two strings int len1 = s1.length(), len2 = s2.length(); if (len1 == 0 || len2 == 0) return 0.0; // Maximum distance upto which matching // is allowed int max_dist = floor(max(len1, len2) / 2) - 1; // Count of matches int match = 0; // Hash for matches int hash_s1[s1.length()] = { 0 }, hash_s2[s2.length()] = { 0 }; // Traverse through the first string for (int i = 0; i < len1; i++) { // Check if there is any matches for (int j = max(0, i - max_dist); j < min(len2, i + max_dist + 1); j++) // If there is a match if (s1[i] == s2[j] && hash_s2[j] == 0) { hash_s1[i] = 1; hash_s2[j] = 1; match++; break; } } // If there is no match if (match == 0) return 0.0; // Number of transpositions double t = 0; int point = 0; // Count number of occurrences // where two characters match but // there is a third matched character // in between the indices for (int i = 0; i < len1; i++) if (hash_s1[i]) { // Find the next matched character // in second string while (hash_s2[point] == 0) point++; if (s1[i] != s2[point++]) t++; } t /= 2; // Return the Jaro Similarity return (((double)match) / ((double)len1) + ((double)match) / ((double)len2) + ((double)match - t) / ((double)match)) / 3.0;} // Jaro Winkler Similaritydouble jaro_Winkler(string s1, string s2){ double jaro_dist = jaro_distance(s1, s2); // If the jaro Similarity is above a threshold if (jaro_dist > 0.7) { // Find the length of common prefix int prefix = 0; for (int i = 0; i < min(s1.length(), s2.length()); i++) { // If the characters match if (s1[i] == s2[i]) prefix++; // Else break else break; } // Maximum of 4 characters are allowed in prefix prefix = min(4, prefix); // Calculate jaro winkler Similarity jaro_dist += 0.1 * prefix * (1 - jaro_dist); } return jaro_dist;} // Driver codeint main(){ string s1 = "TRATE", s2 = "TRACE"; // Print Jaro-Winkler Similarity of two strings cout << "Jaro-Winkler Similarity =" << jaro_Winkler(s1, s2) << endl; return 0;} // Java implementation of above approachclass GFG{ // Function to calculate the // Jaro Similarity of two strings static double jaro_distance(String s1, String s2) { // If the strings are equal if (s1 == s2) return 1.0; // Length of two strings int len1 = s1.length(), len2 = s2.length(); if (len1 == 0 || len2 == 0) return 0.0; // Maximum distance upto which matching // is allowed int max_dist = (int)Math.floor(Math.max(len1, len2) / 2) - 1; // Count of matches int match = 0; // Hash for matches int hash_s1[] = new int [s1.length()]; int hash_s2[] = new int[s2.length()]; // Traverse through the first string for (int i = 0; i < len1; i++) { // Check if there is any matches for (int j = Math.max(0, i - max_dist); j < Math.min(len2, i + max_dist + 1); j++) // If there is a match if (s1.charAt(i) == s2.charAt(j) && hash_s2[j] == 0) { hash_s1[i] = 1; hash_s2[j] = 1; match++; break; } } // If there is no match if (match == 0) return 0.0; // Number of transpositions double t = 0; int point = 0; // Count number of occurrences // where two characters match but // there is a third matched character // in between the indices for (int i = 0; i < len1; i++) if (hash_s1[i] == 1) { // Find the next matched character // in second string while (hash_s2[point] == 0) point++; if (s1.charAt(i) != s2.charAt(point++)) t++; } t /= 2; // Return the Jaro Similarity return (((double)match) / ((double)len1) + ((double)match) / ((double)len2) + ((double)match - t) / ((double)match)) / 3.0; } // Jaro Winkler Similarity static double jaro_Winkler(String s1, String s2) { double jaro_dist = jaro_distance(s1, s2); // If the jaro Similarity is above a threshold if (jaro_dist > 0.7) { // Find the length of common prefix int prefix = 0; for (int i = 0; i < Math.min(s1.length(), s2.length()); i++) { // If the characters match if (s1.charAt(i) == s2.charAt(i)) prefix++; // Else break else break; } // Maximum of 4 characters are allowed in prefix prefix = Math.min(4, prefix); // Calculate jaro winkler Similarity jaro_dist += 0.1 * prefix * (1 - jaro_dist); } return jaro_dist; } // Driver code public static void main (String[] args) { String s1 = "TRATE", s2 = "TRACE"; // Print Jaro-Winkler Similarity of two strings System.out.println("Jaro-Winkler Similarity =" + jaro_Winkler(s1, s2)); }} // This code is contributed by AnkitRai01 # Python3 implementation of above approachfrom math import floor # Function to calculate the# Jaro Similarity of two stringsdef jaro_distance(s1, s2) : # If the strings are equal if (s1 == s2) : return 1.0; # Length of two strings len1 = len(s1); len2 = len(s2); if (len1 == 0 or len2 == 0) : return 0.0; # Maximum distance upto which matching # is allowed max_dist = (max(len(s1), len(s2)) // 2 ) - 1; # Count of matches match = 0; # Hash for matches hash_s1 = [0] * len(s1) ; hash_s2 = [0] * len(s2) ; # Traverse through the first string for i in range(len1) : # Check if there is any matches for j in range( max(0, i - max_dist), min(len2, i + max_dist + 1)) : # If there is a match if (s1[i] == s2[j] and hash_s2[j] == 0) : hash_s1[i] = 1; hash_s2[j] = 1; match += 1; break; # If there is no match if (match == 0) : return 0.0; # Number of transpositions t = 0; point = 0; # Count number of occurrences # where two characters match but # there is a third matched character # in between the indices for i in range(len1) : if (hash_s1[i]) : # Find the next matched character # in second string while (hash_s2[point] == 0) : point += 1; if (s1[i] != s2[point]) : point += 1; t += 1; else : point += 1; t /= 2; # Return the Jaro Similarity return ((match / len1 + match / len2 + (match - t) / match ) / 3.0); # Jaro Winkler Similaritydef jaro_Winkler(s1, s2) : jaro_dist = jaro_distance(s1, s2); # If the jaro Similarity is above a threshold if (jaro_dist > 0.7) : # Find the length of common prefix prefix = 0; for i in range(min(len(s1), len(s2))) : # If the characters match if (s1[i] == s2[i]) : prefix += 1; # Else break else : break; # Maximum of 4 characters are allowed in prefix prefix = min(4, prefix); # Calculate jaro winkler Similarity jaro_dist += 0.1 * prefix * (1 - jaro_dist); return jaro_dist; # Driver codeif __name__ == "__main__" : s1 = "TRATE"; s2 = "TRACE"; # Print Jaro-Winkler Similarity of two strings print("Jaro-Winkler Similarity =", jaro_Winkler(s1, s2)) ; # This code is contributed by AnkitRai01 // C# implementation of above approachusing System; class GFG{ // Function to calculate the // Jaro Similarity of two strings static double jaro_distance(string s1, string s2) { // If the strings are equal if (s1 == s2) return 1.0; // Length of two strings int len1 = s1.Length, len2 = s2.Length; if (len1 == 0 || len2 == 0) return 0.0; // Maximum distance upto which matching // is allowed int max_dist = (int)Math.Floor((double) Math.Max(len1, len2) / 2) - 1; // Count of matches int match = 0; // Hash for matches int []hash_s1 = new int [s1.Length]; int []hash_s2 = new int[s2.Length]; // Traverse through the first string for (int i = 0; i < len1; i++) { // Check if there is any matches for (int j = Math.Max(0, i - max_dist); j < Math.Min(len2, i + max_dist + 1); j++) // If there is a match if (s1[i] == s2[j] && hash_s2[j] == 0) { hash_s1[i] = 1; hash_s2[j] = 1; match++; break; } } // If there is no match if (match == 0) return 0.0; // Number of transpositions double t = 0; int point = 0; // Count number of occurrences // where two characters match but // there is a third matched character // in between the indices for (int i = 0; i < len1; i++) if (hash_s1[i] == 1) { // Find the next matched character // in second string while (hash_s2[point] == 0) point++; if (s1[i] != s2[point++]) t++; } t /= 2; // Return the Jaro Similarity return (((double)match) / ((double)len1) + ((double)match) / ((double)len2) + ((double)match - t) / ((double)match)) / 3.0; } // Jaro Winkler Similarity static double jaro_Winkler(string s1, string s2) { double jaro_dist = jaro_distance(s1, s2); // If the jaro Similarity is above a threshold if (jaro_dist > 0.7) { // Find the length of common prefix int prefix = 0; for (int i = 0; i < Math.Min(s1.Length, s2.Length); i++) { // If the characters match if (s1[i] == s2[i]) prefix++; // Else break else break; } // Maximum of 4 characters are allowed in prefix prefix = Math.Min(4, prefix); // Calculate jaro winkler Similarity jaro_dist += 0.1 * prefix * (1 - jaro_dist); } return jaro_dist; } // Driver code public static void Main () { string s1 = "TRATE", s2 = "TRACE"; // Print Jaro-Winkler Similarity of two strings Console.WriteLine("Jaro-Winkler Similarity =" + jaro_Winkler(s1, s2)); }} // This code is contributed by AnkitRai01 <script> // Javascript implementation of above approach // Function to calculate the // Jaro Similarity of two strings function jaro_distance(s1, s2) { // If the strings are equal if (s1 == s2) return 1.0; // Length of two strings let len1 = s1.length, len2 = s2.length; if (len1 == 0 || len2 == 0) return 0.0; // Maximum distance upto which matching // is allowed let max_dist = Math.floor(Math.max(len1, len2) / 2) - 1; // Count of matches let match = 0; // Hash for matches let hash_s1 = new Array(s1.length); hash_s1.fill(0); let hash_s2 = new Array(s2.length); hash_s2.fill(0); // Traverse through the first string for (let i = 0; i < len1; i++) { // Check if there is any matches for (let j = Math.max(0, i - max_dist); j < Math.min(len2, i + max_dist + 1); j++) // If there is a match if (s1[i] == s2[j] && hash_s2[j] == 0) { hash_s1[i] = 1; hash_s2[j] = 1; match++; break; } } // If there is no match if (match == 0) return 0.0; // Number of transpositions let t = 0; let point = 0; // Count number of occurrences // where two characters match but // there is a third matched character // in between the indices for (let i = 0; i < len1; i++) if (hash_s1[i] == 1) { // Find the next matched character // in second string while (hash_s2[point] == 0) point++; if (s1[i] != s2[point++]) t++; } t /= 2; // Return the Jaro Similarity return ((match) / (len1) + (match) / (len2) + (match - t) / (match)) / 3.0; } // Jaro Winkler Similarity function jaro_Winkler(s1, s2) { let jaro_dist = jaro_distance(s1, s2); // If the jaro Similarity is above a threshold if (jaro_dist > 0.7) { // Find the length of common prefix let prefix = 0; for (let i = 0; i < Math.min(s1.length,s2.length); i++) { // If the characters match if (s1[i] == s2[i]) prefix++; // Else break else break; } // Maximum of 4 characters are allowed in prefix prefix = Math.min(4, prefix); // Calculate jaro winkler Similarity jaro_dist += 0.1 * prefix * (1 - jaro_dist); } return jaro_dist.toFixed(6); } let s1 = "TRATE", s2 = "TRACE"; // Print Jaro-Winkler Similarity of two strings document.write("Jaro-Winkler Similarity =" + jaro_Winkler(s1, s2)); </script> Jaro-Winkler Similarity =0.906667 Time Complexity: O(N * M), where N is the length of string s1 and M is the length of string s2.Auxiliary Space: O(N + M) mohit kumar 29 princiraj1992 ankthon nidhi_biet rutvik_56 decode2207 varshagumber28 sumitgumber28 pankajsharmagfg idahu amartyaghoshgfg subham348 edit-distance substring Technical Scripter 2019 Algorithms Mathematical Strings Technical Scripter Strings Mathematical Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Feb, 2022" }, { "code": null, "e": 256, "s": 54, "text": "Jaro Similarity is the measure of similarity between two strings. The value of Jaro distance ranges from 0 to 1. where 1 means the strings are equal and 0 means no similarity between the two strings. " }, { "code": null, "e": 267, "s": 256, "text": "Examples: " }, { "code": null, "e": 337, "s": 267, "text": "Input: s1 = “CRATE”, s2 = “TRACE”; Output: Jaro Similarity = 0.733333" }, { "code": null, "e": 408, "s": 337, "text": "Input: s1 = “DwAyNE”, s2 = “DuANE”; Output: Jaro Similarity = 0.822222" }, { "code": null, "e": 482, "s": 408, "text": "Algorithm: The Jaro Similarity is calculated using the following formula " }, { "code": null, "e": 494, "s": 487, "text": "where:" }, { "code": null, "e": 533, "s": 494, "text": "m is the number of matching characters" }, { "code": null, "e": 572, "s": 533, "text": "t is half the number of transpositions" }, { "code": null, "e": 643, "s": 572, "text": "where |s1| and |s2| are the lengths of strings s1 and s2 respectively." }, { "code": null, "e": 856, "s": 643, "text": "The characters are said to be matching if they are the same and the characters are not further than Transpositions are half the number of matching characters in both strings but in a different order.Calculation: " }, { "code": null, "e": 949, "s": 856, "text": "Let s1=”arnab”, s2=”raanb”, so the maximum distance to which each character is matched is 1." }, { "code": null, "e": 1138, "s": 949, "text": "It is evident that both the strings have 5 matching characters, but the order is not the same, so the number of characters that are not in order is 4, so the number of transpositions is 2." }, { "code": null, "e": 1258, "s": 1138, "text": "Therefore, Jaro similarity can be calculated as follows: Jaro Similarity = (1/3) * {(5/5) + (5/5) + (5-2)/5 } = 0.86667" }, { "code": null, "e": 1309, "s": 1258, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 1313, "s": 1309, "text": "C++" }, { "code": null, "e": 1318, "s": 1313, "text": "Java" }, { "code": null, "e": 1326, "s": 1318, "text": "Python3" }, { "code": null, "e": 1329, "s": 1326, "text": "C#" }, { "code": null, "e": 1340, "s": 1329, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to calculate the// Jaro Similarity of two stringsdouble jaro_distance(string s1, string s2){ // If the strings are equal if (s1 == s2) return 1.0; // Length of two strings int len1 = s1.length(), len2 = s2.length(); // Maximum distance upto which matching // is allowed int max_dist = floor(max(len1, len2) / 2) - 1; // Count of matches int match = 0; // Hash for matches int hash_s1[s1.length()] = { 0 }, hash_s2[s2.length()] = { 0 }; // Traverse through the first string for (int i = 0; i < len1; i++) { // Check if there is any matches for (int j = max(0, i - max_dist); j < min(len2, i + max_dist + 1); j++) // If there is a match if (s1[i] == s2[j] && hash_s2[j] == 0) { hash_s1[i] = 1; hash_s2[j] = 1; match++; break; } } // If there is no match if (match == 0) return 0.0; // Number of transpositions double t = 0; int point = 0; // Count number of occurrences // where two characters match but // there is a third matched character // in between the indices for (int i = 0; i < len1; i++) if (hash_s1[i]) { // Find the next matched character // in second string while (hash_s2[point] == 0) point++; if (s1[i] != s2[point++]) t++; } t /= 2; // Return the Jaro Similarity return (((double)match) / ((double)len1) + ((double)match) / ((double)len2) + ((double)match - t) / ((double)match)) / 3.0;} // Driver codeint main(){ string s1 = \"CRATE\", s2 = \"TRACE\"; // Print jaro Similarity of two strings cout << jaro_distance(s1, s2) << endl; return 0;}", "e": 3267, "s": 1340, "text": null }, { "code": "// Java implementation of above approachclass GFG{ // Function to calculate the// Jaro Similarity of two Stringsstatic double jaro_distance(String s1, String s2){ // If the Strings are equal if (s1 == s2) return 1.0; // Length of two Strings int len1 = s1.length(), len2 = s2.length(); // Maximum distance upto which matching // is allowed int max_dist = (int) (Math.floor(Math.max(len1, len2) / 2) - 1); // Count of matches int match = 0; // Hash for matches int hash_s1[] = new int[s1.length()]; int hash_s2[] = new int[s2.length()]; // Traverse through the first String for (int i = 0; i < len1; i++) { // Check if there is any matches for (int j = Math.max(0, i - max_dist); j < Math.min(len2, i + max_dist + 1); j++) // If there is a match if (s1.charAt(i) == s2.charAt(j) && hash_s2[j] == 0) { hash_s1[i] = 1; hash_s2[j] = 1; match++; break; } } // If there is no match if (match == 0) return 0.0; // Number of transpositions double t = 0; int point = 0; // Count number of occurrences // where two characters match but // there is a third matched character // in between the indices for (int i = 0; i < len1; i++) if (hash_s1[i] == 1) { // Find the next matched character // in second String while (hash_s2[point] == 0) point++; if (s1.charAt(i) != s2.charAt(point++) ) t++; } t /= 2; // Return the Jaro Similarity return (((double)match) / ((double)len1) + ((double)match) / ((double)len2) + ((double)match - t) / ((double)match)) / 3.0;} // Driver codepublic static void main(String[] args){ String s1 = \"CRATE\", s2 = \"TRACE\"; // Print jaro Similarity of two Strings System.out.print(jaro_distance(s1, s2) +\"\\n\");}} // This code is contributed by PrinciRaj1992", "e": 5323, "s": 3267, "text": null }, { "code": "# Python3 implementation of above approachfrom math import floor, ceil # Function to calculate the# Jaro Similarity of two sdef jaro_distance(s1, s2): # If the s are equal if (s1 == s2): return 1.0 # Length of two s len1 = len(s1) len2 = len(s2) # Maximum distance upto which matching # is allowed max_dist = floor(max(len1, len2) / 2) - 1 # Count of matches match = 0 # Hash for matches hash_s1 = [0] * len(s1) hash_s2 = [0] * len(s2) # Traverse through the first for i in range(len1): # Check if there is any matches for j in range(max(0, i - max_dist), min(len2, i + max_dist + 1)): # If there is a match if (s1[i] == s2[j] and hash_s2[j] == 0): hash_s1[i] = 1 hash_s2[j] = 1 match += 1 break # If there is no match if (match == 0): return 0.0 # Number of transpositions t = 0 point = 0 # Count number of occurrences # where two characters match but # there is a third matched character # in between the indices for i in range(len1): if (hash_s1[i]): # Find the next matched character # in second while (hash_s2[point] == 0): point += 1 if (s1[i] != s2[point]): t += 1 point += 1 t = t//2 # Return the Jaro Similarity return (match/ len1 + match / len2 + (match - t) / match)/ 3.0 # Driver codes1 = \"CRATE\"s2 = \"TRACE\" # Prjaro Similarity of two sprint(round(jaro_distance(s1, s2),6)) # This code is contributed by mohit kumar 29", "e": 7005, "s": 5323, "text": null }, { "code": "// C# implementation of above approachusing System; class GFG{ // Function to calculate the // Jaro Similarity of two Strings static double jaro_distance(string s1, string s2) { // If the Strings are equal if (s1 == s2) return 1.0; // Length of two Strings int len1 = s1.Length ; int len2 = s2.Length; // Maximum distance upto which matching // is allowed int max_dist = (int)(Math.Floor((double)( (Math.Max(len1, len2) / 2) - 1))); // Count of matches int match = 0; // Hash for matches int []hash_s1 = new int[s1.Length]; int []hash_s2 = new int[s2.Length]; // Traverse through the first String for (int i = 0; i < len1; i++) { // Check if there is any matches for (int j = Math.Max(0, i - max_dist); j < Math.Min(len2, i + max_dist + 1); j++) // If there is a match if (s1[i] == s2[j] && hash_s2[j] == 0) { hash_s1[i] = 1; hash_s2[j] = 1; match++; break; } } // If there is no match if (match == 0) return 0.0; // Number of transpositions double t = 0; int point = 0; // Count number of occurrences // where two characters match but // there is a third matched character // in between the indices for (int i = 0; i < len1; i++) if (hash_s1[i] == 1) { // Find the next matched character // in second String while (hash_s2[point] == 0) point++; if (s1[i] != s2[point++] ) t++; } t /= 2; // Return the Jaro Similarity return (((double)match) / ((double)len1) + ((double)match) / ((double)len2) + ((double)match - t) / ((double)match)) / 3.0; } // Driver code public static void Main() { string s1 = \"CRATE\", s2 = \"TRACE\"; // Print jaro Similarity of two Strings Console.WriteLine(jaro_distance(s1, s2)); }} // This code is contributed by AnkitRai01", "e": 9388, "s": 7005, "text": null }, { "code": "<script> // Javascript implementation of above approach // Function to calculate the// Jaro Similarity of two stringsfunction jaro_distance(s1, s2){ // If the strings are equal if (s1 == s2) return 1.0; // Length of two strings var len1 = s1.length, len2 = s2.length; // Maximum distance upto which matching // is allowed var max_dist = Math.floor(Math.max(len1, len2) / 2) - 1; // Count of matches var match = 0; // Hash for matches var hash_s1 = Array(s1.length).fill(0); var hash_s2 = Array(s1.length).fill(0); // Traverse through the first string for (var i = 0; i < len1; i++) { // Check if there is any matches for (var j = Math.max(0, i - max_dist); j < Math.min(len2, i + max_dist + 1); j++) // If there is a match if (s1[i] == s2[j] && hash_s2[j] == 0) { hash_s1[i] = 1; hash_s2[j] = 1; match++; break; } } // If there is no match if (match == 0) return 0.0; // Number of transpositions var t = 0; var point = 0; // Count number of occurrences // where two characters match but // there is a third matched character // in between the indices for (var i = 0; i < len1; i++) if (hash_s1[i]) { // Find the next matched character // in second string while (hash_s2[point] == 0) point++; if (s1[i] != s2[point++]) t++; } t /= 2; // Return the Jaro Similarity return ((match) / (len1) + (match) / (len2) + (match - t) / (match)) / 3.0;} // Driver codevar s1 = \"CRATE\", s2 = \"TRACE\";// Print jaro Similarity of two stringsdocument.write( jaro_distance(s1, s2).toFixed(5)); </script>", "e": 11233, "s": 9388, "text": null }, { "code": null, "e": 11242, "s": 11233, "text": "0.733333" }, { "code": null, "e": 11340, "s": 11244, "text": "Time Complexity: O(N * M), where N is the length of string s1 and M is the length of string s2." }, { "code": null, "e": 11366, "s": 11340, "text": "Auxiliary Space: O(N + M)" }, { "code": null, "e": 11742, "s": 11366, "text": "The Jaro-Winkler similarity is a string metric measuring edit distance between two strings. Jaro – Winkler Similarity is much similar to Jaro Similarity. They both differ when the prefix of two string match. Jaro – Winkler Similarity uses a prefix scale ‘p’ which gives a more accurate answer when the strings have a common prefix up to a defined maximum length l. Examples: " }, { "code": null, "e": 11816, "s": 11742, "text": "Input: s1 = “DwAyNE”, s2 = “DuANE”; Output: Jaro-Winkler Similarity =0.84" }, { "code": null, "e": 11890, "s": 11816, "text": "Input: s1=”TRATE”, s2=”TRACE”; Output: Jaro-Winkler similarity = 0.906667" }, { "code": null, "e": 11904, "s": 11890, "text": "Calculation: " }, { "code": null, "e": 12149, "s": 11904, "text": "Jaro Winkler similarity is defined as follows Sw = Sj + P * L * (1 – Sj) where, Sj, is jaro similaritySw, is jaro- winkler similarityP is the scaling factor (0.1 by default)L is the length of the matching prefix up to a maximum of 4 characters." }, { "code": null, "e": 12172, "s": 12149, "text": "Sj, is jaro similarity" }, { "code": null, "e": 12204, "s": 12172, "text": "Sw, is jaro- winkler similarity" }, { "code": null, "e": 12245, "s": 12204, "text": "P is the scaling factor (0.1 by default)" }, { "code": null, "e": 12317, "s": 12245, "text": "L is the length of the matching prefix up to a maximum of 4 characters." }, { "code": null, "e": 12426, "s": 12317, "text": "Let s1=”arnab”, s2=”aranb”. The Jaro similarity of the two strings is 0.933333 (From the above calculation.)" }, { "code": null, "e": 12504, "s": 12426, "text": "The length of the matching prefix is 2 and we take the scaling factor as 0.1." }, { "code": null, "e": 12605, "s": 12504, "text": "Substituting in the formula; Jaro-Winkler Similarity= 0.9333333 + 0.1 * 2 * (1-0.9333333) = 0.946667" }, { "code": null, "e": 12657, "s": 12605, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 12661, "s": 12657, "text": "C++" }, { "code": null, "e": 12666, "s": 12661, "text": "Java" }, { "code": null, "e": 12674, "s": 12666, "text": "Python3" }, { "code": null, "e": 12677, "s": 12674, "text": "C#" }, { "code": null, "e": 12688, "s": 12677, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to calculate the// Jaro Similarity of two stringsdouble jaro_distance(string s1, string s2){ // If the strings are equal if (s1 == s2) return 1.0; // Length of two strings int len1 = s1.length(), len2 = s2.length(); if (len1 == 0 || len2 == 0) return 0.0; // Maximum distance upto which matching // is allowed int max_dist = floor(max(len1, len2) / 2) - 1; // Count of matches int match = 0; // Hash for matches int hash_s1[s1.length()] = { 0 }, hash_s2[s2.length()] = { 0 }; // Traverse through the first string for (int i = 0; i < len1; i++) { // Check if there is any matches for (int j = max(0, i - max_dist); j < min(len2, i + max_dist + 1); j++) // If there is a match if (s1[i] == s2[j] && hash_s2[j] == 0) { hash_s1[i] = 1; hash_s2[j] = 1; match++; break; } } // If there is no match if (match == 0) return 0.0; // Number of transpositions double t = 0; int point = 0; // Count number of occurrences // where two characters match but // there is a third matched character // in between the indices for (int i = 0; i < len1; i++) if (hash_s1[i]) { // Find the next matched character // in second string while (hash_s2[point] == 0) point++; if (s1[i] != s2[point++]) t++; } t /= 2; // Return the Jaro Similarity return (((double)match) / ((double)len1) + ((double)match) / ((double)len2) + ((double)match - t) / ((double)match)) / 3.0;} // Jaro Winkler Similaritydouble jaro_Winkler(string s1, string s2){ double jaro_dist = jaro_distance(s1, s2); // If the jaro Similarity is above a threshold if (jaro_dist > 0.7) { // Find the length of common prefix int prefix = 0; for (int i = 0; i < min(s1.length(), s2.length()); i++) { // If the characters match if (s1[i] == s2[i]) prefix++; // Else break else break; } // Maximum of 4 characters are allowed in prefix prefix = min(4, prefix); // Calculate jaro winkler Similarity jaro_dist += 0.1 * prefix * (1 - jaro_dist); } return jaro_dist;} // Driver codeint main(){ string s1 = \"TRATE\", s2 = \"TRACE\"; // Print Jaro-Winkler Similarity of two strings cout << \"Jaro-Winkler Similarity =\" << jaro_Winkler(s1, s2) << endl; return 0;}", "e": 15428, "s": 12688, "text": null }, { "code": "// Java implementation of above approachclass GFG{ // Function to calculate the // Jaro Similarity of two strings static double jaro_distance(String s1, String s2) { // If the strings are equal if (s1 == s2) return 1.0; // Length of two strings int len1 = s1.length(), len2 = s2.length(); if (len1 == 0 || len2 == 0) return 0.0; // Maximum distance upto which matching // is allowed int max_dist = (int)Math.floor(Math.max(len1, len2) / 2) - 1; // Count of matches int match = 0; // Hash for matches int hash_s1[] = new int [s1.length()]; int hash_s2[] = new int[s2.length()]; // Traverse through the first string for (int i = 0; i < len1; i++) { // Check if there is any matches for (int j = Math.max(0, i - max_dist); j < Math.min(len2, i + max_dist + 1); j++) // If there is a match if (s1.charAt(i) == s2.charAt(j) && hash_s2[j] == 0) { hash_s1[i] = 1; hash_s2[j] = 1; match++; break; } } // If there is no match if (match == 0) return 0.0; // Number of transpositions double t = 0; int point = 0; // Count number of occurrences // where two characters match but // there is a third matched character // in between the indices for (int i = 0; i < len1; i++) if (hash_s1[i] == 1) { // Find the next matched character // in second string while (hash_s2[point] == 0) point++; if (s1.charAt(i) != s2.charAt(point++)) t++; } t /= 2; // Return the Jaro Similarity return (((double)match) / ((double)len1) + ((double)match) / ((double)len2) + ((double)match - t) / ((double)match)) / 3.0; } // Jaro Winkler Similarity static double jaro_Winkler(String s1, String s2) { double jaro_dist = jaro_distance(s1, s2); // If the jaro Similarity is above a threshold if (jaro_dist > 0.7) { // Find the length of common prefix int prefix = 0; for (int i = 0; i < Math.min(s1.length(), s2.length()); i++) { // If the characters match if (s1.charAt(i) == s2.charAt(i)) prefix++; // Else break else break; } // Maximum of 4 characters are allowed in prefix prefix = Math.min(4, prefix); // Calculate jaro winkler Similarity jaro_dist += 0.1 * prefix * (1 - jaro_dist); } return jaro_dist; } // Driver code public static void main (String[] args) { String s1 = \"TRATE\", s2 = \"TRACE\"; // Print Jaro-Winkler Similarity of two strings System.out.println(\"Jaro-Winkler Similarity =\" + jaro_Winkler(s1, s2)); }} // This code is contributed by AnkitRai01", "e": 18890, "s": 15428, "text": null }, { "code": "# Python3 implementation of above approachfrom math import floor # Function to calculate the# Jaro Similarity of two stringsdef jaro_distance(s1, s2) : # If the strings are equal if (s1 == s2) : return 1.0; # Length of two strings len1 = len(s1); len2 = len(s2); if (len1 == 0 or len2 == 0) : return 0.0; # Maximum distance upto which matching # is allowed max_dist = (max(len(s1), len(s2)) // 2 ) - 1; # Count of matches match = 0; # Hash for matches hash_s1 = [0] * len(s1) ; hash_s2 = [0] * len(s2) ; # Traverse through the first string for i in range(len1) : # Check if there is any matches for j in range( max(0, i - max_dist), min(len2, i + max_dist + 1)) : # If there is a match if (s1[i] == s2[j] and hash_s2[j] == 0) : hash_s1[i] = 1; hash_s2[j] = 1; match += 1; break; # If there is no match if (match == 0) : return 0.0; # Number of transpositions t = 0; point = 0; # Count number of occurrences # where two characters match but # there is a third matched character # in between the indices for i in range(len1) : if (hash_s1[i]) : # Find the next matched character # in second string while (hash_s2[point] == 0) : point += 1; if (s1[i] != s2[point]) : point += 1; t += 1; else : point += 1; t /= 2; # Return the Jaro Similarity return ((match / len1 + match / len2 + (match - t) / match ) / 3.0); # Jaro Winkler Similaritydef jaro_Winkler(s1, s2) : jaro_dist = jaro_distance(s1, s2); # If the jaro Similarity is above a threshold if (jaro_dist > 0.7) : # Find the length of common prefix prefix = 0; for i in range(min(len(s1), len(s2))) : # If the characters match if (s1[i] == s2[i]) : prefix += 1; # Else break else : break; # Maximum of 4 characters are allowed in prefix prefix = min(4, prefix); # Calculate jaro winkler Similarity jaro_dist += 0.1 * prefix * (1 - jaro_dist); return jaro_dist; # Driver codeif __name__ == \"__main__\" : s1 = \"TRATE\"; s2 = \"TRACE\"; # Print Jaro-Winkler Similarity of two strings print(\"Jaro-Winkler Similarity =\", jaro_Winkler(s1, s2)) ; # This code is contributed by AnkitRai01", "e": 21494, "s": 18890, "text": null }, { "code": "// C# implementation of above approachusing System; class GFG{ // Function to calculate the // Jaro Similarity of two strings static double jaro_distance(string s1, string s2) { // If the strings are equal if (s1 == s2) return 1.0; // Length of two strings int len1 = s1.Length, len2 = s2.Length; if (len1 == 0 || len2 == 0) return 0.0; // Maximum distance upto which matching // is allowed int max_dist = (int)Math.Floor((double) Math.Max(len1, len2) / 2) - 1; // Count of matches int match = 0; // Hash for matches int []hash_s1 = new int [s1.Length]; int []hash_s2 = new int[s2.Length]; // Traverse through the first string for (int i = 0; i < len1; i++) { // Check if there is any matches for (int j = Math.Max(0, i - max_dist); j < Math.Min(len2, i + max_dist + 1); j++) // If there is a match if (s1[i] == s2[j] && hash_s2[j] == 0) { hash_s1[i] = 1; hash_s2[j] = 1; match++; break; } } // If there is no match if (match == 0) return 0.0; // Number of transpositions double t = 0; int point = 0; // Count number of occurrences // where two characters match but // there is a third matched character // in between the indices for (int i = 0; i < len1; i++) if (hash_s1[i] == 1) { // Find the next matched character // in second string while (hash_s2[point] == 0) point++; if (s1[i] != s2[point++]) t++; } t /= 2; // Return the Jaro Similarity return (((double)match) / ((double)len1) + ((double)match) / ((double)len2) + ((double)match - t) / ((double)match)) / 3.0; } // Jaro Winkler Similarity static double jaro_Winkler(string s1, string s2) { double jaro_dist = jaro_distance(s1, s2); // If the jaro Similarity is above a threshold if (jaro_dist > 0.7) { // Find the length of common prefix int prefix = 0; for (int i = 0; i < Math.Min(s1.Length, s2.Length); i++) { // If the characters match if (s1[i] == s2[i]) prefix++; // Else break else break; } // Maximum of 4 characters are allowed in prefix prefix = Math.Min(4, prefix); // Calculate jaro winkler Similarity jaro_dist += 0.1 * prefix * (1 - jaro_dist); } return jaro_dist; } // Driver code public static void Main () { string s1 = \"TRATE\", s2 = \"TRACE\"; // Print Jaro-Winkler Similarity of two strings Console.WriteLine(\"Jaro-Winkler Similarity =\" + jaro_Winkler(s1, s2)); }} // This code is contributed by AnkitRai01", "e": 24939, "s": 21494, "text": null }, { "code": "<script> // Javascript implementation of above approach // Function to calculate the // Jaro Similarity of two strings function jaro_distance(s1, s2) { // If the strings are equal if (s1 == s2) return 1.0; // Length of two strings let len1 = s1.length, len2 = s2.length; if (len1 == 0 || len2 == 0) return 0.0; // Maximum distance upto which matching // is allowed let max_dist = Math.floor(Math.max(len1, len2) / 2) - 1; // Count of matches let match = 0; // Hash for matches let hash_s1 = new Array(s1.length); hash_s1.fill(0); let hash_s2 = new Array(s2.length); hash_s2.fill(0); // Traverse through the first string for (let i = 0; i < len1; i++) { // Check if there is any matches for (let j = Math.max(0, i - max_dist); j < Math.min(len2, i + max_dist + 1); j++) // If there is a match if (s1[i] == s2[j] && hash_s2[j] == 0) { hash_s1[i] = 1; hash_s2[j] = 1; match++; break; } } // If there is no match if (match == 0) return 0.0; // Number of transpositions let t = 0; let point = 0; // Count number of occurrences // where two characters match but // there is a third matched character // in between the indices for (let i = 0; i < len1; i++) if (hash_s1[i] == 1) { // Find the next matched character // in second string while (hash_s2[point] == 0) point++; if (s1[i] != s2[point++]) t++; } t /= 2; // Return the Jaro Similarity return ((match) / (len1) + (match) / (len2) + (match - t) / (match)) / 3.0; } // Jaro Winkler Similarity function jaro_Winkler(s1, s2) { let jaro_dist = jaro_distance(s1, s2); // If the jaro Similarity is above a threshold if (jaro_dist > 0.7) { // Find the length of common prefix let prefix = 0; for (let i = 0; i < Math.min(s1.length,s2.length); i++) { // If the characters match if (s1[i] == s2[i]) prefix++; // Else break else break; } // Maximum of 4 characters are allowed in prefix prefix = Math.min(4, prefix); // Calculate jaro winkler Similarity jaro_dist += 0.1 * prefix * (1 - jaro_dist); } return jaro_dist.toFixed(6); } let s1 = \"TRATE\", s2 = \"TRACE\"; // Print Jaro-Winkler Similarity of two strings document.write(\"Jaro-Winkler Similarity =\" + jaro_Winkler(s1, s2)); </script>", "e": 28167, "s": 24939, "text": null }, { "code": null, "e": 28201, "s": 28167, "text": "Jaro-Winkler Similarity =0.906667" }, { "code": null, "e": 28324, "s": 28203, "text": "Time Complexity: O(N * M), where N is the length of string s1 and M is the length of string s2.Auxiliary Space: O(N + M)" }, { "code": null, "e": 28339, "s": 28324, "text": "mohit kumar 29" }, { "code": null, "e": 28353, "s": 28339, "text": "princiraj1992" }, { "code": null, "e": 28361, "s": 28353, "text": "ankthon" }, { "code": null, "e": 28372, "s": 28361, "text": "nidhi_biet" }, { "code": null, "e": 28382, "s": 28372, "text": "rutvik_56" }, { "code": null, "e": 28393, "s": 28382, "text": "decode2207" }, { "code": null, "e": 28408, "s": 28393, "text": "varshagumber28" }, { "code": null, "e": 28422, "s": 28408, "text": "sumitgumber28" }, { "code": null, "e": 28438, "s": 28422, "text": "pankajsharmagfg" }, { "code": null, "e": 28444, "s": 28438, "text": "idahu" }, { "code": null, "e": 28460, "s": 28444, "text": "amartyaghoshgfg" }, { "code": null, "e": 28470, "s": 28460, "text": "subham348" }, { "code": null, "e": 28484, "s": 28470, "text": "edit-distance" }, { "code": null, "e": 28494, "s": 28484, "text": "substring" }, { "code": null, "e": 28518, "s": 28494, "text": "Technical Scripter 2019" }, { "code": null, "e": 28529, "s": 28518, "text": "Algorithms" }, { "code": null, "e": 28542, "s": 28529, "text": "Mathematical" }, { "code": null, "e": 28550, "s": 28542, "text": "Strings" }, { "code": null, "e": 28569, "s": 28550, "text": "Technical Scripter" }, { "code": null, "e": 28577, "s": 28569, "text": "Strings" }, { "code": null, "e": 28590, "s": 28577, "text": "Mathematical" }, { "code": null, "e": 28601, "s": 28590, "text": "Algorithms" } ]
VBScript CDate() Function
20 Oct, 2021 The VBScript CDate Function is used to convert a valid date and time expression to type Date. It returns the correct order of dates. It recognizes date formats according to the locale setting of your system. Note: We can also use the IsDate function to determine if date can be converted to a date or time. Syntax: CDate(date) Parameter: This function accepts a single a parameter as mentioned above and described below. date: It is a required attribute. It specify any valid date expression. Example 1: Below examples illustrates the VBScript CDate Function. VBScript <% gfg=CDate("May 6, 2020") response.write(gfg)%> Output: 5/6/2020 Example 2: Below code illustrates that how to convert numbers with separators to a date: VBScript <% gfg=CDate(#4/22/10#) response.write(gfg)%> Output: 4/22/2010 chhabradhanvi VBScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Oct, 2021" }, { "code": null, "e": 236, "s": 28, "text": "The VBScript CDate Function is used to convert a valid date and time expression to type Date. It returns the correct order of dates. It recognizes date formats according to the locale setting of your system." }, { "code": null, "e": 335, "s": 236, "text": "Note: We can also use the IsDate function to determine if date can be converted to a date or time." }, { "code": null, "e": 343, "s": 335, "text": "Syntax:" }, { "code": null, "e": 355, "s": 343, "text": "CDate(date)" }, { "code": null, "e": 449, "s": 355, "text": "Parameter: This function accepts a single a parameter as mentioned above and described below." }, { "code": null, "e": 521, "s": 449, "text": "date: It is a required attribute. It specify any valid date expression." }, { "code": null, "e": 588, "s": 521, "text": "Example 1: Below examples illustrates the VBScript CDate Function." }, { "code": null, "e": 597, "s": 588, "text": "VBScript" }, { "code": "<% gfg=CDate(\"May 6, 2020\") response.write(gfg)%>", "e": 649, "s": 597, "text": null }, { "code": null, "e": 657, "s": 649, "text": "Output:" }, { "code": null, "e": 666, "s": 657, "text": "5/6/2020" }, { "code": null, "e": 755, "s": 666, "text": "Example 2: Below code illustrates that how to convert numbers with separators to a date:" }, { "code": null, "e": 764, "s": 755, "text": "VBScript" }, { "code": "<% gfg=CDate(#4/22/10#) response.write(gfg)%>", "e": 812, "s": 764, "text": null }, { "code": null, "e": 820, "s": 812, "text": "Output:" }, { "code": null, "e": 830, "s": 820, "text": "4/22/2010" }, { "code": null, "e": 844, "s": 830, "text": "chhabradhanvi" }, { "code": null, "e": 853, "s": 844, "text": "VBScript" }, { "code": null, "e": 870, "s": 853, "text": "Web Technologies" } ]
Java 8 | Consumer Interface in Java with Examples
17 Sep, 2021 The Consumer 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 produces a result. However these kind of functions don’t return any value.Hence this functional interface which takes in one generic namely:- T: denotes the type of the input argument to the operation The lambda expression assigned to an object of Consumer type is used to define its accept() which eventually applies the given operation on its argument. Consumers are useful when it not needed to return any value as they are expected to operate via side-effects. The Consumer interface consists of the following two functions: 1. accept() This method accepts one value and performs the operation on the given argumentSyntax: void accept(T t) Parameters: This method takes in one parameter: t– the input argument Returns: This method does not return any value.Below is the code to illustrate accept() method:Program 1: Java // Java Program to demonstrate// Consumer's accept() method import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.function.Consumer; public class Main { public static void main(String args[]) { // Consumer to display a number Consumer<Integer> display = a -> System.out.println(a); // Implement display using accept() display.accept(10); // Consumer to multiply 2 to every integer of a list Consumer<List<Integer> > modify = list -> { for (int i = 0; i < list.size(); i++) list.set(i, 2 * list.get(i)); }; // Consumer to display a list of numbers Consumer<List<Integer> > dispList = list -> list.stream().forEach(a -> System.out.print(a + " ")); List<Integer> list = new ArrayList<Integer>(); list.add(2); list.add(1); list.add(3); // Implement modify using accept() modify.accept(list); // Implement dispList using accept() dispList.accept(list); }} 10 4 2 6 2. andThen() It returns a composed Consumer wherein the parameterized Consumer will be executed after the first one. If evaluation of either function throws an error, it is relayed to the caller of the composed operation.Note: The function being passed as the argument should be of type Consumer.Syntax: default Consumer <T> andThen(Consumer<? super T> after) Parameters: This method accepts a parameter after which is the Consumer to be applied after the current one.Return Value: This method returns a composed Consumer that first applies the current Consumer first and then the after operation.Exception: This method throws NullPointerException if the after operation is null.Below is the code to illustrate andThen() method:Program 1: Java // Java Program to demonstrate// Consumer's andThen() method import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.function.Consumer; public class Main { public static void main(String args[]) { // Consumer to multiply 2 to every integer of a list Consumer<List<Integer> > modify = list -> { for (int i = 0; i < list.size(); i++) list.set(i, 2 * list.get(i)); }; // Consumer to display a list of integers Consumer<List<Integer> > dispList = list -> list.stream().forEach(a -> System.out.print(a + " ")); List<Integer> list = new ArrayList<Integer>(); list.add(2); list.add(1); list.add(3); // using addThen() modify.andThen(dispList).accept(list); ; }} 4 2 6 Program 2: To demonstrate when NullPointerException is returned. Java // Java Program to demonstrate// Consumer's andThen() method import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.function.Consumer; public class Main { public static void main(String args[]) { // Consumer to multiply 2 to every integer of a list Consumer<List<Integer> > modify = list -> { for (int i = 0; i < list.size(); i++) list.set(i, 2 * list.get(i)); }; // Consumer to display a list of integers Consumer<List<Integer> > dispList = list -> list.stream().forEach(a -> System.out.print(a + " ")); List<Integer> list = new ArrayList<Integer>(); list.add(2); list.add(1); list.add(3); try { // using addThen() modify.andThen(null).accept(list); } catch (Exception e) { System.out.println("Exception: " + e); } }} Exception: java.lang.NullPointerException Program 3: To demonstrate how an Exception in the after function is returned and handled. Java // Java Program to demonstrate// Consumer's andThen() method import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.function.Consumer; public class Main { public static void main(String args[]) { // Consumer to multiply 2 to every integer of a list Consumer<List<Integer> > modify = list -> { for (int i = 0; i <= list.size(); i++) list.set(i, 2 * list.get(i)); }; // Consumer to display a list of integers Consumer<List<Integer> > dispList = list -> list.stream().forEach(a -> System.out.print(a + " ")); System.out.println(); List<Integer> list = new ArrayList<Integer>(); list.add(2); list.add(1); list.add(3); // using addThen() try { dispList.andThen(modify).accept(list); ; } catch (Exception e) { System.out.println("Exception: " + e); } }} 2 1 3 Exception: java.lang.IndexOutOfBoundsException: Index: 3, Size: 3 chhabradhanvi Java - util package Java 8 java-basics Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Sep, 2021" }, { "code": null, "e": 405, "s": 52, "text": "The Consumer 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 produces a result. However these kind of functions don’t return any value.Hence this functional interface which takes in one generic namely:- " }, { "code": null, "e": 464, "s": 405, "text": "T: denotes the type of the input argument to the operation" }, { "code": null, "e": 730, "s": 464, "text": "The lambda expression assigned to an object of Consumer type is used to define its accept() which eventually applies the given operation on its argument. Consumers are useful when it not needed to return any value as they are expected to operate via side-effects. " }, { "code": null, "e": 795, "s": 730, "text": "The Consumer interface consists of the following two functions: " }, { "code": null, "e": 807, "s": 795, "text": "1. accept()" }, { "code": null, "e": 895, "s": 807, "text": "This method accepts one value and performs the operation on the given argumentSyntax: " }, { "code": null, "e": 912, "s": 895, "text": "void accept(T t)" }, { "code": null, "e": 962, "s": 912, "text": "Parameters: This method takes in one parameter: " }, { "code": null, "e": 984, "s": 962, "text": "t– the input argument" }, { "code": null, "e": 1091, "s": 984, "text": "Returns: This method does not return any value.Below is the code to illustrate accept() method:Program 1: " }, { "code": null, "e": 1096, "s": 1091, "text": "Java" }, { "code": "// Java Program to demonstrate// Consumer's accept() method import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.function.Consumer; public class Main { public static void main(String args[]) { // Consumer to display a number Consumer<Integer> display = a -> System.out.println(a); // Implement display using accept() display.accept(10); // Consumer to multiply 2 to every integer of a list Consumer<List<Integer> > modify = list -> { for (int i = 0; i < list.size(); i++) list.set(i, 2 * list.get(i)); }; // Consumer to display a list of numbers Consumer<List<Integer> > dispList = list -> list.stream().forEach(a -> System.out.print(a + \" \")); List<Integer> list = new ArrayList<Integer>(); list.add(2); list.add(1); list.add(3); // Implement modify using accept() modify.accept(list); // Implement dispList using accept() dispList.accept(list); }}", "e": 2165, "s": 1096, "text": null }, { "code": null, "e": 2174, "s": 2165, "text": "10\n4 2 6" }, { "code": null, "e": 2189, "s": 2176, "text": "2. andThen()" }, { "code": null, "e": 2482, "s": 2189, "text": "It returns a composed Consumer wherein the parameterized Consumer will be executed after the first one. If evaluation of either function throws an error, it is relayed to the caller of the composed operation.Note: The function being passed as the argument should be of type Consumer.Syntax: " }, { "code": null, "e": 2547, "s": 2482, "text": "default Consumer <T> \n andThen(Consumer<? super T> after)" }, { "code": null, "e": 2927, "s": 2547, "text": "Parameters: This method accepts a parameter after which is the Consumer to be applied after the current one.Return Value: This method returns a composed Consumer that first applies the current Consumer first and then the after operation.Exception: This method throws NullPointerException if the after operation is null.Below is the code to illustrate andThen() method:Program 1: " }, { "code": null, "e": 2932, "s": 2927, "text": "Java" }, { "code": "// Java Program to demonstrate// Consumer's andThen() method import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.function.Consumer; public class Main { public static void main(String args[]) { // Consumer to multiply 2 to every integer of a list Consumer<List<Integer> > modify = list -> { for (int i = 0; i < list.size(); i++) list.set(i, 2 * list.get(i)); }; // Consumer to display a list of integers Consumer<List<Integer> > dispList = list -> list.stream().forEach(a -> System.out.print(a + \" \")); List<Integer> list = new ArrayList<Integer>(); list.add(2); list.add(1); list.add(3); // using addThen() modify.andThen(dispList).accept(list); ; }}", "e": 3766, "s": 2932, "text": null }, { "code": null, "e": 3772, "s": 3766, "text": "4 2 6" }, { "code": null, "e": 3840, "s": 3774, "text": "Program 2: To demonstrate when NullPointerException is returned. " }, { "code": null, "e": 3845, "s": 3840, "text": "Java" }, { "code": "// Java Program to demonstrate// Consumer's andThen() method import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.function.Consumer; public class Main { public static void main(String args[]) { // Consumer to multiply 2 to every integer of a list Consumer<List<Integer> > modify = list -> { for (int i = 0; i < list.size(); i++) list.set(i, 2 * list.get(i)); }; // Consumer to display a list of integers Consumer<List<Integer> > dispList = list -> list.stream().forEach(a -> System.out.print(a + \" \")); List<Integer> list = new ArrayList<Integer>(); list.add(2); list.add(1); list.add(3); try { // using addThen() modify.andThen(null).accept(list); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 4783, "s": 3845, "text": null }, { "code": null, "e": 4825, "s": 4783, "text": "Exception: java.lang.NullPointerException" }, { "code": null, "e": 4918, "s": 4827, "text": "Program 3: To demonstrate how an Exception in the after function is returned and handled. " }, { "code": null, "e": 4923, "s": 4918, "text": "Java" }, { "code": "// Java Program to demonstrate// Consumer's andThen() method import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.function.Consumer; public class Main { public static void main(String args[]) { // Consumer to multiply 2 to every integer of a list Consumer<List<Integer> > modify = list -> { for (int i = 0; i <= list.size(); i++) list.set(i, 2 * list.get(i)); }; // Consumer to display a list of integers Consumer<List<Integer> > dispList = list -> list.stream().forEach(a -> System.out.print(a + \" \")); System.out.println(); List<Integer> list = new ArrayList<Integer>(); list.add(2); list.add(1); list.add(3); // using addThen() try { dispList.andThen(modify).accept(list); ; } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 5905, "s": 4923, "text": null }, { "code": null, "e": 5977, "s": 5905, "text": "2 1 3 Exception: java.lang.IndexOutOfBoundsException: Index: 3, Size: 3" }, { "code": null, "e": 5993, "s": 5979, "text": "chhabradhanvi" }, { "code": null, "e": 6013, "s": 5993, "text": "Java - util package" }, { "code": null, "e": 6020, "s": 6013, "text": "Java 8" }, { "code": null, "e": 6032, "s": 6020, "text": "java-basics" }, { "code": null, "e": 6037, "s": 6032, "text": "Java" }, { "code": null, "e": 6051, "s": 6037, "text": "Java Programs" }, { "code": null, "e": 6056, "s": 6051, "text": "Java" }, { "code": null, "e": 6154, "s": 6056, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6205, "s": 6154, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 6236, "s": 6205, "text": "How to iterate any Map in Java" }, { "code": null, "e": 6255, "s": 6236, "text": "Interfaces in Java" }, { "code": null, "e": 6285, "s": 6255, "text": "HashMap in Java with Examples" }, { "code": null, "e": 6303, "s": 6285, "text": "ArrayList in Java" }, { "code": null, "e": 6331, "s": 6303, "text": "Initializing a List in Java" }, { "code": null, "e": 6357, "s": 6331, "text": "Java Programming Examples" }, { "code": null, "e": 6401, "s": 6357, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 6435, "s": 6401, "text": "Convert Double to Integer in Java" } ]
find_element_by_link_text() driver method – Selenium Python
09 Sep, 2021 Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task. This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_element_by_link_text() is discussed in this article. With this strategy, the first element with the link text value matching the location will be returned. If no element has a matching link text attribute, a NoSuchElementException will be raised. Syntax – driver.find_element_by_link_text("Text of Link") Example – For instance, consider this page source: HTML <html> <body> <p>Are you sure you want to do this?</p> <a href="continue.html">Continue</a> <a href="cancel.html">Cancel</a></body><html> Now after you have created a driver, you can grab an element using – login_form = driver.find_element_by_link_text('Continue') Let’s try to practically implement this method and get a element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab search form input using its link text “Tutorials”. Create a file called run.py to demonstrate find_element_by_link_text method – Python3 # Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = "geeksforgeeks" # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get elementelement = driver.find_element_by_link_text("Tutorials") # print complete elementprint(element) Now run using – Python run.py First, it will open firefox window with geeksforgeeks, and then select the element and print it on terminal as show below. Browser Output – Terminal Output – NaveenArora surinderdawra388 Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Sep, 2021" }, { "code": null, "e": 525, "s": 28, "text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task. " }, { "code": null, "e": 919, "s": 525, "text": "This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_element_by_link_text() is discussed in this article. With this strategy, the first element with the link text value matching the location will be returned. If no element has a matching link text attribute, a NoSuchElementException will be raised." }, { "code": null, "e": 929, "s": 919, "text": "Syntax – " }, { "code": null, "e": 978, "s": 929, "text": "driver.find_element_by_link_text(\"Text of Link\")" }, { "code": null, "e": 1031, "s": 978, "text": "Example – For instance, consider this page source: " }, { "code": null, "e": 1036, "s": 1031, "text": "HTML" }, { "code": "<html> <body> <p>Are you sure you want to do this?</p> <a href=\"continue.html\">Continue</a> <a href=\"cancel.html\">Cancel</a></body><html>", "e": 1181, "s": 1036, "text": null }, { "code": null, "e": 1251, "s": 1181, "text": "Now after you have created a driver, you can grab an element using – " }, { "code": null, "e": 1309, "s": 1251, "text": "login_form = driver.find_element_by_link_text('Continue')" }, { "code": null, "e": 1491, "s": 1309, "text": "Let’s try to practically implement this method and get a element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab search form input using its link text “Tutorials”. " }, { "code": null, "e": 1571, "s": 1491, "text": "Create a file called run.py to demonstrate find_element_by_link_text method – " }, { "code": null, "e": 1579, "s": 1571, "text": "Python3" }, { "code": "# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = \"geeksforgeeks\" # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get elementelement = driver.find_element_by_link_text(\"Tutorials\") # print complete elementprint(element)", "e": 1951, "s": 1579, "text": null }, { "code": null, "e": 1968, "s": 1951, "text": "Now run using – " }, { "code": null, "e": 1982, "s": 1968, "text": "Python run.py" }, { "code": null, "e": 2106, "s": 1982, "text": "First, it will open firefox window with geeksforgeeks, and then select the element and print it on terminal as show below. " }, { "code": null, "e": 2125, "s": 2106, "text": "Browser Output – " }, { "code": null, "e": 2144, "s": 2125, "text": "Terminal Output – " }, { "code": null, "e": 2162, "s": 2150, "text": "NaveenArora" }, { "code": null, "e": 2179, "s": 2162, "text": "surinderdawra388" }, { "code": null, "e": 2195, "s": 2179, "text": "Python-selenium" }, { "code": null, "e": 2204, "s": 2195, "text": "selenium" }, { "code": null, "e": 2211, "s": 2204, "text": "Python" } ]
Java Program for Rat in a Maze | Backtracking-2
08 Jun, 2022 We have discussed Backtracking and Knight’s tour problem in Set 1. Let us discuss Rat in a Maze as another example problem that can be solved using Backtracking. A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0], and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from the source and has to reach its destination. The rat can move only in two directions: forward and down. In the maze matrix, 0 means the block is a dead end, and 1 means the block can be used in the path from source to destination. Note that this is a simple version of the typical Maze problem. For example, a more complex version can be that the rat can move in 4 directions and a more complex version can be with a limited number of moves. Following is an example maze. Gray blocks are dead ends (value = 0). Following is binary matrix representation of the above maze. {1, 0, 0, 0} {1, 1, 0, 1} {0, 1, 0, 0} {1, 1, 1, 1} Following is a maze with highlighted solution path. Following is the solution matrix (output of program) for the above input matrix. {1, 0, 0, 0} {1, 1, 0, 0} {0, 1, 0, 0} {0, 1, 1, 1} All entries in solution path are marked as 1. Java /* Java program to solve Rat in a Maze problem using backtracking */ public class RatMaze { final int N = 4; /* A utility function to print solution matrix sol[N][N] */ void printSolution(int sol[][]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(" " + sol[i][j] + " "); System.out.println(); } } /* A utility function to check if x, y is valid index for N*N maze */ boolean isSafe(int maze[][], int x, int y) { // if (x, y outside maze) return false return (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1); } /* This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ boolean solveMaze(int maze[][]) { int sol[][] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveMazeUtil(maze, 0, 0, sol) == false) { System.out.print("Solution doesn't exist"); return false; } printSolution(sol); return true; } /* A recursive utility function to solve Maze problem */ boolean solveMazeUtil(int maze[][], int x, int y, int sol[][]) { // if (x, y is goal) return true if (x == N - 1 && y == N - 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // mark x, y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ if (solveMazeUtil(maze, x + 1, y, sol)) return true; /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y + 1, sol)) return true; /* If none of the above movements works then BACKTRACK: unmark x, y as part of solution path */ sol[x][y] = 0; return false; } return false; } public static void main(String args[]) { RatMaze rat = new RatMaze(); int maze[][] = { { 1, 0, 0, 0 }, { 1, 1, 0, 1 }, { 0, 1, 0, 0 }, { 1, 1, 1, 1 } }; rat.solveMaze(maze); }}// This code is contributed by Abhishek Shankhadhar 1 0 0 0 1 1 0 0 0 1 0 0 0 1 1 1 Time Complexity: O(2^(n^2)) Auxiliary Space: O(n^2) Please refer complete article on Rat in a Maze | Backtracking-2 for more details! as5853535 saurabh1990aror chandramauliguptach Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jun, 2022" }, { "code": null, "e": 216, "s": 54, "text": "We have discussed Backtracking and Knight’s tour problem in Set 1. Let us discuss Rat in a Maze as another example problem that can be solved using Backtracking." }, { "code": null, "e": 520, "s": 216, "text": "A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0], and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from the source and has to reach its destination. The rat can move only in two directions: forward and down." }, { "code": null, "e": 858, "s": 520, "text": "In the maze matrix, 0 means the block is a dead end, and 1 means the block can be used in the path from source to destination. Note that this is a simple version of the typical Maze problem. For example, a more complex version can be that the rat can move in 4 directions and a more complex version can be with a limited number of moves." }, { "code": null, "e": 888, "s": 858, "text": "Following is an example maze." }, { "code": null, "e": 929, "s": 888, "text": " Gray blocks are dead ends (value = 0). " }, { "code": null, "e": 990, "s": 929, "text": "Following is binary matrix representation of the above maze." }, { "code": null, "e": 1106, "s": 990, "text": " {1, 0, 0, 0}\n {1, 1, 0, 1}\n {0, 1, 0, 0}\n {1, 1, 1, 1}" }, { "code": null, "e": 1158, "s": 1106, "text": "Following is a maze with highlighted solution path." }, { "code": null, "e": 1239, "s": 1158, "text": "Following is the solution matrix (output of program) for the above input matrix." }, { "code": null, "e": 1402, "s": 1239, "text": " {1, 0, 0, 0}\n {1, 1, 0, 0}\n {0, 1, 0, 0}\n {0, 1, 1, 1}\n All entries in solution path are marked as 1." }, { "code": null, "e": 1407, "s": 1402, "text": "Java" }, { "code": "/* Java program to solve Rat in a Maze problem using backtracking */ public class RatMaze { final int N = 4; /* A utility function to print solution matrix sol[N][N] */ void printSolution(int sol[][]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(\" \" + sol[i][j] + \" \"); System.out.println(); } } /* A utility function to check if x, y is valid index for N*N maze */ boolean isSafe(int maze[][], int x, int y) { // if (x, y outside maze) return false return (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1); } /* This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ boolean solveMaze(int maze[][]) { int sol[][] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveMazeUtil(maze, 0, 0, sol) == false) { System.out.print(\"Solution doesn't exist\"); return false; } printSolution(sol); return true; } /* A recursive utility function to solve Maze problem */ boolean solveMazeUtil(int maze[][], int x, int y, int sol[][]) { // if (x, y is goal) return true if (x == N - 1 && y == N - 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // mark x, y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ if (solveMazeUtil(maze, x + 1, y, sol)) return true; /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y + 1, sol)) return true; /* If none of the above movements works then BACKTRACK: unmark x, y as part of solution path */ sol[x][y] = 0; return false; } return false; } public static void main(String args[]) { RatMaze rat = new RatMaze(); int maze[][] = { { 1, 0, 0, 0 }, { 1, 1, 0, 1 }, { 0, 1, 0, 0 }, { 1, 1, 1, 1 } }; rat.solveMaze(maze); }}// This code is contributed by Abhishek Shankhadhar", "e": 4149, "s": 1407, "text": null }, { "code": null, "e": 4196, "s": 4149, "text": "1 0 0 0 \n1 1 0 0 \n0 1 0 0 \n0 1 1 1" }, { "code": null, "e": 4226, "s": 4198, "text": "Time Complexity: O(2^(n^2))" }, { "code": null, "e": 4250, "s": 4226, "text": "Auxiliary Space: O(n^2)" }, { "code": null, "e": 4333, "s": 4250, "text": "Please refer complete article on Rat in a Maze | Backtracking-2 for more details! " }, { "code": null, "e": 4343, "s": 4333, "text": "as5853535" }, { "code": null, "e": 4359, "s": 4343, "text": "saurabh1990aror" }, { "code": null, "e": 4379, "s": 4359, "text": "chandramauliguptach" }, { "code": null, "e": 4393, "s": 4379, "text": "Java Programs" } ]
How to pretty print JSON string in JavaScript ?
26 Jul, 2021 Given a JavaScript object and the task is to print the JSON object in pretty ( easy to read) format using JavaScript. Use <pre> element to display the object in pretty format. Approach: Declare a JSON object and store it into variable. Use JSON.stringify(obj) method to convert JavaScript objects into strings and display it. Use JSON.stringify(obj, replacer, space) method to convert JavaScript objects into strings in pretty format. In this example, we use space size four. It display the object in aligned format. Example 1: This example uses JSON.stringify() method to print the object element within <pre> tag. <!DOCTYPE html><html> <head> <title> How to pretty print JSON string in JavaScript ? </title></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP" style= "font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run();"> click here </button> <pre id="GFG_DOWN" style= "color:green; font-size: 20px; font-weight: bold;"> </pre> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var obj = { "prop_1": { "prop_11": "val_11", "prop_12": "val_12" }, "prop_2": "val_2", "prop_3": "val_3" }; el_up.innerHTML = JSON.stringify(obj); function gfg_Run() { el_down.innerHTML = JSON.stringify(obj, undefined, 4); } </script></body> </html> Output: Before clicking the button: After clicking the button: Example 2: This example is a bit similar to previous one but it specifying the properties to print the object of object. It also takes the advantage of JSON.stringify() method to print an object within <pre> element. <!DOCTYPE html><html> <head> <title> How to pretty print JSON string in JavaScript ? </title></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP" style= "font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run();"> click here </button> <pre id="GFG_DOWN" style= "color:green; font-size: 20px; font-weight: bold;"> </pre> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var obj = { "prop_1": { "prop_11": "val_11", "prop_12": "val_12" }, "prop_2": "val_2", "prop_3": "val_3" }; el_up.innerHTML = JSON.stringify(obj); function gfg_Run() { el_down.innerHTML = JSON.stringify(obj, ['prop_2', 'prop_3'], 4); } </script></body> </html> Output: Before clicking the button: After clicking the button: JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. JSON JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Differences between Functional Components and Class Components in React Roadmap to Learn JavaScript For Beginners Hide or show elements in HTML using display property Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jul, 2021" }, { "code": null, "e": 204, "s": 28, "text": "Given a JavaScript object and the task is to print the JSON object in pretty ( easy to read) format using JavaScript. Use <pre> element to display the object in pretty format." }, { "code": null, "e": 214, "s": 204, "text": "Approach:" }, { "code": null, "e": 264, "s": 214, "text": "Declare a JSON object and store it into variable." }, { "code": null, "e": 354, "s": 264, "text": "Use JSON.stringify(obj) method to convert JavaScript objects into strings and display it." }, { "code": null, "e": 545, "s": 354, "text": "Use JSON.stringify(obj, replacer, space) method to convert JavaScript objects into strings in pretty format. In this example, we use space size four. It display the object in aligned format." }, { "code": null, "e": 644, "s": 545, "text": "Example 1: This example uses JSON.stringify() method to print the object element within <pre> tag." }, { "code": "<!DOCTYPE html><html> <head> <title> How to pretty print JSON string in JavaScript ? </title></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\" style= \"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run();\"> click here </button> <pre id=\"GFG_DOWN\" style= \"color:green; font-size: 20px; font-weight: bold;\"> </pre> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var obj = { \"prop_1\": { \"prop_11\": \"val_11\", \"prop_12\": \"val_12\" }, \"prop_2\": \"val_2\", \"prop_3\": \"val_3\" }; el_up.innerHTML = JSON.stringify(obj); function gfg_Run() { el_down.innerHTML = JSON.stringify(obj, undefined, 4); } </script></body> </html> ", "e": 1626, "s": 644, "text": null }, { "code": null, "e": 1634, "s": 1626, "text": "Output:" }, { "code": null, "e": 1662, "s": 1634, "text": "Before clicking the button:" }, { "code": null, "e": 1689, "s": 1662, "text": "After clicking the button:" }, { "code": null, "e": 1906, "s": 1689, "text": "Example 2: This example is a bit similar to previous one but it specifying the properties to print the object of object. It also takes the advantage of JSON.stringify() method to print an object within <pre> element." }, { "code": "<!DOCTYPE html><html> <head> <title> How to pretty print JSON string in JavaScript ? </title></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\" style= \"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run();\"> click here </button> <pre id=\"GFG_DOWN\" style= \"color:green; font-size: 20px; font-weight: bold;\"> </pre> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var obj = { \"prop_1\": { \"prop_11\": \"val_11\", \"prop_12\": \"val_12\" }, \"prop_2\": \"val_2\", \"prop_3\": \"val_3\" }; el_up.innerHTML = JSON.stringify(obj); function gfg_Run() { el_down.innerHTML = JSON.stringify(obj, ['prop_2', 'prop_3'], 4); } </script></body> </html> ", "e": 2940, "s": 1906, "text": null }, { "code": null, "e": 2948, "s": 2940, "text": "Output:" }, { "code": null, "e": 2976, "s": 2948, "text": "Before clicking the button:" }, { "code": null, "e": 3003, "s": 2976, "text": "After clicking the button:" }, { "code": null, "e": 3222, "s": 3003, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 3227, "s": 3222, "text": "JSON" }, { "code": null, "e": 3238, "s": 3227, "text": "JavaScript" }, { "code": null, "e": 3255, "s": 3238, "text": "Web Technologies" }, { "code": null, "e": 3282, "s": 3255, "text": "Web technologies Questions" }, { "code": null, "e": 3380, "s": 3282, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3441, "s": 3380, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3481, "s": 3441, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3553, "s": 3481, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3595, "s": 3553, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3648, "s": 3595, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3681, "s": 3648, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3743, "s": 3681, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3804, "s": 3743, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3847, "s": 3804, "text": "How to fetch data from an API in ReactJS ?" } ]
Python: AttributeError
09 Aug, 2021 In every programming language, if we develop new programs, there is a high chance of getting errors or exceptions. These errors yield to the program not being executed. One of the error in Python mostly occurs is “AttributeError”. AttributeError can be defined as an error that is raised when an attribute reference or assignment fails. For example, if we take a variable x we are assigned a value of 10. In this process suppose we want to append another value to that variable. It’s not possible. Because the variable is an integer type it does not support the append method. So in this type of problem, we get an error called “AttributeError”. Suppose if the variable is list type then it supports the append method. Then there is no problem and not getting”Attribute error”. Note: Attribute errors in Python are generally raised when an invalid attribute reference is made.There are a few chances of getting AttributeError. Example 1: Python3 # Python program to demonstrate# AttributeError X = 10 # Raises an AttributeErrorX.append(6) Output: Traceback (most recent call last): File "/home/46576cfdd7cb1db75480a8653e2115cc.py", line 5, in X.append(6) AttributeError: 'int' object has no attribute 'append' Example 2: Sometimes any variation in spelling will cause an Attribute error as Python is a case-sensitive language. Python3 # Python program to demonstrate# AttributeError # Raises an AttributeError as there is no# method as fst for stringsstring = "The famous website is { }".fst("geeksforgeeks")print(string) Output: Traceback (most recent call last): File "/home/2078367df38257e2ec3aead22841c153.py", line 3, in string = "The famous website is { }".fst("geeksforgeeks") AttributeError: 'str' object has no attribute 'fst' Example 3: AttributeError can also be raised for a user-defined class when the user tries to make an invalid attribute reference. Python3 # Python program to demonstrate# AttributeError class Geeks(): def __init__(self): self.a = 'GeeksforGeeks' # Driver's codeobj = Geeks() print(obj.a) # Raises an AttributeError as there# is no attribute bprint(obj.b) Output: GeeksforGeeks Error: Traceback (most recent call last): File "/home/373989a62f52a8b91cb2d3300f411083.py", line 17, in print(obj.b) AttributeError: 'Geeks' object has no attribute 'b' Errors and exceptions in Python can be handled using exception handling i.e. by using try and except in Python. Example: Consider the above class example, we want to do something else rather than printing the traceback Whenever an AttributeError is raised. Python3 # Python program to demonstrate# AttributeError class Geeks(): def __init__(self): self.a = 'GeeksforGeeks' # Driver's codeobj = Geeks() # Try and except statement for# Exception handlingtry: print(obj.a) # Raises an AttributeError print(obj.b) # Prints the below statement# whenever an AttributeError is# raisedexcept AttributeError: print("There is no such attribute") Output: GeeksforGeeks There is no such attribute Note: To know more about exception handling click here. nidhi_biet sumitgumber28 11irishjs Python-exceptions Python Technical Scripter 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 How to Install PIP on Windows ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Aug, 2021" }, { "code": null, "e": 806, "s": 28, "text": "In every programming language, if we develop new programs, there is a high chance of getting errors or exceptions. These errors yield to the program not being executed. One of the error in Python mostly occurs is “AttributeError”. AttributeError can be defined as an error that is raised when an attribute reference or assignment fails. For example, if we take a variable x we are assigned a value of 10. In this process suppose we want to append another value to that variable. It’s not possible. Because the variable is an integer type it does not support the append method. So in this type of problem, we get an error called “AttributeError”. Suppose if the variable is list type then it supports the append method. Then there is no problem and not getting”Attribute error”." }, { "code": null, "e": 955, "s": 806, "text": "Note: Attribute errors in Python are generally raised when an invalid attribute reference is made.There are a few chances of getting AttributeError." }, { "code": null, "e": 966, "s": 955, "text": "Example 1:" }, { "code": null, "e": 974, "s": 966, "text": "Python3" }, { "code": "# Python program to demonstrate# AttributeError X = 10 # Raises an AttributeErrorX.append(6)", "e": 1067, "s": 974, "text": null }, { "code": null, "e": 1075, "s": 1067, "text": "Output:" }, { "code": null, "e": 1245, "s": 1075, "text": "Traceback (most recent call last):\n File \"/home/46576cfdd7cb1db75480a8653e2115cc.py\", line 5, in \n X.append(6)\nAttributeError: 'int' object has no attribute 'append'" }, { "code": null, "e": 1362, "s": 1245, "text": "Example 2: Sometimes any variation in spelling will cause an Attribute error as Python is a case-sensitive language." }, { "code": null, "e": 1370, "s": 1362, "text": "Python3" }, { "code": "# Python program to demonstrate# AttributeError # Raises an AttributeError as there is no# method as fst for stringsstring = \"The famous website is { }\".fst(\"geeksforgeeks\")print(string)", "e": 1557, "s": 1370, "text": null }, { "code": null, "e": 1565, "s": 1557, "text": "Output:" }, { "code": null, "e": 1778, "s": 1565, "text": "Traceback (most recent call last):\n File \"/home/2078367df38257e2ec3aead22841c153.py\", line 3, in \n string = \"The famous website is { }\".fst(\"geeksforgeeks\")\nAttributeError: 'str' object has no attribute 'fst'" }, { "code": null, "e": 1908, "s": 1778, "text": "Example 3: AttributeError can also be raised for a user-defined class when the user tries to make an invalid attribute reference." }, { "code": null, "e": 1916, "s": 1908, "text": "Python3" }, { "code": "# Python program to demonstrate# AttributeError class Geeks(): def __init__(self): self.a = 'GeeksforGeeks' # Driver's codeobj = Geeks() print(obj.a) # Raises an AttributeError as there# is no attribute bprint(obj.b)", "e": 2157, "s": 1916, "text": null }, { "code": null, "e": 2166, "s": 2157, "text": "Output: " }, { "code": null, "e": 2180, "s": 2166, "text": "GeeksforGeeks" }, { "code": null, "e": 2187, "s": 2180, "text": "Error:" }, { "code": null, "e": 2356, "s": 2187, "text": "Traceback (most recent call last):\n File \"/home/373989a62f52a8b91cb2d3300f411083.py\", line 17, in \n print(obj.b)\nAttributeError: 'Geeks' object has no attribute 'b'" }, { "code": null, "e": 2470, "s": 2356, "text": "Errors and exceptions in Python can be handled using exception handling i.e. by using try and except in Python. " }, { "code": null, "e": 2615, "s": 2470, "text": "Example: Consider the above class example, we want to do something else rather than printing the traceback Whenever an AttributeError is raised." }, { "code": null, "e": 2623, "s": 2615, "text": "Python3" }, { "code": "# Python program to demonstrate# AttributeError class Geeks(): def __init__(self): self.a = 'GeeksforGeeks' # Driver's codeobj = Geeks() # Try and except statement for# Exception handlingtry: print(obj.a) # Raises an AttributeError print(obj.b) # Prints the below statement# whenever an AttributeError is# raisedexcept AttributeError: print(\"There is no such attribute\")", "e": 3031, "s": 2623, "text": null }, { "code": null, "e": 3039, "s": 3031, "text": "Output:" }, { "code": null, "e": 3080, "s": 3039, "text": "GeeksforGeeks\nThere is no such attribute" }, { "code": null, "e": 3136, "s": 3080, "text": "Note: To know more about exception handling click here." }, { "code": null, "e": 3147, "s": 3136, "text": "nidhi_biet" }, { "code": null, "e": 3161, "s": 3147, "text": "sumitgumber28" }, { "code": null, "e": 3171, "s": 3161, "text": "11irishjs" }, { "code": null, "e": 3189, "s": 3171, "text": "Python-exceptions" }, { "code": null, "e": 3196, "s": 3189, "text": "Python" }, { "code": null, "e": 3215, "s": 3196, "text": "Technical Scripter" }, { "code": null, "e": 3313, "s": 3215, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3331, "s": 3313, "text": "Python Dictionary" }, { "code": null, "e": 3373, "s": 3331, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3395, "s": 3373, "text": "Enumerate() in Python" }, { "code": null, "e": 3427, "s": 3395, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3453, "s": 3427, "text": "Python String | replace()" }, { "code": null, "e": 3482, "s": 3453, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3509, "s": 3482, "text": "Python Classes and Objects" }, { "code": null, "e": 3530, "s": 3509, "text": "Python OOPs Concepts" }, { "code": null, "e": 3560, "s": 3530, "text": "Iterate over a list in Python" } ]
Designing Deterministic Finite Automata (Set 1)
02 Jun, 2022 Prerequisite – Designing finite automata In this article, we will see some designing of Deterministic Finite Automata (DFA). Problem-1: Construction of a DFA for the set of string over {a, b} such that length of the string |w|=2 i.e, length of the string is exactly 2. Explanation – The desired language will be like: L = {aa, ab, ba, bb} The state transition diagram of the language will be like: Here, State A represent set of all string of length zero (0), state B represent set of all string of length one (1), state C represent set of all string of length two (2). State C is the final state and D is the dead state it is so because after getting any alphabet as input it will not go into final state ever. Number of states: n+2 Where n is |w|=n The above automata will accept all the strings having the length of the string exactly 2. When the length of the string is 1, then it will go from state A to B. When the length of the string is 2, then it will go from state B to C and when the length of the string is greater than 2, then it will go from state C to D (Dead state) and after it from state D TO D itself. Python3 #check string in#in state Adef checkStateA(n): #if length of #string is one #print not accepted if(len(n)==1): print("string not accepted") else: #pass string to stateB to #to check further transitions if(n[0]=='a' or n[0]=='b'): stateB(n[1:]) def stateB(n): #here if length #is not 1 print#string not accepted if(len(n)!=1): print("string not accepted") else: #else pass string #to state c stateC(n[1:])def stateC(n): #here if length #becomes zero #print accepted #else not accepted if (len(n)==0): print("string accepted") else: print("string not accepted") #take input n=input()checkStateA(n) Problem-2: Construction of a DFA for the set of string over {a, b} such that length of the string |w|>=2 i.e, length of the string should be at least 2. Explanation – The desired language will be like: L = {aa, ab, ba, bb, aaa, aab, aba, abb........} The state transition diagram of the language will be like: Here, State A represent set of all string of length zero (0), state B represent set of all string of length one (1), and state C represent set of all string of length two (2). Number of states: n+1 Where n is |w|>=n The above automata will accept all the strings having the length of the string at least 2. When the length of the string is 1, then it will go from state A to B. When the length of the string is 2, then it will go from state B to C and lastly when the length of the string is greater than 2, then it will go from state C to C itself. Python3 #check string in#in state Adef checkStateA(n): #if length of #string is one #print not accepted if(len(n)==1): print("string not accepted") else: #pass string to stateB to #to check further transitions if(n[0]=='a' or n[0]=='b'): stateB(n[1:]) def stateB(n): #here if length #is less than 1 #printstring not accepted if(len(n)<1): print("string not accepted") else: #else pass string #to state c stateC(n[1:]) def stateC(n): #here if length of string #is greater than equal to zero #print accepted #else not accepted if (len(n)>=0): print("string accepted") else: print("string not accepted") #take input n=input()checkStateA(n) Problem-3: Construction of a DFA for the set of string over {a, b} such that length of the string |w|<=2 i.e, length of the string is atmost 2.Explanation – The desired language will be like: L = {?, aa, ab, ba, bb} The state transition diagram of the language will be like: Here, State A represent set of all string of length zero (0), state B represent set of all string of length one (1), state C represent set of all string of length two (2), state A, B, C is the final state and D is the dead state it is so because after getting any alphabet as input it will not go into final state ever. Number of states: n+2 Where n is |w|<=n The above automata will accept all the strings having the length of the string at most 2. When the length of the string is 1, then it will go from state A to B. When the length of the string is 2, then it will go from state B to C and lastly when the length of the string is greater than 2, then it will go from state C to D (Dead state). Python3 #check string in#in state Adef checkStateA(n): #if only two transition occurs #then print string accepted if(n[0]=='a' or n[0]=='b'): stateB(n[1:]) def stateB(n): #if length is 0 #print accepted if(len(n)==0): print("string accepted") else: stateC(n[1:]) def stateC(n): #if length is 0 #print accepted #else not accepted if (len(n)==0): print("string accepted") else: print("string not accepted") #take input n=input()checkStateA(n) parmarnishit1012 _mridul_bhardwaj_ AshokJaiswal surinderdawra388 GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n02 Jun, 2022" }, { "code": null, "e": 179, "s": 53, "text": "Prerequisite – Designing finite automata In this article, we will see some designing of Deterministic Finite Automata (DFA). " }, { "code": null, "e": 372, "s": 179, "text": "Problem-1: Construction of a DFA for the set of string over {a, b} such that length of the string |w|=2 i.e, length of the string is exactly 2. Explanation – The desired language will be like:" }, { "code": null, "e": 394, "s": 372, "text": "L = {aa, ab, ba, bb} " }, { "code": null, "e": 768, "s": 394, "text": "The state transition diagram of the language will be like: Here, State A represent set of all string of length zero (0), state B represent set of all string of length one (1), state C represent set of all string of length two (2). State C is the final state and D is the dead state it is so because after getting any alphabet as input it will not go into final state ever." }, { "code": null, "e": 808, "s": 768, "text": "Number of states: n+2\nWhere n is |w|=n " }, { "code": null, "e": 1179, "s": 808, "text": "The above automata will accept all the strings having the length of the string exactly 2. When the length of the string is 1, then it will go from state A to B. When the length of the string is 2, then it will go from state B to C and when the length of the string is greater than 2, then it will go from state C to D (Dead state) and after it from state D TO D itself. " }, { "code": null, "e": 1187, "s": 1179, "text": "Python3" }, { "code": "#check string in#in state Adef checkStateA(n): #if length of #string is one #print not accepted if(len(n)==1): print(\"string not accepted\") else: #pass string to stateB to #to check further transitions if(n[0]=='a' or n[0]=='b'): stateB(n[1:]) def stateB(n): #here if length #is not 1 print#string not accepted if(len(n)!=1): print(\"string not accepted\") else: #else pass string #to state c stateC(n[1:])def stateC(n): #here if length #becomes zero #print accepted #else not accepted if (len(n)==0): print(\"string accepted\") else: print(\"string not accepted\") #take input n=input()checkStateA(n)", "e": 1952, "s": 1187, "text": null }, { "code": null, "e": 2154, "s": 1952, "text": "Problem-2: Construction of a DFA for the set of string over {a, b} such that length of the string |w|>=2 i.e, length of the string should be at least 2. Explanation – The desired language will be like:" }, { "code": null, "e": 2204, "s": 2154, "text": "L = {aa, ab, ba, bb, aaa, aab, aba, abb........} " }, { "code": null, "e": 2439, "s": 2204, "text": "The state transition diagram of the language will be like: Here, State A represent set of all string of length zero (0), state B represent set of all string of length one (1), and state C represent set of all string of length two (2)." }, { "code": null, "e": 2480, "s": 2439, "text": "Number of states: n+1\nWhere n is |w|>=n " }, { "code": null, "e": 2815, "s": 2480, "text": "The above automata will accept all the strings having the length of the string at least 2. When the length of the string is 1, then it will go from state A to B. When the length of the string is 2, then it will go from state B to C and lastly when the length of the string is greater than 2, then it will go from state C to C itself. " }, { "code": null, "e": 2823, "s": 2815, "text": "Python3" }, { "code": "#check string in#in state Adef checkStateA(n): #if length of #string is one #print not accepted if(len(n)==1): print(\"string not accepted\") else: #pass string to stateB to #to check further transitions if(n[0]=='a' or n[0]=='b'): stateB(n[1:]) def stateB(n): #here if length #is less than 1 #printstring not accepted if(len(n)<1): print(\"string not accepted\") else: #else pass string #to state c stateC(n[1:]) def stateC(n): #here if length of string #is greater than equal to zero #print accepted #else not accepted if (len(n)>=0): print(\"string accepted\") else: print(\"string not accepted\") #take input n=input()checkStateA(n)", "e": 3655, "s": 2823, "text": null }, { "code": null, "e": 3847, "s": 3655, "text": "Problem-3: Construction of a DFA for the set of string over {a, b} such that length of the string |w|<=2 i.e, length of the string is atmost 2.Explanation – The desired language will be like:" }, { "code": null, "e": 3872, "s": 3847, "text": "L = {?, aa, ab, ba, bb} " }, { "code": null, "e": 3933, "s": 3872, "text": "The state transition diagram of the language will be like: " }, { "code": null, "e": 4253, "s": 3933, "text": "Here, State A represent set of all string of length zero (0), state B represent set of all string of length one (1), state C represent set of all string of length two (2), state A, B, C is the final state and D is the dead state it is so because after getting any alphabet as input it will not go into final state ever." }, { "code": null, "e": 4294, "s": 4253, "text": "Number of states: n+2\nWhere n is |w|<=n " }, { "code": null, "e": 4634, "s": 4294, "text": "The above automata will accept all the strings having the length of the string at most 2. When the length of the string is 1, then it will go from state A to B. When the length of the string is 2, then it will go from state B to C and lastly when the length of the string is greater than 2, then it will go from state C to D (Dead state). " }, { "code": null, "e": 4642, "s": 4634, "text": "Python3" }, { "code": "#check string in#in state Adef checkStateA(n): #if only two transition occurs #then print string accepted if(n[0]=='a' or n[0]=='b'): stateB(n[1:]) def stateB(n): #if length is 0 #print accepted if(len(n)==0): print(\"string accepted\") else: stateC(n[1:]) def stateC(n): #if length is 0 #print accepted #else not accepted if (len(n)==0): print(\"string accepted\") else: print(\"string not accepted\") #take input n=input()checkStateA(n)", "e": 5212, "s": 4642, "text": null }, { "code": null, "e": 5229, "s": 5212, "text": "parmarnishit1012" }, { "code": null, "e": 5247, "s": 5229, "text": "_mridul_bhardwaj_" }, { "code": null, "e": 5260, "s": 5247, "text": "AshokJaiswal" }, { "code": null, "e": 5277, "s": 5260, "text": "surinderdawra388" }, { "code": null, "e": 5285, "s": 5277, "text": "GATE CS" }, { "code": null, "e": 5318, "s": 5285, "text": "Theory of Computation & Automata" } ]
What is AOT and JIT Compiler in Angular ?
05 Nov, 2020 An angular application mainly consists of HTML templates, their components which include various TypeScript files. There are some unit testing and configuration file. Whenever we run over an application, the browser cannot understand the code directly hence we have to compile our code. What is Ahead of Time (AOT) compiler ? All technologies Ahead of Time is a process of compiling higher-level language or intermediate language into a native machine code, which is system dependent. In simple words, when you serve/build your angular application, the Ahead of Time compiler converts your code during the build time before your browser downloads and runs that code. From Angular 9, by default compiling option is set to true for ahead of time compiler. Why should you use the Ahead of Time compiler ? When you are using Ahead of Time Compiler, compilation only happens once, while you build your project. We don’t have to ship the HTML templates and the Angular compiler whenever we enter a new component. It can minimize the size of your application. The browser does not need to compile the code in run time, it can directly render the application immediately, without waiting to compile the app first so, it provides quicker component rendering. The Ahead of time compiler detects template error earlier. It detects and reports template binding errors during the build steps before users can see them. AOT provides better security. It compiles HTML components and templates into JavaScript files long before they are served into the client display. So, there are no templates to read and no risky client-side HTML or JavaScript evaluation. This will reduce the chances of injections attacks. How Ahead of Time works ? We use Typescript, HTML, style-sheets to develop our Angular project and ng build –prod or ng build to build our source code into bundles which include JS files, index.html, style-sheets, and assets files. Now Angular uses the angular compiler (whichever you have selected) to build source code, and they do it in three phases, which are code analysis, code generation and template type checking. At the end of this process, bundle size will be much smaller than the JIT compiler’s bundle size. After that AOT builds this into a war file to deploy directly by using Heroku or by JBoss or by any other hosting that supports Node. And then we map this host to the domain by using a CNAME. Now the clients can access your web application via the domain. The browser will download all necessary files like HTML, style-sheets, and JavaScript which is needed for the default view. At last, your application will get bootstrap and get rendered. How to compile your app in ahead of time compiler: For compiling your app in Ahead of time, you don’t have to do much, because from angular 9 default compiling option is set to Ahead of time. Just add –AoT at the end ng serve –aot. What is the Just in Time (JIT) compiler ? Just in time compiler provides compilation during the execution of the program at a run time before execution. In simple words, code get compiles when it’s needed, not at the build time. Why and When Should you use Just In Time Compiler ? Just in time compiler compiles each file separately and it’s mostly compiled in the browser. You don’t have to build your project again after changing your code. Most compiling is done on the browser side, so it will take less compiling time. If you have a big project or a situation where some of your components don’t come in use most of the time then you should use the Just in time compiler. Just in Time compiler is best when your application is in local development. How Just in Time compiler Works? Initially, compiler was responsible for converting a high-level language into machine language, which would then be converted into executable code. Just in time compiler, compiles code at runtime which means instead of interpreting byte code at build time, it will compile byte code when that component is called. A few important points: In case of Just in time, not all code is compiled at the initial time. Only necessary component which are going to be needed at the starting of your application will be compiled. Then if the functionality is need in your project and it’s not in compiled code, that function or component will be compiled. This process will help to reduce the burden on the CPU and make your app render fast. One more interesting thing is, you can see and link to your source code in inspect mode because Just in Time, compiles your code with JIT mode and a map file. Comparison between Ahead of Time (AOT) and Just in Time (JIT) – You can run your app in JIT with this command: ng build OR ng serve To run your app in AOT you have to provide –aot at the end like: ng build --aot OR ng serve --aot Conclusion: You can compile your angular application in two ways: JIT and AOT. Both are suitable for a different scenario like you can use JIT for development mode and AOT is better in production mode. Implementing features and debugging is easy in JIT mode since you have to map files while AOT does not have it. However, that AOT provides a big benefit to angular developers for production mode by reducing bundle size and making your app render faster. AngularJS-Misc AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Nov, 2020" }, { "code": null, "e": 339, "s": 52, "text": "An angular application mainly consists of HTML templates, their components which include various TypeScript files. There are some unit testing and configuration file. Whenever we run over an application, the browser cannot understand the code directly hence we have to compile our code." }, { "code": null, "e": 378, "s": 339, "text": "What is Ahead of Time (AOT) compiler ?" }, { "code": null, "e": 537, "s": 378, "text": "All technologies Ahead of Time is a process of compiling higher-level language or intermediate language into a native machine code, which is system dependent." }, { "code": null, "e": 808, "s": 537, "text": "In simple words, when you serve/build your angular application, the Ahead of Time compiler converts your code during the build time before your browser downloads and runs that code. From Angular 9, by default compiling option is set to true for ahead of time compiler. " }, { "code": null, "e": 856, "s": 808, "text": "Why should you use the Ahead of Time compiler ?" }, { "code": null, "e": 960, "s": 856, "text": "When you are using Ahead of Time Compiler, compilation only happens once, while you build your project." }, { "code": null, "e": 1061, "s": 960, "text": "We don’t have to ship the HTML templates and the Angular compiler whenever we enter a new component." }, { "code": null, "e": 1107, "s": 1061, "text": "It can minimize the size of your application." }, { "code": null, "e": 1304, "s": 1107, "text": "The browser does not need to compile the code in run time, it can directly render the application immediately, without waiting to compile the app first so, it provides quicker component rendering." }, { "code": null, "e": 1460, "s": 1304, "text": "The Ahead of time compiler detects template error earlier. It detects and reports template binding errors during the build steps before users can see them." }, { "code": null, "e": 1750, "s": 1460, "text": "AOT provides better security. It compiles HTML components and templates into JavaScript files long before they are served into the client display. So, there are no templates to read and no risky client-side HTML or JavaScript evaluation. This will reduce the chances of injections attacks." }, { "code": null, "e": 1776, "s": 1750, "text": "How Ahead of Time works ?" }, { "code": null, "e": 1982, "s": 1776, "text": "We use Typescript, HTML, style-sheets to develop our Angular project and ng build –prod or ng build to build our source code into bundles which include JS files, index.html, style-sheets, and assets files." }, { "code": null, "e": 2271, "s": 1982, "text": "Now Angular uses the angular compiler (whichever you have selected) to build source code, and they do it in three phases, which are code analysis, code generation and template type checking. At the end of this process, bundle size will be much smaller than the JIT compiler’s bundle size." }, { "code": null, "e": 2463, "s": 2271, "text": "After that AOT builds this into a war file to deploy directly by using Heroku or by JBoss or by any other hosting that supports Node. And then we map this host to the domain by using a CNAME." }, { "code": null, "e": 2717, "s": 2463, "text": "Now the clients can access your web application via the domain. The browser will download all necessary files like HTML, style-sheets, and JavaScript which is needed for the default view. At last, your application will get bootstrap and get rendered. " }, { "code": null, "e": 2949, "s": 2717, "text": "How to compile your app in ahead of time compiler: For compiling your app in Ahead of time, you don’t have to do much, because from angular 9 default compiling option is set to Ahead of time. Just add –AoT at the end ng serve –aot." }, { "code": null, "e": 2991, "s": 2949, "text": "What is the Just in Time (JIT) compiler ?" }, { "code": null, "e": 3178, "s": 2991, "text": "Just in time compiler provides compilation during the execution of the program at a run time before execution. In simple words, code get compiles when it’s needed, not at the build time." }, { "code": null, "e": 3230, "s": 3178, "text": "Why and When Should you use Just In Time Compiler ?" }, { "code": null, "e": 3392, "s": 3230, "text": "Just in time compiler compiles each file separately and it’s mostly compiled in the browser. You don’t have to build your project again after changing your code." }, { "code": null, "e": 3473, "s": 3392, "text": "Most compiling is done on the browser side, so it will take less compiling time." }, { "code": null, "e": 3626, "s": 3473, "text": "If you have a big project or a situation where some of your components don’t come in use most of the time then you should use the Just in time compiler." }, { "code": null, "e": 3703, "s": 3626, "text": "Just in Time compiler is best when your application is in local development." }, { "code": null, "e": 3736, "s": 3703, "text": "How Just in Time compiler Works?" }, { "code": null, "e": 3884, "s": 3736, "text": "Initially, compiler was responsible for converting a high-level language into machine language, which would then be converted into executable code." }, { "code": null, "e": 4050, "s": 3884, "text": "Just in time compiler, compiles code at runtime which means instead of interpreting byte code at build time, it will compile byte code when that component is called." }, { "code": null, "e": 4074, "s": 4050, "text": "A few important points:" }, { "code": null, "e": 4379, "s": 4074, "text": "In case of Just in time, not all code is compiled at the initial time. Only necessary component which are going to be needed at the starting of your application will be compiled. Then if the functionality is need in your project and it’s not in compiled code, that function or component will be compiled." }, { "code": null, "e": 4465, "s": 4379, "text": "This process will help to reduce the burden on the CPU and make your app render fast." }, { "code": null, "e": 4624, "s": 4465, "text": "One more interesting thing is, you can see and link to your source code in inspect mode because Just in Time, compiles your code with JIT mode and a map file." }, { "code": null, "e": 4688, "s": 4624, "text": "Comparison between Ahead of Time (AOT) and Just in Time (JIT) –" }, { "code": null, "e": 4735, "s": 4688, "text": "You can run your app in JIT with this command:" }, { "code": null, "e": 4756, "s": 4735, "text": "ng build OR ng serve" }, { "code": null, "e": 4821, "s": 4756, "text": "To run your app in AOT you have to provide –aot at the end like:" }, { "code": null, "e": 4856, "s": 4821, "text": "ng build --aot OR ng serve --aot " }, { "code": null, "e": 5313, "s": 4856, "text": "Conclusion: You can compile your angular application in two ways: JIT and AOT. Both are suitable for a different scenario like you can use JIT for development mode and AOT is better in production mode. Implementing features and debugging is easy in JIT mode since you have to map files while AOT does not have it. However, that AOT provides a big benefit to angular developers for production mode by reducing bundle size and making your app render faster." }, { "code": null, "e": 5328, "s": 5313, "text": "AngularJS-Misc" }, { "code": null, "e": 5338, "s": 5328, "text": "AngularJS" }, { "code": null, "e": 5355, "s": 5338, "text": "Web Technologies" } ]
Python | Pandas DataFrame.tz_localize
30 May, 2022 Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas. Pandas DataFrame.tz_localize() function localize tz-naive index of a Series or DataFrame to target time zone. This operation localizes the Index. Syntax: DataFrame.tz_localize(tz, axis=0, level=None, copy=True, ambiguous=’raise’, nonexistent=’raise’) Parameter : tz : string or pytz.timezone object axis : the axis to localize level : If axis is a MultiIndex, localize a specific level. Otherwise must be None copy : Also make a copy of the underlying data ambiguous : When clocks moved backward due to DST, ambiguous times may arise nonexistent : A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST Returns : Same type as the input. Example #1: Use DataFrame.tz_localize() function to localize the given tz-naive index of the dataframe to the target timezone. Python3 # importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71], 'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'], 'Age':[14, 25, 55, 8, 21]}) # Create the indexindex_ = pd.date_range('2010-10-09 08:45', periods = 5, freq ='H', tz = 'US / Central') # Set the indexdf.index = index_ # Print the DataFrameprint(df) Output : Now we will use DataFrame.tz_localize() function to localize the given tz-naive index of the dataframe to the ‘Europe/Berlin’ timezone. Python3 # Let's find out the current timezone# of the given dataframeprint(df.index) # Let's localize the timezone of the# dataframe index to 'Europe / Berlin'df = df = df.tz_localize(tz = 'Europe / Berlin') # Let's find out the current timezone# of the given dataframeprint(df.index) Output : As we can see in the output, the DataFrame.tz_localize() function has successfully localized the tz-naive index of the given dataframe to the target timezone. Example #2 : Use DataFrame.tz_localize() function to localize the tz-naive Index of the given dataframe. The Index of the given dataframe is a MultiIndex. Python3 # importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71], 'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'], 'Age':[14, 25, 55, 8, 21]}) # Create the MultiIndexindex_ = pd.MultiIndex.from_product([['Date'], pd.date_range('2010-10-09 08:45', periods = 5, freq ='H')], names =['Level 1', 'Level 2']) # Set the indexdf.index = index_ # Print the DataFrameprint(df) Output : Now we will use DataFrame.tz_localize() function to localize the tz-naive index of the given dataframe to ‘US/Central’. Python3 # Let's find out the current timezone# of the Level 1 of the given dataframeprint(df.index[1]) # Let's localize the timezone of the# level 1 of the dataframe to 'US / Central'df = df.tz_localize(tz = 'US / Central', level = 1) # Let's find out the current timezone# of the level 1 of the given dataframeprint(df.index[1]) Output : As we can see in the output, the DataFrame.tz_localize() function has successfully localized the tz-naive index of the given dataframe to ‘US/Central’. vinayedula Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Python String | replace() Python Classes and Objects Python OOPs Concepts Iterate over a list in Python Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n30 May, 2022" }, { "code": null, "e": 488, "s": 28, "text": "Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas. Pandas DataFrame.tz_localize() function localize tz-naive index of a Series or DataFrame to target time zone. This operation localizes the Index." }, { "code": null, "e": 1021, "s": 488, "text": "Syntax: DataFrame.tz_localize(tz, axis=0, level=None, copy=True, ambiguous=’raise’, nonexistent=’raise’) Parameter : tz : string or pytz.timezone object axis : the axis to localize level : If axis is a MultiIndex, localize a specific level. Otherwise must be None copy : Also make a copy of the underlying data ambiguous : When clocks moved backward due to DST, ambiguous times may arise nonexistent : A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST Returns : Same type as the input." }, { "code": null, "e": 1149, "s": 1021, "text": "Example #1: Use DataFrame.tz_localize() function to localize the given tz-naive index of the dataframe to the target timezone. " }, { "code": null, "e": 1157, "s": 1149, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71], 'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'], 'Age':[14, 25, 55, 8, 21]}) # Create the indexindex_ = pd.date_range('2010-10-09 08:45', periods = 5, freq ='H', tz = 'US / Central') # Set the indexdf.index = index_ # Print the DataFrameprint(df)", "e": 1559, "s": 1157, "text": null }, { "code": null, "e": 1706, "s": 1559, "text": "Output : Now we will use DataFrame.tz_localize() function to localize the given tz-naive index of the dataframe to the ‘Europe/Berlin’ timezone. " }, { "code": null, "e": 1714, "s": 1706, "text": "Python3" }, { "code": "# Let's find out the current timezone# of the given dataframeprint(df.index) # Let's localize the timezone of the# dataframe index to 'Europe / Berlin'df = df = df.tz_localize(tz = 'Europe / Berlin') # Let's find out the current timezone# of the given dataframeprint(df.index)", "e": 1991, "s": 1714, "text": null }, { "code": null, "e": 2319, "s": 1991, "text": "Output : As we can see in the output, the DataFrame.tz_localize() function has successfully localized the tz-naive index of the given dataframe to the target timezone. Example #2 : Use DataFrame.tz_localize() function to localize the tz-naive Index of the given dataframe. The Index of the given dataframe is a MultiIndex. " }, { "code": null, "e": 2327, "s": 2319, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71], 'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'], 'Age':[14, 25, 55, 8, 21]}) # Create the MultiIndexindex_ = pd.MultiIndex.from_product([['Date'], pd.date_range('2010-10-09 08:45', periods = 5, freq ='H')], names =['Level 1', 'Level 2']) # Set the indexdf.index = index_ # Print the DataFrameprint(df)", "e": 2794, "s": 2327, "text": null }, { "code": null, "e": 2925, "s": 2794, "text": "Output : Now we will use DataFrame.tz_localize() function to localize the tz-naive index of the given dataframe to ‘US/Central’. " }, { "code": null, "e": 2933, "s": 2925, "text": "Python3" }, { "code": "# Let's find out the current timezone# of the Level 1 of the given dataframeprint(df.index[1]) # Let's localize the timezone of the# level 1 of the dataframe to 'US / Central'df = df.tz_localize(tz = 'US / Central', level = 1) # Let's find out the current timezone# of the level 1 of the given dataframeprint(df.index[1])", "e": 3255, "s": 2933, "text": null }, { "code": null, "e": 3418, "s": 3255, "text": "Output : As we can see in the output, the DataFrame.tz_localize() function has successfully localized the tz-naive index of the given dataframe to ‘US/Central’." }, { "code": null, "e": 3429, "s": 3418, "text": "vinayedula" }, { "code": null, "e": 3453, "s": 3429, "text": "Python pandas-dataFrame" }, { "code": null, "e": 3485, "s": 3453, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 3499, "s": 3485, "text": "Python-pandas" }, { "code": null, "e": 3506, "s": 3499, "text": "Python" }, { "code": null, "e": 3604, "s": 3506, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3622, "s": 3604, "text": "Python Dictionary" }, { "code": null, "e": 3664, "s": 3622, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3686, "s": 3664, "text": "Enumerate() in Python" }, { "code": null, "e": 3721, "s": 3686, "text": "Read a file line by line in Python" }, { "code": null, "e": 3753, "s": 3721, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3779, "s": 3753, "text": "Python String | replace()" }, { "code": null, "e": 3806, "s": 3779, "text": "Python Classes and Objects" }, { "code": null, "e": 3827, "s": 3806, "text": "Python OOPs Concepts" }, { "code": null, "e": 3857, "s": 3827, "text": "Iterate over a list in Python" } ]
kbhit in C language
07 Jun, 2022 kbhit() functionality is basically stand for the Keyboard Hit. This function is deals with keyboard pressing kbhit() is present in conio.h and used to determine if a key has been pressed or not. To use kbhit function in your program you should include the header file “conio.h”. If a key has been pressed then it returns a non zero value otherwise returns zero. CPP // C++ program to demonstrate use of kbhit()#include <iostream.h>#include <conio.h> int main(){ while (!kbhit()) printf("Press a key\n"); return 0;} Output: "Press a key" will keep printing on the console until the user presses a key on the keyboard. Note : kbhit() is not a standard library function and should be avoided. Program to fetch the pressed key using kbhit CPP // C++ program to fetch key pressed using// kbhit()#include <iostream>#include <conio.h>using namespace std;int main(){ char ch; while (1) { if ( kbhit() ) { // Stores the pressed key in ch ch = getch(); // Terminates the loop // when escape is pressed if (int(ch) == 27) break; cout << "\nKey pressed= " << ch; } } return 0;} Output: Prints all the keys that will be pressed on the keyboard until the user presses Escape key C #include <stdio.h>// include conio.h file for kbhit function#include <conio.h>main(){ // declare variable char ch; printf("Enter key ESC to exit \n"); // define infinite loop for taking keys while (1) { if (kbhit) { // fetch typed character into ch ch = getch(); if ((int)ch == 27) // when esc button is pressed, then it will exit from loop break; printf("You have entered : %c\n", ch); } }} Output : Enter key ESC to exit You have entered : i You have entered : P You have entered : S You have entered : w You have entered : 7 You have entered : / You have entered : * You have entered : + This article is contributed by Nishu Singh 1. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sahivam4u reshmapatil2772 cpp-input-output C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jun, 2022" }, { "code": null, "e": 162, "s": 52, "text": "kbhit() functionality is basically stand for the Keyboard Hit. This function is deals with keyboard pressing " }, { "code": null, "e": 416, "s": 162, "text": "kbhit() is present in conio.h and used to determine if a key has been pressed or not. To use kbhit function in your program you should include the header file “conio.h”. If a key has been pressed then it returns a non zero value otherwise returns zero. " }, { "code": null, "e": 420, "s": 416, "text": "CPP" }, { "code": "// C++ program to demonstrate use of kbhit()#include <iostream.h>#include <conio.h> int main(){ while (!kbhit()) printf(\"Press a key\\n\"); return 0;}", "e": 583, "s": 420, "text": null }, { "code": null, "e": 591, "s": 583, "text": "Output:" }, { "code": null, "e": 686, "s": 591, "text": "\"Press a key\" will keep printing on the \nconsole until the user presses a key on the keyboard." }, { "code": null, "e": 805, "s": 686, "text": "Note : kbhit() is not a standard library function and should be avoided. Program to fetch the pressed key using kbhit " }, { "code": null, "e": 809, "s": 805, "text": "CPP" }, { "code": "// C++ program to fetch key pressed using// kbhit()#include <iostream>#include <conio.h>using namespace std;int main(){ char ch; while (1) { if ( kbhit() ) { // Stores the pressed key in ch ch = getch(); // Terminates the loop // when escape is pressed if (int(ch) == 27) break; cout << \"\\nKey pressed= \" << ch; } } return 0;}", "e": 1247, "s": 809, "text": null }, { "code": null, "e": 1255, "s": 1247, "text": "Output:" }, { "code": null, "e": 1347, "s": 1255, "text": "Prints all the keys that will be pressed on\n the keyboard until the user presses Escape key" }, { "code": null, "e": 1349, "s": 1347, "text": "C" }, { "code": "#include <stdio.h>// include conio.h file for kbhit function#include <conio.h>main(){ // declare variable char ch; printf(\"Enter key ESC to exit \\n\"); // define infinite loop for taking keys while (1) { if (kbhit) { // fetch typed character into ch ch = getch(); if ((int)ch == 27) // when esc button is pressed, then it will exit from loop break; printf(\"You have entered : %c\\n\", ch); } }}", "e": 1847, "s": 1349, "text": null }, { "code": null, "e": 2046, "s": 1847, "text": "Output :\nEnter key ESC to exit\nYou have entered : i\nYou have entered : P\nYou have entered : S\nYou have entered : w\nYou have entered : 7\nYou have entered : /\nYou have entered : *\nYou have entered : +" }, { "code": null, "e": 2468, "s": 2046, "text": "This article is contributed by Nishu Singh 1. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2478, "s": 2468, "text": "sahivam4u" }, { "code": null, "e": 2494, "s": 2478, "text": "reshmapatil2772" }, { "code": null, "e": 2511, "s": 2494, "text": "cpp-input-output" }, { "code": null, "e": 2522, "s": 2511, "text": "C Language" }, { "code": null, "e": 2526, "s": 2522, "text": "C++" }, { "code": null, "e": 2530, "s": 2526, "text": "CPP" } ]
Exporting variable to CSV file in Python
25 Feb, 2021 The CSV file or comma-separated values file is used to store and share data across platforms. The columns are separated by commas or other relevant delimiters, giving the data a tabular structure. Sometimes we come across ready-made CSV files while sometimes we need to create one according to the requirements in our projects. Python can write CSV files using many modules. The csv module in Python’s standard library provides classes and methods to read & write data in CSV files. To write in our CSV file, we use the following objects and methods of the csv module: This function returns a writer object that converts data into a delimited string and stores it in a file object. The function needs a file object as a parameter. To prevent additional space between lines, the newline parameter is set to ‘’. The writer class has the following methods: csv.writerow()– This function writes items in an iterable (list, tuple, or string), separating them by delimiter csv.writerows()– This function takes a list of iterables as a parameter, and writes each of them into new rows. To write into a CSV file, let us start by creating a variable (List, Tuple, String). We would then export this variable into our file with the help of the above two csv module methods. Examples 1: Exporting a list variable into csv file. Python3 import csv # exporting a list variable into the csv fileinput_variable = ['This', 'is', 'Geeks', 'For', 'Geeks','list'] # Example.csv gets created in the current working directory with open('Example.csv', 'w', newline = '') as csvfile: my_writer = csv.writer(csvfile, delimiter = ' ') my_writer.writerow(input_variable) Output: Example 2: Exporting a Tuple variable into csv file Python3 import csv # exporting a tuple variable into the csv fileinput_variable = ('This', 'is', 'Geeks', 'For', 'Geeks', 'Tuple') # Example.csv gets created in the current working directorywith open('Example.csv', 'w', newline = '') as csvfile: my_writer = csv.writer(csvfile, delimiter = ' ') my_writer.writerow(input_variable) Output: Example 3: Exporting a string variable into CSV file Python3 import csv # exporting a string variable into the csv fileinput_variable = "GeeksForGeeks" # Example.csv gets created in the current working directory with open('Example.csv', 'w', newline = '') as csvfile: my_writer = csv.writer(csvfile, delimiter = ' ') my_writer.writerow(input_variable) Output: Similarly, we can write multiple rows into a CSV with the help of a 2-D list. This structure of data closely resembles a tabular Excel sheet with rows and columns. For example: The below code creates an input variable with a nested list of lists and tuples. Python3 import csv # 2D list of variables (tabular data with rows and columns)input_variable = [ ['S.no','name','e-mail'], [1,'meesha','meesh@email.com'], (2,'abhilasha','ab@email.com'), (3,'arav','arav123@email.com')] # Example.csv gets created in the current working directorywith open ('Example.csv','w',newline = '') as csvfile: my_writer = csv.writer(csvfile, delimiter = ' ') my_writer.writerows(input_variable) Output: Note: Changes in the CSV file will be visible after the successful execution of the above code. You need to review your CSV file after each run. Picked python-csv Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Feb, 2021" }, { "code": null, "e": 226, "s": 28, "text": "The CSV file or comma-separated values file is used to store and share data across platforms. The columns are separated by commas or other relevant delimiters, giving the data a tabular structure. " }, { "code": null, "e": 512, "s": 226, "text": "Sometimes we come across ready-made CSV files while sometimes we need to create one according to the requirements in our projects. Python can write CSV files using many modules. The csv module in Python’s standard library provides classes and methods to read & write data in CSV files." }, { "code": null, "e": 598, "s": 512, "text": "To write in our CSV file, we use the following objects and methods of the csv module:" }, { "code": null, "e": 839, "s": 598, "text": "This function returns a writer object that converts data into a delimited string and stores it in a file object. The function needs a file object as a parameter. To prevent additional space between lines, the newline parameter is set to ‘’." }, { "code": null, "e": 883, "s": 839, "text": "The writer class has the following methods:" }, { "code": null, "e": 996, "s": 883, "text": "csv.writerow()– This function writes items in an iterable (list, tuple, or string), separating them by delimiter" }, { "code": null, "e": 1108, "s": 996, "text": "csv.writerows()– This function takes a list of iterables as a parameter, and writes each of them into new rows." }, { "code": null, "e": 1293, "s": 1108, "text": "To write into a CSV file, let us start by creating a variable (List, Tuple, String). We would then export this variable into our file with the help of the above two csv module methods." }, { "code": null, "e": 1346, "s": 1293, "text": "Examples 1: Exporting a list variable into csv file." }, { "code": null, "e": 1354, "s": 1346, "text": "Python3" }, { "code": "import csv # exporting a list variable into the csv fileinput_variable = ['This', 'is', 'Geeks', 'For', 'Geeks','list'] # Example.csv gets created in the current working directory with open('Example.csv', 'w', newline = '') as csvfile: my_writer = csv.writer(csvfile, delimiter = ' ') my_writer.writerow(input_variable)", "e": 1700, "s": 1354, "text": null }, { "code": null, "e": 1708, "s": 1700, "text": "Output:" }, { "code": null, "e": 1760, "s": 1708, "text": "Example 2: Exporting a Tuple variable into csv file" }, { "code": null, "e": 1768, "s": 1760, "text": "Python3" }, { "code": "import csv # exporting a tuple variable into the csv fileinput_variable = ('This', 'is', 'Geeks', 'For', 'Geeks', 'Tuple') # Example.csv gets created in the current working directorywith open('Example.csv', 'w', newline = '') as csvfile: my_writer = csv.writer(csvfile, delimiter = ' ') my_writer.writerow(input_variable)", "e": 2116, "s": 1768, "text": null }, { "code": null, "e": 2124, "s": 2116, "text": "Output:" }, { "code": null, "e": 2177, "s": 2124, "text": "Example 3: Exporting a string variable into CSV file" }, { "code": null, "e": 2185, "s": 2177, "text": "Python3" }, { "code": "import csv # exporting a string variable into the csv fileinput_variable = \"GeeksForGeeks\" # Example.csv gets created in the current working directory with open('Example.csv', 'w', newline = '') as csvfile: my_writer = csv.writer(csvfile, delimiter = ' ') my_writer.writerow(input_variable)", "e": 2484, "s": 2185, "text": null }, { "code": null, "e": 2492, "s": 2484, "text": "Output:" }, { "code": null, "e": 2657, "s": 2492, "text": "Similarly, we can write multiple rows into a CSV with the help of a 2-D list. This structure of data closely resembles a tabular Excel sheet with rows and columns. " }, { "code": null, "e": 2670, "s": 2657, "text": "For example:" }, { "code": null, "e": 2751, "s": 2670, "text": "The below code creates an input variable with a nested list of lists and tuples." }, { "code": null, "e": 2759, "s": 2751, "text": "Python3" }, { "code": "import csv # 2D list of variables (tabular data with rows and columns)input_variable = [ ['S.no','name','e-mail'], [1,'meesha','meesh@email.com'], (2,'abhilasha','ab@email.com'), (3,'arav','arav123@email.com')] # Example.csv gets created in the current working directorywith open ('Example.csv','w',newline = '') as csvfile: my_writer = csv.writer(csvfile, delimiter = ' ') my_writer.writerows(input_variable)", "e": 3189, "s": 2759, "text": null }, { "code": null, "e": 3197, "s": 3189, "text": "Output:" }, { "code": null, "e": 3342, "s": 3197, "text": "Note: Changes in the CSV file will be visible after the successful execution of the above code. You need to review your CSV file after each run." }, { "code": null, "e": 3349, "s": 3342, "text": "Picked" }, { "code": null, "e": 3360, "s": 3349, "text": "python-csv" }, { "code": null, "e": 3384, "s": 3360, "text": "Technical Scripter 2020" }, { "code": null, "e": 3391, "s": 3384, "text": "Python" }, { "code": null, "e": 3410, "s": 3391, "text": "Technical Scripter" } ]
Fragment to Fragment Communication in Android using Shared ViewModel
06 Jun, 2021 If there are two or more fragments in an activity, they need to communicate and share the data between them. The traditional way of sharing the data between the two fragments is implementing the callback using an interface that is cumbersome and may throw exceptions. But the modern way of doing that is using shared ViewModel. So in this article, it’s been demonstrated how the shared ViewModel can be used to communicate between the fragments. Have a look at the following image to get an overview of the discussion. Note: This discussion is implemented in Kotlin programming language. Prerequisites Fragment Lifecycle in Android ViewModel in Android Architecture Components Step 1: Create an empty activity project Create an empty activity Android Studio project, and select Kotlin as the programming language. Refer to Android | How to Create/Start a New Project in Android Studio?. Step 2: Adding required dependencies The dependencies include the ViewModel and the LiveData. So, in the app level Gradle file add the following dependencies and sync the project. // lifecycle_version and architecture versions may varydef lifecycle_version = “2.3.1” def arch_version = “2.1.0” // ViewModel implementation “androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version” // LiveData implementation “androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version” // Lifecycles only (without ViewModel or LiveData) implementation “androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version” // architecture Lifecycle extensions implementation “androidx.lifecycle:lifecycle-extensions:$arch_version” Step 3: Working with activity_main.xml file The main layout of the application contains the two FrameLayouts which hold the two fragments. To implement the same invoke the following code inside the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="HardcodedText"> <TextView android:id="@+id/textView" style="@style/TextAppearance.MaterialComponents.Headline6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:text="Fragment 1:" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <FrameLayout android:id="@+id/fragment_1_holder" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="8dp" android:layout_marginEnd="16dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> <View android:id="@+id/view" android:layout_width="match_parent" android:layout_height="1dp" android:layout_marginTop="16dp" android:background="@color/green_700" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/fragment_1_holder" /> <TextView android:id="@+id/textView2" style="@style/TextAppearance.MaterialComponents.Headline6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:text="Fragment 2: " app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/view" /> <FrameLayout android:id="@+id/fragment_2_holder" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="8dp" android:layout_marginEnd="16dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView2" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 4: Implementing Shared ViewModel In the SharedViewModel.kt file there are there is one MutableLiveData of CharSequence for setting the data for EditTexts. Two functions setData and getData for updating that mutable live data as soon as the data inside the EditTexts changes. To implement the same invoke the following code. Kotlin import androidx.lifecycle.MutableLiveDataimport androidx.lifecycle.ViewModel class SharedViewModel : ViewModel() { // Mutable LiveData which observed by LiveData // and updated to EditTexts when it is changed. private val mutableLiveData: MutableLiveData<CharSequence> = MutableLiveData() // function to set the changed // data from the EditTexts fun setData(input: CharSequence) { mutableLiveData.value = input } // function to get the changed data from the EditTexts fun getData(): MutableLiveData<CharSequence> = mutableLiveData} Step 5: Creating 2 Fragments Create two Fragments with their own layouts naming Fragment1.kt and Fragment2.kt. For each of the fragment’s layouts, it contains one EditText to get the data to send for fragment 2 and one button, when clicked it shares the data to another fragment. To implement the layout for Fragment 1, invoke the following code inside the fragment_1.xml file XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:clipToPadding="false" android:padding="4dp" tools:context=".Fragment1" tools:ignore="HardcodedText"> <com.google.android.material.textfield.TextInputLayout android:id="@+id/edit_text_layout_1" android:layout_width="match_parent" android:layout_height="wrap_content"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/edit_text_from_fragment_1" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter the data" /> </com.google.android.material.textfield.TextInputLayout> <Button android:id="@+id/send_button_fragment_1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/edit_text_layout_1" android:layout_alignParentEnd="true" android:layout_marginTop="8dp" android:layout_marginEnd="16dp" android:text="Send Data to Fragment 2" /> </RelativeLayout> To implement the layout for Fragment 2, invoke the following code inside the fragment_2.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:clipToPadding="false" android:padding="4dp" tools:context=".Fragment2" tools:ignore="HardcodedText"> <com.google.android.material.textfield.TextInputLayout android:id="@+id/edit_text_layout_2" android:layout_width="match_parent" android:layout_height="wrap_content"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/edit_text_from_fragment_2" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter the data" /> </com.google.android.material.textfield.TextInputLayout> <Button android:id="@+id/send_button_fragment_2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/edit_text_layout_2" android:layout_alignParentEnd="true" android:layout_marginTop="8dp" android:layout_marginEnd="16dp" android:text="Send Data to Fragment 1" /> </RelativeLayout> Step 6: Creating instances of shared view model inside the Fragment.kt files There is a need to create the instance of the ViewModel of the type ShareViewModel when the Activity is created. So one needs to override the onActivityCreated() method inside each of the Fragments. This is so because when we see the lifecycle of the fragments the views are created and updated after the onCreateView() is called and onAcrivityCreated() callback is called after the onCreateView() is executed. So the LiveData can keep track of UI elements for which elements they have updated. Have a look at the following chart for the activity lifecycle of the fragment. To implement the same in both fragments invoke the, following code inside Fragment1.kt. Kotlin import android.os.Bundleimport android.text.Editableimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.EditTextimport androidx.lifecycle.Observerimport androidx.lifecycle.ViewModelProviders class Fragment1 : Fragment() { private var sharedViewModelInstance: SharedViewModel? = null private var editTextFromFragment1: EditText? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view: View = inflater.inflate(R.layout.fragment_1, container, false) val sendDataButton: Button = view.findViewById(R.id.send_button_fragment_1) editTextFromFragment1 = view.findViewById(R.id.edit_text_from_fragment_1) // as soon as the button is clicked // send the data to ViewModel // and the Live data will take care of // updating the data inside another Fragment sendDataButton.setOnClickListener { sharedViewModelInstance?.setData(editTextFromFragment1!!.text) } return view } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) // create instances of the shared view model // when the activity is created sharedViewModelInstance = ViewModelProviders.of(activity!!).get(SharedViewModel::class.java) // observe the data inside the view model that // is mutable live of type CharSequence and // set the data for edit text sharedViewModelInstance!!.getData().observe(viewLifecycleOwner, Observer { editTextFromFragment1!!.text = it as Editable? }) }} And same goes with the Fragment2.kt file, invoke the following code. Kotlin import android.os.Bundleimport android.text.Editableimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.EditTextimport androidx.lifecycle.Observerimport androidx.lifecycle.ViewModelProviders class Fragment2 : Fragment() { private var sharedViewModelInstance: SharedViewModel? = null private var editTextFromFragment2: EditText? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view: View = inflater.inflate(R.layout.fragment_2, container, false) val sendDataButton: Button = view.findViewById(R.id.send_button_fragment_2) editTextFromFragment2 = view.findViewById(R.id.edit_text_from_fragment_2) // as soon as the button is clicked // send the data to ViewModel // and the Live data will take care of // updating the data inside another Fragment sendDataButton.setOnClickListener { sharedViewModelInstance?.setData(editTextFromFragment2!!.text) } return view } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) // create instances of the shared view model // when the activity is created sharedViewModelInstance = ViewModelProviders.of(activity!!).get(SharedViewModel::class.java) // observe the data inside the view model that is mutable // live of type CharSequence and set the data for edit text sharedViewModelInstance!!.getData().observe(viewLifecycleOwner, Observer { editTextFromFragment2!!.text = it as Editable? }) }} Step 7: Populate the fragment holders using MainActivity.kt file Inside the MainActivity.kt file, one needs to populate the fragment holders from the activity_main.xml, with both fragments. To implement the same invoke the following code inside the MainActivity.kt file. Kotlin import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.fragment.app.FragmentTransaction class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val fragmentTransaction: FragmentTransaction = supportFragmentManager.beginTransaction() fragmentTransaction.apply { add(R.id.fragment_1_holder, Fragment1()) add(R.id.fragment_2_holder, Fragment2()) commit() } }} Output: Kotlin Android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jun, 2021" }, { "code": null, "e": 547, "s": 28, "text": "If there are two or more fragments in an activity, they need to communicate and share the data between them. The traditional way of sharing the data between the two fragments is implementing the callback using an interface that is cumbersome and may throw exceptions. But the modern way of doing that is using shared ViewModel. So in this article, it’s been demonstrated how the shared ViewModel can be used to communicate between the fragments. Have a look at the following image to get an overview of the discussion." }, { "code": null, "e": 616, "s": 547, "text": "Note: This discussion is implemented in Kotlin programming language." }, { "code": null, "e": 630, "s": 616, "text": "Prerequisites" }, { "code": null, "e": 660, "s": 630, "text": "Fragment Lifecycle in Android" }, { "code": null, "e": 705, "s": 660, "text": "ViewModel in Android Architecture Components" }, { "code": null, "e": 746, "s": 705, "text": "Step 1: Create an empty activity project" }, { "code": null, "e": 915, "s": 746, "text": "Create an empty activity Android Studio project, and select Kotlin as the programming language. Refer to Android | How to Create/Start a New Project in Android Studio?." }, { "code": null, "e": 952, "s": 915, "text": "Step 2: Adding required dependencies" }, { "code": null, "e": 1095, "s": 952, "text": "The dependencies include the ViewModel and the LiveData. So, in the app level Gradle file add the following dependencies and sync the project." }, { "code": null, "e": 1182, "s": 1095, "text": "// lifecycle_version and architecture versions may varydef lifecycle_version = “2.3.1”" }, { "code": null, "e": 1209, "s": 1182, "text": "def arch_version = “2.1.0”" }, { "code": null, "e": 1222, "s": 1209, "text": "// ViewModel" }, { "code": null, "e": 1301, "s": 1222, "text": "implementation “androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version”" }, { "code": null, "e": 1313, "s": 1301, "text": "// LiveData" }, { "code": null, "e": 1391, "s": 1313, "text": "implementation “androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version”" }, { "code": null, "e": 1442, "s": 1391, "text": "// Lifecycles only (without ViewModel or LiveData)" }, { "code": null, "e": 1519, "s": 1442, "text": "implementation “androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version”" }, { "code": null, "e": 1556, "s": 1519, "text": "// architecture Lifecycle extensions" }, { "code": null, "e": 1627, "s": 1556, "text": "implementation “androidx.lifecycle:lifecycle-extensions:$arch_version”" }, { "code": null, "e": 1671, "s": 1627, "text": "Step 3: Working with activity_main.xml file" }, { "code": null, "e": 1849, "s": 1671, "text": "The main layout of the application contains the two FrameLayouts which hold the two fragments. To implement the same invoke the following code inside the activity_main.xml file." }, { "code": null, "e": 1853, "s": 1849, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <TextView android:id=\"@+id/textView\" style=\"@style/TextAppearance.MaterialComponents.Headline6\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:text=\"Fragment 1:\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <FrameLayout android:id=\"@+id/fragment_1_holder\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"8dp\" android:layout_marginEnd=\"16dp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.0\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/textView\" /> <View android:id=\"@+id/view\" android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:layout_marginTop=\"16dp\" android:background=\"@color/green_700\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/fragment_1_holder\" /> <TextView android:id=\"@+id/textView2\" style=\"@style/TextAppearance.MaterialComponents.Headline6\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:text=\"Fragment 2: \" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/view\" /> <FrameLayout android:id=\"@+id/fragment_2_holder\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"8dp\" android:layout_marginEnd=\"16dp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.0\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/textView2\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 4496, "s": 1853, "text": null }, { "code": null, "e": 4534, "s": 4496, "text": "Step 4: Implementing Shared ViewModel" }, { "code": null, "e": 4776, "s": 4534, "text": "In the SharedViewModel.kt file there are there is one MutableLiveData of CharSequence for setting the data for EditTexts. Two functions setData and getData for updating that mutable live data as soon as the data inside the EditTexts changes." }, { "code": null, "e": 4825, "s": 4776, "text": "To implement the same invoke the following code." }, { "code": null, "e": 4832, "s": 4825, "text": "Kotlin" }, { "code": "import androidx.lifecycle.MutableLiveDataimport androidx.lifecycle.ViewModel class SharedViewModel : ViewModel() { // Mutable LiveData which observed by LiveData // and updated to EditTexts when it is changed. private val mutableLiveData: MutableLiveData<CharSequence> = MutableLiveData() // function to set the changed // data from the EditTexts fun setData(input: CharSequence) { mutableLiveData.value = input } // function to get the changed data from the EditTexts fun getData(): MutableLiveData<CharSequence> = mutableLiveData}", "e": 5411, "s": 4832, "text": null }, { "code": null, "e": 5440, "s": 5411, "text": "Step 5: Creating 2 Fragments" }, { "code": null, "e": 5522, "s": 5440, "text": "Create two Fragments with their own layouts naming Fragment1.kt and Fragment2.kt." }, { "code": null, "e": 5691, "s": 5522, "text": "For each of the fragment’s layouts, it contains one EditText to get the data to send for fragment 2 and one button, when clicked it shares the data to another fragment." }, { "code": null, "e": 5788, "s": 5691, "text": "To implement the layout for Fragment 1, invoke the following code inside the fragment_1.xml file" }, { "code": null, "e": 5792, "s": 5788, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:clipToPadding=\"false\" android:padding=\"4dp\" tools:context=\".Fragment1\" tools:ignore=\"HardcodedText\"> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/edit_text_layout_1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/edit_text_from_fragment_1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:hint=\"Enter the data\" /> </com.google.android.material.textfield.TextInputLayout> <Button android:id=\"@+id/send_button_fragment_1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/edit_text_layout_1\" android:layout_alignParentEnd=\"true\" android:layout_marginTop=\"8dp\" android:layout_marginEnd=\"16dp\" android:text=\"Send Data to Fragment 2\" /> </RelativeLayout>", "e": 7063, "s": 5792, "text": null }, { "code": null, "e": 7161, "s": 7063, "text": "To implement the layout for Fragment 2, invoke the following code inside the fragment_2.xml file." }, { "code": null, "e": 7165, "s": 7161, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:clipToPadding=\"false\" android:padding=\"4dp\" tools:context=\".Fragment2\" tools:ignore=\"HardcodedText\"> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/edit_text_layout_2\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <com.google.android.material.textfield.TextInputEditText android:id=\"@+id/edit_text_from_fragment_2\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:hint=\"Enter the data\" /> </com.google.android.material.textfield.TextInputLayout> <Button android:id=\"@+id/send_button_fragment_2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/edit_text_layout_2\" android:layout_alignParentEnd=\"true\" android:layout_marginTop=\"8dp\" android:layout_marginEnd=\"16dp\" android:text=\"Send Data to Fragment 1\" /> </RelativeLayout>", "e": 8436, "s": 7165, "text": null }, { "code": null, "e": 8513, "s": 8436, "text": "Step 6: Creating instances of shared view model inside the Fragment.kt files" }, { "code": null, "e": 8626, "s": 8513, "text": "There is a need to create the instance of the ViewModel of the type ShareViewModel when the Activity is created." }, { "code": null, "e": 8712, "s": 8626, "text": "So one needs to override the onActivityCreated() method inside each of the Fragments." }, { "code": null, "e": 9087, "s": 8712, "text": "This is so because when we see the lifecycle of the fragments the views are created and updated after the onCreateView() is called and onAcrivityCreated() callback is called after the onCreateView() is executed. So the LiveData can keep track of UI elements for which elements they have updated. Have a look at the following chart for the activity lifecycle of the fragment." }, { "code": null, "e": 9175, "s": 9087, "text": "To implement the same in both fragments invoke the, following code inside Fragment1.kt." }, { "code": null, "e": 9182, "s": 9175, "text": "Kotlin" }, { "code": "import android.os.Bundleimport android.text.Editableimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.EditTextimport androidx.lifecycle.Observerimport androidx.lifecycle.ViewModelProviders class Fragment1 : Fragment() { private var sharedViewModelInstance: SharedViewModel? = null private var editTextFromFragment1: EditText? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view: View = inflater.inflate(R.layout.fragment_1, container, false) val sendDataButton: Button = view.findViewById(R.id.send_button_fragment_1) editTextFromFragment1 = view.findViewById(R.id.edit_text_from_fragment_1) // as soon as the button is clicked // send the data to ViewModel // and the Live data will take care of // updating the data inside another Fragment sendDataButton.setOnClickListener { sharedViewModelInstance?.setData(editTextFromFragment1!!.text) } return view } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) // create instances of the shared view model // when the activity is created sharedViewModelInstance = ViewModelProviders.of(activity!!).get(SharedViewModel::class.java) // observe the data inside the view model that // is mutable live of type CharSequence and // set the data for edit text sharedViewModelInstance!!.getData().observe(viewLifecycleOwner, Observer { editTextFromFragment1!!.text = it as Editable? }) }}", "e": 10998, "s": 9182, "text": null }, { "code": null, "e": 11067, "s": 10998, "text": "And same goes with the Fragment2.kt file, invoke the following code." }, { "code": null, "e": 11074, "s": 11067, "text": "Kotlin" }, { "code": "import android.os.Bundleimport android.text.Editableimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.EditTextimport androidx.lifecycle.Observerimport androidx.lifecycle.ViewModelProviders class Fragment2 : Fragment() { private var sharedViewModelInstance: SharedViewModel? = null private var editTextFromFragment2: EditText? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view: View = inflater.inflate(R.layout.fragment_2, container, false) val sendDataButton: Button = view.findViewById(R.id.send_button_fragment_2) editTextFromFragment2 = view.findViewById(R.id.edit_text_from_fragment_2) // as soon as the button is clicked // send the data to ViewModel // and the Live data will take care of // updating the data inside another Fragment sendDataButton.setOnClickListener { sharedViewModelInstance?.setData(editTextFromFragment2!!.text) } return view } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) // create instances of the shared view model // when the activity is created sharedViewModelInstance = ViewModelProviders.of(activity!!).get(SharedViewModel::class.java) // observe the data inside the view model that is mutable // live of type CharSequence and set the data for edit text sharedViewModelInstance!!.getData().observe(viewLifecycleOwner, Observer { editTextFromFragment2!!.text = it as Editable? }) }}", "e": 12877, "s": 11074, "text": null }, { "code": null, "e": 12942, "s": 12877, "text": "Step 7: Populate the fragment holders using MainActivity.kt file" }, { "code": null, "e": 13148, "s": 12942, "text": "Inside the MainActivity.kt file, one needs to populate the fragment holders from the activity_main.xml, with both fragments. To implement the same invoke the following code inside the MainActivity.kt file." }, { "code": null, "e": 13155, "s": 13148, "text": "Kotlin" }, { "code": "import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.fragment.app.FragmentTransaction class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val fragmentTransaction: FragmentTransaction = supportFragmentManager.beginTransaction() fragmentTransaction.apply { add(R.id.fragment_1_holder, Fragment1()) add(R.id.fragment_2_holder, Fragment2()) commit() } }}", "e": 13735, "s": 13155, "text": null }, { "code": null, "e": 13743, "s": 13735, "text": "Output:" }, { "code": null, "e": 13758, "s": 13743, "text": "Kotlin Android" }, { "code": null, "e": 13766, "s": 13758, "text": "Android" }, { "code": null, "e": 13773, "s": 13766, "text": "Kotlin" }, { "code": null, "e": 13781, "s": 13773, "text": "Android" } ]
D3.js - Timer API
Timer API module is used to perform the concurrent animations with synchronized timing delay. It uses requestAnimationFrame for animation. This chapter explains Timer API module in detail. This method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation. We can easily load the timer directly from d3js.org by using the following script. <script src = "https://d3js.org/d3-timer.v1.min.js"></script> <script> var timer = d3.timer(callback); </script> The Timer API supports the following important methods. All of these are explained in detail as follows. This method returns the current time. This method is used to schedule a new timer and invokes the timer until stopped. You can set a numeric delay in MS, but it is optional otherwise, it defaults to zero. If time is not specified, it is considered as d3.now(). Restart a timer with the specified callback and optional delay and time. This method stops the timer, preventing subsequent callbacks. It is used to stop the timer on its first callback. Callback is passed as the elapsed time. It is invoked on a particular time delay interval. If delay is not specified, it takes the timer time. Create a webpage “timer.html” and add the following script to it. <!DOCTYPE html> <html> <head> <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script> </head> <body> <h3> Timer API </h3> <script> var timer = d3.timer(function(duration) { console.log(duration); if (duration > 150) timer.stop(); }, 100); </script> </body> </html> We will see the following response on the screen. Print Add Notes Bookmark this page
[ { "code": null, "e": 2319, "s": 2130, "text": "Timer API module is used to perform the concurrent animations with synchronized timing delay. It uses requestAnimationFrame for animation. This chapter explains Timer API module in detail." }, { "code": null, "e": 2467, "s": 2319, "text": "This method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation." }, { "code": null, "e": 2550, "s": 2467, "text": "We can easily load the timer directly from d3js.org by using the following script." }, { "code": null, "e": 2666, "s": 2550, "text": "<script src = \"https://d3js.org/d3-timer.v1.min.js\"></script>\n<script>\n var timer = d3.timer(callback);\n</script>" }, { "code": null, "e": 2771, "s": 2666, "text": "The Timer API supports the following important methods. All of these are explained in detail as follows." }, { "code": null, "e": 2809, "s": 2771, "text": "This method returns the current time." }, { "code": null, "e": 3032, "s": 2809, "text": "This method is used to schedule a new timer and invokes the timer until stopped. You can set a numeric delay in MS, but it is optional otherwise, it defaults to zero. If time is not specified, it is considered as d3.now()." }, { "code": null, "e": 3105, "s": 3032, "text": "Restart a timer with the specified callback and optional delay and time." }, { "code": null, "e": 3167, "s": 3105, "text": "This method stops the timer, preventing subsequent callbacks." }, { "code": null, "e": 3259, "s": 3167, "text": "It is used to stop the timer on its first callback. Callback is passed as the elapsed time." }, { "code": null, "e": 3362, "s": 3259, "text": "It is invoked on a particular time delay interval. If delay is not specified, it takes the timer time." }, { "code": null, "e": 3428, "s": 3362, "text": "Create a webpage “timer.html” and add the following script to it." }, { "code": null, "e": 3797, "s": 3428, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"></script>\n </head>\n\n <body>\n <h3> Timer API </h3>\n <script>\n var timer = d3.timer(function(duration) {\n console.log(duration);\n if (duration > 150) timer.stop();\n }, 100);\n </script>\n </body>\n</html>" }, { "code": null, "e": 3847, "s": 3797, "text": "We will see the following response on the screen." }, { "code": null, "e": 3854, "s": 3847, "text": " Print" }, { "code": null, "e": 3865, "s": 3854, "text": " Add Notes" } ]
ML | Heart Disease Prediction Using Logistic Regression . - GeeksforGeeks
08 Nov, 2021 World Health Organization has estimated that four out of five cardiovascular diseases(CVD) deaths are due to heart attacks. This whole research intends to pinpoint the ratio of patients who possess a good chance of being affected by CVD and also to predict the overall risk using Logistic Regression. What is Logistic Regression? Logistic Regression is a statistical and machine-learning technique classifying records of a dataset based on the values of the input fields. It predicts a dependent variable based on one or more set of independent variables to predict outcomes. It can be used both for binary classification and multi-class classification. To know more about it, click here. Code: Loading the libraries . Python3 import pandas as pdimport pylab as plimport numpy as npimport scipy.optimize as optimport statsmodels.api as smfrom sklearn import preprocessing'exec(% matplotlib inline)'import matplotlib.pyplot as pltimport matplotlib.mlab as mlabimport seaborn as sn Data Preparation : The dataset is publicly available on the Kaggle website, and it is from an ongoing cardiovascular study on residents of the town of Framingham, Massachusetts. The classification goal is to predict whether the patient has 10-years risk of future coronary heart disease (CHD). The dataset provides the patients’ information. It includes over 4,000 records and 15 attributes. Loading the Dataset. Python3 # datasetdisease_df = pd.read_csv("../input / framingham.csv")disease_df.drop(['education'], inplace = True, axis = 1)disease_df.rename(columns ={'male':'Sex_male'}, inplace = True) # removing NaN / NULL valuesdisease_df.dropna(axis = 0, inplace = True)print(disease_df.head(), disease_df.shape)print(disease_df.TenYearCHD.value_counts()) Output : Sex_male age currentSmoker ... heartRate glucose TenYearCHD 0 1 39 0 ... 80.0 77.0 0 1 0 46 0 ... 95.0 76.0 0 2 1 48 1 ... 75.0 70.0 0 3 0 61 1 ... 65.0 103.0 1 4 0 46 1 ... 85.0 85.0 0 [5 rows x 15 columns] (3751, 15) 0 3179 1 572 Name: TenYearCHD, dtype: int64 Code: Ten Year’s CHD Record of all the patients available in the dataset : Python3 # counting no. of patients affected with CHDplt.figure(figsize = (7, 5))sn.countplot(x ='TenYearCHD', data = disease_df, palette ="BuGn_r" )plt.show() Output : Graph Display : Code: Counting number of patients affected by CHD where (0= Not Affected; 1= Affected) : Python3 laste = disease_df['TenYearCHD'].plot()plt.show(laste) Output: Graph Display : Code : Training and Test Sets: Splitting Data | Normalization of the Dataset Python3 X = np.asarray(disease_df[['age', 'Sex_male', 'cigsPerDay', 'totChol', 'sysBP', 'glucose']])y = np.asarray(disease_df['TenYearCHD']) # normalization of the datasetX = preprocessing.StandardScaler().fit(X).transform(X) # Train-and-Test -Splitfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( X, y, test_size = 0.3, random_state = 4)print ('Train set:', X_train.shape, y_train.shape)print ('Test set:', X_test.shape, y_test.shape) Output : Train Set : (2625, 6) (2625, ) Test Set : (1126, 6) (1126, ) Code: Modeling of the Dataset | Evaluation and Accuracy : Python3 from sklearn.linear_model import LogisticRegressionlogreg = LogisticRegression()logreg.fit(X_train, y_train)y_pred = logreg.predict(X_test) # Evaluation and accuracyfrom sklearn.metrics import jaccard_similarity_scoreprint('')print('Accuracy of the model in jaccard similarity score is = ', jaccard_similarity_score(y_test, y_pred)) Output : Accuracy of the model in jaccard similarity score is = 0.8490230905861457 Code: Using Confusion Matrix to find the Accuracy of the model : Python3 # Confusion matrixfrom sklearn.metrics import confusion_matrix, classification_report cm = confusion_matrix(y_test, y_pred)conf_matrix = pd.DataFrame(data = cm, columns = ['Predicted:0', 'Predicted:1'], index =['Actual:0', 'Actual:1'])plt.figure(figsize = (8, 5))sn.heatmap(conf_matrix, annot = True, fmt = 'd', cmap = "Greens")plt.show() print('The details for confusion matrix is =')print (classification_report(y_test, y_pred)) # This code is contributed by parna_28 . Output : The details for confusion matrix is = precision recall f1-score support 0 0.85 0.99 0.92 951 1 0.61 0.08 0.14 175 accuracy 0.85 1126 macro avg 0.73 0.54 0.53 1126 weighted avg 0.82 0.85 0.80 1126 Confusion Matrix : abhishek0719kadiyan sooda367 ruhelaa48 ML-Classification 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 | Underfitting and Overfitting Python | Decision tree implementation Decision Tree Introduction with example Support Vector Machine Algorithm Search Algorithms in AI Adding new column to existing DataFrame in Pandas Read JSON file using Python Python map() function Python Dictionary Taking input in Python
[ { "code": null, "e": 24284, "s": 24256, "text": "\n08 Nov, 2021" }, { "code": null, "e": 24585, "s": 24284, "text": "World Health Organization has estimated that four out of five cardiovascular diseases(CVD) deaths are due to heart attacks. This whole research intends to pinpoint the ratio of patients who possess a good chance of being affected by CVD and also to predict the overall risk using Logistic Regression." }, { "code": null, "e": 24974, "s": 24585, "text": "What is Logistic Regression? Logistic Regression is a statistical and machine-learning technique classifying records of a dataset based on the values of the input fields. It predicts a dependent variable based on one or more set of independent variables to predict outcomes. It can be used both for binary classification and multi-class classification. To know more about it, click here. " }, { "code": null, "e": 25004, "s": 24974, "text": "Code: Loading the libraries ." }, { "code": null, "e": 25012, "s": 25004, "text": "Python3" }, { "code": "import pandas as pdimport pylab as plimport numpy as npimport scipy.optimize as optimport statsmodels.api as smfrom sklearn import preprocessing'exec(% matplotlib inline)'import matplotlib.pyplot as pltimport matplotlib.mlab as mlabimport seaborn as sn", "e": 25265, "s": 25012, "text": null }, { "code": null, "e": 25680, "s": 25265, "text": "Data Preparation : The dataset is publicly available on the Kaggle website, and it is from an ongoing cardiovascular study on residents of the town of Framingham, Massachusetts. The classification goal is to predict whether the patient has 10-years risk of future coronary heart disease (CHD). The dataset provides the patients’ information. It includes over 4,000 records and 15 attributes. Loading the Dataset. " }, { "code": null, "e": 25688, "s": 25680, "text": "Python3" }, { "code": "# datasetdisease_df = pd.read_csv(\"../input / framingham.csv\")disease_df.drop(['education'], inplace = True, axis = 1)disease_df.rename(columns ={'male':'Sex_male'}, inplace = True) # removing NaN / NULL valuesdisease_df.dropna(axis = 0, inplace = True)print(disease_df.head(), disease_df.shape)print(disease_df.TenYearCHD.value_counts())", "e": 26027, "s": 25688, "text": null }, { "code": null, "e": 26037, "s": 26027, "text": "Output : " }, { "code": null, "e": 26537, "s": 26037, "text": " Sex_male age currentSmoker ... heartRate glucose TenYearCHD\n0 1 39 0 ... 80.0 77.0 0\n1 0 46 0 ... 95.0 76.0 0\n2 1 48 1 ... 75.0 70.0 0\n3 0 61 1 ... 65.0 103.0 1\n4 0 46 1 ... 85.0 85.0 0\n\n[5 rows x 15 columns] (3751, 15)\n0 3179\n1 572\nName: TenYearCHD, dtype: int64" }, { "code": null, "e": 26612, "s": 26537, "text": "Code: Ten Year’s CHD Record of all the patients available in the dataset :" }, { "code": null, "e": 26620, "s": 26612, "text": "Python3" }, { "code": "# counting no. of patients affected with CHDplt.figure(figsize = (7, 5))sn.countplot(x ='TenYearCHD', data = disease_df, palette =\"BuGn_r\" )plt.show()", "e": 26783, "s": 26620, "text": null }, { "code": null, "e": 26810, "s": 26783, "text": "Output : Graph Display : " }, { "code": null, "e": 26901, "s": 26810, "text": "Code: Counting number of patients affected by CHD where (0= Not Affected; 1= Affected) : " }, { "code": null, "e": 26909, "s": 26901, "text": "Python3" }, { "code": "laste = disease_df['TenYearCHD'].plot()plt.show(laste)", "e": 26964, "s": 26909, "text": null }, { "code": null, "e": 26990, "s": 26964, "text": "Output: Graph Display : " }, { "code": null, "e": 27068, "s": 26990, "text": "Code : Training and Test Sets: Splitting Data | Normalization of the Dataset " }, { "code": null, "e": 27076, "s": 27068, "text": "Python3" }, { "code": "X = np.asarray(disease_df[['age', 'Sex_male', 'cigsPerDay', 'totChol', 'sysBP', 'glucose']])y = np.asarray(disease_df['TenYearCHD']) # normalization of the datasetX = preprocessing.StandardScaler().fit(X).transform(X) # Train-and-Test -Splitfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( X, y, test_size = 0.3, random_state = 4)print ('Train set:', X_train.shape, y_train.shape)print ('Test set:', X_test.shape, y_test.shape)", "e": 27595, "s": 27076, "text": null }, { "code": null, "e": 27605, "s": 27595, "text": "Output : " }, { "code": null, "e": 27668, "s": 27605, "text": "Train Set :\n(2625, 6) (2625, )\n\nTest Set : \n(1126, 6) (1126, )" }, { "code": null, "e": 27727, "s": 27668, "text": "Code: Modeling of the Dataset | Evaluation and Accuracy : " }, { "code": null, "e": 27735, "s": 27727, "text": "Python3" }, { "code": "from sklearn.linear_model import LogisticRegressionlogreg = LogisticRegression()logreg.fit(X_train, y_train)y_pred = logreg.predict(X_test) # Evaluation and accuracyfrom sklearn.metrics import jaccard_similarity_scoreprint('')print('Accuracy of the model in jaccard similarity score is = ', jaccard_similarity_score(y_test, y_pred))", "e": 28073, "s": 27735, "text": null }, { "code": null, "e": 28083, "s": 28073, "text": "Output : " }, { "code": null, "e": 28157, "s": 28083, "text": "Accuracy of the model in jaccard similarity score is = 0.8490230905861457" }, { "code": null, "e": 28223, "s": 28157, "text": "Code: Using Confusion Matrix to find the Accuracy of the model : " }, { "code": null, "e": 28231, "s": 28223, "text": "Python3" }, { "code": "# Confusion matrixfrom sklearn.metrics import confusion_matrix, classification_report cm = confusion_matrix(y_test, y_pred)conf_matrix = pd.DataFrame(data = cm, columns = ['Predicted:0', 'Predicted:1'], index =['Actual:0', 'Actual:1'])plt.figure(figsize = (8, 5))sn.heatmap(conf_matrix, annot = True, fmt = 'd', cmap = \"Greens\")plt.show() print('The details for confusion matrix is =')print (classification_report(y_test, y_pred)) # This code is contributed by parna_28 .", "e": 28755, "s": 28231, "text": null }, { "code": null, "e": 28765, "s": 28755, "text": "Output : " }, { "code": null, "e": 29129, "s": 28765, "text": "The details for confusion matrix is =\n precision recall f1-score support\n\n 0 0.85 0.99 0.92 951\n 1 0.61 0.08 0.14 175\n\n accuracy 0.85 1126\n macro avg 0.73 0.54 0.53 1126\nweighted avg 0.82 0.85 0.80 1126" }, { "code": null, "e": 29150, "s": 29129, "text": "Confusion Matrix : " }, { "code": null, "e": 29172, "s": 29152, "text": "abhishek0719kadiyan" }, { "code": null, "e": 29181, "s": 29172, "text": "sooda367" }, { "code": null, "e": 29191, "s": 29181, "text": "ruhelaa48" }, { "code": null, "e": 29209, "s": 29191, "text": "ML-Classification" }, { "code": null, "e": 29226, "s": 29209, "text": "Machine Learning" }, { "code": null, "e": 29233, "s": 29226, "text": "Python" }, { "code": null, "e": 29250, "s": 29233, "text": "Machine Learning" }, { "code": null, "e": 29348, "s": 29250, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29357, "s": 29348, "text": "Comments" }, { "code": null, "e": 29370, "s": 29357, "text": "Old Comments" }, { "code": null, "e": 29404, "s": 29370, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 29442, "s": 29404, "text": "Python | Decision tree implementation" }, { "code": null, "e": 29482, "s": 29442, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 29515, "s": 29482, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 29539, "s": 29515, "text": "Search Algorithms in AI" }, { "code": null, "e": 29589, "s": 29539, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29617, "s": 29589, "text": "Read JSON file using Python" }, { "code": null, "e": 29639, "s": 29617, "text": "Python map() function" }, { "code": null, "e": 29657, "s": 29639, "text": "Python Dictionary" } ]
Min Cost Path
A matrix of the different cost is given. Also, the destination cell is provided. We have to find minimum cost path to reach the destination cell from the starting cell (0, 0). Each cell of the matrix represents the cost to traverse through that cell. From a cell, we cannot move anywhere, we can move either to the right or to the bottom or to the lower right diagonal cell, to reach the destination. Input: The cost matrix. And the destination point. In this case the destination point is (2, 2). 1 2 3 4 8 2 1 5 3 Output: The minimum cost to reach to the destination from (0, 0). The minimum cost is 8. minCostPath(destX, destY, cost) Input − The (x, y) place of the destination, and the cost matrix. Output − Minimum cost to reach a destination. Begin define matrix totalCost, whose order is same as cost matrix totalCost[0, 0] = cost[0, 0] for i := 1 to destX, do totalCost[i, 0] := totalCost[i-1, 0] + cost[i, 0] done for j := 1 to destY, do totalCost[0, j] := totalCost[0, j-1] + cost[0, j] done for all places (i, j) from (1, 1) to (destX, destY), do totalCost[i, j] := minimum of totalCost[i-1, j-1], totalCost[i-1, j] and (totalCost[i, j-1] + cost[i,j]) done return totalCost[destX, destY] End #include<iostream> #define ROW 3 #define COL 3 using namespace std; int cost[ROW][COL] = { {1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; int min(int a, int b, int c) { return (a<b)?((a<c)?a:c):((b<c)?b:c); } int minCostPath(int destX, int destY) { int totalCost[ROW][COL]; totalCost[0][0] = cost[0][0]; for (int i = 1; i <= destX; i++) totalCost[i][0] = totalCost[i-1][0] + cost[i][0]; //set first col of totalCost array for (int j = 1; j <= destY; j++) //set first row of totalCost array totalCost[0][j] = totalCost[0][j-1] + cost[0][j]; for (int i = 1; i <= destX; i++) //for second row and column to all for (int j = 1; j <= destY; j++) totalCost[i][j] = min(totalCost[i-1][j-1], totalCost[i- 1][j], totalCost[i][j-1]) + cost[i][j]; return totalCost[destX][destY]; } int main() { cout << "Minimum Cost: "<< minCostPath(2, 2); //destination (2, 2) return 0; } Minimum Cost: 8
[ { "code": null, "e": 1238, "s": 1062, "text": "A matrix of the different cost is given. Also, the destination cell is provided. We have to find minimum cost path to reach the destination cell from the starting cell (0, 0)." }, { "code": null, "e": 1314, "s": 1238, "text": "Each cell of the matrix represents the cost to traverse through that cell. " }, { "code": null, "e": 1464, "s": 1314, "text": "From a cell, we cannot move anywhere, we can move either to the right or to the bottom or to the lower right diagonal cell, to reach the destination." }, { "code": null, "e": 1670, "s": 1464, "text": "Input:\nThe cost matrix. And the destination point. In this case the destination point is (2, 2).\n1 2 3\n4 8 2\n1 5 3\n\nOutput:\nThe minimum cost to reach to the destination from (0, 0). The minimum cost is 8.\n" }, { "code": null, "e": 1702, "s": 1670, "text": "minCostPath(destX, destY, cost)" }, { "code": null, "e": 1768, "s": 1702, "text": "Input − The (x, y) place of the destination, and the cost matrix." }, { "code": null, "e": 1814, "s": 1768, "text": "Output − Minimum cost to reach a destination." }, { "code": null, "e": 2317, "s": 1814, "text": "Begin\n define matrix totalCost, whose order is same as cost matrix\n totalCost[0, 0] = cost[0, 0]\n\n for i := 1 to destX, do\n totalCost[i, 0] := totalCost[i-1, 0] + cost[i, 0]\n done\n\n for j := 1 to destY, do\n totalCost[0, j] := totalCost[0, j-1] + cost[0, j]\n done\n\n for all places (i, j) from (1, 1) to (destX, destY), do\n totalCost[i, j] := minimum of totalCost[i-1, j-1], totalCost[i-1, j] and (totalCost[i, j-1] + cost[i,j])\n done\n\n return totalCost[destX, destY]\nEnd" }, { "code": null, "e": 3267, "s": 2317, "text": "#include<iostream>\n#define ROW 3\n#define COL 3\nusing namespace std;\n\nint cost[ROW][COL] = {\n {1, 2, 3},\n {4, 8, 2},\n {1, 5, 3}\n};\n\nint min(int a, int b, int c) {\n return (a<b)?((a<c)?a:c):((b<c)?b:c);\n}\n\nint minCostPath(int destX, int destY) {\n int totalCost[ROW][COL];\n\n totalCost[0][0] = cost[0][0];\n\n for (int i = 1; i <= destX; i++)\n totalCost[i][0] = totalCost[i-1][0] + cost[i][0]; //set first col of totalCost array\n\n for (int j = 1; j <= destY; j++) //set first row of totalCost array\n totalCost[0][j] = totalCost[0][j-1] + cost[0][j];\n\n for (int i = 1; i <= destX; i++) //for second row and column to all\n for (int j = 1; j <= destY; j++)\n totalCost[i][j] = min(totalCost[i-1][j-1], totalCost[i- 1][j], totalCost[i][j-1]) + cost[i][j];\n return totalCost[destX][destY];\n}\n\nint main() {\n cout << \"Minimum Cost: \"<< minCostPath(2, 2); //destination (2, 2)\n return 0;\n}" }, { "code": null, "e": 3283, "s": 3267, "text": "Minimum Cost: 8" } ]
Calculate the power on a BigInteger in Java
Use the BigInteger pow() method in Java to calculate the power on a BigInteger. First, let us create some objects. BigInteger one, two; one = new BigInteger("5"); Perform the power operation and assign it to the second object − // power operation two = one.pow(3); The following is an example − Live Demo import java.math.*; public class BigIntegerDemo { public static void main(String[] args) { BigInteger one, two; one = new BigInteger("5"); System.out.println("Actual Value: " +one); // power operation two = one.pow(3); System.out.println("Result: " +two); } } Actual Value: 5 Negated Value: 125
[ { "code": null, "e": 1142, "s": 1062, "text": "Use the BigInteger pow() method in Java to calculate the power on a BigInteger." }, { "code": null, "e": 1177, "s": 1142, "text": "First, let us create some objects." }, { "code": null, "e": 1225, "s": 1177, "text": "BigInteger one, two;\none = new BigInteger(\"5\");" }, { "code": null, "e": 1290, "s": 1225, "text": "Perform the power operation and assign it to the second object −" }, { "code": null, "e": 1327, "s": 1290, "text": "// power operation\ntwo = one.pow(3);" }, { "code": null, "e": 1357, "s": 1327, "text": "The following is an example −" }, { "code": null, "e": 1368, "s": 1357, "text": " Live Demo" }, { "code": null, "e": 1670, "s": 1368, "text": "import java.math.*;\npublic class BigIntegerDemo {\n public static void main(String[] args) {\n BigInteger one, two;\n one = new BigInteger(\"5\");\n System.out.println(\"Actual Value: \" +one);\n // power operation\n two = one.pow(3);\n System.out.println(\"Result: \" +two);\n }\n}" }, { "code": null, "e": 1705, "s": 1670, "text": "Actual Value: 5\nNegated Value: 125" } ]
Return from void functions in C++
The void functions are called void because they do not return anything. “A void function cannot return anything” this statement is not always true. From a void function, we cannot return any values, but we can return something other than values. Some of them are like below. A void function cannot return any values. But we can use the return statement. It indicates that the function is terminated. It increases the readability of code. Live Demo #include <iostream> using namespace std; void my_func() { cout << "From my_function" << endl; return; } int main() { my_func(); return 0; } From my_function In this approach, one void function can call another void function while it is terminating. The code will look like this. Live Demo #include <iostream> using namespace std; void another_func() { cout << "From another_function" << endl; return; } void my_func() { cout << "From my_function" << endl; return another_func(); } int main() { my_func(); return 0; } From my_function From another_function
[ { "code": null, "e": 1337, "s": 1062, "text": "The void functions are called void because they do not return anything. “A void function cannot return anything” this statement is not always true. From a void function, we cannot return any values, but we can return something other than values. Some of them are like below." }, { "code": null, "e": 1500, "s": 1337, "text": "A void function cannot return any values. But we can use the return statement. It indicates that the function is terminated. It increases the readability of code." }, { "code": null, "e": 1511, "s": 1500, "text": " Live Demo" }, { "code": null, "e": 1665, "s": 1511, "text": "#include <iostream>\nusing namespace std;\n\nvoid my_func() {\n cout << \"From my_function\" << endl;\n return;\n}\n\nint main() {\n my_func();\n return 0;\n}" }, { "code": null, "e": 1682, "s": 1665, "text": "From my_function" }, { "code": null, "e": 1804, "s": 1682, "text": "In this approach, one void function can call another void function while it is terminating. The code will look like this." }, { "code": null, "e": 1815, "s": 1804, "text": " Live Demo" }, { "code": null, "e": 2064, "s": 1815, "text": "#include <iostream>\nusing namespace std;\n\nvoid another_func() {\n cout << \"From another_function\" << endl;\n return;\n}\n\nvoid my_func() {\n cout << \"From my_function\" << endl;\n return another_func();\n}\n\nint main() {\n my_func();\n return 0;\n}" }, { "code": null, "e": 2103, "s": 2064, "text": "From my_function\nFrom another_function" } ]
React ES6 Ternary Operator
The ternary operator is a simplified conditional operator like if / else. Syntax: condition ? <expression if true> : <expression if false> Here is an example using if / else: if (authenticated) { renderApp(); } else { renderLogin(); } Try it Yourself » Here is the same example using a ternary operator: authenticated ? renderApp() : renderLogin(); Try it Yourself » Complete this ternary operator statement. blue renderBlue() renderRed(); Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 74, "s": 0, "text": "The ternary operator is a simplified conditional operator like if / else." }, { "code": null, "e": 139, "s": 74, "text": "Syntax: condition ? <expression if true> : <expression if false>" }, { "code": null, "e": 175, "s": 139, "text": "Here is an example using if / else:" }, { "code": null, "e": 240, "s": 175, "text": "if (authenticated) {\n renderApp();\n} else {\n renderLogin();\n}\n" }, { "code": null, "e": 260, "s": 240, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 311, "s": 260, "text": "Here is the same example using a ternary operator:" }, { "code": null, "e": 357, "s": 311, "text": "authenticated ? renderApp() : renderLogin();\n" }, { "code": null, "e": 377, "s": 357, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 419, "s": 377, "text": "Complete this ternary operator statement." }, { "code": null, "e": 453, "s": 419, "text": "blue renderBlue() renderRed();\n" }, { "code": null, "e": 472, "s": 453, "text": "Start the Exercise" }, { "code": null, "e": 505, "s": 472, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 547, "s": 505, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 654, "s": 547, "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": 673, "s": 654, "text": "help@w3schools.com" } ]
NLP Sentiment Analysis Handbook | Towards Data Science
Natural Language Processing (NLP) is the area of machine learning that focuses on the generation and understanding of language. Its main objective is to enable machines to understand, communicate and interact with humans in a natural way. NLP has many tasks such as Text Generation, Text Classification, Machine Translation, Speech Recognition, Sentiment Analysis, etc. For a beginner to NLP, looking at these tasks and all the techniques involved in handling such tasks can be quite daunting. And in fact, it is very difficult for a newbie to know exactly where and how to start. Out of all the NLP tasks, I personally think that Sentiment Analysis (SA) is probably the easiest, which makes it the most suitable starting point for anyone who wants to start go into NLP. In this article, I compile various techniques of how to perform SA, ranging from simple ones like TextBlob and NLTK to more advanced ones like Sklearn and Long Short Term Memory (LSTM) networks. After reading this, you can expect to understand the followings: Toolkits used in SA: TextBlob and NLTKAlgorithms used in SA: Naive Bayes, SVM, Logistic Regression and LSTMJargons like stop-word removal, stemming, bag of words, corpus, tokenisation etc.Create a word cloud Toolkits used in SA: TextBlob and NLTK Algorithms used in SA: Naive Bayes, SVM, Logistic Regression and LSTM Jargons like stop-word removal, stemming, bag of words, corpus, tokenisation etc. Create a word cloud Data cleaning and pre-processingTextBlobAlgorithms: Logistic Regression, Naive Bayes, SVM and LSTM Data cleaning and pre-processing TextBlob Algorithms: Logistic Regression, Naive Bayes, SVM and LSTM Let’s get started! In this article, I will the sentiment data set that consists of 3000 sentences coming from reviews on imdb.com, amazon.com, and yelp.com. Each sentence is labeled according to whether it comes from a positive review (labelled as 1) or negative review (labelled as 0). Data can be downloaded from the website. Alternatively, it can be downloaded from here (highly recommended). The folder sentiment_labelled_sentences(containing the data file full_set.txt) should be in the same directory as your notebook. %matplotlib inlineimport stringimport numpy as npimport matplotlibimport matplotlib.pyplot as pltmatplotlib.rc('xtick', labelsize=14) matplotlib.rc('ytick', labelsize=14) Now, we load in the data and look at the first 10 comments with open("sentiment_labelled_sentences/full_set.txt") as f: content = f.readlines()content[0:10] ## Remove leading and trailing white spacecontent = [x.strip() for x in content]## Separate the sentences from the labelssentences = [x.split("\t")[0] for x in content]labels = [x.split("\t")[1] for x in content]sentences[0:10]labels[0:10] One can stop here for this section. But for me, I prefer transforming y into (-1,1) form, where -1 represents negative and 1 represents positive. ## Transform the labels from '0 v.s. 1' to '-1 v.s. 1'y = np.array(labels, dtype='int8')y = 2*y - 1 NOTICE THAT SO FAR WE HAVE NOT DONE ANY TO THE WORDS YET!!! The next section focuses on words in sentences. To input data into the any model, the data input must be in vector form. We will do the following transformations: Remove punctuation and numbers Transform all words to lower-case Remove stop words (e.g. the, a, that, this, it, ...) Tokenizer the texts Convert the sentences into vectors, using a bag-of-words representation I will explain some jargons here. Stop words: common words that are not interesting for the task at hand. These usually include articles such as ‘a’ and ‘the’, pronouns such as ‘i’ and ‘they’, and prepositions such as ‘to’ and ‘from’, ... Stop words: common words that are not interesting for the task at hand. These usually include articles such as ‘a’ and ‘the’, pronouns such as ‘i’ and ‘they’, and prepositions such as ‘to’ and ‘from’, ... ## Demonstrate ##def removeStopWords(stopWords, txt): newtxt = ' '.join([word for word in txt.split() if word not in stopWords]) return newtxtstoppers = ['a', 'is', 'of','the','this','uhm','uh']removeStopWords(stoppers, "this is a test of the stop word removal code") Or we can use NLTK if we do want a complete set of common stop words used from nltk.corpus import stopwordsstops = stopwords.words("English")removeStopWords(stops, "this is a test of the stop word removal code.") Same result 2. Corpus: simply a collection of text. Order of words matter. ‘Not great’ is different from ‘great’ 3. Document-Term Matrix or Bag of Words (BOW) is simply a vectorial representation of text sentences (or documents) A common way to represent a set of features like this is called a One-Hot vector. For example, lets say our vocabular from our set of texts is: today, here, I, a, fine, sun, moon, bird, saw The sentence we want to build a BOW for is: I saw a bird today Using a 1-0 for each word in the vocabulary, our BOW encoded as a one-hot vector would be: 1 0 1 1 0 0 1 1 In order to create a bag of words, we need to break down a long sentence or a document into smaller pieces. This process is called Tokenization. The most common tokenization technique is to break down text into words. We can do this using CountVectorizer in Scikit-Learn, where every row will represent a different document and every column will represent a different word. Now let’s put everything together for our dataset def full_remove(x, removal_list): for w in removal_list: x = x.replace(w, ' ') return x## Remove digits ##digits = [str(x) for x in range(10)]remove_digits = [full_remove(x, digits) for x in sentences]## Remove punctuation ##remove_punc = [full_remove(x, list(string.punctuation)) for x in remove_digits]## Make everything lower-case and remove any white space ##sents_lower = [x.lower() for x in remove_punc]sents_lower = [x.strip() for x in sents_lower]## Remove stop words ##from nltk.corpus import stopwordsstops = stopwords.words("English")def removeStopWords(stopWords, txt): newtxt = ' '.join([word for word in txt.split() if word not in stopWords]) return newtxtsents_processed = [removeStopWords(stops,x) for x in sents_lower] Let’s look at how our sentences look like now Uhm, wait a minute! Removing many stop words makes many sentences lose their meanings. For example, ‘way plug us unless go converter’ does not make any sense to me. This is because we remove all the common English stop words by using NLTK. To overcome this meaning problem, let’s create our own set of stop words instead. stop_set = ['the', 'a', 'an', 'i', 'he', 'she', 'they', 'to', 'of', 'it', 'from']sents_processed = [removeStopWords(stop_set,x) for x in sents_lower] It is ok to stop here and move to Tokenization. However, one can continue with stemming. The goal of stemming is too strip off prefixes and suffixes in the word and convert the word into its base form, e.g. studying->study, beautiful->beauty, cared->care, ...In NLTK, there are 2 popular stemming techniques called porter and lanscaster. [Reference: DataCamp] import nltkdef stem_with_porter(words): porter = nltk.PorterStemmer() new_words = [porter.stem(w) for w in words] return new_words def stem_with_lancaster(words): porter = nltk.LancasterStemmer() new_words = [porter.stem(w) for w in words] return new_words ## Demonstrate ## str = "Please don't unbuckle your seat-belt while I am driving, he said"print("porter:", stem_with_porter(str.split()))print("lancaster:", stem_with_lancaster(str.split())) Let’s try on our sents_processed to see whether it makes sense. porter = [stem_with_porter(x.split()) for x in sents_processed]porter = [" ".join(i) for i in porter]porter[0:10] Some weird changes occur, e.g. very->veri, quality->qualiti, value->valu, ... 4. Term Document Inverse Document Frequency (TD/IDF). This is a measure of the relative importance of a word within a document, in the context of multiple documents. In our case here, multiple reviews. We start with the TD part — this is simply a normalized frequency of the word in the document: (word count in document) / (total words in document) The IDF is a weighting of the uniquess of the word across all of the documents. Here is the complete formula of TD/IDF: td_idf(t,d) = wc(t,d)/wc(d) / dc(t)/dc() where: — wc(t,d) = # of occurrences of term t in doc d — wc(d) = # of words in doc d — dc(t) = # of docs that contain at least 1 occurrence of term t — dc() = # of docs in collection Now, let’s create a bag of words and normalise the texts from sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction.text import TfidfTransformervectorizer = CountVectorizer(analyzer = "word", preprocessor = None, stop_words = 'english', max_features = 6000, ngram_range=(1,5))data_features = vectorizer.fit_transform(sents_processed)tfidf_transformer = TfidfTransformer()data_features_tfidf = tfidf_transformer.fit_transform(data_features)data_mat = data_features_tfidf.toarray() Now data_mat is our Document-Term matrix. Input is ready to put into model. Let’s create Training and Test sets. Here, I split the data into a training set of 2500 sentences and a test set of 500 sentences (of which 250 are positive and 250 negative). np.random.seed(0)test_index = np.append(np.random.choice((np.where(y==-1))[0], 250, replace=False), np.random.choice((np.where(y==1))[0], 250, replace=False))train_index = list(set(range(len(labels))) - set(test_index))train_data = data_mat[train_index,]train_labels = y[train_index]test_data = data_mat[test_index,]test_labels = y[test_index] TextBlob: Linguistic researchers have labeled the sentiment of words based on their domain expertise. Sentiment of words can vary based on where it is in a sentence. The TextBlob module allows us to take advantage of these labels. TextBlod finds all the words and phrases that it can assign polarity and subjectivity to, and average all of them togetherSentiment Labels: Each word in a corpus is labeled in terms of polarity and subjectivity (there are more labels as well, but we’re going to ignore them for now). A corpus’ sentiment is the average of these. TextBlob: Linguistic researchers have labeled the sentiment of words based on their domain expertise. Sentiment of words can vary based on where it is in a sentence. The TextBlob module allows us to take advantage of these labels. TextBlod finds all the words and phrases that it can assign polarity and subjectivity to, and average all of them together Sentiment Labels: Each word in a corpus is labeled in terms of polarity and subjectivity (there are more labels as well, but we’re going to ignore them for now). A corpus’ sentiment is the average of these. Polarity: How positive or negative a word is. -1 is very negative. +1 is very positive. Subjectivity: How subjective, or opinionated a word is. 0 is fact. +1 is very much an opinion. from textblob import TextBlob#Create polarity function and subjectivity functionpol = lambda x: TextBlob(x).sentiment.polaritysub = lambda x: TextBlob(x).sentiment.subjectivitypol_list = [pol(x) for x in sents_processed]sub_list = [sub(x) for x in sents_processed] This is a rule-based method that determines the sentiment (polarity and subjectivity) of a review. The next section will look at various algorithms. from sklearn.linear_model import SGDClassifier## Fit logistic classifier on training dataclf = SGDClassifier(loss="log", penalty="none")clf.fit(train_data, train_labels)## Pull out the parameters (w,b) of the logistic regression modelw = clf.coef_[0,:]b = clf.intercept_## Get predictions on training and test datapreds_train = clf.predict(train_data)preds_test = clf.predict(test_data)## Compute errorserrs_train = np.sum((preds_train > 0.0) != (train_labels > 0.0))errs_test = np.sum((preds_test > 0.0) != (test_labels > 0.0))print("Training error: ", float(errs_train)/len(train_labels))print("Test error: ", float(errs_test)/len(test_labels))Training error: 0.0116Test error: 0.184 Words with large influence Which words are most important in deciding whether a sentence is positive? As a first approximation to this, we simply take the words whose coefficients in w have the largest positive values. Likewise, we look at the words whose coefficients in w have the most negative values, and we think of these as influential in negative predictions. ## Convert vocabulary into a list:vocab = np.array([z[0] for z in sorted(vectorizer.vocabulary_.items(), key=lambda x:x[1])])## Get indices of sorting winds = np.argsort(w)## Words with large negative valuesneg_inds = inds[0:50]print("Highly negative words: ")print([str(x) for x in list(vocab[neg_inds])])## Words with large positive valuespos_inds = inds[-49:-1]print("Highly positive words: ")print([str(x) for x in list(vocab[pos_inds])]) Create a Word Cloud from wordcloud import WordCloudwc = WordCloud(stopwords=stop_set, background_color="white", colormap="Dark2", max_font_size=150, random_state=42)#plt.rcParams['figure.figsize'] = [16, 6]wc.generate(" ".join(list(vocab[neg_inds])))plt.imshow(wc, interpolation="bilinear")plt.axis("off") plt.show() from sklearn.naive_bayes import MultinomialNBnb_clf = MultinomialNB().fit(train_data, train_labels)nb_preds_test = nb_clf.predict(test_data)nb_errs_test = np.sum((nb_preds_test > 0.0) != (test_labels > 0.0))print("Test error: ", float(nb_errs_test)/len(test_labels))Test error: 0.174 Let’s do some prediction cases. [1] means positive and [-1] means negative print(nb_clf.predict(vectorizer.transform(["It's a sad movie but very good"])))[1]print(nb_clf.predict(vectorizer.transform(["Waste of my time"])))[-1]print(nb_clf.predict(vectorizer.transform(["It is not what like"])))[-1]print(nb_clf.predict(vectorizer.transform(["It is not what I m looking for"])))[1] The last test case has problem. It should be a negative comment but the model predicts positive. from sklearn.linear_model import SGDClassifiersvm_clf = SGDClassifier(loss="hinge", penalty='l2')svm_clf.fit(train_data, train_labels)svm_preds_test = svm_clf.predict(test_data)svm_errs_test = np.sum((svm_preds_test > 0.0) != (test_labels > 0.0))print("Test error: ", float(svm_errs_test)/len(test_labels))Test error: 0.2 Again, let’s do some prediction print(svm_clf.predict(vectorizer.transform(["This is not what I like"])))[-1]print(svm_clf.predict(vectorizer.transform(["It is not what I am looking for"])))[-1]print(svm_clf.predict(vectorizer.transform(["I would not recommend this movie"])))[1] SVM can predict the comment ‘It is not what I am looking for’ correctly. However, it could not predict the comment ‘I do not recommend this movie’. A detailed discussion about LSTM networks can be found here. from keras.models import Sequentialfrom keras.layers import Densefrom keras.layers import LSTMfrom keras.layers import SpatialDropout1Dfrom keras.layers.embeddings import Embeddingfrom keras.preprocessing import sequencefrom keras.preprocessing.text import Tokenizerfrom keras.callbacks import EarlyStoppingmax_review_length = 200tokenizer = Tokenizer(num_words=10000, #max no. of unique words to keep filters='!"#$%&()*+,-./:;<=>?@[\]^_`{|}~', lower=True #convert to lower case )tokenizer.fit_on_texts(sents_processed) Truncate and pad the input sequences so that they are all in the same length X = tokenizer.texts_to_sequences(sents_processed)X = sequence.pad_sequences(X, maxlen= max_review_length)print('Shape of data tensor:', X.shape)Shape of data tensor: (3000, 200) Recall that y is vector of 1 and -1. Now I change it to a matrix with 2 columns that represent -1 and 1. import pandas as pdY=pd.get_dummies(y).valuesY np.random.seed(0)test_inds = np.append(np.random.choice((np.where(y==-1))[0], 250, replace=False), np.random.choice((np.where(y==1))[0], 250, replace=False))train_inds = list(set(range(len(labels))) - set(test_inds))train_data = X[train_inds,]train_labels = Y[train_inds]test_data = X[test_inds,]test_labels = Y[test_inds] Create networks EMBEDDING_DIM = 200model = Sequential()model.add(Embedding(10000, EMBEDDING_DIM, input_length=X.shape[1]))model.add(SpatialDropout1D(0.2))model.add(LSTM(250, dropout=0.2,return_sequences=True))model.add(LSTM(100, dropout=0.2, recurrent_dropout=0.2))model.add(Dense(2, activation='softmax'))model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])print(model.summary()) epochs = 2batch_size = 40model.fit(train_data, train_labels, epochs=epochs, batch_size=batch_size, validation_split=0.1) loss, acc = model.evaluate(test_data, test_labels, verbose=2, batch_size=batch_size)print(f"loss: {loss}")print(f"Validation accuracy: {acc}") LSTM performs the best out of all the models trained so far, i.e. Logistic, Naive Bayes and SVM. Now let’s see how it predict a test case outcome_labels = ['Negative', 'Positive']new = ["I would not recommend this movie"] seq = tokenizer.texts_to_sequences(new)padded = sequence.pad_sequences(seq, maxlen=max_review_length)pred = model.predict(padded)print("Probability distribution: ", pred)print("Is this a Positive or Negative review? ")print(outcome_labels[np.argmax(pred)]) new = ["It is not what i am looking for"] new = ["This isn't what i am looking for"] For this case, the difference between probability for negative and positive is not much. And the LSTM model classifies this as positive. new = ["I wouldn't recommend this movie"] The same happens for this comment. Hence, this means that our model could not distinguish between n't and not. One possible solution to this would be, in the pre-processing step, instead of removing all punctuations, change all the n't short form into not. This can simply be done with the re module in Python. You can check it out yourself to see how our models prediction improve. That is it! Hope you guys enjoyed and picked up something from this article. If you have any questions, feel free to put them down in the comment section below. Thank you for your read. Have a great day and take care everyone!!
[ { "code": null, "e": 411, "s": 172, "text": "Natural Language Processing (NLP) is the area of machine learning that focuses on the generation and understanding of language. Its main objective is to enable machines to understand, communicate and interact with humans in a natural way." }, { "code": null, "e": 753, "s": 411, "text": "NLP has many tasks such as Text Generation, Text Classification, Machine Translation, Speech Recognition, Sentiment Analysis, etc. For a beginner to NLP, looking at these tasks and all the techniques involved in handling such tasks can be quite daunting. And in fact, it is very difficult for a newbie to know exactly where and how to start." }, { "code": null, "e": 943, "s": 753, "text": "Out of all the NLP tasks, I personally think that Sentiment Analysis (SA) is probably the easiest, which makes it the most suitable starting point for anyone who wants to start go into NLP." }, { "code": null, "e": 1138, "s": 943, "text": "In this article, I compile various techniques of how to perform SA, ranging from simple ones like TextBlob and NLTK to more advanced ones like Sklearn and Long Short Term Memory (LSTM) networks." }, { "code": null, "e": 1203, "s": 1138, "text": "After reading this, you can expect to understand the followings:" }, { "code": null, "e": 1411, "s": 1203, "text": "Toolkits used in SA: TextBlob and NLTKAlgorithms used in SA: Naive Bayes, SVM, Logistic Regression and LSTMJargons like stop-word removal, stemming, bag of words, corpus, tokenisation etc.Create a word cloud" }, { "code": null, "e": 1450, "s": 1411, "text": "Toolkits used in SA: TextBlob and NLTK" }, { "code": null, "e": 1520, "s": 1450, "text": "Algorithms used in SA: Naive Bayes, SVM, Logistic Regression and LSTM" }, { "code": null, "e": 1602, "s": 1520, "text": "Jargons like stop-word removal, stemming, bag of words, corpus, tokenisation etc." }, { "code": null, "e": 1622, "s": 1602, "text": "Create a word cloud" }, { "code": null, "e": 1721, "s": 1622, "text": "Data cleaning and pre-processingTextBlobAlgorithms: Logistic Regression, Naive Bayes, SVM and LSTM" }, { "code": null, "e": 1754, "s": 1721, "text": "Data cleaning and pre-processing" }, { "code": null, "e": 1763, "s": 1754, "text": "TextBlob" }, { "code": null, "e": 1822, "s": 1763, "text": "Algorithms: Logistic Regression, Naive Bayes, SVM and LSTM" }, { "code": null, "e": 1841, "s": 1822, "text": "Let’s get started!" }, { "code": null, "e": 2109, "s": 1841, "text": "In this article, I will the sentiment data set that consists of 3000 sentences coming from reviews on imdb.com, amazon.com, and yelp.com. Each sentence is labeled according to whether it comes from a positive review (labelled as 1) or negative review (labelled as 0)." }, { "code": null, "e": 2347, "s": 2109, "text": "Data can be downloaded from the website. Alternatively, it can be downloaded from here (highly recommended). The folder sentiment_labelled_sentences(containing the data file full_set.txt) should be in the same directory as your notebook." }, { "code": null, "e": 2518, "s": 2347, "text": "%matplotlib inlineimport stringimport numpy as npimport matplotlibimport matplotlib.pyplot as pltmatplotlib.rc('xtick', labelsize=14) matplotlib.rc('ytick', labelsize=14)" }, { "code": null, "e": 2577, "s": 2518, "text": "Now, we load in the data and look at the first 10 comments" }, { "code": null, "e": 2678, "s": 2577, "text": "with open(\"sentiment_labelled_sentences/full_set.txt\") as f: content = f.readlines()content[0:10]" }, { "code": null, "e": 2918, "s": 2678, "text": "## Remove leading and trailing white spacecontent = [x.strip() for x in content]## Separate the sentences from the labelssentences = [x.split(\"\\t\")[0] for x in content]labels = [x.split(\"\\t\")[1] for x in content]sentences[0:10]labels[0:10]" }, { "code": null, "e": 3064, "s": 2918, "text": "One can stop here for this section. But for me, I prefer transforming y into (-1,1) form, where -1 represents negative and 1 represents positive." }, { "code": null, "e": 3164, "s": 3064, "text": "## Transform the labels from '0 v.s. 1' to '-1 v.s. 1'y = np.array(labels, dtype='int8')y = 2*y - 1" }, { "code": null, "e": 3272, "s": 3164, "text": "NOTICE THAT SO FAR WE HAVE NOT DONE ANY TO THE WORDS YET!!! The next section focuses on words in sentences." }, { "code": null, "e": 3387, "s": 3272, "text": "To input data into the any model, the data input must be in vector form. We will do the following transformations:" }, { "code": null, "e": 3418, "s": 3387, "text": "Remove punctuation and numbers" }, { "code": null, "e": 3452, "s": 3418, "text": "Transform all words to lower-case" }, { "code": null, "e": 3505, "s": 3452, "text": "Remove stop words (e.g. the, a, that, this, it, ...)" }, { "code": null, "e": 3525, "s": 3505, "text": "Tokenizer the texts" }, { "code": null, "e": 3597, "s": 3525, "text": "Convert the sentences into vectors, using a bag-of-words representation" }, { "code": null, "e": 3631, "s": 3597, "text": "I will explain some jargons here." }, { "code": null, "e": 3836, "s": 3631, "text": "Stop words: common words that are not interesting for the task at hand. These usually include articles such as ‘a’ and ‘the’, pronouns such as ‘i’ and ‘they’, and prepositions such as ‘to’ and ‘from’, ..." }, { "code": null, "e": 4041, "s": 3836, "text": "Stop words: common words that are not interesting for the task at hand. These usually include articles such as ‘a’ and ‘the’, pronouns such as ‘i’ and ‘they’, and prepositions such as ‘to’ and ‘from’, ..." }, { "code": null, "e": 4315, "s": 4041, "text": "## Demonstrate ##def removeStopWords(stopWords, txt): newtxt = ' '.join([word for word in txt.split() if word not in stopWords]) return newtxtstoppers = ['a', 'is', 'of','the','this','uhm','uh']removeStopWords(stoppers, \"this is a test of the stop word removal code\")" }, { "code": null, "e": 4389, "s": 4315, "text": "Or we can use NLTK if we do want a complete set of common stop words used" }, { "code": null, "e": 4528, "s": 4389, "text": "from nltk.corpus import stopwordsstops = stopwords.words(\"English\")removeStopWords(stops, \"this is a test of the stop word removal code.\")" }, { "code": null, "e": 4540, "s": 4528, "text": "Same result" }, { "code": null, "e": 4641, "s": 4540, "text": "2. Corpus: simply a collection of text. Order of words matter. ‘Not great’ is different from ‘great’" }, { "code": null, "e": 4757, "s": 4641, "text": "3. Document-Term Matrix or Bag of Words (BOW) is simply a vectorial representation of text sentences (or documents)" }, { "code": null, "e": 4901, "s": 4757, "text": "A common way to represent a set of features like this is called a One-Hot vector. For example, lets say our vocabular from our set of texts is:" }, { "code": null, "e": 4947, "s": 4901, "text": "today, here, I, a, fine, sun, moon, bird, saw" }, { "code": null, "e": 4991, "s": 4947, "text": "The sentence we want to build a BOW for is:" }, { "code": null, "e": 5102, "s": 4991, "text": "I saw a bird today Using a 1-0 for each word in the vocabulary, our BOW encoded as a one-hot vector would be:" }, { "code": null, "e": 5118, "s": 5102, "text": "1 0 1 1 0 0 1 1" }, { "code": null, "e": 5492, "s": 5118, "text": "In order to create a bag of words, we need to break down a long sentence or a document into smaller pieces. This process is called Tokenization. The most common tokenization technique is to break down text into words. We can do this using CountVectorizer in Scikit-Learn, where every row will represent a different document and every column will represent a different word." }, { "code": null, "e": 5542, "s": 5492, "text": "Now let’s put everything together for our dataset" }, { "code": null, "e": 6297, "s": 5542, "text": "def full_remove(x, removal_list): for w in removal_list: x = x.replace(w, ' ') return x## Remove digits ##digits = [str(x) for x in range(10)]remove_digits = [full_remove(x, digits) for x in sentences]## Remove punctuation ##remove_punc = [full_remove(x, list(string.punctuation)) for x in remove_digits]## Make everything lower-case and remove any white space ##sents_lower = [x.lower() for x in remove_punc]sents_lower = [x.strip() for x in sents_lower]## Remove stop words ##from nltk.corpus import stopwordsstops = stopwords.words(\"English\")def removeStopWords(stopWords, txt): newtxt = ' '.join([word for word in txt.split() if word not in stopWords]) return newtxtsents_processed = [removeStopWords(stops,x) for x in sents_lower]" }, { "code": null, "e": 6343, "s": 6297, "text": "Let’s look at how our sentences look like now" }, { "code": null, "e": 6665, "s": 6343, "text": "Uhm, wait a minute! Removing many stop words makes many sentences lose their meanings. For example, ‘way plug us unless go converter’ does not make any sense to me. This is because we remove all the common English stop words by using NLTK. To overcome this meaning problem, let’s create our own set of stop words instead." }, { "code": null, "e": 6815, "s": 6665, "text": "stop_set = ['the', 'a', 'an', 'i', 'he', 'she', 'they', 'to', 'of', 'it', 'from']sents_processed = [removeStopWords(stop_set,x) for x in sents_lower]" }, { "code": null, "e": 7175, "s": 6815, "text": "It is ok to stop here and move to Tokenization. However, one can continue with stemming. The goal of stemming is too strip off prefixes and suffixes in the word and convert the word into its base form, e.g. studying->study, beautiful->beauty, cared->care, ...In NLTK, there are 2 popular stemming techniques called porter and lanscaster. [Reference: DataCamp]" }, { "code": null, "e": 7650, "s": 7175, "text": "import nltkdef stem_with_porter(words): porter = nltk.PorterStemmer() new_words = [porter.stem(w) for w in words] return new_words def stem_with_lancaster(words): porter = nltk.LancasterStemmer() new_words = [porter.stem(w) for w in words] return new_words ## Demonstrate ## str = \"Please don't unbuckle your seat-belt while I am driving, he said\"print(\"porter:\", stem_with_porter(str.split()))print(\"lancaster:\", stem_with_lancaster(str.split()))" }, { "code": null, "e": 7714, "s": 7650, "text": "Let’s try on our sents_processed to see whether it makes sense." }, { "code": null, "e": 7828, "s": 7714, "text": "porter = [stem_with_porter(x.split()) for x in sents_processed]porter = [\" \".join(i) for i in porter]porter[0:10]" }, { "code": null, "e": 7906, "s": 7828, "text": "Some weird changes occur, e.g. very->veri, quality->qualiti, value->valu, ..." }, { "code": null, "e": 8108, "s": 7906, "text": "4. Term Document Inverse Document Frequency (TD/IDF). This is a measure of the relative importance of a word within a document, in the context of multiple documents. In our case here, multiple reviews." }, { "code": null, "e": 8203, "s": 8108, "text": "We start with the TD part — this is simply a normalized frequency of the word in the document:" }, { "code": null, "e": 8376, "s": 8203, "text": "(word count in document) / (total words in document) The IDF is a weighting of the uniquess of the word across all of the documents. Here is the complete formula of TD/IDF:" }, { "code": null, "e": 8417, "s": 8376, "text": "td_idf(t,d) = wc(t,d)/wc(d) / dc(t)/dc()" }, { "code": null, "e": 8604, "s": 8417, "text": "where: — wc(t,d) = # of occurrences of term t in doc d — wc(d) = # of words in doc d — dc(t) = # of docs that contain at least 1 occurrence of term t — dc() = # of docs in collection" }, { "code": null, "e": 8661, "s": 8604, "text": "Now, let’s create a bag of words and normalise the texts" }, { "code": null, "e": 9204, "s": 8661, "text": "from sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction.text import TfidfTransformervectorizer = CountVectorizer(analyzer = \"word\", preprocessor = None, stop_words = 'english', max_features = 6000, ngram_range=(1,5))data_features = vectorizer.fit_transform(sents_processed)tfidf_transformer = TfidfTransformer()data_features_tfidf = tfidf_transformer.fit_transform(data_features)data_mat = data_features_tfidf.toarray()" }, { "code": null, "e": 9456, "s": 9204, "text": "Now data_mat is our Document-Term matrix. Input is ready to put into model. Let’s create Training and Test sets. Here, I split the data into a training set of 2500 sentences and a test set of 500 sentences (of which 250 are positive and 250 negative)." }, { "code": null, "e": 9800, "s": 9456, "text": "np.random.seed(0)test_index = np.append(np.random.choice((np.where(y==-1))[0], 250, replace=False), np.random.choice((np.where(y==1))[0], 250, replace=False))train_index = list(set(range(len(labels))) - set(test_index))train_data = data_mat[train_index,]train_labels = y[train_index]test_data = data_mat[test_index,]test_labels = y[test_index]" }, { "code": null, "e": 10360, "s": 9800, "text": "TextBlob: Linguistic researchers have labeled the sentiment of words based on their domain expertise. Sentiment of words can vary based on where it is in a sentence. The TextBlob module allows us to take advantage of these labels. TextBlod finds all the words and phrases that it can assign polarity and subjectivity to, and average all of them togetherSentiment Labels: Each word in a corpus is labeled in terms of polarity and subjectivity (there are more labels as well, but we’re going to ignore them for now). A corpus’ sentiment is the average of these." }, { "code": null, "e": 10714, "s": 10360, "text": "TextBlob: Linguistic researchers have labeled the sentiment of words based on their domain expertise. Sentiment of words can vary based on where it is in a sentence. The TextBlob module allows us to take advantage of these labels. TextBlod finds all the words and phrases that it can assign polarity and subjectivity to, and average all of them together" }, { "code": null, "e": 10921, "s": 10714, "text": "Sentiment Labels: Each word in a corpus is labeled in terms of polarity and subjectivity (there are more labels as well, but we’re going to ignore them for now). A corpus’ sentiment is the average of these." }, { "code": null, "e": 11009, "s": 10921, "text": "Polarity: How positive or negative a word is. -1 is very negative. +1 is very positive." }, { "code": null, "e": 11104, "s": 11009, "text": "Subjectivity: How subjective, or opinionated a word is. 0 is fact. +1 is very much an opinion." }, { "code": null, "e": 11369, "s": 11104, "text": "from textblob import TextBlob#Create polarity function and subjectivity functionpol = lambda x: TextBlob(x).sentiment.polaritysub = lambda x: TextBlob(x).sentiment.subjectivitypol_list = [pol(x) for x in sents_processed]sub_list = [sub(x) for x in sents_processed]" }, { "code": null, "e": 11468, "s": 11369, "text": "This is a rule-based method that determines the sentiment (polarity and subjectivity) of a review." }, { "code": null, "e": 11518, "s": 11468, "text": "The next section will look at various algorithms." }, { "code": null, "e": 12206, "s": 11518, "text": "from sklearn.linear_model import SGDClassifier## Fit logistic classifier on training dataclf = SGDClassifier(loss=\"log\", penalty=\"none\")clf.fit(train_data, train_labels)## Pull out the parameters (w,b) of the logistic regression modelw = clf.coef_[0,:]b = clf.intercept_## Get predictions on training and test datapreds_train = clf.predict(train_data)preds_test = clf.predict(test_data)## Compute errorserrs_train = np.sum((preds_train > 0.0) != (train_labels > 0.0))errs_test = np.sum((preds_test > 0.0) != (test_labels > 0.0))print(\"Training error: \", float(errs_train)/len(train_labels))print(\"Test error: \", float(errs_test)/len(test_labels))Training error: 0.0116Test error: 0.184" }, { "code": null, "e": 12233, "s": 12206, "text": "Words with large influence" }, { "code": null, "e": 12425, "s": 12233, "text": "Which words are most important in deciding whether a sentence is positive? As a first approximation to this, we simply take the words whose coefficients in w have the largest positive values." }, { "code": null, "e": 12573, "s": 12425, "text": "Likewise, we look at the words whose coefficients in w have the most negative values, and we think of these as influential in negative predictions." }, { "code": null, "e": 13016, "s": 12573, "text": "## Convert vocabulary into a list:vocab = np.array([z[0] for z in sorted(vectorizer.vocabulary_.items(), key=lambda x:x[1])])## Get indices of sorting winds = np.argsort(w)## Words with large negative valuesneg_inds = inds[0:50]print(\"Highly negative words: \")print([str(x) for x in list(vocab[neg_inds])])## Words with large positive valuespos_inds = inds[-49:-1]print(\"Highly positive words: \")print([str(x) for x in list(vocab[pos_inds])])" }, { "code": null, "e": 13036, "s": 13016, "text": "Create a Word Cloud" }, { "code": null, "e": 13350, "s": 13036, "text": "from wordcloud import WordCloudwc = WordCloud(stopwords=stop_set, background_color=\"white\", colormap=\"Dark2\", max_font_size=150, random_state=42)#plt.rcParams['figure.figsize'] = [16, 6]wc.generate(\" \".join(list(vocab[neg_inds])))plt.imshow(wc, interpolation=\"bilinear\")plt.axis(\"off\") plt.show()" }, { "code": null, "e": 13635, "s": 13350, "text": "from sklearn.naive_bayes import MultinomialNBnb_clf = MultinomialNB().fit(train_data, train_labels)nb_preds_test = nb_clf.predict(test_data)nb_errs_test = np.sum((nb_preds_test > 0.0) != (test_labels > 0.0))print(\"Test error: \", float(nb_errs_test)/len(test_labels))Test error: 0.174" }, { "code": null, "e": 13710, "s": 13635, "text": "Let’s do some prediction cases. [1] means positive and [-1] means negative" }, { "code": null, "e": 14016, "s": 13710, "text": "print(nb_clf.predict(vectorizer.transform([\"It's a sad movie but very good\"])))[1]print(nb_clf.predict(vectorizer.transform([\"Waste of my time\"])))[-1]print(nb_clf.predict(vectorizer.transform([\"It is not what like\"])))[-1]print(nb_clf.predict(vectorizer.transform([\"It is not what I m looking for\"])))[1]" }, { "code": null, "e": 14113, "s": 14016, "text": "The last test case has problem. It should be a negative comment but the model predicts positive." }, { "code": null, "e": 14436, "s": 14113, "text": "from sklearn.linear_model import SGDClassifiersvm_clf = SGDClassifier(loss=\"hinge\", penalty='l2')svm_clf.fit(train_data, train_labels)svm_preds_test = svm_clf.predict(test_data)svm_errs_test = np.sum((svm_preds_test > 0.0) != (test_labels > 0.0))print(\"Test error: \", float(svm_errs_test)/len(test_labels))Test error: 0.2" }, { "code": null, "e": 14468, "s": 14436, "text": "Again, let’s do some prediction" }, { "code": null, "e": 14716, "s": 14468, "text": "print(svm_clf.predict(vectorizer.transform([\"This is not what I like\"])))[-1]print(svm_clf.predict(vectorizer.transform([\"It is not what I am looking for\"])))[-1]print(svm_clf.predict(vectorizer.transform([\"I would not recommend this movie\"])))[1]" }, { "code": null, "e": 14864, "s": 14716, "text": "SVM can predict the comment ‘It is not what I am looking for’ correctly. However, it could not predict the comment ‘I do not recommend this movie’." }, { "code": null, "e": 14925, "s": 14864, "text": "A detailed discussion about LSTM networks can be found here." }, { "code": null, "e": 15509, "s": 14925, "text": "from keras.models import Sequentialfrom keras.layers import Densefrom keras.layers import LSTMfrom keras.layers import SpatialDropout1Dfrom keras.layers.embeddings import Embeddingfrom keras.preprocessing import sequencefrom keras.preprocessing.text import Tokenizerfrom keras.callbacks import EarlyStoppingmax_review_length = 200tokenizer = Tokenizer(num_words=10000, #max no. of unique words to keep filters='!\"#$%&()*+,-./:;<=>?@[\\]^_`{|}~', lower=True #convert to lower case )tokenizer.fit_on_texts(sents_processed)" }, { "code": null, "e": 15586, "s": 15509, "text": "Truncate and pad the input sequences so that they are all in the same length" }, { "code": null, "e": 15764, "s": 15586, "text": "X = tokenizer.texts_to_sequences(sents_processed)X = sequence.pad_sequences(X, maxlen= max_review_length)print('Shape of data tensor:', X.shape)Shape of data tensor: (3000, 200)" }, { "code": null, "e": 15869, "s": 15764, "text": "Recall that y is vector of 1 and -1. Now I change it to a matrix with 2 columns that represent -1 and 1." }, { "code": null, "e": 15916, "s": 15869, "text": "import pandas as pdY=pd.get_dummies(y).valuesY" }, { "code": null, "e": 16239, "s": 15916, "text": "np.random.seed(0)test_inds = np.append(np.random.choice((np.where(y==-1))[0], 250, replace=False), np.random.choice((np.where(y==1))[0], 250, replace=False))train_inds = list(set(range(len(labels))) - set(test_inds))train_data = X[train_inds,]train_labels = Y[train_inds]test_data = X[test_inds,]test_labels = Y[test_inds]" }, { "code": null, "e": 16255, "s": 16239, "text": "Create networks" }, { "code": null, "e": 16654, "s": 16255, "text": "EMBEDDING_DIM = 200model = Sequential()model.add(Embedding(10000, EMBEDDING_DIM, input_length=X.shape[1]))model.add(SpatialDropout1D(0.2))model.add(LSTM(250, dropout=0.2,return_sequences=True))model.add(LSTM(100, dropout=0.2, recurrent_dropout=0.2))model.add(Dense(2, activation='softmax'))model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])print(model.summary())" }, { "code": null, "e": 16804, "s": 16654, "text": "epochs = 2batch_size = 40model.fit(train_data, train_labels, epochs=epochs, batch_size=batch_size, validation_split=0.1)" }, { "code": null, "e": 16974, "s": 16804, "text": "loss, acc = model.evaluate(test_data, test_labels, verbose=2, batch_size=batch_size)print(f\"loss: {loss}\")print(f\"Validation accuracy: {acc}\")" }, { "code": null, "e": 17112, "s": 16974, "text": "LSTM performs the best out of all the models trained so far, i.e. Logistic, Naive Bayes and SVM. Now let’s see how it predict a test case" }, { "code": null, "e": 17456, "s": 17112, "text": "outcome_labels = ['Negative', 'Positive']new = [\"I would not recommend this movie\"] seq = tokenizer.texts_to_sequences(new)padded = sequence.pad_sequences(seq, maxlen=max_review_length)pred = model.predict(padded)print(\"Probability distribution: \", pred)print(\"Is this a Positive or Negative review? \")print(outcome_labels[np.argmax(pred)])" }, { "code": null, "e": 17498, "s": 17456, "text": "new = [\"It is not what i am looking for\"]" }, { "code": null, "e": 17541, "s": 17498, "text": "new = [\"This isn't what i am looking for\"]" }, { "code": null, "e": 17678, "s": 17541, "text": "For this case, the difference between probability for negative and positive is not much. And the LSTM model classifies this as positive." }, { "code": null, "e": 17720, "s": 17678, "text": "new = [\"I wouldn't recommend this movie\"]" }, { "code": null, "e": 18103, "s": 17720, "text": "The same happens for this comment. Hence, this means that our model could not distinguish between n't and not. One possible solution to this would be, in the pre-processing step, instead of removing all punctuations, change all the n't short form into not. This can simply be done with the re module in Python. You can check it out yourself to see how our models prediction improve." } ]
How to aggregate sum in MongoDB to get the total count?
To aggregate sum in MongoDB to get the total count, you can use the $sum operator. To understand the above concept, let us create a collection with the document − > db.aggregateSumDemo.insertOne({"CustomerName":"Larry","Amount":140}); { "acknowledged" : true, "insertedId" : ObjectId("5c8baa0680f10143d8431e18") } > db.aggregateSumDemo.insertOne({"CustomerName":"Mike","Amount":160}); { "acknowledged" : true, "insertedId" : ObjectId("5c8baa1380f10143d8431e19") } > db.aggregateSumDemo.insertOne({"CustomerName":"Sam","Amount":300}); { "acknowledged" : true, "insertedId" : ObjectId("5c8baa1c80f10143d8431e1a") } > db.aggregateSumDemo.insertOne({"CustomerName":"David","Amount":500}); { "acknowledged" : true, "insertedId" : ObjectId("5c8baa2580f10143d8431e1b") } Display all documents from a collection with the help of find() method. The query is as follows − > db.aggregateSumDemo.find().pretty(); The following is the output − { "_id" : ObjectId("5c8baa0680f10143d8431e18"), "CustomerName" : "Larry", "Amount" : 140 } { "_id" : ObjectId("5c8baa1380f10143d8431e19"), "CustomerName" : "Mike", "Amount" : 160 } { "_id" : ObjectId("5c8baa1c80f10143d8431e1a"), "CustomerName" : "Sam", "Amount" : 300 } { "_id" : ObjectId("5c8baa2580f10143d8431e1b"), "CustomerName" : "David", "Amount" : 500 } Here is the query to get the total count. Case 1 − The query is as follows − > db.aggregateSumDemo.aggregate([ { ... $group: { ... _id: null, ... "TotalCount": { ... $sum:1 ... } ... } ... } ] ); The following is the output − { "_id" : null, "TotalCount" : 4 } Here is the query to aggregate sum in MongoDB to get the total sum. Case 2 − The query is as follows − > db.aggregateSumDemo.aggregate([ { ... $group: { ... _id: null, ... "TotalAmount": { ... $sum: "$Amount" ... } ... } ... } ] ); The following is the output − { "_id" : null, "TotalAmount" : 1100 }
[ { "code": null, "e": 1225, "s": 1062, "text": "To aggregate sum in MongoDB to get the total count, you can use the $sum operator. To understand the above concept, let us create a collection with the document −" }, { "code": null, "e": 1850, "s": 1225, "text": "> db.aggregateSumDemo.insertOne({\"CustomerName\":\"Larry\",\"Amount\":140});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8baa0680f10143d8431e18\")\n}\n> db.aggregateSumDemo.insertOne({\"CustomerName\":\"Mike\",\"Amount\":160});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8baa1380f10143d8431e19\")\n}\n> db.aggregateSumDemo.insertOne({\"CustomerName\":\"Sam\",\"Amount\":300});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8baa1c80f10143d8431e1a\")\n}\n> db.aggregateSumDemo.insertOne({\"CustomerName\":\"David\",\"Amount\":500});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8baa2580f10143d8431e1b\")\n}" }, { "code": null, "e": 1948, "s": 1850, "text": "Display all documents from a collection with the help of find() method. The query is as follows −" }, { "code": null, "e": 1987, "s": 1948, "text": "> db.aggregateSumDemo.find().pretty();" }, { "code": null, "e": 2017, "s": 1987, "text": "The following is the output −" }, { "code": null, "e": 2414, "s": 2017, "text": "{\n \"_id\" : ObjectId(\"5c8baa0680f10143d8431e18\"),\n \"CustomerName\" : \"Larry\",\n \"Amount\" : 140\n}\n{\n \"_id\" : ObjectId(\"5c8baa1380f10143d8431e19\"),\n \"CustomerName\" : \"Mike\",\n \"Amount\" : 160\n}\n{\n \"_id\" : ObjectId(\"5c8baa1c80f10143d8431e1a\"),\n \"CustomerName\" : \"Sam\",\n \"Amount\" : 300\n}\n{\n \"_id\" : ObjectId(\"5c8baa2580f10143d8431e1b\"),\n \"CustomerName\" : \"David\",\n \"Amount\" : 500\n}" }, { "code": null, "e": 2456, "s": 2414, "text": "Here is the query to get the total count." }, { "code": null, "e": 2491, "s": 2456, "text": "Case 1 − The query is as follows −" }, { "code": null, "e": 2643, "s": 2491, "text": "> db.aggregateSumDemo.aggregate([ {\n ... $group: {\n ... _id: null,\n ... \"TotalCount\": {\n ... $sum:1\n ... }\n ... }\n... } ] );" }, { "code": null, "e": 2673, "s": 2643, "text": "The following is the output −" }, { "code": null, "e": 2708, "s": 2673, "text": "{ \"_id\" : null, \"TotalCount\" : 4 }" }, { "code": null, "e": 2776, "s": 2708, "text": "Here is the query to aggregate sum in MongoDB to get the total sum." }, { "code": null, "e": 2811, "s": 2776, "text": "Case 2 − The query is as follows −" }, { "code": null, "e": 2973, "s": 2811, "text": "> db.aggregateSumDemo.aggregate([ {\n ... $group: {\n ... _id: null,\n ... \"TotalAmount\": {\n ... $sum: \"$Amount\"\n ... }\n ... }\n... } ] );" }, { "code": null, "e": 3003, "s": 2973, "text": "The following is the output −" }, { "code": null, "e": 3042, "s": 3003, "text": "{ \"_id\" : null, \"TotalAmount\" : 1100 }" } ]
C# Program to find the sum of a sequence
Firstly, set a sequence. List<int> myList = new List<int> { 1, 2, 3, 4 ,5}; Now find the sum using the Queryable Sum() method. myList.AsQueryable().Sum(); Live Demo using System; using System.Linq; using System.Collections.Generic; public class Demo { public static void Main() { List<int> myList = new List<int> { 1, 2, 3, 4 ,5}; Console.WriteLine("Sum of elements in a list..."); foreach (int res in myList) { Console.WriteLine(res); } int sum = myList.AsQueryable().Sum(); Console.WriteLine("Sum = {0}", sum); } } Sum of elements in a list... 1 2 3 4 5 Sum = 15
[ { "code": null, "e": 1087, "s": 1062, "text": "Firstly, set a sequence." }, { "code": null, "e": 1138, "s": 1087, "text": "List<int> myList = new List<int> { 1, 2, 3, 4 ,5};" }, { "code": null, "e": 1189, "s": 1138, "text": "Now find the sum using the Queryable Sum() method." }, { "code": null, "e": 1217, "s": 1189, "text": "myList.AsQueryable().Sum();" }, { "code": null, "e": 1228, "s": 1217, "text": " Live Demo" }, { "code": null, "e": 1631, "s": 1228, "text": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main() {\n List<int> myList = new List<int> { 1, 2, 3, 4 ,5};\n Console.WriteLine(\"Sum of elements in a list...\");\n foreach (int res in myList) {\n Console.WriteLine(res);\n }\n int sum = myList.AsQueryable().Sum();\n Console.WriteLine(\"Sum = {0}\", sum);\n }\n}" }, { "code": null, "e": 1679, "s": 1631, "text": "Sum of elements in a list...\n1\n2\n3\n4\n5\nSum = 15" } ]
putchar() function in C - GeeksforGeeks
10 Jan, 2019 The putchar(int char) method in C is used to write a character, of unsigned char type, to stdout. This character is passed as the parameter to this method. Syntax: int putchar(int char) Parameters: This method accepts a mandatory parameter char which is the character to be written to stdout. Return Value: This function returns the character written on the stdout as an unsigned char. It also returns EOF when some error occurs. Below examples illustrate the use of putchar() method: Example 1: // C program to demonstrate putchar() method #include <stdio.h> int main(){ // Get the character to be written char ch = 'G'; // Write the Character to stdout putchar(ch); return (0);} G Example 2: // C program to demonstrate putchar() method #include <stdio.h> int main(){ // Get the character to be written char ch = '1'; // Write the Character to stdout for (ch = '1'; ch <= '9'; ch++) putchar(ch); return (0);} 123456789 C-Functions C Language 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 Exception Handling in C++ Multithreading in C Arrow operator -> in C/C++ with Examples 'this' pointer in C++ How to split a string in C/C++, Python and Java? Smart Pointers in C++ and How to Use Them How to dynamically allocate a 2D array in C? UDP Server-Client implementation in C Input-output system calls in C | Create, Open, Close, Read, Write
[ { "code": null, "e": 23841, "s": 23813, "text": "\n10 Jan, 2019" }, { "code": null, "e": 23997, "s": 23841, "text": "The putchar(int char) method in C is used to write a character, of unsigned char type, to stdout. This character is passed as the parameter to this method." }, { "code": null, "e": 24005, "s": 23997, "text": "Syntax:" }, { "code": null, "e": 24027, "s": 24005, "text": "int putchar(int char)" }, { "code": null, "e": 24134, "s": 24027, "text": "Parameters: This method accepts a mandatory parameter char which is the character to be written to stdout." }, { "code": null, "e": 24271, "s": 24134, "text": "Return Value: This function returns the character written on the stdout as an unsigned char. It also returns EOF when some error occurs." }, { "code": null, "e": 24326, "s": 24271, "text": "Below examples illustrate the use of putchar() method:" }, { "code": null, "e": 24337, "s": 24326, "text": "Example 1:" }, { "code": "// C program to demonstrate putchar() method #include <stdio.h> int main(){ // Get the character to be written char ch = 'G'; // Write the Character to stdout putchar(ch); return (0);}", "e": 24545, "s": 24337, "text": null }, { "code": null, "e": 24548, "s": 24545, "text": "G\n" }, { "code": null, "e": 24559, "s": 24548, "text": "Example 2:" }, { "code": "// C program to demonstrate putchar() method #include <stdio.h> int main(){ // Get the character to be written char ch = '1'; // Write the Character to stdout for (ch = '1'; ch <= '9'; ch++) putchar(ch); return (0);}", "e": 24806, "s": 24559, "text": null }, { "code": null, "e": 24817, "s": 24806, "text": "123456789\n" }, { "code": null, "e": 24829, "s": 24817, "text": "C-Functions" }, { "code": null, "e": 24840, "s": 24829, "text": "C Language" }, { "code": null, "e": 24938, "s": 24840, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24947, "s": 24938, "text": "Comments" }, { "code": null, "e": 24960, "s": 24947, "text": "Old Comments" }, { "code": null, "e": 24998, "s": 24960, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 25024, "s": 24998, "text": "Exception Handling in C++" }, { "code": null, "e": 25044, "s": 25024, "text": "Multithreading in C" }, { "code": null, "e": 25085, "s": 25044, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 25107, "s": 25085, "text": "'this' pointer in C++" }, { "code": null, "e": 25156, "s": 25107, "text": "How to split a string in C/C++, Python and Java?" }, { "code": null, "e": 25198, "s": 25156, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 25243, "s": 25198, "text": "How to dynamically allocate a 2D array in C?" }, { "code": null, "e": 25281, "s": 25243, "text": "UDP Server-Client implementation in C" } ]
JasmineJS - Spies
Jasmine spy is another functionality which does the exact same as its name specifies. It will allow you to spy on your application function calls. There are two types of spying technology available in Jasmine. The first methodology can be implemented by using spyOn() and the second methodology can be implemented using createSpy(). In this chapter, we will learn more about these two methodologies. spyOn() is inbuilt into the Jasmine library which allows you to spy on a definite piece of code. Let us create a new spec file “spyJasmineSpec.js” and another js file named as “spyJasmine.js”. Following is the entry of these two files. var Person = function() {}; Person.prototype.sayHelloWorld = function(dict) { return dict.hello() + " " + dict.world(); }; var Dictionary = function() {}; Dictionary.prototype.hello = function() { return "hello"; }; Dictionary.prototype.world = function() { return "world"; }; describe("Example Of jasmine Spy using spyOn()", function() { it('uses the dictionary to say "hello world"', function() { var dictionary = new Dictionary; var person = new Person; spyOn(dictionary, "hello"); // replace hello function with a spy spyOn(dictionary, "world"); // replace world function with another spy person.sayHelloWorld(dictionary); expect(dictionary.hello).toHaveBeenCalled(); // not possible without first spy expect(dictionary.world).toHaveBeenCalled(); // not possible withoutsecond spy }); }); In the above piece of code, we want person object to say “Hello world” but we also want that person object should consult with dictionary object to give us the output literal “Hello world”. Take a look at the Spec file where you can see that we have used spyOn() function, which actually mimics the functionality of the hello and world function. Hence, we are not actually calling the function but mimicking the function call. That is the specialty of Spies. The above piece of code will yield the following output. Another method of obtaining the spying functionality is using createSpy(). Let us modify our two js files using the following code. var Person = function() {}; Person.prototype.sayHelloWorld = function(dict) { return dict.hello() + " " + dict.world(); }; var Dictionary = function() {}; Dictionary.prototype.hello = function() { return "hello"; }; Dictionary.prototype.world = function() { return "world"; }; describe("Example Of jasmine Spy using Create Spy", function() { it("can have a spy function", function() { var person = new Person(); person.getName11 = jasmine.createSpy("Name spy"); person.getName11(); expect(person.getName11).toHaveBeenCalled(); }); }); Take a look at the spec file, we are calling the getName11() of the Person object. Although this function is not present in the person object in spy Jasmine.js, we are not getting any error and hence the output is green and positive. In this example, createSpy() method actually mimics the functionality of the getName11(). The above code will generate the following output. Print Add Notes Bookmark this page
[ { "code": null, "e": 2450, "s": 2050, "text": "Jasmine spy is another functionality which does the exact same as its name specifies. It will allow you to spy on your application function calls. There are two types of spying technology available in Jasmine. The first methodology can be implemented by using spyOn() and the second methodology can be implemented using createSpy(). In this chapter, we will learn more about these two methodologies." }, { "code": null, "e": 2686, "s": 2450, "text": "spyOn() is inbuilt into the Jasmine library which allows you to spy on a definite piece of code. Let us create a new spec file “spyJasmineSpec.js” and another js file named as “spyJasmine.js”. Following is the entry of these two files." }, { "code": null, "e": 2987, "s": 2686, "text": "var Person = function() {}; \n\nPerson.prototype.sayHelloWorld = function(dict) { \n return dict.hello() + \" \" + dict.world(); \n}; \n\nvar Dictionary = function() {}; \n\nDictionary.prototype.hello = function() { \n return \"hello\"; \n}; \n\nDictionary.prototype.world = function() { \n return \"world\"; \n}; " }, { "code": null, "e": 3590, "s": 2987, "text": "describe(\"Example Of jasmine Spy using spyOn()\", function() { \n \n it('uses the dictionary to say \"hello world\"', function() { \n var dictionary = new Dictionary; \n var person = new Person; \n\t\t\n spyOn(dictionary, \"hello\"); // replace hello function with a spy \n spyOn(dictionary, \"world\"); // replace world function with another spy \n\t\t\n person.sayHelloWorld(dictionary);\n expect(dictionary.hello).toHaveBeenCalled(); \n // not possible without first spy \n \n expect(dictionary.world).toHaveBeenCalled(); \n // not possible withoutsecond spy \n }); \n});" }, { "code": null, "e": 3780, "s": 3590, "text": "In the above piece of code, we want person object to say “Hello world” but we also want that person object should consult with dictionary object to give us the output literal “Hello world”." }, { "code": null, "e": 4106, "s": 3780, "text": "Take a look at the Spec file where you can see that we have used spyOn() function, which actually mimics the functionality of the hello and world function. Hence, we are not actually calling the function but mimicking the function call. That is the specialty of Spies. The above piece of code will yield the following output." }, { "code": null, "e": 4238, "s": 4106, "text": "Another method of obtaining the spying functionality is using createSpy(). Let us modify our two js files using the following code." }, { "code": null, "e": 4542, "s": 4238, "text": "var Person = function() {}; \n\nPerson.prototype.sayHelloWorld = function(dict) { \n return dict.hello() + \" \" + dict.world(); \n}; \n\nvar Dictionary = function() {}; \n\nDictionary.prototype.hello = function() { \n return \"hello\"; \n}; \n\nDictionary.prototype.world = function() { \n return \"world\"; \n}; " }, { "code": null, "e": 4842, "s": 4542, "text": "describe(\"Example Of jasmine Spy using Create Spy\", function() { \n \n it(\"can have a spy function\", function() { \n var person = new Person(); \n person.getName11 = jasmine.createSpy(\"Name spy\"); \n person.getName11(); \n expect(person.getName11).toHaveBeenCalled(); \n }); \n}); " }, { "code": null, "e": 5166, "s": 4842, "text": "Take a look at the spec file, we are calling the getName11() of the Person object. Although this function is not present in the person object in spy Jasmine.js, we are not getting any error and hence the output is green and positive. In this example, createSpy() method actually mimics the functionality of the getName11()." }, { "code": null, "e": 5217, "s": 5166, "text": "The above code will generate the following output." }, { "code": null, "e": 5224, "s": 5217, "text": " Print" }, { "code": null, "e": 5235, "s": 5224, "text": " Add Notes" } ]
What is Android background music service?
What is Android background music service? Before getting into an example, we should know what service is in android. Service is going to do background operation without interacting with UI and it works even after activity destroy. This example demonstrates what is Android background music service. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity"> <TextView android:id = "@+id/text" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Start Service" android:textSize = "25sp" app:layout_constraintBottom_toBottomOf = "parent" app:layout_constraintLeft_toLeftOf = "parent" app:layout_constraintRight_toRightOf = "parent" app:layout_constraintTop_toTopOf = "parent" /> </android.support.constraint.ConstraintLayout> In the above code, we have taken text view, when user click on text view, it will start music service and stop music service. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TextView text = findViewById(R.id.text); text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isMyServiceRunning(service.class)) { text.setText("Stoped"); stopService(new Intent(MainActivity.this, service.class)); } else { text.setText("Started"); startService(new Intent(MainActivity.this, service.class)); } } }); } private boolean isMyServiceRunning(Class<?> serviceClass) { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } } In the above code to start and stop service. We have used intent and passed context and service class. Now create a service class in package folder as service.class and add the following code – package com.example.andy.myapplication; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.IBinder; import android.widget.Toast; public class service extends Service { MediaPlayer musicPlayer; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); musicPlayer = MediaPlayer.create(this, R.raw.abc); musicPlayer.setLooping(false); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "Music Service started by user.", Toast.LENGTH_LONG).show(); musicPlayer.start(); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); musicPlayer.stop(); Toast.makeText(this, "Music Service destroyed by user.", Toast.LENGTH_LONG).show(); } } In the above code we have music Player class and started music player and stopped music player as shown below – @Override public void onCreate() { super.onCreate(); musicPlayer = MediaPlayer.create(this, R.raw.abc); musicPlayer.setLooping(false); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "Music Service started by user.", Toast.LENGTH_LONG).show(); musicPlayer.start(); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); musicPlayer.stop(); Toast.makeText(this, "Music Service destroyed by user.", Toast.LENGTH_LONG).show(); } Step 4 − Add the following code to manifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication"> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name = ".service"/> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – In the above result is an initial screen, Click on Text view, it will start music service as shown below – In the above result, service is startd now click on text view, it will stop music service as shown below - Click here to download the project code
[ { "code": null, "e": 1104, "s": 1062, "text": "What is Android background music service?" }, { "code": null, "e": 1293, "s": 1104, "text": "Before getting into an example, we should know what service is in android. Service is going to do background operation without interacting with UI and it works even after activity destroy." }, { "code": null, "e": 1361, "s": 1293, "text": "This example demonstrates what is Android background music service." }, { "code": null, "e": 1490, "s": 1361, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1555, "s": 1490, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2396, "s": 1555, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/text\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:text = \"Start Service\"\n android:textSize = \"25sp\"\n app:layout_constraintBottom_toBottomOf = \"parent\"\n app:layout_constraintLeft_toLeftOf = \"parent\"\n app:layout_constraintRight_toRightOf = \"parent\"\n app:layout_constraintTop_toTopOf = \"parent\" />\n</android.support.constraint.ConstraintLayout>" }, { "code": null, "e": 2522, "s": 2396, "text": "In the above code, we have taken text view, when user click on text view, it will start music service and stop music service." }, { "code": null, "e": 2579, "s": 2522, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4010, "s": 2579, "text": "package com.example.andy.myapplication;\nimport android.app.ActivityManager;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final TextView text = findViewById(R.id.text);\n text.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (isMyServiceRunning(service.class)) {\n text.setText(\"Stoped\");\n stopService(new Intent(MainActivity.this, service.class));\n } else {\n text.setText(\"Started\");\n startService(new Intent(MainActivity.this, service.class));\n }\n }\n });\n }\n private boolean isMyServiceRunning(Class<?> serviceClass) {\n ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);\n for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {\n if (serviceClass.getName().equals(service.service.getClassName())) {\n return true;\n }\n }\n return false;\n }\n}" }, { "code": null, "e": 4204, "s": 4010, "text": "In the above code to start and stop service. We have used intent and passed context and service class. Now create a service class in package folder as service.class and add the following code –" }, { "code": null, "e": 5123, "s": 4204, "text": "package com.example.andy.myapplication;\nimport android.app.Service;\nimport android.content.Intent;\nimport android.media.MediaPlayer;\nimport android.os.IBinder;\nimport android.widget.Toast;\npublic class service extends Service {\n MediaPlayer musicPlayer;\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n @Override\n public void onCreate() {\n super.onCreate();\n musicPlayer = MediaPlayer.create(this, R.raw.abc);\n musicPlayer.setLooping(false);\n }\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n Toast.makeText(this, \"Music Service started by user.\", Toast.LENGTH_LONG).show();\n musicPlayer.start();\n return START_STICKY;\n }\n @Override\n public void onDestroy() {\n super.onDestroy();\n musicPlayer.stop();\n Toast.makeText(this, \"Music Service destroyed by user.\", Toast.LENGTH_LONG).show();\n }\n}" }, { "code": null, "e": 5235, "s": 5123, "text": "In the above code we have music Player class and started music player and stopped music player as shown below –" }, { "code": null, "e": 5763, "s": 5235, "text": "@Override\npublic void onCreate() {\n super.onCreate();\n musicPlayer = MediaPlayer.create(this, R.raw.abc);\n musicPlayer.setLooping(false);\n}\n@Override\npublic int onStartCommand(Intent intent, int flags, int startId) {\n Toast.makeText(this, \"Music Service started by user.\", Toast.LENGTH_LONG).show();\n musicPlayer.start();\n return START_STICKY;\n}\n@Override\npublic void onDestroy() {\n super.onDestroy();\n musicPlayer.stop();\n Toast.makeText(this, \"Music Service destroyed by user.\", Toast.LENGTH_LONG).show();\n}" }, { "code": null, "e": 5811, "s": 5763, "text": "Step 4 − Add the following code to manifest.xml" }, { "code": null, "e": 6569, "s": 5811, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.andy.myapplication\">\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <service android:name = \".service\"/>\n </application>\n</manifest>" }, { "code": null, "e": 6916, "s": 6569, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 7023, "s": 6916, "text": "In the above result is an initial screen, Click on Text view, it will start music service as shown below –" }, { "code": null, "e": 7130, "s": 7023, "text": "In the above result, service is startd now click on text view, it will stop music service as shown below -" }, { "code": null, "e": 7170, "s": 7130, "text": "Click here to download the project code" } ]
Python | Prefix key match in dictionary - GeeksforGeeks
02 Aug, 2019 Sometimes, while working with dictionaries, we can have a problem in which we need to find the dictionary items that have some constraints on keys. One such constraint can be a prefix match on keys. Let’s discuss certain ways in which this task can be performed. Method #1 : Using dictionary comprehension + startswith()The combination of above two methods can be used to perform this particular task. In this, dictionary comprehension does the basic task of dictionary construction and startswith() performs the utility task of checking keys starting with specific prefix. # Python3 code to demonstrate working of# Prefix key match in dictionary# Using dictionary comprehension + startswith() # Initialize dictionarytest_dict = {'tough' : 1, 'to' : 2, 'do' : 3, 'todays' : 4, 'work' : 5} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Initialize prefix test_pref = 'to' # Using dictionary comprehension + startswith()# Prefix key match in dictionaryres = {key:val for key, val in test_dict.items() if key.startswith(test_pref)} # printing result print("Filtered dictionary keys are : " + str(res)) The original dictionary : {‘to’: 2, ‘tough’: 1, ‘work’: 5, ‘todays’: 4, ‘do’: 3}Filtered dictionary keys are : {‘to’: 2, ‘tough’: 1, ‘todays’: 4} Method #2 : Using map() + filter() + items() + startswith()This particular task can also be performed using the combination of above functions. The map function ties the filter logic of startswith() to each dictionary’s items extracted by items() # Python3 code to demonstrate working of# Prefix key match in dictionary# Using map() + filter() + items() + startswith() # Initialize dictionarytest_dict = {'tough' : 1, 'to' : 2, 'do' : 3, 'todays' : 4, 'work' : 5} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Initialize prefix test_pref = 'to' # Using map() + filter() + items() + startswith()# Prefix key match in dictionaryres = dict(filter(lambda item: item[0].startswith(test_pref), test_dict.items())) # printing result print("Filtered dictionary keys are : " + str(res)) The original dictionary : {‘to’: 2, ‘tough’: 1, ‘work’: 5, ‘todays’: 4, ‘do’: 3}Filtered dictionary keys are : {‘to’: 2, ‘tough’: 1, ‘todays’: 4} Python dictionary-programs Python Python Programs 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 Python program to convert a list to string Defaultdict in Python Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 24286, "s": 24258, "text": "\n02 Aug, 2019" }, { "code": null, "e": 24549, "s": 24286, "text": "Sometimes, while working with dictionaries, we can have a problem in which we need to find the dictionary items that have some constraints on keys. One such constraint can be a prefix match on keys. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 24860, "s": 24549, "text": "Method #1 : Using dictionary comprehension + startswith()The combination of above two methods can be used to perform this particular task. In this, dictionary comprehension does the basic task of dictionary construction and startswith() performs the utility task of checking keys starting with specific prefix." }, { "code": "# Python3 code to demonstrate working of# Prefix key match in dictionary# Using dictionary comprehension + startswith() # Initialize dictionarytest_dict = {'tough' : 1, 'to' : 2, 'do' : 3, 'todays' : 4, 'work' : 5} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # Initialize prefix test_pref = 'to' # Using dictionary comprehension + startswith()# Prefix key match in dictionaryres = {key:val for key, val in test_dict.items() if key.startswith(test_pref)} # printing result print(\"Filtered dictionary keys are : \" + str(res))", "e": 25448, "s": 24860, "text": null }, { "code": null, "e": 25594, "s": 25448, "text": "The original dictionary : {‘to’: 2, ‘tough’: 1, ‘work’: 5, ‘todays’: 4, ‘do’: 3}Filtered dictionary keys are : {‘to’: 2, ‘tough’: 1, ‘todays’: 4}" }, { "code": null, "e": 25843, "s": 25596, "text": "Method #2 : Using map() + filter() + items() + startswith()This particular task can also be performed using the combination of above functions. The map function ties the filter logic of startswith() to each dictionary’s items extracted by items()" }, { "code": "# Python3 code to demonstrate working of# Prefix key match in dictionary# Using map() + filter() + items() + startswith() # Initialize dictionarytest_dict = {'tough' : 1, 'to' : 2, 'do' : 3, 'todays' : 4, 'work' : 5} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # Initialize prefix test_pref = 'to' # Using map() + filter() + items() + startswith()# Prefix key match in dictionaryres = dict(filter(lambda item: item[0].startswith(test_pref), test_dict.items())) # printing result print(\"Filtered dictionary keys are : \" + str(res))", "e": 26460, "s": 25843, "text": null }, { "code": null, "e": 26606, "s": 26460, "text": "The original dictionary : {‘to’: 2, ‘tough’: 1, ‘work’: 5, ‘todays’: 4, ‘do’: 3}Filtered dictionary keys are : {‘to’: 2, ‘tough’: 1, ‘todays’: 4}" }, { "code": null, "e": 26633, "s": 26606, "text": "Python dictionary-programs" }, { "code": null, "e": 26640, "s": 26633, "text": "Python" }, { "code": null, "e": 26656, "s": 26640, "text": "Python Programs" }, { "code": null, "e": 26754, "s": 26656, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26763, "s": 26754, "text": "Comments" }, { "code": null, "e": 26776, "s": 26763, "text": "Old Comments" }, { "code": null, "e": 26794, "s": 26776, "text": "Python Dictionary" }, { "code": null, "e": 26829, "s": 26794, "text": "Read a file line by line in Python" }, { "code": null, "e": 26851, "s": 26829, "text": "Enumerate() in Python" }, { "code": null, "e": 26883, "s": 26851, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26913, "s": 26883, "text": "Iterate over a list in Python" }, { "code": null, "e": 26956, "s": 26913, "text": "Python program to convert a list to string" }, { "code": null, "e": 26978, "s": 26956, "text": "Defaultdict in Python" }, { "code": null, "e": 27024, "s": 26978, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27062, "s": 27024, "text": "Python | Convert a list to dictionary" } ]
Pandas Tutorial
Pandas is a Python library. Pandas is used to analyze data. We have created 14 tutorial pages for you to learn more about Pandas. Starting with a basic introduction and ends up with cleaning and plotting data: Test your Pandas skills with a quiz test. Start Pandas Quiz Insert the correct Pandas method to create a Series. pd.(mylist) Start the Exercise In our "Try it Yourself" editor, you can use the Pandas module, and modify the code to see the result. Load a CSV file into a Pandas DataFrame: Click on the "Try it Yourself" button to see how it works. We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 28, "s": 0, "text": "Pandas is a Python library." }, { "code": null, "e": 60, "s": 28, "text": "Pandas is used to analyze data." }, { "code": null, "e": 130, "s": 60, "text": "We have created 14 tutorial pages for you to learn more about Pandas." }, { "code": null, "e": 210, "s": 130, "text": "Starting with a basic introduction and ends up with cleaning and plotting data:" }, { "code": null, "e": 252, "s": 210, "text": "Test your Pandas skills with a quiz test." }, { "code": null, "e": 270, "s": 252, "text": "Start Pandas Quiz" }, { "code": null, "e": 323, "s": 270, "text": "Insert the correct Pandas method to create a Series." }, { "code": null, "e": 336, "s": 323, "text": "pd.(mylist)\n" }, { "code": null, "e": 355, "s": 336, "text": "Start the Exercise" }, { "code": null, "e": 458, "s": 355, "text": "In our \"Try it Yourself\" editor, you can use the Pandas module, and modify the code to see the result." }, { "code": null, "e": 499, "s": 458, "text": "Load a CSV file into a Pandas DataFrame:" }, { "code": null, "e": 558, "s": 499, "text": "Click on the \"Try it Yourself\" button to see how it works." }, { "code": null, "e": 591, "s": 558, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 633, "s": 591, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 740, "s": 633, "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": 759, "s": 740, "text": "help@w3schools.com" } ]
Longest Path in a Directed Acyclic Graph - GeeksforGeeks
13 Sep, 2021 Given a Weighted Directed Acyclic Graph (DAG) and a source vertex s in it, find the longest distances from s to all other vertices in the given graph.The longest path problem for a general graph is not as easy as the shortest path problem because the longest path problem doesn’t have optimal substructure property. In fact, the Longest Path problem is NP-Hard for a general graph. However, the longest path problem has a linear time solution for directed acyclic graphs. The idea is similar to linear time solution for shortest path in a directed acyclic graph., we use Topological Sorting. We initialize distances to all vertices as minus infinite and distance to source as 0, then we find a topological sorting of the graph. Topological Sorting of a graph represents a linear ordering of the graph (See below, figure (b) is a linear representation of figure (a) ). Once we have topological order (or linear representation), we one by one process all vertices in topological order. For every vertex being processed, we update distances of its adjacent using distance of current vertex.Following figure shows step by step process of finding longest paths. Following is complete algorithm for finding longest distances. 1) Initialize dist[] = {NINF, NINF, ....} and dist[s] = 0 where s is the source vertex. Here NINF means negative infinite. 2) Create a topological order of all vertices. 3) Do following for every vertex u in topological order. ...........Do following for every adjacent vertex v of u ..................if (dist[v] < dist[u] + weight(u, v)) ...........................dist[v] = dist[u] + weight(u, v) Following is C++ implementation of the above algorithm. CPP Java Python3 // A C++ program to find single source longest distances// in a DAG#include <iostream>#include <limits.h>#include <list>#include <stack>#define NINF INT_MINusing namespace std; // Graph is represented using adjacency list. Every// node of adjacency list contains vertex number of// the vertex to which edge connects. It also// contains weight of the edgeclass AdjListNode { int v; int weight; public: AdjListNode(int _v, int _w) { v = _v; weight = _w; } int getV() { return v; } int getWeight() { return weight; }}; // Class to represent a graph using adjacency list// representationclass Graph { int V; // No. of vertices' // Pointer to an array containing adjacency lists list<AdjListNode>* adj; // A function used by longestPath void topologicalSortUtil(int v, bool visited[], stack<int>& Stack); public: Graph(int V); // Constructor ~Graph(); // Destructor // function to add an edge to graph void addEdge(int u, int v, int weight); // Finds longest distances from given source vertex void longestPath(int s);}; Graph::Graph(int V) // Constructor{ this->V = V; adj = new list<AdjListNode>[V];} Graph::~Graph() // Destructor{ delete [] adj;} void Graph::addEdge(int u, int v, int weight){ AdjListNode node(v, weight); adj[u].push_back(node); // Add v to u's list} // A recursive function used by longestPath. See below// link for details// https:// www.geeksforgeeks.org/topological-sorting/void Graph::topologicalSortUtil(int v, bool visited[], stack<int>& Stack){ // Mark the current node as visited visited[v] = true; // Recur for all the vertices adjacent to this vertex list<AdjListNode>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) { AdjListNode node = *i; if (!visited[node.getV()]) topologicalSortUtil(node.getV(), visited, Stack); } // Push current vertex to stack which stores topological // sort Stack.push(v);} // The function to find longest distances from a given vertex.// It uses recursive topologicalSortUtil() to get topological// sorting.void Graph::longestPath(int s){ stack<int> Stack; int dist[V]; // Mark all the vertices as not visited bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function to store Topological // Sort starting from all vertices one by one for (int i = 0; i < V; i++) if (visited[i] == false) topologicalSortUtil(i, visited, Stack); // Initialize distances to all vertices as infinite and // distance to source as 0 for (int i = 0; i < V; i++) dist[i] = NINF; dist[s] = 0; // Process vertices in topological order while (Stack.empty() == false) { // Get the next vertex from topological order int u = Stack.top(); Stack.pop(); // Update distances of all adjacent vertices list<AdjListNode>::iterator i; if (dist[u] != NINF) { for (i = adj[u].begin(); i != adj[u].end(); ++i){ if (dist[i->getV()] < dist[u] + i->getWeight()) dist[i->getV()] = dist[u] + i->getWeight(); } } } // Print the calculated longest distances for (int i = 0; i < V; i++) (dist[i] == NINF) ? cout << "INF " : cout << dist[i] << " "; delete [] visited;} // Driver program to test above functionsint main(){ // Create a graph given in the above diagram. // Here vertex numbers are 0, 1, 2, 3, 4, 5 with // following mappings: // 0=r, 1=s, 2=t, 3=x, 4=y, 5=z Graph g(6); g.addEdge(0, 1, 5); g.addEdge(0, 2, 3); g.addEdge(1, 3, 6); g.addEdge(1, 2, 2); g.addEdge(2, 4, 4); g.addEdge(2, 5, 2); g.addEdge(2, 3, 7); g.addEdge(3, 5, 1); g.addEdge(3, 4, -1); g.addEdge(4, 5, -2); int s = 1; cout << "Following are longest distances from " "source vertex " << s << " \n"; g.longestPath(s); return 0;} // A Java program to find single source longest distances// in a DAGimport java.util.*;class GFG{ // Graph is represented using adjacency list. Every // node of adjacency list contains vertex number of // the vertex to which edge connects. It also // contains weight of the edge static class AdjListNode { int v; int weight; AdjListNode(int _v, int _w) { v = _v; weight = _w; } int getV() { return v; } int getWeight() { return weight; } } // Class to represent a graph using adjacency list // representation static class Graph { int V; // No. of vertices' // Pointer to an array containing adjacency lists ArrayList<ArrayList<AdjListNode>> adj; Graph(int V) // Constructor { this.V = V; adj = new ArrayList<ArrayList<AdjListNode>>(V); for(int i = 0; i < V; i++){ adj.add(new ArrayList<AdjListNode>()); } } void addEdge(int u, int v, int weight) { AdjListNode node = new AdjListNode(v, weight); adj.get(u).add(node); // Add v to u's list } // A recursive function used by longestPath. See below // link for details // https:// www.geeksforgeeks.org/topological-sorting/ void topologicalSortUtil(int v, boolean visited[], Stack<Integer> stack) { // Mark the current node as visited visited[v] = true; // Recur for all the vertices adjacent to this vertex for (int i = 0; i<adj.get(v).size(); i++) { AdjListNode node = adj.get(v).get(i); if (!visited[node.getV()]) topologicalSortUtil(node.getV(), visited, stack); } // Push current vertex to stack which stores topological // sort stack.push(v); } // The function to find longest distances from a given vertex. // It uses recursive topologicalSortUtil() to get topological // sorting. void longestPath(int s) { Stack<Integer> stack = new Stack<Integer>(); int dist[] = new int[V]; // Mark all the vertices as not visited boolean visited[] = new boolean[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function to store Topological // Sort starting from all vertices one by one for (int i = 0; i < V; i++) if (visited[i] == false) topologicalSortUtil(i, visited, stack); // Initialize distances to all vertices as infinite and // distance to source as 0 for (int i = 0; i < V; i++) dist[i] = Integer.MIN_VALUE; dist[s] = 0; // Process vertices in topological order while (stack.isEmpty() == false) { // Get the next vertex from topological order int u = stack.peek(); stack.pop(); // Update distances of all adjacent vertices ; if (dist[u] != Integer.MIN_VALUE) { for (int i = 0; i<adj.get(u).size(); i++) { AdjListNode node = adj.get(u).get(i); if (dist[node.getV()] < dist[u] + node.getWeight()) dist[node.getV()] = dist[u] + node.getWeight(); } } } // Print the calculated longest distances for (int i = 0; i < V; i++) if(dist[i] == Integer.MIN_VALUE) System.out.print("INF "); else System.out.print(dist[i] + " "); } } // Driver program to test above functions public static void main(String args[]) { // Create a graph given in the above diagram. // Here vertex numbers are 0, 1, 2, 3, 4, 5 with // following mappings: // 0=r, 1=s, 2=t, 3=x, 4=y, 5=z Graph g = new Graph(6); g.addEdge(0, 1, 5); g.addEdge(0, 2, 3); g.addEdge(1, 3, 6); g.addEdge(1, 2, 2); g.addEdge(2, 4, 4); g.addEdge(2, 5, 2); g.addEdge(2, 3, 7); g.addEdge(3, 5, 1); g.addEdge(3, 4, -1); g.addEdge(4, 5, -2); int s = 1; System.out.print("Following are longest distances from source vertex "+ s + " \n" ); g.longestPath(s); }} // This code is contribute by adityapande88. # A recursive function used by longestPath. See below# link for details# https:#www.geeksforgeeks.org/topological-sorting/def topologicalSortUtil(v): global Stack, visited, adj visited[v] = True # Recur for all the vertices adjacent to this vertex # list<AdjListNode>::iterator i for i in adj[v]: if (not visited[i[0]]): topologicalSortUtil(i[0]) # Push current vertex to stack which stores topological # sort Stack.append(v) # The function to find longest distances from a given vertex.# It uses recursive topologicalSortUtil() to get topological# sorting.def longestPath(s): global Stack, visited, adj, V dist = [-10**9 for i in range(V)] # Call the recursive helper function to store Topological # Sort starting from all vertices one by one for i in range(V): if (visited[i] == False): topologicalSortUtil(i) # print(Stack) # Initialize distances to all vertices as infinite and # distance to source as 0 dist[s] = 0 # Stack.append(1) # Process vertices in topological order while (len(Stack) > 0): # Get the next vertex from topological order u = Stack[-1] del Stack[-1] #print(u) # Update distances of all adjacent vertices # list<AdjListNode>::iterator i if (dist[u] != 10**9): for i in adj[u]: # print(u, i) if (dist[i[0]] < dist[u] + i[1]): dist[i[0]] = dist[u] + i[1] # Print calculated longest distances # print(dist) for i in range(V): print("INF ",end="") if (dist[i] == -10**9) else print(dist[i],end=" ") # Driver codeif __name__ == '__main__': V, Stack, visited = 6, [], [False for i in range(7)] adj = [[] for i in range(7)] # Create a graph given in the above diagram. # Here vertex numbers are 0, 1, 2, 3, 4, 5 with # following mappings: # 0=r, 1=s, 2=t, 3=x, 4=y, 5=z adj[0].append([1, 5]) adj[0].append([2, 3]) adj[1].append([3, 6]) adj[1].append([2, 2]) adj[2].append([4, 4]) adj[2].append([5, 2]) adj[2].append([3, 7]) adj[3].append([5, 1]) adj[3].append([4, -1]) adj[4].append([5, -2]) s = 1 print("Following are longest distances from source vertex ",s) longestPath(s) # This code is contributed by mohit kumar 29. Output: Following are longest distances from source vertex 1 INF 0 2 9 8 10 Time Complexity: Time complexity of topological sorting is O(V+E). After finding topological order, the algorithm process all vertices and for every vertex, it runs a loop for all adjacent vertices. Total adjacent vertices in a graph is O(E). So the inner loop runs O(V+E) times. Therefore, overall time complexity of this algorithm is O(V+E).Exercise: The above solution print longest distances, extend the code to print paths also. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Rohit0803 pranith maddineni joelm mohit kumar 29 adityapande88 surindertarika1234 khushboogoyal499 anikaseth98 Microfocus Shortest Path Topological Sorting Graph Graph Shortest Path Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Traveling Salesman Problem (TSP) Implementation Ford-Fulkerson Algorithm for Maximum Flow Problem Shortest path in an unweighted graph Strongly Connected Components Union-Find Algorithm | Set 2 (Union By Rank and Path Compression) Best First Search (Informed Search) Find the number of islands | Set 1 (Using DFS)
[ { "code": null, "e": 34594, "s": 34566, "text": "\n13 Sep, 2021" }, { "code": null, "e": 35752, "s": 34594, "text": "Given a Weighted Directed Acyclic Graph (DAG) and a source vertex s in it, find the longest distances from s to all other vertices in the given graph.The longest path problem for a general graph is not as easy as the shortest path problem because the longest path problem doesn’t have optimal substructure property. In fact, the Longest Path problem is NP-Hard for a general graph. However, the longest path problem has a linear time solution for directed acyclic graphs. The idea is similar to linear time solution for shortest path in a directed acyclic graph., we use Topological Sorting. We initialize distances to all vertices as minus infinite and distance to source as 0, then we find a topological sorting of the graph. Topological Sorting of a graph represents a linear ordering of the graph (See below, figure (b) is a linear representation of figure (a) ). Once we have topological order (or linear representation), we one by one process all vertices in topological order. For every vertex being processed, we update distances of its adjacent using distance of current vertex.Following figure shows step by step process of finding longest paths. " }, { "code": null, "e": 36217, "s": 35752, "text": "Following is complete algorithm for finding longest distances. 1) Initialize dist[] = {NINF, NINF, ....} and dist[s] = 0 where s is the source vertex. Here NINF means negative infinite. 2) Create a topological order of all vertices. 3) Do following for every vertex u in topological order. ...........Do following for every adjacent vertex v of u ..................if (dist[v] < dist[u] + weight(u, v)) ...........................dist[v] = dist[u] + weight(u, v) " }, { "code": null, "e": 36274, "s": 36217, "text": "Following is C++ implementation of the above algorithm. " }, { "code": null, "e": 36278, "s": 36274, "text": "CPP" }, { "code": null, "e": 36283, "s": 36278, "text": "Java" }, { "code": null, "e": 36291, "s": 36283, "text": "Python3" }, { "code": "// A C++ program to find single source longest distances// in a DAG#include <iostream>#include <limits.h>#include <list>#include <stack>#define NINF INT_MINusing namespace std; // Graph is represented using adjacency list. Every// node of adjacency list contains vertex number of// the vertex to which edge connects. It also// contains weight of the edgeclass AdjListNode { int v; int weight; public: AdjListNode(int _v, int _w) { v = _v; weight = _w; } int getV() { return v; } int getWeight() { return weight; }}; // Class to represent a graph using adjacency list// representationclass Graph { int V; // No. of vertices' // Pointer to an array containing adjacency lists list<AdjListNode>* adj; // A function used by longestPath void topologicalSortUtil(int v, bool visited[], stack<int>& Stack); public: Graph(int V); // Constructor ~Graph(); // Destructor // function to add an edge to graph void addEdge(int u, int v, int weight); // Finds longest distances from given source vertex void longestPath(int s);}; Graph::Graph(int V) // Constructor{ this->V = V; adj = new list<AdjListNode>[V];} Graph::~Graph() // Destructor{ delete [] adj;} void Graph::addEdge(int u, int v, int weight){ AdjListNode node(v, weight); adj[u].push_back(node); // Add v to u's list} // A recursive function used by longestPath. See below// link for details// https:// www.geeksforgeeks.org/topological-sorting/void Graph::topologicalSortUtil(int v, bool visited[], stack<int>& Stack){ // Mark the current node as visited visited[v] = true; // Recur for all the vertices adjacent to this vertex list<AdjListNode>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) { AdjListNode node = *i; if (!visited[node.getV()]) topologicalSortUtil(node.getV(), visited, Stack); } // Push current vertex to stack which stores topological // sort Stack.push(v);} // The function to find longest distances from a given vertex.// It uses recursive topologicalSortUtil() to get topological// sorting.void Graph::longestPath(int s){ stack<int> Stack; int dist[V]; // Mark all the vertices as not visited bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function to store Topological // Sort starting from all vertices one by one for (int i = 0; i < V; i++) if (visited[i] == false) topologicalSortUtil(i, visited, Stack); // Initialize distances to all vertices as infinite and // distance to source as 0 for (int i = 0; i < V; i++) dist[i] = NINF; dist[s] = 0; // Process vertices in topological order while (Stack.empty() == false) { // Get the next vertex from topological order int u = Stack.top(); Stack.pop(); // Update distances of all adjacent vertices list<AdjListNode>::iterator i; if (dist[u] != NINF) { for (i = adj[u].begin(); i != adj[u].end(); ++i){ if (dist[i->getV()] < dist[u] + i->getWeight()) dist[i->getV()] = dist[u] + i->getWeight(); } } } // Print the calculated longest distances for (int i = 0; i < V; i++) (dist[i] == NINF) ? cout << \"INF \" : cout << dist[i] << \" \"; delete [] visited;} // Driver program to test above functionsint main(){ // Create a graph given in the above diagram. // Here vertex numbers are 0, 1, 2, 3, 4, 5 with // following mappings: // 0=r, 1=s, 2=t, 3=x, 4=y, 5=z Graph g(6); g.addEdge(0, 1, 5); g.addEdge(0, 2, 3); g.addEdge(1, 3, 6); g.addEdge(1, 2, 2); g.addEdge(2, 4, 4); g.addEdge(2, 5, 2); g.addEdge(2, 3, 7); g.addEdge(3, 5, 1); g.addEdge(3, 4, -1); g.addEdge(4, 5, -2); int s = 1; cout << \"Following are longest distances from \" \"source vertex \" << s << \" \\n\"; g.longestPath(s); return 0;}", "e": 40413, "s": 36291, "text": null }, { "code": "// A Java program to find single source longest distances// in a DAGimport java.util.*;class GFG{ // Graph is represented using adjacency list. Every // node of adjacency list contains vertex number of // the vertex to which edge connects. It also // contains weight of the edge static class AdjListNode { int v; int weight; AdjListNode(int _v, int _w) { v = _v; weight = _w; } int getV() { return v; } int getWeight() { return weight; } } // Class to represent a graph using adjacency list // representation static class Graph { int V; // No. of vertices' // Pointer to an array containing adjacency lists ArrayList<ArrayList<AdjListNode>> adj; Graph(int V) // Constructor { this.V = V; adj = new ArrayList<ArrayList<AdjListNode>>(V); for(int i = 0; i < V; i++){ adj.add(new ArrayList<AdjListNode>()); } } void addEdge(int u, int v, int weight) { AdjListNode node = new AdjListNode(v, weight); adj.get(u).add(node); // Add v to u's list } // A recursive function used by longestPath. See below // link for details // https:// www.geeksforgeeks.org/topological-sorting/ void topologicalSortUtil(int v, boolean visited[], Stack<Integer> stack) { // Mark the current node as visited visited[v] = true; // Recur for all the vertices adjacent to this vertex for (int i = 0; i<adj.get(v).size(); i++) { AdjListNode node = adj.get(v).get(i); if (!visited[node.getV()]) topologicalSortUtil(node.getV(), visited, stack); } // Push current vertex to stack which stores topological // sort stack.push(v); } // The function to find longest distances from a given vertex. // It uses recursive topologicalSortUtil() to get topological // sorting. void longestPath(int s) { Stack<Integer> stack = new Stack<Integer>(); int dist[] = new int[V]; // Mark all the vertices as not visited boolean visited[] = new boolean[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function to store Topological // Sort starting from all vertices one by one for (int i = 0; i < V; i++) if (visited[i] == false) topologicalSortUtil(i, visited, stack); // Initialize distances to all vertices as infinite and // distance to source as 0 for (int i = 0; i < V; i++) dist[i] = Integer.MIN_VALUE; dist[s] = 0; // Process vertices in topological order while (stack.isEmpty() == false) { // Get the next vertex from topological order int u = stack.peek(); stack.pop(); // Update distances of all adjacent vertices ; if (dist[u] != Integer.MIN_VALUE) { for (int i = 0; i<adj.get(u).size(); i++) { AdjListNode node = adj.get(u).get(i); if (dist[node.getV()] < dist[u] + node.getWeight()) dist[node.getV()] = dist[u] + node.getWeight(); } } } // Print the calculated longest distances for (int i = 0; i < V; i++) if(dist[i] == Integer.MIN_VALUE) System.out.print(\"INF \"); else System.out.print(dist[i] + \" \"); } } // Driver program to test above functions public static void main(String args[]) { // Create a graph given in the above diagram. // Here vertex numbers are 0, 1, 2, 3, 4, 5 with // following mappings: // 0=r, 1=s, 2=t, 3=x, 4=y, 5=z Graph g = new Graph(6); g.addEdge(0, 1, 5); g.addEdge(0, 2, 3); g.addEdge(1, 3, 6); g.addEdge(1, 2, 2); g.addEdge(2, 4, 4); g.addEdge(2, 5, 2); g.addEdge(2, 3, 7); g.addEdge(3, 5, 1); g.addEdge(3, 4, -1); g.addEdge(4, 5, -2); int s = 1; System.out.print(\"Following are longest distances from source vertex \"+ s + \" \\n\" ); g.longestPath(s); }} // This code is contribute by adityapande88.", "e": 44425, "s": 40413, "text": null }, { "code": "# A recursive function used by longestPath. See below# link for details# https:#www.geeksforgeeks.org/topological-sorting/def topologicalSortUtil(v): global Stack, visited, adj visited[v] = True # Recur for all the vertices adjacent to this vertex # list<AdjListNode>::iterator i for i in adj[v]: if (not visited[i[0]]): topologicalSortUtil(i[0]) # Push current vertex to stack which stores topological # sort Stack.append(v) # The function to find longest distances from a given vertex.# It uses recursive topologicalSortUtil() to get topological# sorting.def longestPath(s): global Stack, visited, adj, V dist = [-10**9 for i in range(V)] # Call the recursive helper function to store Topological # Sort starting from all vertices one by one for i in range(V): if (visited[i] == False): topologicalSortUtil(i) # print(Stack) # Initialize distances to all vertices as infinite and # distance to source as 0 dist[s] = 0 # Stack.append(1) # Process vertices in topological order while (len(Stack) > 0): # Get the next vertex from topological order u = Stack[-1] del Stack[-1] #print(u) # Update distances of all adjacent vertices # list<AdjListNode>::iterator i if (dist[u] != 10**9): for i in adj[u]: # print(u, i) if (dist[i[0]] < dist[u] + i[1]): dist[i[0]] = dist[u] + i[1] # Print calculated longest distances # print(dist) for i in range(V): print(\"INF \",end=\"\") if (dist[i] == -10**9) else print(dist[i],end=\" \") # Driver codeif __name__ == '__main__': V, Stack, visited = 6, [], [False for i in range(7)] adj = [[] for i in range(7)] # Create a graph given in the above diagram. # Here vertex numbers are 0, 1, 2, 3, 4, 5 with # following mappings: # 0=r, 1=s, 2=t, 3=x, 4=y, 5=z adj[0].append([1, 5]) adj[0].append([2, 3]) adj[1].append([3, 6]) adj[1].append([2, 2]) adj[2].append([4, 4]) adj[2].append([5, 2]) adj[2].append([3, 7]) adj[3].append([5, 1]) adj[3].append([4, -1]) adj[4].append([5, -2]) s = 1 print(\"Following are longest distances from source vertex \",s) longestPath(s) # This code is contributed by mohit kumar 29.", "e": 46766, "s": 44425, "text": null }, { "code": null, "e": 46775, "s": 46766, "text": "Output: " }, { "code": null, "e": 46843, "s": 46775, "text": "Following are longest distances from source vertex 1\nINF 0 2 9 8 10" }, { "code": null, "e": 47279, "s": 46843, "text": "Time Complexity: Time complexity of topological sorting is O(V+E). After finding topological order, the algorithm process all vertices and for every vertex, it runs a loop for all adjacent vertices. Total adjacent vertices in a graph is O(E). So the inner loop runs O(V+E) times. Therefore, overall time complexity of this algorithm is O(V+E).Exercise: The above solution print longest distances, extend the code to print paths also. " }, { "code": null, "e": 47404, "s": 47279, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 47414, "s": 47404, "text": "Rohit0803" }, { "code": null, "e": 47432, "s": 47414, "text": "pranith maddineni" }, { "code": null, "e": 47438, "s": 47432, "text": "joelm" }, { "code": null, "e": 47453, "s": 47438, "text": "mohit kumar 29" }, { "code": null, "e": 47467, "s": 47453, "text": "adityapande88" }, { "code": null, "e": 47486, "s": 47467, "text": "surindertarika1234" }, { "code": null, "e": 47503, "s": 47486, "text": "khushboogoyal499" }, { "code": null, "e": 47515, "s": 47503, "text": "anikaseth98" }, { "code": null, "e": 47526, "s": 47515, "text": "Microfocus" }, { "code": null, "e": 47540, "s": 47526, "text": "Shortest Path" }, { "code": null, "e": 47560, "s": 47540, "text": "Topological Sorting" }, { "code": null, "e": 47566, "s": 47560, "text": "Graph" }, { "code": null, "e": 47572, "s": 47566, "text": "Graph" }, { "code": null, "e": 47586, "s": 47572, "text": "Shortest Path" }, { "code": null, "e": 47684, "s": 47586, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47715, "s": 47684, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 47748, "s": 47715, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 47816, "s": 47748, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 47864, "s": 47816, "text": "Traveling Salesman Problem (TSP) Implementation" }, { "code": null, "e": 47914, "s": 47864, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 47951, "s": 47914, "text": "Shortest path in an unweighted graph" }, { "code": null, "e": 47981, "s": 47951, "text": "Strongly Connected Components" }, { "code": null, "e": 48047, "s": 47981, "text": "Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)" }, { "code": null, "e": 48083, "s": 48047, "text": "Best First Search (Informed Search)" } ]
Get the number of rows and number of columns in Pandas Dataframe - GeeksforGeeks
02 Jul, 2020 Pandas provide data analysts a variety of pre-defined functions to Get the number of rows and columns in a data frame. In this article, we will learn about the syntax and implementation of few such functions. axes() method in pandas allows to get the number of rows and columns in a go. It accepts the argument ‘0’ for rows and ‘1’ for columns. Syntax: df.axes[0 or 1] Parameters:0: for number of Rows1: for number of columns Example: # import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi'], 'Age' : [23, 21, 22, 21], 'University' : ['BHU', 'JNU', 'DU', 'BHU'],} # creating a Dataframe object df = pd.DataFrame(details, columns = ['Name', 'Age', 'University'],\ index = ['a', 'b', 'c', 'd']) # Get the number of rows and columnsrows = len(df.axes[0])cols = len(df.axes[1]) # Print the number of rows and columnsprint("Number of Rows: " + str(rows))print("Number of Columns: " + str(cols)) Output: Number of Rows: 4 Number of Columns: 3 df.info() method provides all the information about the data frame, including the number of rows and columns. Syntax: df.info Example: # import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi'], 'Age' : [23, 21, 22, 21], 'University' : ['BHU', 'JNU', 'DU', 'BHU'],} # creating a Dataframe object df = pd.DataFrame(details, columns = ['Name', 'Age', 'University'], index = ['a', 'b', 'c', 'd']) # Get the info of data framedf.info() Output: Here in the above code, the value in the Index gives the number of rows and the value in Data columns gives the number of columns. len() method is used to get the number of rows and number of columns individually. Syntax: len(df) and len(df.columns) Example 1: Get the number of rows # import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi'], 'Age' : [23, 21, 22, 21], 'University' : ['BHU', 'JNU', 'DU', 'BHU'],} # creating a Dataframe object df = pd.DataFrame(details, columns = ['Name', 'Age', 'University'], index = ['a', 'b', 'c', 'd']) # Get the number of rowsprint("Number of Rows:", len(df)) Output: Number of Rows: 4 Example 2: Get the number of columns # import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi'], 'Age' : [23, 21, 22, 21], 'University' : ['BHU', 'JNU', 'DU', 'BHU'],} # creating a Dataframe object df = pd.DataFrame(details, columns = ['Name', 'Age', 'University'], index = ['a', 'b', 'c', 'd']) # Get the number of columnsprint("Number of Columns:", len(df.columns)) Output: Number of Columns: 3 df.shape() method returns the number of rows and columns in the form of a tuple. Example: # import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi'], 'Age' : [23, 21, 22, 21], 'University' : ['BHU', 'JNU', 'DU', 'BHU'],} # creating a Dataframe object df = pd.DataFrame(details, columns = ['Name', 'Age', 'University'], index = ['a', 'b', 'c', 'd']) # Get the number of Rows and columnsdf.shape Output: (4, 3) Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n02 Jul, 2020" }, { "code": null, "e": 24501, "s": 24292, "text": "Pandas provide data analysts a variety of pre-defined functions to Get the number of rows and columns in a data frame. In this article, we will learn about the syntax and implementation of few such functions." }, { "code": null, "e": 24637, "s": 24501, "text": "axes() method in pandas allows to get the number of rows and columns in a go. It accepts the argument ‘0’ for rows and ‘1’ for columns." }, { "code": null, "e": 24661, "s": 24637, "text": "Syntax: df.axes[0 or 1]" }, { "code": null, "e": 24718, "s": 24661, "text": "Parameters:0: for number of Rows1: for number of columns" }, { "code": null, "e": 24727, "s": 24718, "text": "Example:" }, { "code": "# import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi'], 'Age' : [23, 21, 22, 21], 'University' : ['BHU', 'JNU', 'DU', 'BHU'],} # creating a Dataframe object df = pd.DataFrame(details, columns = ['Name', 'Age', 'University'],\\ index = ['a', 'b', 'c', 'd']) # Get the number of rows and columnsrows = len(df.axes[0])cols = len(df.axes[1]) # Print the number of rows and columnsprint(\"Number of Rows: \" + str(rows))print(\"Number of Columns: \" + str(cols))", "e": 25310, "s": 24727, "text": null }, { "code": null, "e": 25318, "s": 25310, "text": "Output:" }, { "code": null, "e": 25358, "s": 25318, "text": "Number of Rows: 4\nNumber of Columns: 3\n" }, { "code": null, "e": 25468, "s": 25358, "text": "df.info() method provides all the information about the data frame, including the number of rows and columns." }, { "code": null, "e": 25476, "s": 25468, "text": "Syntax:" }, { "code": null, "e": 25484, "s": 25476, "text": "df.info" }, { "code": null, "e": 25493, "s": 25484, "text": "Example:" }, { "code": "# import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi'], 'Age' : [23, 21, 22, 21], 'University' : ['BHU', 'JNU', 'DU', 'BHU'],} # creating a Dataframe object df = pd.DataFrame(details, columns = ['Name', 'Age', 'University'], index = ['a', 'b', 'c', 'd']) # Get the info of data framedf.info()", "e": 25915, "s": 25493, "text": null }, { "code": null, "e": 25923, "s": 25915, "text": "Output:" }, { "code": null, "e": 26054, "s": 25923, "text": "Here in the above code, the value in the Index gives the number of rows and the value in Data columns gives the number of columns." }, { "code": null, "e": 26137, "s": 26054, "text": "len() method is used to get the number of rows and number of columns individually." }, { "code": null, "e": 26145, "s": 26137, "text": "Syntax:" }, { "code": null, "e": 26173, "s": 26145, "text": "len(df)\nand\nlen(df.columns)" }, { "code": null, "e": 26207, "s": 26173, "text": "Example 1: Get the number of rows" }, { "code": "# import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi'], 'Age' : [23, 21, 22, 21], 'University' : ['BHU', 'JNU', 'DU', 'BHU'],} # creating a Dataframe object df = pd.DataFrame(details, columns = ['Name', 'Age', 'University'], index = ['a', 'b', 'c', 'd']) # Get the number of rowsprint(\"Number of Rows:\", len(df))", "e": 26649, "s": 26207, "text": null }, { "code": null, "e": 26657, "s": 26649, "text": "Output:" }, { "code": null, "e": 26676, "s": 26657, "text": "Number of Rows: 4\n" }, { "code": null, "e": 26713, "s": 26676, "text": "Example 2: Get the number of columns" }, { "code": "# import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi'], 'Age' : [23, 21, 22, 21], 'University' : ['BHU', 'JNU', 'DU', 'BHU'],} # creating a Dataframe object df = pd.DataFrame(details, columns = ['Name', 'Age', 'University'], index = ['a', 'b', 'c', 'd']) # Get the number of columnsprint(\"Number of Columns:\", len(df.columns))", "e": 27169, "s": 26713, "text": null }, { "code": null, "e": 27177, "s": 27169, "text": "Output:" }, { "code": null, "e": 27199, "s": 27177, "text": "Number of Columns: 3\n" }, { "code": null, "e": 27280, "s": 27199, "text": "df.shape() method returns the number of rows and columns in the form of a tuple." }, { "code": null, "e": 27289, "s": 27280, "text": "Example:" }, { "code": "# import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi'], 'Age' : [23, 21, 22, 21], 'University' : ['BHU', 'JNU', 'DU', 'BHU'],} # creating a Dataframe object df = pd.DataFrame(details, columns = ['Name', 'Age', 'University'], index = ['a', 'b', 'c', 'd']) # Get the number of Rows and columnsdf.shape", "e": 27718, "s": 27289, "text": null }, { "code": null, "e": 27726, "s": 27718, "text": "Output:" }, { "code": null, "e": 27733, "s": 27726, "text": "(4, 3)" }, { "code": null, "e": 27757, "s": 27733, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27771, "s": 27757, "text": "Python-pandas" }, { "code": null, "e": 27778, "s": 27771, "text": "Python" }, { "code": null, "e": 27876, "s": 27778, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27908, "s": 27876, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27964, "s": 27908, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28006, "s": 27964, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28048, "s": 28006, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28070, "s": 28048, "text": "Defaultdict in Python" }, { "code": null, "e": 28109, "s": 28070, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28140, "s": 28109, "text": "Python | os.path.join() method" }, { "code": null, "e": 28195, "s": 28140, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28224, "s": 28195, "text": "Create a directory in Python" } ]
PHP Tags
A PHP code script is a text file having .php extension and is stored on web server. The PHP parser on server looks for special sequence of characters <?php and ?>. These are called PHP's opening and closing tags. Statements witihn these two are interpreted by the parser. PHP script within these tags can be embedded in HTML document, so that embedded code is executed on server, leaving rest of the document to be processed by client browser's HTML parser. <?php //one or more PHP statements .. .. ?> PHP allows a using a shorter representation of opening tag <? instead of cannonical usage <?php if it s enabled in php.ini file by enabling short_open_tag in php.ini file <? //one or more PHP statements .. .. ?> This setting is recommended to be Off for production environment. Use of ASP style tags <%, %> and <script language="PHP"> has been discontinued since PHP 7.0 Following example shows use of PHP tags Live Demo <?php //cannonical PHP tags echo "Hello World"; ?> This will produce following result − Hello World PHP supports a short echo tag <?= which is equivalent to the more verbose <?php echo. Live Demo <?= "Hello World"; ?> This will produce following result − Hello World Example using short tags Live Demo <?php //set short_open_tag=on echo "Hello World"; ?> This will produce following result − Hello World
[ { "code": null, "e": 1520, "s": 1062, "text": "A PHP code script is a text file having .php extension and is stored on web server. The PHP parser on server looks for special sequence of characters <?php and ?>. These are called PHP's opening and closing tags. Statements witihn these two are interpreted by the parser. PHP script within these tags can be embedded in HTML document, so that embedded code is executed on server, leaving rest of the document to be processed by client browser's HTML parser." }, { "code": null, "e": 1564, "s": 1520, "text": "<?php\n//one or more PHP statements\n..\n..\n?>" }, { "code": null, "e": 1735, "s": 1564, "text": "PHP allows a using a shorter representation of opening tag <? instead of cannonical usage <?php if it s enabled in php.ini file by enabling short_open_tag in php.ini file" }, { "code": null, "e": 1776, "s": 1735, "text": "<?\n//one or more PHP statements\n..\n..\n?>" }, { "code": null, "e": 1935, "s": 1776, "text": "This setting is recommended to be Off for production environment. Use of ASP style tags <%, %> and <script language=\"PHP\"> has been discontinued since PHP 7.0" }, { "code": null, "e": 1975, "s": 1935, "text": "Following example shows use of PHP tags" }, { "code": null, "e": 1986, "s": 1975, "text": " Live Demo" }, { "code": null, "e": 2037, "s": 1986, "text": "<?php\n//cannonical PHP tags\necho \"Hello World\";\n?>" }, { "code": null, "e": 2074, "s": 2037, "text": "This will produce following result −" }, { "code": null, "e": 2086, "s": 2074, "text": "Hello World" }, { "code": null, "e": 2172, "s": 2086, "text": "PHP supports a short echo tag <?= which is equivalent to the more verbose <?php echo." }, { "code": null, "e": 2183, "s": 2172, "text": " Live Demo" }, { "code": null, "e": 2205, "s": 2183, "text": "<?= \"Hello World\";\n?>" }, { "code": null, "e": 2242, "s": 2205, "text": "This will produce following result −" }, { "code": null, "e": 2254, "s": 2242, "text": "Hello World" }, { "code": null, "e": 2279, "s": 2254, "text": "Example using short tags" }, { "code": null, "e": 2290, "s": 2279, "text": " Live Demo" }, { "code": null, "e": 2343, "s": 2290, "text": "<?php\n//set short_open_tag=on\necho \"Hello World\";\n?>" }, { "code": null, "e": 2380, "s": 2343, "text": "This will produce following result −" }, { "code": null, "e": 2392, "s": 2380, "text": "Hello World" } ]
VBScript String Function
The String Function fills a string with the specified character the specified number of times. String(number,character) Number, a Required Parameter. An integer value, which would be repeated for the specified number of times against the character parameter. Number, a Required Parameter. An integer value, which would be repeated for the specified number of times against the character parameter. Character, a Required Parameter. Character value, which has to be repeated for the specified number of times. Character, a Required Parameter. Character value, which has to be repeated for the specified number of times. <!DOCTYPE html> <html> <body> <script language = "vbscript" type = "text/vbscript"> document.write("Line 1 :" & String(3,"$") & "<br />") document.write("Line 2 :" & String(4,"*") & "<br />") document.write("Line 3 :" & String(5,100) & "<br />") document.write("Line 4 :" & String(6,"ABCDE") & "<br />") </script> </body> </html> When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result − Line 1 :$$$ Line 2 :**** Line 3 :ddddd Line 4 :AAAAAA 63 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2175, "s": 2080, "text": "The String Function fills a string with the specified character the specified number of times." }, { "code": null, "e": 2201, "s": 2175, "text": "String(number,character)\n" }, { "code": null, "e": 2340, "s": 2201, "text": "Number, a Required Parameter. An integer value, which would be repeated for the specified number of times against the character parameter." }, { "code": null, "e": 2479, "s": 2340, "text": "Number, a Required Parameter. An integer value, which would be repeated for the specified number of times against the character parameter." }, { "code": null, "e": 2589, "s": 2479, "text": "Character, a Required Parameter. Character value, which has to be repeated for the specified number of times." }, { "code": null, "e": 2699, "s": 2589, "text": "Character, a Required Parameter. Character value, which has to be repeated for the specified number of times." }, { "code": null, "e": 3084, "s": 2699, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n document.write(\"Line 1 :\" & String(3,\"$\") & \"<br />\")\n document.write(\"Line 2 :\" & String(4,\"*\") & \"<br />\")\n document.write(\"Line 3 :\" & String(5,100) & \"<br />\")\n document.write(\"Line 4 :\" & String(6,\"ABCDE\") & \"<br />\")\n\n </script>\n </body>\n</html>" }, { "code": null, "e": 3205, "s": 3084, "text": "When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −" }, { "code": null, "e": 3260, "s": 3205, "text": "Line 1 :$$$\nLine 2 :****\nLine 3 :ddddd\nLine 4 :AAAAAA\n" }, { "code": null, "e": 3293, "s": 3260, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 3310, "s": 3293, "text": " Frahaan Hussain" }, { "code": null, "e": 3317, "s": 3310, "text": " Print" }, { "code": null, "e": 3328, "s": 3317, "text": " Add Notes" } ]
C++ Program to Perform Graph Coloring on Bipartite Graphs
A bipartite graph is a graph in which if the graph coloring is possible using two colors i.e.; vertices in a set are colored with the same color. In this program we take a bipartite graph as input and outputs colors of each vertex after coloring the vertices. Begin BFS algorithm is used to traverse all the vertices. Take a vertex and colour it yellow. Colour all its neighbour vertices as blue. Colour the next level vertices as yellow and so, until all vertices are coloured. End. #include<bits/stdc++.h> using namespace std; int n, e, i, j; vector<vector<int> > g; vector<int> color; bool v[11101]; void c(int node,int n) { queue<int> q; if(v[node]) return; color[node]=n; v[node]=1; for(i=0;i<n;i++) { if(!v[g[node][i]]) { q.push(g[node][i]); } } while(!q.empty()) { c(q.front(),(n+1)%2); q.pop(); } return; } int main() { int a,b; cout<<"Enter number of vertices and edges respectively:"; cin>>n>>e; cout<<"'Y' is for Yellow Colour and 'B' is for Blue Colour."; cout<<"\n"; g.resize(n); color.resize(n); memset(v,0,sizeof(v)); for(i=0;i<e;i++) { cout<<"\nEnter edge vertices of edge "<<i+1<<" :"; cin>>a>>b; a--; b--; g[a].push_back(b); g[b].push_back(a); } c(0,1); for(i=0;i<n;i++) { if(color[i]) cout<<i+1<<" "<<'Y'<<"\n"; else cout<<i+1<<" "<<'B'<<"\n"; } } Enter number of vertices and edges respectively:4 3 'Y' is for Yellow Colour and 'B' is for Blue Colour. Enter edge vertices of edge 1 :1 2 Enter edge vertices of edge 2 :3 2 Enter edge vertices of edge 3 :4 2 1 Y 2 B 3 B 4 B
[ { "code": null, "e": 1322, "s": 1062, "text": "A bipartite graph is a graph in which if the graph coloring is possible using two colors i.e.; vertices in a set are colored with the same color. In this program we take a bipartite graph as input and outputs colors of each vertex after coloring the vertices." }, { "code": null, "e": 1558, "s": 1322, "text": "Begin\n BFS algorithm is used to traverse all the vertices.\n Take a vertex and colour it yellow.\n Colour all its neighbour vertices as blue.\n Colour the next level vertices as yellow and so, until all vertices are coloured.\nEnd." }, { "code": null, "e": 2506, "s": 1558, "text": "#include<bits/stdc++.h>\nusing namespace std;\nint n, e, i, j;\nvector<vector<int> > g;\nvector<int> color;\nbool v[11101];\nvoid c(int node,int n) {\n queue<int> q;\n if(v[node])\n return;\n color[node]=n;\n v[node]=1;\n for(i=0;i<n;i++) {\n if(!v[g[node][i]]) {\n q.push(g[node][i]);\n }\n }\n while(!q.empty()) {\n c(q.front(),(n+1)%2);\n q.pop();\n }\n return;\n}\nint main() {\n int a,b;\n cout<<\"Enter number of vertices and edges respectively:\";\n cin>>n>>e;\n cout<<\"'Y' is for Yellow Colour and 'B' is for Blue Colour.\";\n cout<<\"\\n\";\n g.resize(n);\n color.resize(n);\n memset(v,0,sizeof(v));\n for(i=0;i<e;i++) {\n cout<<\"\\nEnter edge vertices of edge \"<<i+1<<\" :\";\n cin>>a>>b;\n a--; b--;\n g[a].push_back(b);\n g[b].push_back(a);\n }\n c(0,1);\n for(i=0;i<n;i++) {\n if(color[i])\n cout<<i+1<<\" \"<<'Y'<<\"\\n\";\n else\n cout<<i+1<<\" \"<<'B'<<\"\\n\";\n }\n}" }, { "code": null, "e": 2733, "s": 2506, "text": "Enter number of vertices and edges respectively:4 3\n'Y' is for Yellow Colour and 'B' is for Blue Colour.\n\nEnter edge vertices of edge 1 :1 2\nEnter edge vertices of edge 2 :3 2\nEnter edge vertices of edge 3 :4 2\n1 Y\n2 B\n3 B\n4 B" } ]
Find closest value for every element in array in C++
Here we will see how to find the closest value for every element in an array. If an element x has next element that is larger than it, and also present in the array, then that will be the greater value of that element. If the element is not present, then return -1. Suppose the array elements are [10, 5, 11, 6, 20, 12], then the greater elements are [11, 6, 12, 10, -1, 20]. As 20 has not greater value in the array, then print -1. To solve this, we will use the set in C++ STL. The set is implemented using the binary tree approach. In binary tree always the inorder successor is the next larger element. So we can get the element in O(log n) time. #include<iostream> #include<set> using namespace std; void nearestGreatest(int arr[], int n) { set<int> tempSet; for (int i = 0; i < n; i++) tempSet.insert(arr[i]); for (int i = 0; i < n; i++) { auto next_greater = tempSet.upper_bound(arr[i]); if (next_greater == tempSet.end()) cout << -1 << " "; else cout << *next_greater << " "; } } int main() { int arr[] = {10, 5, 11, 6, 20, 12}; int n = sizeof(arr) / sizeof(arr[0]); nearestGreatest(arr, n); } 11 6 12 10 -1 20
[ { "code": null, "e": 1495, "s": 1062, "text": "Here we will see how to find the closest value for every element in an array. If an element x has next element that is larger than it, and also present in the array, then that will be the greater value of that element. If the element is not present, then return -1. Suppose the array elements are [10, 5, 11, 6, 20, 12], then the greater elements are [11, 6, 12, 10, -1, 20]. As 20 has not greater value in the array, then print -1." }, { "code": null, "e": 1713, "s": 1495, "text": "To solve this, we will use the set in C++ STL. The set is implemented using the binary tree approach. In binary tree always the inorder successor is the next larger element. So we can get the element in O(log n) time." }, { "code": null, "e": 2227, "s": 1713, "text": "#include<iostream>\n#include<set>\nusing namespace std;\nvoid nearestGreatest(int arr[], int n) {\n set<int> tempSet;\n for (int i = 0; i < n; i++)\n tempSet.insert(arr[i]);\n for (int i = 0; i < n; i++) {\n auto next_greater = tempSet.upper_bound(arr[i]);\n if (next_greater == tempSet.end())\n cout << -1 << \" \";\n else\n cout << *next_greater << \" \";\n }\n}\nint main() {\n int arr[] = {10, 5, 11, 6, 20, 12};\n int n = sizeof(arr) / sizeof(arr[0]);\n nearestGreatest(arr, n);\n}" }, { "code": null, "e": 2244, "s": 2227, "text": "11 6 12 10 -1 20" } ]
deque::clear() and deque::erase() in C++ STL - GeeksforGeeks
22 Apr, 2022 Deque or Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in the case of insertion and deletion of elements at the end, and also at the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. The clear() function is used to remove all the elements of the deque container, thus making its size 0. Syntax : dequename.clear() Parameters : No parameters are passed. Result : All the elements of the deque are removed ( or destroyed ) Examples: Input : mydeque = {1, 2, 3, 4, 5} mydeque.clear();Output : mydeque = {} Input : mydeque = {} mydeque.clear();Output : mydeque = {} Errors and Exceptions:1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. CPP // CPP program to illustrate// Implementation of clear() function#include <deque>#include <iostream>using namespace std; int main(){ deque<int> mydeque{ 1, 2, 3, 4, 5 }; mydeque.clear(); // Deque becomes empty // Printing the deque for (auto it = mydeque.begin(); it != mydeque.end(); ++it) cout << ' ' << *it; return 0;} The erase() function is used to remove elements from a container from the specified position or range.Syntax : 1. dequename.erase(position) 2. dequename.erase(startingposition, endingposition) Parameters : Position of the element to be removed in the form of iterator. or the range specified using start and end iterator i.e., [start iterator, end iterator). Result : Elements are removed from the specified position of the container. Examples: Input: mydeque{1, 2, 3, 4, 5}, iterator= 2 mydeque.erase(iterator);Output: 1, 2, 4, 5 Input : mydeque{1, 2, 3, 4, 5, 6, 7, 8}, iterator1= 3, iterator2= 6 mydeque.erase(iterator1, iterator2);Output: 1, 2, 3, 7, 8 Errors and Exceptions:1. It has a no exception throw guarantee if the position is valid. 2. Shows undefined behavior otherwise.Removing elements from a particular position CPP // CPP program to illustrate// Implementation of erase() function#include <deque>#include <iostream>using namespace std; int main(){ deque<int> mydeque{ 1, 2, 3, 4, 5 }; deque<int>::iterator it; it = mydeque.begin(); mydeque.erase(it); // Printing the deque for (auto it = mydeque.begin(); it != mydeque.end(); ++it) cout << ' ' << *it; return 0;} 2 3 4 5 Removing elements within a range CPP // CPP program to illustrate// Implementation of erase() function#include <deque>#include <iostream>using namespace std; int main(){ deque<int> mydeque{ 1, 2, 3, 4, 5 }; deque<int>::iterator it1, it2; it1 = mydeque.begin(); it2 = mydeque.end(); it2--; it2--; mydeque.erase(it1, it2); // Printing the deque for (auto it = mydeque.begin(); it != mydeque.end(); ++it) cout << ' ' << *it; return 0;} 4 5 Application:Given a list of integers, remove all the even elements from the deque and print the deque. Input : 1, 2, 3, 4, 5, 6, 7, 8, 9Output:1 3 5 7 9Explanation: 2, 4, 6 and 8 which are even are erased from the deque Algorithm:1. Run a loop till the size of the deque. 2. Check if the element at each position is divisible by 2, if yes, remove the element and increment the iterator, else just increment the iterator to check the next element. 3. Print the final deque. CPP // CPP program to illustrate// Application of erase() function#include <deque>#include <iostream>using namespace std; int main(){ deque<int> mydeque{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }; deque<int>::iterator i; i = mydeque.begin(); while (i != mydeque.end()) { if (*i % 2 == 0) /* Not a good idea to erase inside loop, if you delete last element, mydeque.end() cannot be found resulting in infinite loop */ mydeque.erase(i); i++; } // Printing the deque for (auto it = mydeque.begin(); it != mydeque.end(); ++it) cout << ' ' << *it; return 0;} 1 3 5 7 9 clear() removes all the elements from a deque container, thus making its size 0. All the elements of the deque are removed using clear() function. erase() function on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed. timelessvaibhav keerthiniab dheerajvarmabudde cpp-deque CPP-Library deque STL C++ Misc Misc Misc STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ C++ Classes and Objects Virtual Function in C++ Templates in C++ with Examples Constructors in C++ vector::push_back() and vector::pop_back() in C++ STL Top 10 algorithms in Interview Questions Overview of Data Structures | Set 1 (Linear Data Structures) How to write Regular Expressions?
[ { "code": null, "e": 24596, "s": 24568, "text": "\n22 Apr, 2022" }, { "code": null, "e": 24920, "s": 24596, "text": "Deque or Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in the case of insertion and deletion of elements at the end, and also at the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. " }, { "code": null, "e": 25034, "s": 24920, "text": "The clear() function is used to remove all the elements of the deque container, thus making its size 0. Syntax : " }, { "code": null, "e": 25159, "s": 25034, "text": "dequename.clear()\nParameters :\nNo parameters are passed.\nResult :\nAll the elements of the deque are\nremoved ( or destroyed )" }, { "code": null, "e": 25170, "s": 25159, "text": "Examples: " }, { "code": null, "e": 25253, "s": 25170, "text": "Input : mydeque = {1, 2, 3, 4, 5} mydeque.clear();Output : mydeque = {}" }, { "code": null, "e": 25323, "s": 25253, "text": "Input : mydeque = {} mydeque.clear();Output : mydeque = {}" }, { "code": null, "e": 25431, "s": 25323, "text": "Errors and Exceptions:1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. " }, { "code": null, "e": 25435, "s": 25431, "text": "CPP" }, { "code": "// CPP program to illustrate// Implementation of clear() function#include <deque>#include <iostream>using namespace std; int main(){ deque<int> mydeque{ 1, 2, 3, 4, 5 }; mydeque.clear(); // Deque becomes empty // Printing the deque for (auto it = mydeque.begin(); it != mydeque.end(); ++it) cout << ' ' << *it; return 0;}", "e": 25784, "s": 25435, "text": null }, { "code": null, "e": 25899, "s": 25786, "text": "The erase() function is used to remove elements from a container from the specified position or range.Syntax : " }, { "code": null, "e": 26223, "s": 25899, "text": "1. dequename.erase(position)\n2. dequename.erase(startingposition, endingposition)\nParameters :\nPosition of the element to be removed in the form of iterator.\nor the range specified using start and end iterator i.e., [start iterator, end iterator).\nResult :\nElements are removed from the specified\nposition of the container." }, { "code": null, "e": 26234, "s": 26223, "text": "Examples: " }, { "code": null, "e": 26330, "s": 26234, "text": "Input: mydeque{1, 2, 3, 4, 5}, iterator= 2 mydeque.erase(iterator);Output: 1, 2, 4, 5" }, { "code": null, "e": 26467, "s": 26330, "text": "Input : mydeque{1, 2, 3, 4, 5, 6, 7, 8}, iterator1= 3, iterator2= 6 mydeque.erase(iterator1, iterator2);Output: 1, 2, 3, 7, 8" }, { "code": null, "e": 26641, "s": 26467, "text": "Errors and Exceptions:1. It has a no exception throw guarantee if the position is valid. 2. Shows undefined behavior otherwise.Removing elements from a particular position " }, { "code": null, "e": 26645, "s": 26641, "text": "CPP" }, { "code": "// CPP program to illustrate// Implementation of erase() function#include <deque>#include <iostream>using namespace std; int main(){ deque<int> mydeque{ 1, 2, 3, 4, 5 }; deque<int>::iterator it; it = mydeque.begin(); mydeque.erase(it); // Printing the deque for (auto it = mydeque.begin(); it != mydeque.end(); ++it) cout << ' ' << *it; return 0;}", "e": 27023, "s": 26645, "text": null }, { "code": null, "e": 27032, "s": 27023, "text": " 2 3 4 5" }, { "code": null, "e": 27067, "s": 27032, "text": "Removing elements within a range " }, { "code": null, "e": 27071, "s": 27067, "text": "CPP" }, { "code": "// CPP program to illustrate// Implementation of erase() function#include <deque>#include <iostream>using namespace std; int main(){ deque<int> mydeque{ 1, 2, 3, 4, 5 }; deque<int>::iterator it1, it2; it1 = mydeque.begin(); it2 = mydeque.end(); it2--; it2--; mydeque.erase(it1, it2); // Printing the deque for (auto it = mydeque.begin(); it != mydeque.end(); ++it) cout << ' ' << *it; return 0;}", "e": 27507, "s": 27071, "text": null }, { "code": null, "e": 27512, "s": 27507, "text": " 4 5" }, { "code": null, "e": 27617, "s": 27512, "text": "Application:Given a list of integers, remove all the even elements from the deque and print the deque. " }, { "code": null, "e": 27734, "s": 27617, "text": "Input : 1, 2, 3, 4, 5, 6, 7, 8, 9Output:1 3 5 7 9Explanation: 2, 4, 6 and 8 which are even are erased from the deque" }, { "code": null, "e": 27988, "s": 27734, "text": "Algorithm:1. Run a loop till the size of the deque. 2. Check if the element at each position is divisible by 2, if yes, remove the element and increment the iterator, else just increment the iterator to check the next element. 3. Print the final deque. " }, { "code": null, "e": 27992, "s": 27988, "text": "CPP" }, { "code": "// CPP program to illustrate// Application of erase() function#include <deque>#include <iostream>using namespace std; int main(){ deque<int> mydeque{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }; deque<int>::iterator i; i = mydeque.begin(); while (i != mydeque.end()) { if (*i % 2 == 0) /* Not a good idea to erase inside loop, if you delete last element, mydeque.end() cannot be found resulting in infinite loop */ mydeque.erase(i); i++; } // Printing the deque for (auto it = mydeque.begin(); it != mydeque.end(); ++it) cout << ' ' << *it; return 0;}", "e": 28597, "s": 27992, "text": null }, { "code": null, "e": 28608, "s": 28597, "text": " 1 3 5 7 9" }, { "code": null, "e": 28948, "s": 28608, "text": "clear() removes all the elements from a deque container, thus making its size 0. All the elements of the deque are removed using clear() function. erase() function on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed. " }, { "code": null, "e": 28964, "s": 28948, "text": "timelessvaibhav" }, { "code": null, "e": 28976, "s": 28964, "text": "keerthiniab" }, { "code": null, "e": 28994, "s": 28976, "text": "dheerajvarmabudde" }, { "code": null, "e": 29004, "s": 28994, "text": "cpp-deque" }, { "code": null, "e": 29016, "s": 29004, "text": "CPP-Library" }, { "code": null, "e": 29022, "s": 29016, "text": "deque" }, { "code": null, "e": 29026, "s": 29022, "text": "STL" }, { "code": null, "e": 29030, "s": 29026, "text": "C++" }, { "code": null, "e": 29035, "s": 29030, "text": "Misc" }, { "code": null, "e": 29040, "s": 29035, "text": "Misc" }, { "code": null, "e": 29045, "s": 29040, "text": "Misc" }, { "code": null, "e": 29049, "s": 29045, "text": "STL" }, { "code": null, "e": 29053, "s": 29049, "text": "CPP" }, { "code": null, "e": 29151, "s": 29053, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29170, "s": 29151, "text": "Inheritance in C++" }, { "code": null, "e": 29194, "s": 29170, "text": "C++ Classes and Objects" }, { "code": null, "e": 29218, "s": 29194, "text": "Virtual Function in C++" }, { "code": null, "e": 29249, "s": 29218, "text": "Templates in C++ with Examples" }, { "code": null, "e": 29269, "s": 29249, "text": "Constructors in C++" }, { "code": null, "e": 29323, "s": 29269, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 29364, "s": 29323, "text": "Top 10 algorithms in Interview Questions" }, { "code": null, "e": 29425, "s": 29364, "text": "Overview of Data Structures | Set 1 (Linear Data Structures)" } ]
How to plot data from multiple two-column text files with legends in Matplotlib?
To plot data from multiple two-column text files with legends in matplotlib, we can take the following steps − Import genfromtxt from pylab. It has several options to read data from a text file and plot the data. Import genfromtxt from pylab. It has several options to read data from a text file and plot the data. Read two text files, test.txt and test1.txt (having two columns of data), using genfromtxt and store the data in two variables, firstfiledata and secondfiledata. Read two text files, test.txt and test1.txt (having two columns of data), using genfromtxt and store the data in two variables, firstfiledata and secondfiledata. Plot the data using plot() method. label will be displayed as the legend. Plot the data using plot() method. label will be displayed as the legend. To display the figure, use show() method. To display the figure, use show() method. from matplotlib import pyplot as plt; from pylab import genfromtxt; plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True firstfiledata = genfromtxt("test.txt"); secondfiledata = genfromtxt("test1.txt"); plt.plot(firstfiledata[:, 0], firstfiledata[:, 1], label="test.txt Data"); plt.plot(secondfiledata[:, 0], secondfiledata[:, 1], label="test1.txt Data"); plt.legend(); plt.show(); Suppse the two text files have the following data − test.txt ======== 1 3 2 5 3 27 4 9 5 11 6 13 7 15 8 17 9 19 test1.txt ========= 11 13 12 15 13 17 14 19 15 21 16 23 17 25 18 27 19 29 When we execute the code, it will produce the following output −
[ { "code": null, "e": 1173, "s": 1062, "text": "To plot data from multiple two-column text files with legends in matplotlib, we can take the following steps −" }, { "code": null, "e": 1275, "s": 1173, "text": "Import genfromtxt from pylab. It has several options to read data from a text file and plot the data." }, { "code": null, "e": 1377, "s": 1275, "text": "Import genfromtxt from pylab. It has several options to read data from a text file and plot the data." }, { "code": null, "e": 1539, "s": 1377, "text": "Read two text files, test.txt and test1.txt (having two columns of data), using genfromtxt and store the data in two variables, firstfiledata and secondfiledata." }, { "code": null, "e": 1701, "s": 1539, "text": "Read two text files, test.txt and test1.txt (having two columns of data), using genfromtxt and store the data in two variables, firstfiledata and secondfiledata." }, { "code": null, "e": 1775, "s": 1701, "text": "Plot the data using plot() method. label will be displayed as the legend." }, { "code": null, "e": 1849, "s": 1775, "text": "Plot the data using plot() method. label will be displayed as the legend." }, { "code": null, "e": 1891, "s": 1849, "text": "To display the figure, use show() method." }, { "code": null, "e": 1933, "s": 1891, "text": "To display the figure, use show() method." }, { "code": null, "e": 2351, "s": 1933, "text": "from matplotlib import pyplot as plt;\nfrom pylab import genfromtxt;\n\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfirstfiledata = genfromtxt(\"test.txt\");\nsecondfiledata = genfromtxt(\"test1.txt\");\nplt.plot(firstfiledata[:, 0], firstfiledata[:, 1], label=\"test.txt Data\");\nplt.plot(secondfiledata[:, 0], secondfiledata[:, 1], label=\"test1.txt Data\");\nplt.legend();\nplt.show();" }, { "code": null, "e": 2403, "s": 2351, "text": "Suppse the two text files have the following data −" }, { "code": null, "e": 2490, "s": 2403, "text": "test.txt\n========\n1 3\n2 5\n3 27\n4 9\n5 11\n6 13\n7 15\n8 17\n9 19" }, { "code": null, "e": 2591, "s": 2490, "text": "test1.txt\n=========\n11 13\n12 15\n13 17\n14 19\n15 21\n16 23\n17 25\n18 27\n19 29" }, { "code": null, "e": 2656, "s": 2591, "text": "When we execute the code, it will produce the following output −" } ]
Cache Memory in Computer Organization - GeeksforGeeks
28 Nov, 2021 Cache Memory is a special very high-speed memory. It is used to speed up and synchronizing with high-speed CPU. Cache memory is costlier than main memory or disk memory but economical than CPU registers. Cache memory is an extremely fast memory type that acts as a buffer between RAM and the CPU. It holds frequently requested data and instructions so that they are immediately available to the CPU when needed. Cache memory is used to reduce the average time to access data from the Main memory. The cache is a smaller and faster memory which stores copies of the data from frequently used main memory locations. There are various different independent caches in a CPU, which store instructions and data. Levels of memory: Level 1 or Register –It is a type of memory in which data is stored and accepted that are immediately stored in CPU. Most commonly used register is accumulator, Program counter, address register etc. Level 2 or Cache memory –It is the fastest memory which has faster access time where data is temporarily stored for faster access. Level 3 or Main Memory –It is memory on which computer works currently. It is small in size and once power is off data no longer stays in this memory. Level 4 or Secondary Memory –It is external memory which is not as fast as main memory but data stays permanently in this memory. Cache Performance:When the processor needs to read or write a location in main memory, it first checks for a corresponding entry in the cache. If the processor finds that the memory location is in the cache, a cache hit has occurred and data is read from cache If the processor does not find the memory location in the cache, a cache miss has occurred. For a cache miss, the cache allocates a new entry and copies in data from main memory, then the request is fulfilled from the contents of the cache. The performance of cache memory is frequently measured in terms of a quantity called Hit ratio. Hit ratio = hit / (hit + miss) = no. of hits/total accesses We can improve Cache performance using higher cache block size, higher associativity, reduce miss rate, reduce miss penalty, and reduce the time to hit in the cache. Cache Mapping:There are three different types of mapping used for the purpose of cache memory which are as follows: Direct mapping, Associative mapping, and Set-Associative mapping. These are explained below. Direct Mapping –The simplest technique, known as direct mapping, maps each block of main memory into only one possible cache line. orIn Direct mapping, assign each memory block to a specific line in the cache. If a line is previously taken up by a memory block when a new block needs to be loaded, the old block is trashed. An address space is split into two parts index field and a tag field. The cache is used to store the tag field whereas the rest is stored in the main memory. Direct mapping`s performance is directly proportional to the Hit ratio.i = j modulo m where i=cache line number j= main memory block number m=number of lines in the cacheFor purposes of cache access, each main memory address can be viewed as consisting of three fields. The least significant w bits identify a unique word or byte within a block of main memory. In most contemporary machines, the address is at the byte level. The remaining s bits specify one of the 2s blocks of main memory. The cache logic interprets these s bits as a tag of s-r bits (most significant portion) and a line field of r bits. This latter field identifies one of the m=2r lines of the cache.Associative Mapping –In this type of mapping, the associative memory is used to store content and addresses of the memory word. Any block can go into any line of the cache. This means that the word id bits are used to identify which word in the block is needed, but the tag becomes all of the remaining bits. This enables the placement of any word at any place in the cache memory. It is considered to be the fastest and the most flexible mapping form.Set-associative Mapping –This form of mapping is an enhanced form of direct mapping where the drawbacks of direct mapping are removed. Set associative addresses the problem of possible thrashing in the direct mapping method. It does this by saying that instead of having exactly one line that a block can map to in the cache, we will group a few lines together creating a set. Then a block in memory can map to any one of the lines of a specific set..Set-associative mapping allows that each word that is present in the cache can have two or more words in the main memory for the same index address. Set associative cache mapping combines the best of direct and associative cache mapping techniques.In this case, the cache consists of a number of sets, each of which consists of a number of lines. The relationships arem = v * k i= j mod v where i=cache set number j=main memory block number v=number of sets m=number of lines in the cache number of sets k=number of lines in each set Application of Cache Memory –Usually, the cache memory can store a reasonable number of blocks at any given time, but this number is small compared to the total number of blocks in the main memory.The correspondence between the main memory blocks and those in the cache is specified by a mapping function.Types of Cache –Primary Cache –A primary cache is always located on the processor chip. This cache is small and its access time is comparable to that of processor registers.Secondary Cache –Secondary cache is placed between the primary cache and the rest of the memory. It is referred to as the level 2 (L2) cache. Often, the Level 2 cache is also housed on the processor chip.Locality of reference –Since size of cache memory is less as compared to main memory. So to check which part of main memory should be given priority and loaded in cache is decided based on locality of reference.Types of Locality of referenceSpatial Locality of referenceThis says that there is a chance that element will be present in the close proximity to the reference point and next time if again searched then more close proximity to the point of reference.Temporal Locality of referenceIn this Least recently used algorithm will be used. Whenever there is page fault occurs within a word will not only load word in main memory but complete page fault will be loaded because spatial locality of reference rule says that if you are referring any word next word will be referred in its register that’s why we load complete page table so the complete block will be loaded.GATE Practice Questions –Que-1: A computer has a 256 KByte, 4-way set associative, write back data cache with the block size of 32 Bytes. The processor sends 32-bit addresses to the cache controller. Each cache tag directory entry contains, in addition, to address tag, 2 valid bits, 1 modified bit and 1 replacement bit. The number of bits in the tag field of an address is(A) 11 (B) 14 (C) 16 (D) 27 Answer: (C)Explanation: https://www.geeksforgeeks.org/gate-gate-cs-2012-question-54/Que-2: Consider the data given in previous question. The size of the cache tag directory is(A) 160 Kbits (B) 136 bits (C) 40 Kbits (D) 32 bits Answer: (A)Explanation: https://www.geeksforgeeks.org/gate-gate-cs-2012-question-55/Que-3: An 8KB direct-mapped write-back cache is organized as multiple blocks, each of size 32-bytes. The processor generates 32-bit addresses. The cache controller maintains the tag information for each cache block comprising of the following.1 Valid bit 1 Modified bit As many bits as the minimum needed to identify the memory block mapped in the cache. What is the total size of memory needed at the cache controller to store meta-data (tags) for the cache?(A) 4864 bits (B) 6144 bits (C) 6656 bits (D) 5376 bits Answer: (D)Explanation: https://www.geeksforgeeks.org/gate-gate-cs-2011-question-43/Article Contributed by Pooja Taneja and Vaishali Bhatia. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave Direct Mapping –The simplest technique, known as direct mapping, maps each block of main memory into only one possible cache line. orIn Direct mapping, assign each memory block to a specific line in the cache. If a line is previously taken up by a memory block when a new block needs to be loaded, the old block is trashed. An address space is split into two parts index field and a tag field. The cache is used to store the tag field whereas the rest is stored in the main memory. Direct mapping`s performance is directly proportional to the Hit ratio.i = j modulo m where i=cache line number j= main memory block number m=number of lines in the cacheFor purposes of cache access, each main memory address can be viewed as consisting of three fields. The least significant w bits identify a unique word or byte within a block of main memory. In most contemporary machines, the address is at the byte level. The remaining s bits specify one of the 2s blocks of main memory. The cache logic interprets these s bits as a tag of s-r bits (most significant portion) and a line field of r bits. This latter field identifies one of the m=2r lines of the cache. i = j modulo m where i=cache line number j= main memory block number m=number of lines in the cache For purposes of cache access, each main memory address can be viewed as consisting of three fields. The least significant w bits identify a unique word or byte within a block of main memory. In most contemporary machines, the address is at the byte level. The remaining s bits specify one of the 2s blocks of main memory. The cache logic interprets these s bits as a tag of s-r bits (most significant portion) and a line field of r bits. This latter field identifies one of the m=2r lines of the cache. Associative Mapping –In this type of mapping, the associative memory is used to store content and addresses of the memory word. Any block can go into any line of the cache. This means that the word id bits are used to identify which word in the block is needed, but the tag becomes all of the remaining bits. This enables the placement of any word at any place in the cache memory. It is considered to be the fastest and the most flexible mapping form. Set-associative Mapping –This form of mapping is an enhanced form of direct mapping where the drawbacks of direct mapping are removed. Set associative addresses the problem of possible thrashing in the direct mapping method. It does this by saying that instead of having exactly one line that a block can map to in the cache, we will group a few lines together creating a set. Then a block in memory can map to any one of the lines of a specific set..Set-associative mapping allows that each word that is present in the cache can have two or more words in the main memory for the same index address. Set associative cache mapping combines the best of direct and associative cache mapping techniques.In this case, the cache consists of a number of sets, each of which consists of a number of lines. The relationships arem = v * k i= j mod v where i=cache set number j=main memory block number v=number of sets m=number of lines in the cache number of sets k=number of lines in each set Application of Cache Memory –Usually, the cache memory can store a reasonable number of blocks at any given time, but this number is small compared to the total number of blocks in the main memory.The correspondence between the main memory blocks and those in the cache is specified by a mapping function.Types of Cache –Primary Cache –A primary cache is always located on the processor chip. This cache is small and its access time is comparable to that of processor registers.Secondary Cache –Secondary cache is placed between the primary cache and the rest of the memory. It is referred to as the level 2 (L2) cache. Often, the Level 2 cache is also housed on the processor chip.Locality of reference –Since size of cache memory is less as compared to main memory. So to check which part of main memory should be given priority and loaded in cache is decided based on locality of reference.Types of Locality of referenceSpatial Locality of referenceThis says that there is a chance that element will be present in the close proximity to the reference point and next time if again searched then more close proximity to the point of reference.Temporal Locality of referenceIn this Least recently used algorithm will be used. Whenever there is page fault occurs within a word will not only load word in main memory but complete page fault will be loaded because spatial locality of reference rule says that if you are referring any word next word will be referred in its register that’s why we load complete page table so the complete block will be loaded.GATE Practice Questions –Que-1: A computer has a 256 KByte, 4-way set associative, write back data cache with the block size of 32 Bytes. The processor sends 32-bit addresses to the cache controller. Each cache tag directory entry contains, in addition, to address tag, 2 valid bits, 1 modified bit and 1 replacement bit. The number of bits in the tag field of an address is(A) 11 (B) 14 (C) 16 (D) 27 Answer: (C)Explanation: https://www.geeksforgeeks.org/gate-gate-cs-2012-question-54/Que-2: Consider the data given in previous question. The size of the cache tag directory is(A) 160 Kbits (B) 136 bits (C) 40 Kbits (D) 32 bits Answer: (A)Explanation: https://www.geeksforgeeks.org/gate-gate-cs-2012-question-55/Que-3: An 8KB direct-mapped write-back cache is organized as multiple blocks, each of size 32-bytes. The processor generates 32-bit addresses. The cache controller maintains the tag information for each cache block comprising of the following.1 Valid bit 1 Modified bit As many bits as the minimum needed to identify the memory block mapped in the cache. What is the total size of memory needed at the cache controller to store meta-data (tags) for the cache?(A) 4864 bits (B) 6144 bits (C) 6656 bits (D) 5376 bits Answer: (D)Explanation: https://www.geeksforgeeks.org/gate-gate-cs-2011-question-43/Article Contributed by Pooja Taneja and Vaishali Bhatia. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave In this case, the cache consists of a number of sets, each of which consists of a number of lines. The relationships are m = v * k i= j mod v where i=cache set number j=main memory block number v=number of sets m=number of lines in the cache number of sets k=number of lines in each set Application of Cache Memory – Usually, the cache memory can store a reasonable number of blocks at any given time, but this number is small compared to the total number of blocks in the main memory.The correspondence between the main memory blocks and those in the cache is specified by a mapping function. Usually, the cache memory can store a reasonable number of blocks at any given time, but this number is small compared to the total number of blocks in the main memory. The correspondence between the main memory blocks and those in the cache is specified by a mapping function. Types of Cache – Primary Cache –A primary cache is always located on the processor chip. This cache is small and its access time is comparable to that of processor registers. Secondary Cache –Secondary cache is placed between the primary cache and the rest of the memory. It is referred to as the level 2 (L2) cache. Often, the Level 2 cache is also housed on the processor chip. Locality of reference –Since size of cache memory is less as compared to main memory. So to check which part of main memory should be given priority and loaded in cache is decided based on locality of reference. Types of Locality of reference Spatial Locality of referenceThis says that there is a chance that element will be present in the close proximity to the reference point and next time if again searched then more close proximity to the point of reference.Temporal Locality of referenceIn this Least recently used algorithm will be used. Whenever there is page fault occurs within a word will not only load word in main memory but complete page fault will be loaded because spatial locality of reference rule says that if you are referring any word next word will be referred in its register that’s why we load complete page table so the complete block will be loaded. Spatial Locality of referenceThis says that there is a chance that element will be present in the close proximity to the reference point and next time if again searched then more close proximity to the point of reference. Temporal Locality of referenceIn this Least recently used algorithm will be used. Whenever there is page fault occurs within a word will not only load word in main memory but complete page fault will be loaded because spatial locality of reference rule says that if you are referring any word next word will be referred in its register that’s why we load complete page table so the complete block will be loaded. GATE Practice Questions – Que-1: A computer has a 256 KByte, 4-way set associative, write back data cache with the block size of 32 Bytes. The processor sends 32-bit addresses to the cache controller. Each cache tag directory entry contains, in addition, to address tag, 2 valid bits, 1 modified bit and 1 replacement bit. The number of bits in the tag field of an address is (A) 11 (B) 14 (C) 16 (D) 27 Answer: (C) Explanation: https://www.geeksforgeeks.org/gate-gate-cs-2012-question-54/ Que-2: Consider the data given in previous question. The size of the cache tag directory is (A) 160 Kbits (B) 136 bits (C) 40 Kbits (D) 32 bits Answer: (A) Explanation: https://www.geeksforgeeks.org/gate-gate-cs-2012-question-55/ Que-3: An 8KB direct-mapped write-back cache is organized as multiple blocks, each of size 32-bytes. The processor generates 32-bit addresses. The cache controller maintains the tag information for each cache block comprising of the following. 1 Valid bit 1 Modified bit As many bits as the minimum needed to identify the memory block mapped in the cache. What is the total size of memory needed at the cache controller to store meta-data (tags) for the cache? (A) 4864 bits (B) 6144 bits (C) 6656 bits (D) 5376 bits Answer: (D) Explanation: https://www.geeksforgeeks.org/gate-gate-cs-2011-question-43/ Article Contributed by Pooja Taneja and Vaishali Bhatia. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. VaibhavRai3 SarswatiPandey shruti_sharma gauravjitborah kk773572498 Operating Systems-Memory Management Computer Organization & Architecture GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Logical and Physical Address in Operating System Program for Decimal to Binary Conversion Direct Access Media (DMA) Controller in Computer Architecture Interrupts Addressing modes in 8085 microprocessor Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 28707, "s": 28679, "text": "\n28 Nov, 2021" }, { "code": null, "e": 29119, "s": 28707, "text": "Cache Memory is a special very high-speed memory. It is used to speed up and synchronizing with high-speed CPU. Cache memory is costlier than main memory or disk memory but economical than CPU registers. Cache memory is an extremely fast memory type that acts as a buffer between RAM and the CPU. It holds frequently requested data and instructions so that they are immediately available to the CPU when needed." }, { "code": null, "e": 29413, "s": 29119, "text": "Cache memory is used to reduce the average time to access data from the Main memory. The cache is a smaller and faster memory which stores copies of the data from frequently used main memory locations. There are various different independent caches in a CPU, which store instructions and data." }, { "code": null, "e": 29431, "s": 29413, "text": "Levels of memory:" }, { "code": null, "e": 29631, "s": 29431, "text": "Level 1 or Register –It is a type of memory in which data is stored and accepted that are immediately stored in CPU. Most commonly used register is accumulator, Program counter, address register etc." }, { "code": null, "e": 29762, "s": 29631, "text": "Level 2 or Cache memory –It is the fastest memory which has faster access time where data is temporarily stored for faster access." }, { "code": null, "e": 29913, "s": 29762, "text": "Level 3 or Main Memory –It is memory on which computer works currently. It is small in size and once power is off data no longer stays in this memory." }, { "code": null, "e": 30043, "s": 29913, "text": "Level 4 or Secondary Memory –It is external memory which is not as fast as main memory but data stays permanently in this memory." }, { "code": null, "e": 30186, "s": 30043, "text": "Cache Performance:When the processor needs to read or write a location in main memory, it first checks for a corresponding entry in the cache." }, { "code": null, "e": 30304, "s": 30186, "text": "If the processor finds that the memory location is in the cache, a cache hit has occurred and data is read from cache" }, { "code": null, "e": 30545, "s": 30304, "text": "If the processor does not find the memory location in the cache, a cache miss has occurred. For a cache miss, the cache allocates a new entry and copies in data from main memory, then the request is fulfilled from the contents of the cache." }, { "code": null, "e": 30641, "s": 30545, "text": "The performance of cache memory is frequently measured in terms of a quantity called Hit ratio." }, { "code": null, "e": 30702, "s": 30641, "text": "Hit ratio = hit / (hit + miss) = no. of hits/total accesses" }, { "code": null, "e": 30868, "s": 30702, "text": "We can improve Cache performance using higher cache block size, higher associativity, reduce miss rate, reduce miss penalty, and reduce the time to hit in the cache." }, { "code": null, "e": 31077, "s": 30868, "text": "Cache Mapping:There are three different types of mapping used for the purpose of cache memory which are as follows: Direct mapping, Associative mapping, and Set-Associative mapping. These are explained below." }, { "code": null, "e": 36755, "s": 31077, "text": "Direct Mapping –The simplest technique, known as direct mapping, maps each block of main memory into only one possible cache line. orIn Direct mapping, assign each memory block to a specific line in the cache. If a line is previously taken up by a memory block when a new block needs to be loaded, the old block is trashed. An address space is split into two parts index field and a tag field. The cache is used to store the tag field whereas the rest is stored in the main memory. Direct mapping`s performance is directly proportional to the Hit ratio.i = j modulo m\nwhere\ni=cache line number\nj= main memory block number\nm=number of lines in the cacheFor purposes of cache access, each main memory address can be viewed as consisting of three fields. The least significant w bits identify a unique word or byte within a block of main memory. In most contemporary machines, the address is at the byte level. The remaining s bits specify one of the 2s blocks of main memory. The cache logic interprets these s bits as a tag of s-r bits (most significant portion) and a line field of r bits. This latter field identifies one of the m=2r lines of the cache.Associative Mapping –In this type of mapping, the associative memory is used to store content and addresses of the memory word. Any block can go into any line of the cache. This means that the word id bits are used to identify which word in the block is needed, but the tag becomes all of the remaining bits. This enables the placement of any word at any place in the cache memory. It is considered to be the fastest and the most flexible mapping form.Set-associative Mapping –This form of mapping is an enhanced form of direct mapping where the drawbacks of direct mapping are removed. Set associative addresses the problem of possible thrashing in the direct mapping method. It does this by saying that instead of having exactly one line that a block can map to in the cache, we will group a few lines together creating a set. Then a block in memory can map to any one of the lines of a specific set..Set-associative mapping allows that each word that is present in the cache can have two or more words in the main memory for the same index address. Set associative cache mapping combines the best of direct and associative cache mapping techniques.In this case, the cache consists of a number of sets, each of which consists of a number of lines. The relationships arem = v * k\ni= j mod v\n\nwhere\ni=cache set number\nj=main memory block number\nv=number of sets\nm=number of lines in the cache number of sets \nk=number of lines in each set Application of Cache Memory –Usually, the cache memory can store a reasonable number of blocks at any given time, but this number is small compared to the total number of blocks in the main memory.The correspondence between the main memory blocks and those in the cache is specified by a mapping function.Types of Cache –Primary Cache –A primary cache is always located on the processor chip. This cache is small and its access time is comparable to that of processor registers.Secondary Cache –Secondary cache is placed between the primary cache and the rest of the memory. It is referred to as the level 2 (L2) cache. Often, the Level 2 cache is also housed on the processor chip.Locality of reference –Since size of cache memory is less as compared to main memory. So to check which part of main memory should be given priority and loaded in cache is decided based on locality of reference.Types of Locality of referenceSpatial Locality of referenceThis says that there is a chance that element will be present in the close proximity to the reference point and next time if again searched then more close proximity to the point of reference.Temporal Locality of referenceIn this Least recently used algorithm will be used. Whenever there is page fault occurs within a word will not only load word in main memory but complete page fault will be loaded because spatial locality of reference rule says that if you are referring any word next word will be referred in its register that’s why we load complete page table so the complete block will be loaded.GATE Practice Questions –Que-1: A computer has a 256 KByte, 4-way set associative, write back data cache with the block size of 32 Bytes. The processor sends 32-bit addresses to the cache controller. Each cache tag directory entry contains, in addition, to address tag, 2 valid bits, 1 modified bit and 1 replacement bit. The number of bits in the tag field of an address is(A) 11\n(B) 14\n(C) 16\n(D) 27 Answer: (C)Explanation: https://www.geeksforgeeks.org/gate-gate-cs-2012-question-54/Que-2: Consider the data given in previous question. The size of the cache tag directory is(A) 160 Kbits\n(B) 136 bits\n(C) 40 Kbits\n(D) 32 bits Answer: (A)Explanation: https://www.geeksforgeeks.org/gate-gate-cs-2012-question-55/Que-3: An 8KB direct-mapped write-back cache is organized as multiple blocks, each of size 32-bytes. The processor generates 32-bit addresses. The cache controller maintains the tag information for each cache block comprising of the following.1 Valid bit\n1 Modified bit As many bits as the minimum needed to identify the memory block mapped in the cache. What is the total size of memory needed at the cache controller to store meta-data (tags) for the cache?(A) 4864 bits\n(B) 6144 bits\n(C) 6656 bits\n(D) 5376 bits Answer: (D)Explanation: https://www.geeksforgeeks.org/gate-gate-cs-2011-question-43/Article Contributed by Pooja Taneja and Vaishali Bhatia. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 37910, "s": 36755, "text": "Direct Mapping –The simplest technique, known as direct mapping, maps each block of main memory into only one possible cache line. orIn Direct mapping, assign each memory block to a specific line in the cache. If a line is previously taken up by a memory block when a new block needs to be loaded, the old block is trashed. An address space is split into two parts index field and a tag field. The cache is used to store the tag field whereas the rest is stored in the main memory. Direct mapping`s performance is directly proportional to the Hit ratio.i = j modulo m\nwhere\ni=cache line number\nj= main memory block number\nm=number of lines in the cacheFor purposes of cache access, each main memory address can be viewed as consisting of three fields. The least significant w bits identify a unique word or byte within a block of main memory. In most contemporary machines, the address is at the byte level. The remaining s bits specify one of the 2s blocks of main memory. The cache logic interprets these s bits as a tag of s-r bits (most significant portion) and a line field of r bits. This latter field identifies one of the m=2r lines of the cache." }, { "code": null, "e": 38010, "s": 37910, "text": "i = j modulo m\nwhere\ni=cache line number\nj= main memory block number\nm=number of lines in the cache" }, { "code": null, "e": 38513, "s": 38010, "text": "For purposes of cache access, each main memory address can be viewed as consisting of three fields. The least significant w bits identify a unique word or byte within a block of main memory. In most contemporary machines, the address is at the byte level. The remaining s bits specify one of the 2s blocks of main memory. The cache logic interprets these s bits as a tag of s-r bits (most significant portion) and a line field of r bits. This latter field identifies one of the m=2r lines of the cache." }, { "code": null, "e": 38966, "s": 38513, "text": "Associative Mapping –In this type of mapping, the associative memory is used to store content and addresses of the memory word. Any block can go into any line of the cache. This means that the word id bits are used to identify which word in the block is needed, but the tag becomes all of the remaining bits. This enables the placement of any word at any place in the cache memory. It is considered to be the fastest and the most flexible mapping form." }, { "code": null, "e": 43038, "s": 38966, "text": "Set-associative Mapping –This form of mapping is an enhanced form of direct mapping where the drawbacks of direct mapping are removed. Set associative addresses the problem of possible thrashing in the direct mapping method. It does this by saying that instead of having exactly one line that a block can map to in the cache, we will group a few lines together creating a set. Then a block in memory can map to any one of the lines of a specific set..Set-associative mapping allows that each word that is present in the cache can have two or more words in the main memory for the same index address. Set associative cache mapping combines the best of direct and associative cache mapping techniques.In this case, the cache consists of a number of sets, each of which consists of a number of lines. The relationships arem = v * k\ni= j mod v\n\nwhere\ni=cache set number\nj=main memory block number\nv=number of sets\nm=number of lines in the cache number of sets \nk=number of lines in each set Application of Cache Memory –Usually, the cache memory can store a reasonable number of blocks at any given time, but this number is small compared to the total number of blocks in the main memory.The correspondence between the main memory blocks and those in the cache is specified by a mapping function.Types of Cache –Primary Cache –A primary cache is always located on the processor chip. This cache is small and its access time is comparable to that of processor registers.Secondary Cache –Secondary cache is placed between the primary cache and the rest of the memory. It is referred to as the level 2 (L2) cache. Often, the Level 2 cache is also housed on the processor chip.Locality of reference –Since size of cache memory is less as compared to main memory. So to check which part of main memory should be given priority and loaded in cache is decided based on locality of reference.Types of Locality of referenceSpatial Locality of referenceThis says that there is a chance that element will be present in the close proximity to the reference point and next time if again searched then more close proximity to the point of reference.Temporal Locality of referenceIn this Least recently used algorithm will be used. Whenever there is page fault occurs within a word will not only load word in main memory but complete page fault will be loaded because spatial locality of reference rule says that if you are referring any word next word will be referred in its register that’s why we load complete page table so the complete block will be loaded.GATE Practice Questions –Que-1: A computer has a 256 KByte, 4-way set associative, write back data cache with the block size of 32 Bytes. The processor sends 32-bit addresses to the cache controller. Each cache tag directory entry contains, in addition, to address tag, 2 valid bits, 1 modified bit and 1 replacement bit. The number of bits in the tag field of an address is(A) 11\n(B) 14\n(C) 16\n(D) 27 Answer: (C)Explanation: https://www.geeksforgeeks.org/gate-gate-cs-2012-question-54/Que-2: Consider the data given in previous question. The size of the cache tag directory is(A) 160 Kbits\n(B) 136 bits\n(C) 40 Kbits\n(D) 32 bits Answer: (A)Explanation: https://www.geeksforgeeks.org/gate-gate-cs-2012-question-55/Que-3: An 8KB direct-mapped write-back cache is organized as multiple blocks, each of size 32-bytes. The processor generates 32-bit addresses. The cache controller maintains the tag information for each cache block comprising of the following.1 Valid bit\n1 Modified bit As many bits as the minimum needed to identify the memory block mapped in the cache. What is the total size of memory needed at the cache controller to store meta-data (tags) for the cache?(A) 4864 bits\n(B) 6144 bits\n(C) 6656 bits\n(D) 5376 bits Answer: (D)Explanation: https://www.geeksforgeeks.org/gate-gate-cs-2011-question-43/Article Contributed by Pooja Taneja and Vaishali Bhatia. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 43159, "s": 43038, "text": "In this case, the cache consists of a number of sets, each of which consists of a number of lines. The relationships are" }, { "code": null, "e": 43328, "s": 43159, "text": "m = v * k\ni= j mod v\n\nwhere\ni=cache set number\nj=main memory block number\nv=number of sets\nm=number of lines in the cache number of sets \nk=number of lines in each set " }, { "code": null, "e": 43358, "s": 43328, "text": "Application of Cache Memory –" }, { "code": null, "e": 43635, "s": 43358, "text": "Usually, the cache memory can store a reasonable number of blocks at any given time, but this number is small compared to the total number of blocks in the main memory.The correspondence between the main memory blocks and those in the cache is specified by a mapping function." }, { "code": null, "e": 43804, "s": 43635, "text": "Usually, the cache memory can store a reasonable number of blocks at any given time, but this number is small compared to the total number of blocks in the main memory." }, { "code": null, "e": 43913, "s": 43804, "text": "The correspondence between the main memory blocks and those in the cache is specified by a mapping function." }, { "code": null, "e": 43930, "s": 43913, "text": "Types of Cache –" }, { "code": null, "e": 44088, "s": 43930, "text": "Primary Cache –A primary cache is always located on the processor chip. This cache is small and its access time is comparable to that of processor registers." }, { "code": null, "e": 44293, "s": 44088, "text": "Secondary Cache –Secondary cache is placed between the primary cache and the rest of the memory. It is referred to as the level 2 (L2) cache. Often, the Level 2 cache is also housed on the processor chip." }, { "code": null, "e": 44505, "s": 44293, "text": "Locality of reference –Since size of cache memory is less as compared to main memory. So to check which part of main memory should be given priority and loaded in cache is decided based on locality of reference." }, { "code": null, "e": 44536, "s": 44505, "text": "Types of Locality of reference" }, { "code": null, "e": 45170, "s": 44536, "text": "Spatial Locality of referenceThis says that there is a chance that element will be present in the close proximity to the reference point and next time if again searched then more close proximity to the point of reference.Temporal Locality of referenceIn this Least recently used algorithm will be used. Whenever there is page fault occurs within a word will not only load word in main memory but complete page fault will be loaded because spatial locality of reference rule says that if you are referring any word next word will be referred in its register that’s why we load complete page table so the complete block will be loaded." }, { "code": null, "e": 45392, "s": 45170, "text": "Spatial Locality of referenceThis says that there is a chance that element will be present in the close proximity to the reference point and next time if again searched then more close proximity to the point of reference." }, { "code": null, "e": 45805, "s": 45392, "text": "Temporal Locality of referenceIn this Least recently used algorithm will be used. Whenever there is page fault occurs within a word will not only load word in main memory but complete page fault will be loaded because spatial locality of reference rule says that if you are referring any word next word will be referred in its register that’s why we load complete page table so the complete block will be loaded." }, { "code": null, "e": 45831, "s": 45805, "text": "GATE Practice Questions –" }, { "code": null, "e": 46181, "s": 45831, "text": "Que-1: A computer has a 256 KByte, 4-way set associative, write back data cache with the block size of 32 Bytes. The processor sends 32-bit addresses to the cache controller. Each cache tag directory entry contains, in addition, to address tag, 2 valid bits, 1 modified bit and 1 replacement bit. The number of bits in the tag field of an address is" }, { "code": null, "e": 46210, "s": 46181, "text": "(A) 11\n(B) 14\n(C) 16\n(D) 27 " }, { "code": null, "e": 46222, "s": 46210, "text": "Answer: (C)" }, { "code": null, "e": 46296, "s": 46222, "text": "Explanation: https://www.geeksforgeeks.org/gate-gate-cs-2012-question-54/" }, { "code": null, "e": 46388, "s": 46296, "text": "Que-2: Consider the data given in previous question. The size of the cache tag directory is" }, { "code": null, "e": 46441, "s": 46388, "text": "(A) 160 Kbits\n(B) 136 bits\n(C) 40 Kbits\n(D) 32 bits " }, { "code": null, "e": 46453, "s": 46441, "text": "Answer: (A)" }, { "code": null, "e": 46527, "s": 46453, "text": "Explanation: https://www.geeksforgeeks.org/gate-gate-cs-2012-question-55/" }, { "code": null, "e": 46771, "s": 46527, "text": "Que-3: An 8KB direct-mapped write-back cache is organized as multiple blocks, each of size 32-bytes. The processor generates 32-bit addresses. The cache controller maintains the tag information for each cache block comprising of the following." }, { "code": null, "e": 46799, "s": 46771, "text": "1 Valid bit\n1 Modified bit " }, { "code": null, "e": 46989, "s": 46799, "text": "As many bits as the minimum needed to identify the memory block mapped in the cache. What is the total size of memory needed at the cache controller to store meta-data (tags) for the cache?" }, { "code": null, "e": 47046, "s": 46989, "text": "(A) 4864 bits\n(B) 6144 bits\n(C) 6656 bits\n(D) 5376 bits " }, { "code": null, "e": 47058, "s": 47046, "text": "Answer: (D)" }, { "code": null, "e": 47132, "s": 47058, "text": "Explanation: https://www.geeksforgeeks.org/gate-gate-cs-2011-question-43/" }, { "code": null, "e": 47314, "s": 47132, "text": "Article Contributed by Pooja Taneja and Vaishali Bhatia. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 47326, "s": 47314, "text": "VaibhavRai3" }, { "code": null, "e": 47341, "s": 47326, "text": "SarswatiPandey" }, { "code": null, "e": 47355, "s": 47341, "text": "shruti_sharma" }, { "code": null, "e": 47370, "s": 47355, "text": "gauravjitborah" }, { "code": null, "e": 47382, "s": 47370, "text": "kk773572498" }, { "code": null, "e": 47418, "s": 47382, "text": "Operating Systems-Memory Management" }, { "code": null, "e": 47455, "s": 47418, "text": "Computer Organization & Architecture" }, { "code": null, "e": 47463, "s": 47455, "text": "GATE CS" }, { "code": null, "e": 47481, "s": 47463, "text": "Operating Systems" }, { "code": null, "e": 47499, "s": 47481, "text": "Operating Systems" }, { "code": null, "e": 47597, "s": 47499, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47646, "s": 47597, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 47687, "s": 47646, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 47749, "s": 47687, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 47760, "s": 47749, "text": "Interrupts" }, { "code": null, "e": 47800, "s": 47760, "text": "Addressing modes in 8085 microprocessor" }, { "code": null, "e": 47820, "s": 47800, "text": "Layers of OSI Model" }, { "code": null, "e": 47844, "s": 47820, "text": "ACID Properties in DBMS" }, { "code": null, "e": 47857, "s": 47844, "text": "TCP/IP Model" }, { "code": null, "e": 47884, "s": 47857, "text": "Types of Operating Systems" } ]
Sort multidimensional array by multiple keys in PHP
The array_multisort function can be used to sort a multidimensional array based on multiple keys − $my_list = array( array('ID' => 1, 'title' => 'data one', 'event_type' => 'one'), array('ID' => 2, 'title' => 'data two', 'event_type' => 'zero'), array('ID' => 3, 'title' => 'data three', 'event_type' => 'one'), array('ID' => 4, 'title' => 'data four', 'event_type' => 'zero') ); # The list of sorted columns and their data can be obtained. This will be passed to the array_multisort function. $sort = array(); foreach($my_list as $k=>$v) { $sort['title'][$k] = $v['title']; $sort['event_type'][$k] = $v['event_type']; } # It is sorted by event_type in descending order and the title is sorted in ascending order. array_multisort($sort['event_type'], SORT_DESC, $sort['title'], SORT_ASC,$my_list); For PHP version 5.5.0 − array_multisort(array_column($my_list, 'event_type'), SORT_DESC, array_column($my_list, 'title'), SORT_ASC, $my_list); This will produce the following output − array ( 0 => array ( 'ID' => 4, 'title' => 'data four', 'event_type' => 'zero', ), 1 => array ( 'ID' => 3, 'title' => 'data two', 'event_type' => 'zero', ), 2 => array ( 'ID' => 1, 'title' => 'data one', 'event_type' => 'one', ), 3 => array ( 'ID' => 2, 'title' => 'data three', 'event_type' => 'one', ), )
[ { "code": null, "e": 1161, "s": 1062, "text": "The array_multisort function can be used to sort a multidimensional array based on multiple keys −" }, { "code": null, "e": 1878, "s": 1161, "text": "$my_list = array(\n array('ID' => 1, 'title' => 'data one', 'event_type' => 'one'),\n array('ID' => 2, 'title' => 'data two', 'event_type' => 'zero'),\n array('ID' => 3, 'title' => 'data three', 'event_type' => 'one'),\n array('ID' => 4, 'title' => 'data four', 'event_type' => 'zero')\n);\n# The list of sorted columns and their data can be obtained. This will be passed to the array_multisort function.\n$sort = array();\nforeach($my_list as $k=>$v) {\n $sort['title'][$k] = $v['title'];\n $sort['event_type'][$k] = $v['event_type'];\n}\n# It is sorted by event_type in descending order and the title is sorted in ascending order.\narray_multisort($sort['event_type'], SORT_DESC, $sort['title'], SORT_ASC,$my_list);" }, { "code": null, "e": 1902, "s": 1878, "text": "For PHP version 5.5.0 −" }, { "code": null, "e": 2021, "s": 1902, "text": "array_multisort(array_column($my_list, 'event_type'), SORT_DESC,\narray_column($my_list, 'title'), SORT_ASC,\n$my_list);" }, { "code": null, "e": 2062, "s": 2021, "text": "This will produce the following output −" }, { "code": null, "e": 2477, "s": 2062, "text": "array (\n 0 =>\n array (\n 'ID' => 4,\n 'title' => 'data four',\n 'event_type' => 'zero',\n ),\n 1 =>\n array (\n 'ID' => 3,\n 'title' => 'data two',\n 'event_type' => 'zero',\n ),\n 2 =>\n array (\n 'ID' => 1,\n 'title' => 'data one',\n 'event_type' => 'one',\n ),\n 3 =>\n array (\n 'ID' => 2,\n 'title' => 'data three',\n 'event_type' => 'one',\n ),\n)" } ]
How to perform browser navigations in Selenium?
There are various navigate() methods to perform navigations in Selenium. They are as the listed below − navigate().to(url)This is used to launch a new browser and open a particular URL as in the parameter. navigate().to(url) This is used to launch a new browser and open a particular URL as in the parameter. navigate().refresh()This is used to reload a page. navigate().refresh() This is used to reload a page. navigate().back()This is used to jump to the previous page as per browser history context. navigate().back() This is used to jump to the previous page as per browser history context. navigate().forward()This is used to jump to the next page as per browser history context. navigate().forward() This is used to jump to the next page as per browser history context. import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import java.util.List; public class BrowserNavigation { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://www.tutorialspoint.com/index.htm"; // new browser will launch and navigate to the URL driver.navigate().to(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); // refresh the current browser driver.navigate().refresh(); //Using id tagname attribute combination for css expression driver.findElement(By.cssSelector("input[name=’search’]")). sendKeys("Selenium"); //browser will go back to the previous page driver.navigate().back(); //browser will go move to the next page driver.navigate().forward(); driver.close(); } }
[ { "code": null, "e": 1166, "s": 1062, "text": "There are various navigate() methods to perform navigations in Selenium. They are as the listed below −" }, { "code": null, "e": 1268, "s": 1166, "text": "navigate().to(url)This is used to launch a new browser and open a particular URL as in the parameter." }, { "code": null, "e": 1287, "s": 1268, "text": "navigate().to(url)" }, { "code": null, "e": 1371, "s": 1287, "text": "This is used to launch a new browser and open a particular URL as in the parameter." }, { "code": null, "e": 1422, "s": 1371, "text": "navigate().refresh()This is used to reload a page." }, { "code": null, "e": 1443, "s": 1422, "text": "navigate().refresh()" }, { "code": null, "e": 1474, "s": 1443, "text": "This is used to reload a page." }, { "code": null, "e": 1565, "s": 1474, "text": "navigate().back()This is used to jump to the previous page as per browser history context." }, { "code": null, "e": 1583, "s": 1565, "text": "navigate().back()" }, { "code": null, "e": 1657, "s": 1583, "text": "This is used to jump to the previous page as per browser history context." }, { "code": null, "e": 1747, "s": 1657, "text": "navigate().forward()This is used to jump to the next page as per browser history context." }, { "code": null, "e": 1768, "s": 1747, "text": "navigate().forward()" }, { "code": null, "e": 1838, "s": 1768, "text": "This is used to jump to the next page as per browser history context." }, { "code": null, "e": 2966, "s": 1838, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.Keys;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport java.util.List;\npublic class BrowserNavigation {\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/index.htm\";\n // new browser will launch and navigate to the URL\n driver.navigate().to(url);\n driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);\n // refresh the current browser\n driver.navigate().refresh();\n //Using id tagname attribute combination for css expression\n driver.findElement(By.cssSelector(\"input[name=’search’]\")).\n sendKeys(\"Selenium\");\n //browser will go back to the previous page\n driver.navigate().back();\n //browser will go move to the next page\n driver.navigate().forward();\n driver.close();\n }\n}" } ]
Introducing Skippa. SciKIt-learn Pre-processing Pipelines... | by Robert van Straalen | Towards Data Science
Any data scientist is probably familiar with pandas and scikit-learn. The usual workflow entails data cleaning in pandas, further pre-processing using either pandas again or scikit-learn transformers like StandardScaler, OneHotEncoder etc., after which a machine learning algorithm is fitted (something from scikit-learn again). Now there are some problems with this approach: 1. The development workflow is rather complex and requires a lot of code 😰 2. It’s hard to reproduce the workflow for prediction in a deployment 😩 3. Existing solutions to mitigate these issues are simply not good enough 😞 Skippa is a package designed to: ✨ drastically simplify development 📦 package / serialize all data cleaning, pre-processing together with your model algorithm into a single pipeline file 😌 reuse the interface/components from pandas & scikit-learn that you’re already familiar with Skippa helps you to easily define data cleaning & pre-processing operations on a pandas DataFrame and combine it with a scikit-learn model/algorithm into a single executable pipeline. It works roughly like this: from skippa import Skippa, columnsfrom sklearn.linear_model import LogisticRegressionX, y = get_training_data(...)pipeline = ( Skippa() .impute(columns(dtype_include='object'), strategy='most_frequent') .impute(columns(dtype_include='number'), strategy='median') .scale(columns(dtype_include='number'), type='standard') .onehot(columns(['category1', 'category2'])) .model(LogisticRegression()))pipeline.fit(X, y)predictions = pipeline.predict_proba(X) ☝️ Skippa does not presume to fix all problems, does not cover all functionality you might ever need and is not a highly scalable solution, but it should be able to offer a massive simplification for > 80% of regular pandas/sklearn based machine learning projects. 📂 Github 📦 pypi 📝 readthedocs ⏩ skip the essay and go directly to the fun part For tasks that are conceptually quite simple — imputing missing values, one-hot encoding categorical values, selecting a subset of columns, scaling etc. — you need quite a lot of code. If generally you start out with a pandasdataframe consisting of columns of various data types, you require different transformations of different columns and a lot of your code involves selecting column subsets and merging transformed data. What you want is basically a set of steps where you say: I want to apply this transformation to these columns. If only there was a package that enabled you to code in such idioms... If you want to deploy your model, you need to be able to reproduce your pre-processing code for use in a prediction context. Also, besides your pickled model file, you need pickled files for your fitted scaler, fitted one-hot encoder(s) and possible other transformations, since they are needed to generate predictions on new data! This quickly becomes hard to maintain. If only you could save all this logic into a single file... Now, a lot of work has already been done on this subject. In scikit-learn you have the Pipeline which you can use to chain certain transformers to your algorithm and the ColumnTransformer which you can use to define pipelines of transformers on different sets of columns. I find this cumbersome to work with though. Look at this example: import numpy as npimport pandas as pdfrom sklearn.compose import ColumnTransformerfrom sklearn.impute import SimpleImputerfrom sklearn.pipeline import Pipelinefrom sklearn.preprocessing import OneHotEncoderfrom sklearn.tree import DecisionTreeClassifier# this is the input dataframedf = pd.DataFrame({ 'favorite_color':['blue','green','red','green','blue'], 'age': [10,15,10,np.nan,10], 'target':[1,0,1,0,1]})# define individual transformers in a pipelinecategorical_preprocessing = Pipeline([('ohe', OneHotEncoder())])numerical_preprocessing = Pipeline([('imputation', SimpleImputer())])# define which transformer applies to which columnspreprocess = ColumnTransformer([ ('categorical_preprocessing', categorical_preprocessing, ['favorite_color']), ('numerical_preprocessing', numerical_preprocessing, ['age'])])# create the final pipeline with preprocessing steps and # the final classifier steppipeline = Pipeline([ ('preprocess', preprocess), ('clf', DecisionTreeClassifier())])# now fit the pipeline using the whole dataframedf_features = df[['favorite_color','age']]df_target = df['target']# call fit on the dataframespipeline.fit(df_features, df_target) Now this does work, but it’s rather complex and cumbersome to work with you run into limitations if you need serial transformations on various sets of columns, because the output of each transformer is a numpy array, rather than a pandas dataframe There is a package sklearn-pandas which is a noble effort to remedy these issues. While it does solve some problems, I’m not satisfied with it. The most important design principle of skippa is that the output of a transformation is always a pandas DataFrame. Why? Because conceptually you start out with a DataFrame, consisting of different columns of different data types, requiring different transformations. Using sklearn, the output of a transformation is a numpy array. This generally means you lose column names and data types (everything becomes float). Conceptually, when chaining together a pipeline, you want to keep referring to columns using their names and/or data types. This is only possible when the DataFrame is consistently used throughout the pipeline as the central data representation. Skippa achieves this result by implementing customized versions of existing transformations. Now, there is of course a drawback to this approach: those transformations cannot be used directly and a specific wrapper needs to be implemented. This always means a development cost and a maintainability cost. I hope this cost is outweighed by the benefits offered by Skippa. Other design considerations: Skippa aims to have a syntax that is the shortest and simplest way possible to define your transformations. Skippa doesn’t support all functionality you might ever need. The intent is to provide added value for the large majority of use cases, not for all use cases. But there’s still a fallback way to define arbitrary transformations! Yes, you need to learn a slightly new ‘language’ (i.e. the Skippa methods), but I feel this is quite straightforward and very easy to learn for anyone familiar with pandas and scikit-learn. So, after all this complaining and being a smart ass claiming to know better, let’s show what Skippa can do! Installation is just via pypi: $ pip install skippa Import the Skippa object and the columns helper function: from skippa import Skippa, columns The idea is that you start out with a pandas DataFrame. You then initiate a Skippa pipeline and then use chaining commands to define transformations that need to be applied to certain columns. The last step is generally a model estimator (e.g. a classifier, regressor, clusterer) from scikit-learn. X, y = get_training_data(...)pipeline = ( Skippa() .<transformation-1>(<column-definition>, <optional-args>) .<transformation-2>(<column-definition>, <optional-args>) ... .model(<model-estimator>(<optional-args>)))pipeline.fit(X, y)pipeline.save('./models/mypipeline') Ok, now a specific example. We have a pandas DataFrame X with 10 columns: 4 float columns, 2 integer columns, 3 categorical columns and 1 date column We have missing values in float columns and in a categorical column and we have a set of labels y (either 0 or 1) What we want to do is the following remove a bunch of columns we don’t need impute missing values (median value for numeric columns, most frequent value for categorical columns) one-hot encode categorical columns scale the numerical columns fit a logistic regression model We can do this in a couple of lines: pipe = ( Skippa() .select(columns(exclude=['a', 'f', 'i', 'j'])) .impute(columns(dtype_include='number'), strategy='median') .impute(columns(dtype_include='object'), strategy='most_frequent') .scale(columns(dtype_include='number'), type='standard') .onehot(columns(['g', 'h'])) .model(LogisticRegression()))pipe.fit(X, y)pipeline.save('./models/mypipeline') The file we saved is a SkippaPipeline which is a child class of scikit-learn’s Pipeline. It contains the entire pipeline of the pre-processing and the logistic regression. It’s easy to deploy and reuse: df_scoring = get_scoring_data(...)my_pipeline = Skippa.load_pipeline('./models/mypipeline')predictions = my_pipeline.predict_proba(df_scoring) Since the Skippa pipeline is (extends) a regular scikit-learn Pipeline object, you can use all the standard methods like .fit, .transform, .predict, .predict_proba etc. It’s entirely feasible that you’re just interested in processing data, without the wish to finish your pipeline with a modeling algorithm. Or maybe you simply want to inspect the final dataset that goes into your algorithm. That’s possible using the .build() method: pipe = ( Skippa() .select(columns(exclude=['a', 'f', 'i', 'j'])) .impute(columns(dtype_include='number'), strategy='median') .impute(columns(dtype_include='object'), strategy='most_frequent') .scale(columns(dtype_include='number'), type='standard') .onehot(columns(['g', 'h'])) .build())df_processed = pipe.fit_transform(X)df_processed.info() Defining a subset of columns for a transformation is done using the columns() function. There are several ways to use this. E.g. including or excluding a list of column names: columns(['a', 'b']) simply define a list of column names columns(include=['a', 'b']) this is equivalent columns(exclude=['a', 'b']) analogously, you can de-select columns You can also use dtype_include, dtype_exclude and pattern from sklearn’s make_column_selector() function. columns(dtype_include='float') selects all float columns columns(dtype_exclude='number') deselect all numeric columns columns(pattern='myprefix_*') selects all columns starting with myprefix_ You can also add / subtract multiple column selectors! columns(dtype_include='object') — columns(['c', ‘d']) selects all object columns except c and d. These are the transformations Skippa supports. They can be either a wrapper around existing scikit-learn transformers, existing pandas.DataFrame methods, or custom implementations if needed. .impute() Wrapper around sklearn’s SimpleImputer. Example: .impute(columns(dtype_include='int'), method='medium') .scale() Wrapper around sklearn’s StandardScaler (if type='standard') or MinMaxScaler (if type='minmax').Example: .scale(columns(dtype_include='numeric'), 'minmax') .onehot() Wrapper around sklearn’s OneHotEncoder.Example: .onehot(columns(dtype_include='category')) .encode_date() Custom transformer for creating features out of a date values. It applies pandas’ pd.to_datetime() and uses the properties from the resulting .dt object.Example: .encode_date(columns(['mydate']), {'year': False, 'month': True, 'day': True}) .cast() Wrapper around pandas.DataFrame.astype(). It has aliases .astype() and .as_type().Example: .cast(columns(dtype_include='int'), 'float') .rename() Wrapper around pandas.DataFrame.rename().N.B. Does not have a columns specifier!Example: .rename({'a': 'name', 'b': 'age'}) .assign() Wrapper around pandas.DataFrame.assign(). N.B. Does not have a columns specifier!Example: .assign(y_sq=lambda df: df['y']*df['y']) .apply() Wrapper round pandas.DataFrame.apply().Example: .apply(np.log) .select() Simply selecting a subset of columns.Example: .select(columns(dtype_exclude='object')) .model() Not a transformer but an estimator. Can only be used as the final step in your pipeline. Provide an (instantiated) sklearn estimator as argument.Example: .model(RandomForestClassifier(n_estimators=200, max_depth=5)) .concat() Concatenate another parallel pipeline to the current one. This will concatenate those pipelines’ resulting set of features.Example:pipe1 = Skippa().apply(np.log)pipe2 = Skippa().apply(np.sqrt)final = pipe2.concat(pipe1).model(LinearRegression()) ☝️ The idea is to keep adding transformers for extra functionality, but for any functionality that is not (or not yet) supported there is always an option to use the .assign or .apply methods to apply any transformation. I’m eager to receive feedback on your experiences, opinions and feature requests, so please leave a reaction or create an issue in Github!
[ { "code": null, "e": 501, "s": 172, "text": "Any data scientist is probably familiar with pandas and scikit-learn. The usual workflow entails data cleaning in pandas, further pre-processing using either pandas again or scikit-learn transformers like StandardScaler, OneHotEncoder etc., after which a machine learning algorithm is fitted (something from scikit-learn again)." }, { "code": null, "e": 549, "s": 501, "text": "Now there are some problems with this approach:" }, { "code": null, "e": 624, "s": 549, "text": "1. The development workflow is rather complex and requires a lot of code 😰" }, { "code": null, "e": 696, "s": 624, "text": "2. It’s hard to reproduce the workflow for prediction in a deployment 😩" }, { "code": null, "e": 772, "s": 696, "text": "3. Existing solutions to mitigate these issues are simply not good enough 😞" }, { "code": null, "e": 805, "s": 772, "text": "Skippa is a package designed to:" }, { "code": null, "e": 840, "s": 805, "text": "✨ drastically simplify development" }, { "code": null, "e": 959, "s": 840, "text": "📦 package / serialize all data cleaning, pre-processing together with your model algorithm into a single pipeline file" }, { "code": null, "e": 1053, "s": 959, "text": "😌 reuse the interface/components from pandas & scikit-learn that you’re already familiar with" }, { "code": null, "e": 1265, "s": 1053, "text": "Skippa helps you to easily define data cleaning & pre-processing operations on a pandas DataFrame and combine it with a scikit-learn model/algorithm into a single executable pipeline. It works roughly like this:" }, { "code": null, "e": 1735, "s": 1265, "text": "from skippa import Skippa, columnsfrom sklearn.linear_model import LogisticRegressionX, y = get_training_data(...)pipeline = ( Skippa() .impute(columns(dtype_include='object'), strategy='most_frequent') .impute(columns(dtype_include='number'), strategy='median') .scale(columns(dtype_include='number'), type='standard') .onehot(columns(['category1', 'category2'])) .model(LogisticRegression()))pipeline.fit(X, y)predictions = pipeline.predict_proba(X)" }, { "code": null, "e": 2000, "s": 1735, "text": "☝️ Skippa does not presume to fix all problems, does not cover all functionality you might ever need and is not a highly scalable solution, but it should be able to offer a massive simplification for > 80% of regular pandas/sklearn based machine learning projects." }, { "code": null, "e": 2009, "s": 2000, "text": "📂 Github" }, { "code": null, "e": 2016, "s": 2009, "text": "📦 pypi" }, { "code": null, "e": 2030, "s": 2016, "text": "📝 readthedocs" }, { "code": null, "e": 2079, "s": 2030, "text": "⏩ skip the essay and go directly to the fun part" }, { "code": null, "e": 2505, "s": 2079, "text": "For tasks that are conceptually quite simple — imputing missing values, one-hot encoding categorical values, selecting a subset of columns, scaling etc. — you need quite a lot of code. If generally you start out with a pandasdataframe consisting of columns of various data types, you require different transformations of different columns and a lot of your code involves selecting column subsets and merging transformed data." }, { "code": null, "e": 2687, "s": 2505, "text": "What you want is basically a set of steps where you say: I want to apply this transformation to these columns. If only there was a package that enabled you to code in such idioms..." }, { "code": null, "e": 3118, "s": 2687, "text": "If you want to deploy your model, you need to be able to reproduce your pre-processing code for use in a prediction context. Also, besides your pickled model file, you need pickled files for your fitted scaler, fitted one-hot encoder(s) and possible other transformations, since they are needed to generate predictions on new data! This quickly becomes hard to maintain. If only you could save all this logic into a single file..." }, { "code": null, "e": 3201, "s": 3118, "text": "Now, a lot of work has already been done on this subject. In scikit-learn you have" }, { "code": null, "e": 3280, "s": 3201, "text": "the Pipeline which you can use to chain certain transformers to your algorithm" }, { "code": null, "e": 3390, "s": 3280, "text": "and the ColumnTransformer which you can use to define pipelines of transformers on different sets of columns." }, { "code": null, "e": 3456, "s": 3390, "text": "I find this cumbersome to work with though. Look at this example:" }, { "code": null, "e": 4638, "s": 3456, "text": "import numpy as npimport pandas as pdfrom sklearn.compose import ColumnTransformerfrom sklearn.impute import SimpleImputerfrom sklearn.pipeline import Pipelinefrom sklearn.preprocessing import OneHotEncoderfrom sklearn.tree import DecisionTreeClassifier# this is the input dataframedf = pd.DataFrame({ 'favorite_color':['blue','green','red','green','blue'], 'age': [10,15,10,np.nan,10], 'target':[1,0,1,0,1]})# define individual transformers in a pipelinecategorical_preprocessing = Pipeline([('ohe', OneHotEncoder())])numerical_preprocessing = Pipeline([('imputation', SimpleImputer())])# define which transformer applies to which columnspreprocess = ColumnTransformer([ ('categorical_preprocessing', categorical_preprocessing, ['favorite_color']), ('numerical_preprocessing', numerical_preprocessing, ['age'])])# create the final pipeline with preprocessing steps and # the final classifier steppipeline = Pipeline([ ('preprocess', preprocess), ('clf', DecisionTreeClassifier())])# now fit the pipeline using the whole dataframedf_features = df[['favorite_color','age']]df_target = df['target']# call fit on the dataframespipeline.fit(df_features, df_target)" }, { "code": null, "e": 4662, "s": 4638, "text": "Now this does work, but" }, { "code": null, "e": 4710, "s": 4662, "text": "it’s rather complex and cumbersome to work with" }, { "code": null, "e": 4886, "s": 4710, "text": "you run into limitations if you need serial transformations on various sets of columns, because the output of each transformer is a numpy array, rather than a pandas dataframe" }, { "code": null, "e": 5030, "s": 4886, "text": "There is a package sklearn-pandas which is a noble effort to remedy these issues. While it does solve some problems, I’m not satisfied with it." }, { "code": null, "e": 5693, "s": 5030, "text": "The most important design principle of skippa is that the output of a transformation is always a pandas DataFrame. Why? Because conceptually you start out with a DataFrame, consisting of different columns of different data types, requiring different transformations. Using sklearn, the output of a transformation is a numpy array. This generally means you lose column names and data types (everything becomes float). Conceptually, when chaining together a pipeline, you want to keep referring to columns using their names and/or data types. This is only possible when the DataFrame is consistently used throughout the pipeline as the central data representation." }, { "code": null, "e": 6064, "s": 5693, "text": "Skippa achieves this result by implementing customized versions of existing transformations. Now, there is of course a drawback to this approach: those transformations cannot be used directly and a specific wrapper needs to be implemented. This always means a development cost and a maintainability cost. I hope this cost is outweighed by the benefits offered by Skippa." }, { "code": null, "e": 6093, "s": 6064, "text": "Other design considerations:" }, { "code": null, "e": 6201, "s": 6093, "text": "Skippa aims to have a syntax that is the shortest and simplest way possible to define your transformations." }, { "code": null, "e": 6430, "s": 6201, "text": "Skippa doesn’t support all functionality you might ever need. The intent is to provide added value for the large majority of use cases, not for all use cases. But there’s still a fallback way to define arbitrary transformations!" }, { "code": null, "e": 6620, "s": 6430, "text": "Yes, you need to learn a slightly new ‘language’ (i.e. the Skippa methods), but I feel this is quite straightforward and very easy to learn for anyone familiar with pandas and scikit-learn." }, { "code": null, "e": 6729, "s": 6620, "text": "So, after all this complaining and being a smart ass claiming to know better, let’s show what Skippa can do!" }, { "code": null, "e": 6760, "s": 6729, "text": "Installation is just via pypi:" }, { "code": null, "e": 6781, "s": 6760, "text": "$ pip install skippa" }, { "code": null, "e": 6839, "s": 6781, "text": "Import the Skippa object and the columns helper function:" }, { "code": null, "e": 6874, "s": 6839, "text": "from skippa import Skippa, columns" }, { "code": null, "e": 7173, "s": 6874, "text": "The idea is that you start out with a pandas DataFrame. You then initiate a Skippa pipeline and then use chaining commands to define transformations that need to be applied to certain columns. The last step is generally a model estimator (e.g. a classifier, regressor, clusterer) from scikit-learn." }, { "code": null, "e": 7457, "s": 7173, "text": "X, y = get_training_data(...)pipeline = ( Skippa() .<transformation-1>(<column-definition>, <optional-args>) .<transformation-2>(<column-definition>, <optional-args>) ... .model(<model-estimator>(<optional-args>)))pipeline.fit(X, y)pipeline.save('./models/mypipeline')" }, { "code": null, "e": 7531, "s": 7457, "text": "Ok, now a specific example. We have a pandas DataFrame X with 10 columns:" }, { "code": null, "e": 7607, "s": 7531, "text": "4 float columns, 2 integer columns, 3 categorical columns and 1 date column" }, { "code": null, "e": 7675, "s": 7607, "text": "We have missing values in float columns and in a categorical column" }, { "code": null, "e": 7721, "s": 7675, "text": "and we have a set of labels y (either 0 or 1)" }, { "code": null, "e": 7757, "s": 7721, "text": "What we want to do is the following" }, { "code": null, "e": 7797, "s": 7757, "text": "remove a bunch of columns we don’t need" }, { "code": null, "e": 7899, "s": 7797, "text": "impute missing values (median value for numeric columns, most frequent value for categorical columns)" }, { "code": null, "e": 7934, "s": 7899, "text": "one-hot encode categorical columns" }, { "code": null, "e": 7962, "s": 7934, "text": "scale the numerical columns" }, { "code": null, "e": 7994, "s": 7962, "text": "fit a logistic regression model" }, { "code": null, "e": 8031, "s": 7994, "text": "We can do this in a couple of lines:" }, { "code": null, "e": 8410, "s": 8031, "text": "pipe = ( Skippa() .select(columns(exclude=['a', 'f', 'i', 'j'])) .impute(columns(dtype_include='number'), strategy='median') .impute(columns(dtype_include='object'), strategy='most_frequent') .scale(columns(dtype_include='number'), type='standard') .onehot(columns(['g', 'h'])) .model(LogisticRegression()))pipe.fit(X, y)pipeline.save('./models/mypipeline')" }, { "code": null, "e": 8613, "s": 8410, "text": "The file we saved is a SkippaPipeline which is a child class of scikit-learn’s Pipeline. It contains the entire pipeline of the pre-processing and the logistic regression. It’s easy to deploy and reuse:" }, { "code": null, "e": 8756, "s": 8613, "text": "df_scoring = get_scoring_data(...)my_pipeline = Skippa.load_pipeline('./models/mypipeline')predictions = my_pipeline.predict_proba(df_scoring)" }, { "code": null, "e": 8925, "s": 8756, "text": "Since the Skippa pipeline is (extends) a regular scikit-learn Pipeline object, you can use all the standard methods like .fit, .transform, .predict, .predict_proba etc." }, { "code": null, "e": 9192, "s": 8925, "text": "It’s entirely feasible that you’re just interested in processing data, without the wish to finish your pipeline with a modeling algorithm. Or maybe you simply want to inspect the final dataset that goes into your algorithm. That’s possible using the .build() method:" }, { "code": null, "e": 9556, "s": 9192, "text": "pipe = ( Skippa() .select(columns(exclude=['a', 'f', 'i', 'j'])) .impute(columns(dtype_include='number'), strategy='median') .impute(columns(dtype_include='object'), strategy='most_frequent') .scale(columns(dtype_include='number'), type='standard') .onehot(columns(['g', 'h'])) .build())df_processed = pipe.fit_transform(X)df_processed.info()" }, { "code": null, "e": 9732, "s": 9556, "text": "Defining a subset of columns for a transformation is done using the columns() function. There are several ways to use this. E.g. including or excluding a list of column names:" }, { "code": null, "e": 9789, "s": 9732, "text": "columns(['a', 'b']) simply define a list of column names" }, { "code": null, "e": 9836, "s": 9789, "text": "columns(include=['a', 'b']) this is equivalent" }, { "code": null, "e": 9903, "s": 9836, "text": "columns(exclude=['a', 'b']) analogously, you can de-select columns" }, { "code": null, "e": 10009, "s": 9903, "text": "You can also use dtype_include, dtype_exclude and pattern from sklearn’s make_column_selector() function." }, { "code": null, "e": 10066, "s": 10009, "text": "columns(dtype_include='float') selects all float columns" }, { "code": null, "e": 10127, "s": 10066, "text": "columns(dtype_exclude='number') deselect all numeric columns" }, { "code": null, "e": 10201, "s": 10127, "text": "columns(pattern='myprefix_*') selects all columns starting with myprefix_" }, { "code": null, "e": 10256, "s": 10201, "text": "You can also add / subtract multiple column selectors!" }, { "code": null, "e": 10353, "s": 10256, "text": "columns(dtype_include='object') — columns(['c', ‘d']) selects all object columns except c and d." }, { "code": null, "e": 10544, "s": 10353, "text": "These are the transformations Skippa supports. They can be either a wrapper around existing scikit-learn transformers, existing pandas.DataFrame methods, or custom implementations if needed." }, { "code": null, "e": 10658, "s": 10544, "text": ".impute() Wrapper around sklearn’s SimpleImputer. Example: .impute(columns(dtype_include='int'), method='medium')" }, { "code": null, "e": 10823, "s": 10658, "text": ".scale() Wrapper around sklearn’s StandardScaler (if type='standard') or MinMaxScaler (if type='minmax').Example: .scale(columns(dtype_include='numeric'), 'minmax')" }, { "code": null, "e": 10924, "s": 10823, "text": ".onehot() Wrapper around sklearn’s OneHotEncoder.Example: .onehot(columns(dtype_include='category'))" }, { "code": null, "e": 11180, "s": 10924, "text": ".encode_date() Custom transformer for creating features out of a date values. It applies pandas’ pd.to_datetime() and uses the properties from the resulting .dt object.Example: .encode_date(columns(['mydate']), {'year': False, 'month': True, 'day': True})" }, { "code": null, "e": 11324, "s": 11180, "text": ".cast() Wrapper around pandas.DataFrame.astype(). It has aliases .astype() and .as_type().Example: .cast(columns(dtype_include='int'), 'float')" }, { "code": null, "e": 11458, "s": 11324, "text": ".rename() Wrapper around pandas.DataFrame.rename().N.B. Does not have a columns specifier!Example: .rename({'a': 'name', 'b': 'age'})" }, { "code": null, "e": 11599, "s": 11458, "text": ".assign() Wrapper around pandas.DataFrame.assign(). N.B. Does not have a columns specifier!Example: .assign(y_sq=lambda df: df['y']*df['y'])" }, { "code": null, "e": 11671, "s": 11599, "text": ".apply() Wrapper round pandas.DataFrame.apply().Example: .apply(np.log)" }, { "code": null, "e": 11768, "s": 11671, "text": ".select() Simply selecting a subset of columns.Example: .select(columns(dtype_exclude='object'))" }, { "code": null, "e": 11993, "s": 11768, "text": ".model() Not a transformer but an estimator. Can only be used as the final step in your pipeline. Provide an (instantiated) sklearn estimator as argument.Example: .model(RandomForestClassifier(n_estimators=200, max_depth=5))" }, { "code": null, "e": 12249, "s": 11993, "text": ".concat() Concatenate another parallel pipeline to the current one. This will concatenate those pipelines’ resulting set of features.Example:pipe1 = Skippa().apply(np.log)pipe2 = Skippa().apply(np.sqrt)final = pipe2.concat(pipe1).model(LinearRegression())" }, { "code": null, "e": 12470, "s": 12249, "text": "☝️ The idea is to keep adding transformers for extra functionality, but for any functionality that is not (or not yet) supported there is always an option to use the .assign or .apply methods to apply any transformation." } ]
Count number less than N which are product of perfect squares - GeeksforGeeks
10 May, 2021 Given an Integer N. The task is count numbers P less than N such that P is a product of two distinct perfect squares.Examples: Input : N = 36 Output : 5 Numbers are 4 = 12 * 22, 9 = 12 * 32, 16 = 12 * 42, 25 = 12 * 52, 36 = 12 * 62 Input : N = 1000000 Output : 999 Approach: Let us consider a number P = (a2 * b2) such that P <= N. So we have (a2 * b2) <= N. This can be written as (a * b) <= sqrt(N).So we have to count pairs (a, b) such that (a * b) <= sqrt(N) and a <= b. Let us take a number Q = (a * b) such that Q <= sqrt(N). Taking a = 1, we have b = sqrt(N) – 1 numbers such that, ( a * b = Q <= sqrt(N)).Thus we can have all sqrt(N) – 1 numbers such that (a2 * b2) <= N.Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // C++ program to count number less// than N which are product of// any two perfect squares #include <bits/stdc++.h>using namespace std; // Function to count number less// than N which are product of// any two perfect squaresint countNumbers(int N){ return int(sqrt(N)) - 1;} // Driver programint main(){ int N = 36; cout << countNumbers(N); return 0;} // Java program to count number less// than N which are product of// any two perfect squaresimport java.util.*; class solution{ // Function to count number less// than N which are product of// any two perfect squaresstatic int countNumbers(int N){ return (int)Math.sqrt(N) - 1;} // Driver programpublic static void main(String args[]){ int N = 36; System.out.println(countNumbers(N)); } } //This code is contributed by// Surendra_Gangwar # Python 3 program to count number# less than N which are product of# any two perfect squaresimport math # Function to count number less# than N which are product of# any two perfect squaresdef countNumbers(N): return int(math.sqrt(N)) - 1 # Driver Codeif __name__ == "__main__": N = 36 print(countNumbers(N)) # This code is contributed# by ChitraNayal // C# program to count number less// than N which are product of// any two perfect squaresusing System; class GFG{// Function to count number less// than N which are product of// any two perfect squaresstatic int countNumbers(int N){ return (int)(Math.Sqrt(N)) - 1;} // Driver Codepublic static void Main(){ int N = 36; Console.Write(countNumbers(N));}} // This code is contributed// by Akanksha Rai <?php// PHP program to count number less// than N which are product of// any two perfect squares // Function to count number less// than N which are product of// any two perfect squaresfunction countNumbers($N){ return (int)(sqrt($N)) - 1;} // Driver Code$N = 36;echo countNumbers($N); // This code is contributed by akt_mit?> <script> // Javascript program to count number less // than N which are product of // any two perfect squares // Function to count number less // than N which are product of // any two perfect squares function countNumbers(N) { return parseInt(Math.sqrt(N), 10) - 1; } let N = 36; document.write(countNumbers(N)); </script> 5 Time Complexity: O(log(N)) ukasp Akanksha_Rai SURENDRA_GANGWAR jit_t decode2207 maths-perfect-square number-theory Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Fizz Buzz Implementation Program to multiply two matrices Modular multiplicative inverse Check if a number is Palindrome Find first and last digits of a number Count ways to reach the n'th stair Program to convert a given number to words Find Union and Intersection of two unsorted arrays
[ { "code": null, "e": 24692, "s": 24664, "text": "\n10 May, 2021" }, { "code": null, "e": 24821, "s": 24692, "text": "Given an Integer N. The task is count numbers P less than N such that P is a product of two distinct perfect squares.Examples: " }, { "code": null, "e": 24964, "s": 24821, "text": "Input : N = 36\nOutput : 5\nNumbers are 4 = 12 * 22, \n9 = 12 * 32, \n16 = 12 * 42, \n25 = 12 * 52, \n36 = 12 * 62\n\nInput : N = 1000000\nOutput : 999" }, { "code": null, "e": 25432, "s": 24966, "text": "Approach: Let us consider a number P = (a2 * b2) such that P <= N. So we have (a2 * b2) <= N. This can be written as (a * b) <= sqrt(N).So we have to count pairs (a, b) such that (a * b) <= sqrt(N) and a <= b. Let us take a number Q = (a * b) such that Q <= sqrt(N). Taking a = 1, we have b = sqrt(N) – 1 numbers such that, ( a * b = Q <= sqrt(N)).Thus we can have all sqrt(N) – 1 numbers such that (a2 * b2) <= N.Below is the implementation of the above approach: " }, { "code": null, "e": 25436, "s": 25432, "text": "C++" }, { "code": null, "e": 25441, "s": 25436, "text": "Java" }, { "code": null, "e": 25450, "s": 25441, "text": "Python 3" }, { "code": null, "e": 25453, "s": 25450, "text": "C#" }, { "code": null, "e": 25457, "s": 25453, "text": "PHP" }, { "code": null, "e": 25468, "s": 25457, "text": "Javascript" }, { "code": "// C++ program to count number less// than N which are product of// any two perfect squares #include <bits/stdc++.h>using namespace std; // Function to count number less// than N which are product of// any two perfect squaresint countNumbers(int N){ return int(sqrt(N)) - 1;} // Driver programint main(){ int N = 36; cout << countNumbers(N); return 0;}", "e": 25835, "s": 25468, "text": null }, { "code": "// Java program to count number less// than N which are product of// any two perfect squaresimport java.util.*; class solution{ // Function to count number less// than N which are product of// any two perfect squaresstatic int countNumbers(int N){ return (int)Math.sqrt(N) - 1;} // Driver programpublic static void main(String args[]){ int N = 36; System.out.println(countNumbers(N)); } } //This code is contributed by// Surendra_Gangwar", "e": 26288, "s": 25835, "text": null }, { "code": "# Python 3 program to count number# less than N which are product of# any two perfect squaresimport math # Function to count number less# than N which are product of# any two perfect squaresdef countNumbers(N): return int(math.sqrt(N)) - 1 # Driver Codeif __name__ == \"__main__\": N = 36 print(countNumbers(N)) # This code is contributed# by ChitraNayal", "e": 26651, "s": 26288, "text": null }, { "code": "// C# program to count number less// than N which are product of// any two perfect squaresusing System; class GFG{// Function to count number less// than N which are product of// any two perfect squaresstatic int countNumbers(int N){ return (int)(Math.Sqrt(N)) - 1;} // Driver Codepublic static void Main(){ int N = 36; Console.Write(countNumbers(N));}} // This code is contributed// by Akanksha Rai", "e": 27061, "s": 26651, "text": null }, { "code": "<?php// PHP program to count number less// than N which are product of// any two perfect squares // Function to count number less// than N which are product of// any two perfect squaresfunction countNumbers($N){ return (int)(sqrt($N)) - 1;} // Driver Code$N = 36;echo countNumbers($N); // This code is contributed by akt_mit?>", "e": 27391, "s": 27061, "text": null }, { "code": "<script> // Javascript program to count number less // than N which are product of // any two perfect squares // Function to count number less // than N which are product of // any two perfect squares function countNumbers(N) { return parseInt(Math.sqrt(N), 10) - 1; } let N = 36; document.write(countNumbers(N)); </script>", "e": 27772, "s": 27391, "text": null }, { "code": null, "e": 27774, "s": 27772, "text": "5" }, { "code": null, "e": 27804, "s": 27776, "text": "Time Complexity: O(log(N)) " }, { "code": null, "e": 27810, "s": 27804, "text": "ukasp" }, { "code": null, "e": 27823, "s": 27810, "text": "Akanksha_Rai" }, { "code": null, "e": 27840, "s": 27823, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 27846, "s": 27840, "text": "jit_t" }, { "code": null, "e": 27857, "s": 27846, "text": "decode2207" }, { "code": null, "e": 27878, "s": 27857, "text": "maths-perfect-square" }, { "code": null, "e": 27892, "s": 27878, "text": "number-theory" }, { "code": null, "e": 27905, "s": 27892, "text": "Mathematical" }, { "code": null, "e": 27919, "s": 27905, "text": "number-theory" }, { "code": null, "e": 27932, "s": 27919, "text": "Mathematical" }, { "code": null, "e": 28030, "s": 27932, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28062, "s": 28030, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 28106, "s": 28062, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 28131, "s": 28106, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 28164, "s": 28131, "text": "Program to multiply two matrices" }, { "code": null, "e": 28195, "s": 28164, "text": "Modular multiplicative inverse" }, { "code": null, "e": 28227, "s": 28195, "text": "Check if a number is Palindrome" }, { "code": null, "e": 28266, "s": 28227, "text": "Find first and last digits of a number" }, { "code": null, "e": 28301, "s": 28266, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 28344, "s": 28301, "text": "Program to convert a given number to words" } ]
Android ViewPager in Kotlin - GeeksforGeeks
21 Apr, 2021 ViewPager allows the users to swipe left or right through the pages containing data or see an entirely new screen. You can find this feature in all most many social media apps. WhatsApp also shows users three tabs in their app when it is opened: chats, status, and calls. It would be exciting to learn this feature as we have seen the real-world applications of this feature. It is also used to help the user to know about the app and its features while installing the app for the first time. We will be using TabLayout as an example for applying the ViewPager concept in the app. After reading this article, it would be easy for you to apply this feature in any app. We will start by adding the TabLayout and ViewPager in the activity_main.xml. After doing this, we will add three blank fragments to the app. We will change the text as per our needs in all the three XML files of the fragments. Now, we will create PageAdapter.kt class in which we have to work with three functions getCount(), getItem() and getPageTitle(). Finally, we just need to call the Adapter and the TabLayout. A sample gif is given below to get practical knowledge about the idea that we are implementing. getCount() – Returns the number of fragments to show. getItem() – Returns the fragment at the position index. getPageTitle – Returns the title given to the page(in our case, the title which is given to each page like tab1, tab2, tab3) Step 1: Create a project with the Empty Activity To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Make sure you have chosen Kotlin as the language while creating the project. Step 2: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Here we have just added the TabLayout and ViewPager. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <com.google.android.material.tabs.TabLayout android:id="@+id/tabLayout" android:layout_width="409dp" android:layout_height="wrap_content" android:layout_marginTop="1dp" android:layout_marginBottom="1dp" app:layout_constraintBottom_toTopOf="@+id/viewPager" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" > </com.google.android.material.tabs.TabLayout> <androidx.viewpager.widget.ViewPager android:id="@+id/viewPager" android:layout_width="0dp" android:layout_height="0dp" android:layout_marginStart="1dp" android:layout_marginEnd="1dp" android:layout_marginBottom="1dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/tabLayout" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 3: Adding the blank fragments This is the path to create a blank fragment in Android Studio. After clicking on the Blank Fragment, name the fragment and click on finish. Make three fragments in total. Step 4: Working with the XML files of fragments In each fragment, we have changed the text and added the basic things to our XML file like textColor, textSize, etc. Fragment 1 XML <?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Fragment1"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:textColor="@color/green" android:textSize="50dp" android:text="GFG 1" /> </FrameLayout> Fragment 2 XML <?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Fragment2"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:textColor="@color/green" android:textSize="50dp" android:text="GFG 2" /> </FrameLayout> Fragment 3 XML <?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Fragment3"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:textColor="@color/green" android:textSize="50dp" android:text="GFG 3" /> </FrameLayout> Step 5: Adding a Page Adapter Kotlin import androidx.fragment.app.Fragmentimport androidx.fragment.app.FragmentManagerimport androidx.fragment.app.FragmentPagerAdapter class PageAdapter(fm:FragmentManager) : FragmentPagerAdapter(fm) { override fun getCount(): Int { return 3; } override fun getItem(position: Int): Fragment { when(position) { 0 -> { return Fragment1() } 1 -> { return Fragment2() } 2 -> { return Fragment3() } else -> { return Fragment1() } } } override fun getPageTitle(position: Int): CharSequence? { when(position) { 0 -> { return "Tab 1" } 1 -> { return "Tab 2" } 2 -> { return "Tab 3" } } return super.getPageTitle(position) } } Step 6: Working with MainActivity.kt Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport androidx.viewpager.widget.ViewPagerimport com.google.android.material.tabs.TabLayout class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val viewPager = findViewById<ViewPager>(R.id.viewPager) viewPager.adapter = PageAdapter(supportFragmentManager) val tabLayout = findViewById<TabLayout>(R.id.tabLayout) tabLayout.setupWithViewPager(viewPager) }} Output: You can also try to do use this concept to make a similar thing in java. Click here to get the article. Kotlin Android Picked Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Android Listview in Java with Example Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 24725, "s": 24697, "text": "\n21 Apr, 2021" }, { "code": null, "e": 25393, "s": 24725, "text": "ViewPager allows the users to swipe left or right through the pages containing data or see an entirely new screen. You can find this feature in all most many social media apps. WhatsApp also shows users three tabs in their app when it is opened: chats, status, and calls. It would be exciting to learn this feature as we have seen the real-world applications of this feature. It is also used to help the user to know about the app and its features while installing the app for the first time. We will be using TabLayout as an example for applying the ViewPager concept in the app. After reading this article, it would be easy for you to apply this feature in any app." }, { "code": null, "e": 25908, "s": 25393, "text": "We will start by adding the TabLayout and ViewPager in the activity_main.xml. After doing this, we will add three blank fragments to the app. We will change the text as per our needs in all the three XML files of the fragments. Now, we will create PageAdapter.kt class in which we have to work with three functions getCount(), getItem() and getPageTitle(). Finally, we just need to call the Adapter and the TabLayout. A sample gif is given below to get practical knowledge about the idea that we are implementing. " }, { "code": null, "e": 25962, "s": 25908, "text": "getCount() – Returns the number of fragments to show." }, { "code": null, "e": 26018, "s": 25962, "text": "getItem() – Returns the fragment at the position index." }, { "code": null, "e": 26143, "s": 26018, "text": "getPageTitle – Returns the title given to the page(in our case, the title which is given to each page like tab1, tab2, tab3)" }, { "code": null, "e": 26192, "s": 26143, "text": "Step 1: Create a project with the Empty Activity" }, { "code": null, "e": 26380, "s": 26192, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Make sure you have chosen Kotlin as the language while creating the project." }, { "code": null, "e": 26428, "s": 26380, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 26624, "s": 26428, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Here we have just added the TabLayout and ViewPager. " }, { "code": null, "e": 26628, "s": 26624, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <com.google.android.material.tabs.TabLayout android:id=\"@+id/tabLayout\" android:layout_width=\"409dp\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"1dp\" android:layout_marginBottom=\"1dp\" app:layout_constraintBottom_toTopOf=\"@+id/viewPager\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" > </com.google.android.material.tabs.TabLayout> <androidx.viewpager.widget.ViewPager android:id=\"@+id/viewPager\" android:layout_width=\"0dp\" android:layout_height=\"0dp\" android:layout_marginStart=\"1dp\" android:layout_marginEnd=\"1dp\" android:layout_marginBottom=\"1dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/tabLayout\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 28044, "s": 26628, "text": null }, { "code": null, "e": 28080, "s": 28044, "text": "Step 3: Adding the blank fragments " }, { "code": null, "e": 28143, "s": 28080, "text": "This is the path to create a blank fragment in Android Studio." }, { "code": null, "e": 28252, "s": 28143, "text": "After clicking on the Blank Fragment, name the fragment and click on finish. Make three fragments in total. " }, { "code": null, "e": 28301, "s": 28252, "text": "Step 4: Working with the XML files of fragments " }, { "code": null, "e": 28419, "s": 28301, "text": "In each fragment, we have changed the text and added the basic things to our XML file like textColor, textSize, etc. " }, { "code": null, "e": 28430, "s": 28419, "text": "Fragment 1" }, { "code": null, "e": 28434, "s": 28430, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><FrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".Fragment1\"> <TextView android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:textColor=\"@color/green\" android:textSize=\"50dp\" android:text=\"GFG 1\" /> </FrameLayout>", "e": 28928, "s": 28434, "text": null }, { "code": null, "e": 28939, "s": 28928, "text": "Fragment 2" }, { "code": null, "e": 28943, "s": 28939, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><FrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".Fragment2\"> <TextView android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:textColor=\"@color/green\" android:textSize=\"50dp\" android:text=\"GFG 2\" /> </FrameLayout>", "e": 29437, "s": 28943, "text": null }, { "code": null, "e": 29448, "s": 29437, "text": "Fragment 3" }, { "code": null, "e": 29452, "s": 29448, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><FrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".Fragment3\"> <TextView android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:textColor=\"@color/green\" android:textSize=\"50dp\" android:text=\"GFG 3\" /> </FrameLayout>", "e": 29945, "s": 29452, "text": null }, { "code": null, "e": 29975, "s": 29945, "text": "Step 5: Adding a Page Adapter" }, { "code": null, "e": 29982, "s": 29975, "text": "Kotlin" }, { "code": "import androidx.fragment.app.Fragmentimport androidx.fragment.app.FragmentManagerimport androidx.fragment.app.FragmentPagerAdapter class PageAdapter(fm:FragmentManager) : FragmentPagerAdapter(fm) { override fun getCount(): Int { return 3; } override fun getItem(position: Int): Fragment { when(position) { 0 -> { return Fragment1() } 1 -> { return Fragment2() } 2 -> { return Fragment3() } else -> { return Fragment1() } } } override fun getPageTitle(position: Int): CharSequence? { when(position) { 0 -> { return \"Tab 1\" } 1 -> { return \"Tab 2\" } 2 -> { return \"Tab 3\" } } return super.getPageTitle(position) } }", "e": 30921, "s": 29982, "text": null }, { "code": null, "e": 30958, "s": 30921, "text": "Step 6: Working with MainActivity.kt" }, { "code": null, "e": 31144, "s": 30958, "text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 31151, "s": 31144, "text": "Kotlin" }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport androidx.viewpager.widget.ViewPagerimport com.google.android.material.tabs.TabLayout class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val viewPager = findViewById<ViewPager>(R.id.viewPager) viewPager.adapter = PageAdapter(supportFragmentManager) val tabLayout = findViewById<TabLayout>(R.id.tabLayout) tabLayout.setupWithViewPager(viewPager) }}", "e": 31758, "s": 31151, "text": null }, { "code": null, "e": 31766, "s": 31758, "text": "Output:" }, { "code": null, "e": 31870, "s": 31766, "text": "You can also try to do use this concept to make a similar thing in java. Click here to get the article." }, { "code": null, "e": 31885, "s": 31870, "text": "Kotlin Android" }, { "code": null, "e": 31892, "s": 31885, "text": "Picked" }, { "code": null, "e": 31900, "s": 31892, "text": "Android" }, { "code": null, "e": 31905, "s": 31900, "text": "Java" }, { "code": null, "e": 31910, "s": 31905, "text": "Java" }, { "code": null, "e": 31918, "s": 31910, "text": "Android" }, { "code": null, "e": 32016, "s": 31918, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32025, "s": 32016, "text": "Comments" }, { "code": null, "e": 32038, "s": 32025, "text": "Old Comments" }, { "code": null, "e": 32077, "s": 32038, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 32127, "s": 32077, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 32178, "s": 32127, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 32216, "s": 32178, "text": "Android Listview in Java with Example" }, { "code": null, "e": 32258, "s": 32216, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 32273, "s": 32258, "text": "Arrays in Java" }, { "code": null, "e": 32317, "s": 32273, "text": "Split() String method in Java with examples" }, { "code": null, "e": 32339, "s": 32317, "text": "For-each loop in Java" }, { "code": null, "e": 32364, "s": 32339, "text": "Reverse a string in Java" } ]
XML - Character Entities
This chapter describes the XML Character Entities. Before we understand the Character Entities, let us first understand what an XML entity is. As put by W3 Consortium the definition of an entity is as follows − This means, entities are the placeholders in XML. These can be declared in the document prolog or in a DTD. There are different types of entities and in this chapter we will discuss Character Entity. Both, HTML and XML, have some symbols reserved for their use, which cannot be used as content in XML code. For example, < and > signs are used for opening and closing XML tags. To display these special characters, the character entities are used. There are few special characters or symbols which are not available to be typed directly from the keyboard. Character Entities can also be used to display those symbols/special characters. There are three types of character entities − Predefined Character Entities Numbered Character Entities Named Character Entities They are introduced to avoid the ambiguity while using some symbols. For example, an ambiguity is observed when less than ( < ) or greater than ( > ) symbol is used with the angle tag (<>). Character entities are basically used to delimit tags in XML. Following is a list of pre-defined character entities from XML specification. These can be used to express characters without ambiguity. Ampersand − &amp; Ampersand − &amp; Single quote − &apos; Single quote − &apos; Greater than − &gt; Greater than − &gt; Less than − &lt; Less than − &lt; Double quote − " Double quote − " The numeric reference is used to refer to a character entity. Numeric reference can either be in decimal or hexadecimal format. As there are thousands of numeric references available, these are a bit hard to remember. Numeric reference refers to the character by its number in the Unicode character set. General syntax for decimal numeric reference is − &# decimal number ; General syntax for hexadecimal numeric reference is − &#x Hexadecimal number ; The following table lists some predefined character entities with their numeric values − As it is hard to remember the numeric characters, the most preferred type of character entity is the named character entity. Here, each entity is identified with a name. For example − 'Aacute' represents capital character with acute accent. 'Aacute' represents capital character with acute accent. 'ugrave' represents the small with grave accent. 'ugrave' represents the small with grave accent. 84 Lectures 6 hours Frahaan Hussain 29 Lectures 2 hours YouAccel 27 Lectures 1 hours Jordan Stanchev 16 Lectures 2 hours Simon Sez IT Print Add Notes Bookmark this page
[ { "code": null, "e": 2104, "s": 1961, "text": "This chapter describes the XML Character Entities. Before we understand the Character Entities, let us first understand what an XML entity is." }, { "code": null, "e": 2172, "s": 2104, "text": "As put by W3 Consortium the definition of an entity is as follows −" }, { "code": null, "e": 2372, "s": 2172, "text": "This means, entities are the placeholders in XML. These can be declared in the document prolog or in a DTD. There are different types of entities and in this chapter we will discuss Character Entity." }, { "code": null, "e": 2619, "s": 2372, "text": "Both, HTML and XML, have some symbols reserved for their use, which cannot be used as content in XML code. For example, < and > signs are used for opening and closing XML tags. To display these special characters, the character entities are used." }, { "code": null, "e": 2808, "s": 2619, "text": "There are few special characters or symbols which are not available to be typed directly from the keyboard. Character Entities can also be used to display those symbols/special characters." }, { "code": null, "e": 2854, "s": 2808, "text": "There are three types of character entities −" }, { "code": null, "e": 2884, "s": 2854, "text": "Predefined Character Entities" }, { "code": null, "e": 2912, "s": 2884, "text": "Numbered Character Entities" }, { "code": null, "e": 2937, "s": 2912, "text": "Named Character Entities" }, { "code": null, "e": 3326, "s": 2937, "text": "They are introduced to avoid the ambiguity while using some symbols. For example, an ambiguity is observed when less than ( < ) or greater than ( > ) symbol is used with the angle tag (<>). Character entities are basically used to delimit tags in XML. Following is a list of pre-defined character entities from XML specification. These can be used to express characters without ambiguity." }, { "code": null, "e": 3344, "s": 3326, "text": "Ampersand − &amp;" }, { "code": null, "e": 3362, "s": 3344, "text": "Ampersand − &amp;" }, { "code": null, "e": 3384, "s": 3362, "text": "Single quote − &apos;" }, { "code": null, "e": 3406, "s": 3384, "text": "Single quote − &apos;" }, { "code": null, "e": 3426, "s": 3406, "text": "Greater than − &gt;" }, { "code": null, "e": 3446, "s": 3426, "text": "Greater than − &gt;" }, { "code": null, "e": 3463, "s": 3446, "text": "Less than − &lt;" }, { "code": null, "e": 3480, "s": 3463, "text": "Less than − &lt;" }, { "code": null, "e": 3497, "s": 3480, "text": "Double quote − \"" }, { "code": null, "e": 3514, "s": 3497, "text": "Double quote − \"" }, { "code": null, "e": 3818, "s": 3514, "text": "The numeric reference is used to refer to a character entity. Numeric reference can either be in decimal or hexadecimal format. As there are thousands of numeric references available, these are a bit hard to remember. Numeric reference refers to the character by its number in the Unicode character set." }, { "code": null, "e": 3868, "s": 3818, "text": "General syntax for decimal numeric reference is −" }, { "code": null, "e": 3889, "s": 3868, "text": "&# decimal number ;\n" }, { "code": null, "e": 3943, "s": 3889, "text": "General syntax for hexadecimal numeric reference is −" }, { "code": null, "e": 3969, "s": 3943, "text": "&#x Hexadecimal number ;\n" }, { "code": null, "e": 4058, "s": 3969, "text": "The following table lists some predefined character entities with their numeric values −" }, { "code": null, "e": 4228, "s": 4058, "text": "As it is hard to remember the numeric characters, the most preferred type of character\nentity is the named character entity. Here, each entity is identified with a name." }, { "code": null, "e": 4242, "s": 4228, "text": "For example −" }, { "code": null, "e": 4300, "s": 4242, "text": "'Aacute' represents capital character with acute accent." }, { "code": null, "e": 4358, "s": 4300, "text": "'Aacute' represents capital character with acute accent." }, { "code": null, "e": 4408, "s": 4358, "text": "'ugrave' represents the small with grave accent." }, { "code": null, "e": 4458, "s": 4408, "text": "'ugrave' represents the small with grave accent." }, { "code": null, "e": 4491, "s": 4458, "text": "\n 84 Lectures \n 6 hours \n" }, { "code": null, "e": 4508, "s": 4491, "text": " Frahaan Hussain" }, { "code": null, "e": 4541, "s": 4508, "text": "\n 29 Lectures \n 2 hours \n" }, { "code": null, "e": 4551, "s": 4541, "text": " YouAccel" }, { "code": null, "e": 4584, "s": 4551, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 4601, "s": 4584, "text": " Jordan Stanchev" }, { "code": null, "e": 4634, "s": 4601, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 4648, "s": 4634, "text": " Simon Sez IT" }, { "code": null, "e": 4655, "s": 4648, "text": " Print" }, { "code": null, "e": 4666, "s": 4655, "text": " Add Notes" } ]
JavaScript | handler.get() Method - GeeksforGeeks
28 Sep, 2021 The handler.get() method in JavaScript is a trap for getting a property value.Syntax: const p = new Proxy(target, { get: function(target, property, receiver) { } }); Parameters: This method accept three parameters as mentioned above and described below: Target: This parameter holds the target object. Property: This parameter holds the name of the property which is to be get. Receiver: This parameter holds the proxy or an object that inherits from the proxy. Return value: This method returns any value.Below examples illustrate the handler.get() method in JavaScript:Example 1: javascript <script>const monster1 = { string: 'Geeksforgeeks', num: 334}; const handler1 = { get: function(target, prop, receiver) { if (prop === 'string') { return `${target.string.substr(0, 8)} ... Best portal!`; } else { return Reflect.get(...arguments); } }}; const proxy1 = new Proxy(monster1, handler1); console.log(proxy1.num);console.log(proxy1.string);console.log(proxy1.numstring); const obj = new Proxy({}, { get: function(target, property, receiver) { console.log('Property : ' + property); return 56.56; }}); console.log(obj.value);</script> Output: 334 "Geeksfor ... Best portal!" undefined "Property : value" 56.56 Example 2: javascript <script>const obj = {};Object.defineProperty(obj, 'a', { configurable: false, enumerable: false, value: 10, writable: false}); const p = new Proxy(obj, { get: function(target, property) { return 10; }}); console.log(p.a); var datalist = { "vala": 32, "valb": 7 } var get = new Proxy( datalist, { get: function(y, idx) { return y[idx] * 11 } } ) for(var z in get) { console.log(z +" : "+ get[z]) } </script> Output: 10 "vala : 352" "valb : 77" Supported Browsers: The browsers supported by handler.get() method are listed below: Google Chrome 49 and above Edge 12 and above Firefox 18 and above Opera 36 and above Safari 10 and above ysachin2314 javascript-functions JavaScript 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 How to get character array from string in JavaScript? How to remove duplicate elements from JavaScript Array ? How to get selected value in dropdown list 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": 25220, "s": 25192, "text": "\n28 Sep, 2021" }, { "code": null, "e": 25308, "s": 25220, "text": "The handler.get() method in JavaScript is a trap for getting a property value.Syntax: " }, { "code": null, "e": 25392, "s": 25308, "text": "const p = new Proxy(target, {\n get: function(target, property, receiver) {\n }\n});" }, { "code": null, "e": 25482, "s": 25392, "text": "Parameters: This method accept three parameters as mentioned above and described below: " }, { "code": null, "e": 25530, "s": 25482, "text": "Target: This parameter holds the target object." }, { "code": null, "e": 25606, "s": 25530, "text": "Property: This parameter holds the name of the property which is to be get." }, { "code": null, "e": 25690, "s": 25606, "text": "Receiver: This parameter holds the proxy or an object that inherits from the proxy." }, { "code": null, "e": 25812, "s": 25690, "text": "Return value: This method returns any value.Below examples illustrate the handler.get() method in JavaScript:Example 1: " }, { "code": null, "e": 25823, "s": 25812, "text": "javascript" }, { "code": "<script>const monster1 = { string: 'Geeksforgeeks', num: 334}; const handler1 = { get: function(target, prop, receiver) { if (prop === 'string') { return `${target.string.substr(0, 8)} ... Best portal!`; } else { return Reflect.get(...arguments); } }}; const proxy1 = new Proxy(monster1, handler1); console.log(proxy1.num);console.log(proxy1.string);console.log(proxy1.numstring); const obj = new Proxy({}, { get: function(target, property, receiver) { console.log('Property : ' + property); return 56.56; }}); console.log(obj.value);</script>", "e": 26398, "s": 25823, "text": null }, { "code": null, "e": 26408, "s": 26398, "text": "Output: " }, { "code": null, "e": 26475, "s": 26408, "text": "334\n\"Geeksfor ... Best portal!\"\nundefined\n\"Property : value\"\n56.56" }, { "code": null, "e": 26488, "s": 26475, "text": "Example 2: " }, { "code": null, "e": 26499, "s": 26488, "text": "javascript" }, { "code": "<script>const obj = {};Object.defineProperty(obj, 'a', { configurable: false, enumerable: false, value: 10, writable: false}); const p = new Proxy(obj, { get: function(target, property) { return 10; }}); console.log(p.a); var datalist = { \"vala\": 32, \"valb\": 7 } var get = new Proxy( datalist, { get: function(y, idx) { return y[idx] * 11 } } ) for(var z in get) { console.log(z +\" : \"+ get[z]) } </script>", "e": 26948, "s": 26499, "text": null }, { "code": null, "e": 26958, "s": 26948, "text": "Output: " }, { "code": null, "e": 26986, "s": 26958, "text": "10\n\"vala : 352\"\n\"valb : 77\"" }, { "code": null, "e": 27073, "s": 26986, "text": "Supported Browsers: The browsers supported by handler.get() method are listed below: " }, { "code": null, "e": 27100, "s": 27073, "text": "Google Chrome 49 and above" }, { "code": null, "e": 27118, "s": 27100, "text": "Edge 12 and above" }, { "code": null, "e": 27139, "s": 27118, "text": "Firefox 18 and above" }, { "code": null, "e": 27158, "s": 27139, "text": "Opera 36 and above" }, { "code": null, "e": 27178, "s": 27158, "text": "Safari 10 and above" }, { "code": null, "e": 27192, "s": 27180, "text": "ysachin2314" }, { "code": null, "e": 27213, "s": 27192, "text": "javascript-functions" }, { "code": null, "e": 27224, "s": 27213, "text": "JavaScript" }, { "code": null, "e": 27241, "s": 27224, "text": "Web Technologies" }, { "code": null, "e": 27339, "s": 27241, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27348, "s": 27339, "text": "Comments" }, { "code": null, "e": 27361, "s": 27348, "text": "Old Comments" }, { "code": null, "e": 27422, "s": 27361, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27463, "s": 27422, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27517, "s": 27463, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27574, "s": 27517, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 27636, "s": 27574, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 27678, "s": 27636, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27711, "s": 27678, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27773, "s": 27711, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27816, "s": 27773, "text": "How to fetch data from an API in ReactJS ?" } ]
Creating an Interactive Dashboard from Jupyter Notebook with Voila | by Ruben Winastwan | Towards Data Science
With the emergence of BI tools such as PowerBI and Tableau, Jupyter Notebook probably wouldn’t be the first tool that comes up in your mind when you want to create an interactive dashboard. However, thanks to Voila, now it is possible to build an interactive dashboard directly from Jupyter Notebook. In this article, I want to show you the step-by-step guide on how to create interactive plots with Jupyter Notebook, turn them into a standalone dashboard, and then deploy it on the cloud with Heroku so that other people can see your dashboard. So, let’s get started! In this article, I’m going to use the San Fransisco dataset. The dataset contains more than 150,000 rows of crime history that occurred in San Fransisco during 2016. As usual, we can load the dataset with Pandas. To get a sense of what the dataset looks like, let’s print out the first five rows of the dataset afterward. import numpy as np import pandas as pd import folium df = pd.read_csv('SF_crimes.csv') df.head() Since the purpose of the article is to show how to turn interactive visualizations in your Jupyter Notebook into a standalone dashboard using Voila, then I’m not going to do EDA of this dataset. Let’s jump into creating widgets to add interactivity to the visualizations of this dataset. Now that we’ve loaded the data, we can start right away to create widgets. These widgets are essentials to add interactivity to our visualizations. In this article, we’re going to use three widgets: one slider widget and two multiple selection widgets. To create these widgets, we can use ipywidgets library that is available for Jupyter Notebook. The first widget that we are going to create is the slider widget. To do this, we can use IntSlider()attribute from ipywidgets. This slider widget will control how many rows of the dataset that Pandas should load. For example, if the slider value is 1000, then Pandas should load the first 1000 rows of the dataset. Below is the code implementation of that. import ipywidgets as widgetsimport pandas as pdstyle = {'description_width': 'initial'}limit_case = widgets.IntSlider( value=1000, min=100, max=5000, step=1, description='Max Number of Case:', disabled=False, style=style) In the code above, we passed several arguments into IntSlider()attribute from ipywidgets. The first one is value , which is the default value that will be displayed when we run the code. Next, min and max are the minimum and maximum range values that can be considered in the slider. Meanwhile, step is the value increment or decrement when we move the slider up or down. Finally, we add style argument such that the word in description will not be truncated. Next, with interactive()attribute from ipywidgets, we can link up the widget with the variable in which the value we want to interactively change. Now if we change the slider value, we can see that the length of the dataset will be changed accordingly. import ipywidgets as widgets import pandas as pd style = {'description_width': 'initial'} limit_case = widgets.IntSlider( value=1000, min=100, max=5000, step=1, description='Max Number of Case:', disabled=False, style=style) def update_df_length(limit): df = pd.read_csv('SF_crimes.csv') df = df.iloc[0:limit, :] print("Number of rows in the dataset that have been successfully loaded:"+str(len(df))) widgets.interactive(update_df_length, limit=limit_case) interactive(children=(IntSlider(value=1000, description='Max Number of Case:', max=5000, min=100, style=Slider... If you run the code cells above, you’ll get an interactive slider widget like this. Next, let’s create the second widget, which is the multiple selection widget. We can do this by using SelectMultiple()attribute from ipywidgets. With this widget, we have the option to visualize the crime only in particular selection of districts instead of all districts. In order to create this multiple selection widget, below is the code implementation. import pandas as pdimport ipywidgets as widgetsfrom ipywidgets import Layoutdf = pd.read_csv('SF_crimes.csv')unique_district = df.PdDistrict.unique()district = widgets.SelectMultiple( options = unique_district.tolist(), value = ['BAYVIEW', 'NORTHERN'], description='District', disabled=False, layout = Layout(width='50%', height='80px', display='flex')) In the code above, we use SelectMultiple() attribute to enable us to pick more than one values of our district variable. The first argument that we should specify is options , which should contain the list of available options of our variable (in our case different kinds of San Fransisco districts). The next one is value , which should contain the variable values that we want to display as default, and then description is for the text field to describe the name of the widget. import pandas as pd import ipywidgets as widgets df = pd.read_csv('SF_crimes.csv') unique_district = df.PdDistrict.unique() from ipywidgets import Layout district = widgets.SelectMultiple( options = unique_district.tolist(), value = ['BAYVIEW', 'NORTHERN'], description='District', disabled=False, layout = Layout(width='50%', height='80px', display='flex') ) district SelectMultiple(description='District', index=(1, 4), layout=Layout(display='flex', height='80px', width='50%')... If you run the code cells above, you’ll get the following interactive multiple selection widget. To wrap up, we can create the third widget that is exactly the same as the previous multiple selection widget. The purpose of this widget is to enable us to choose which category of crimes that we want to visualize. Below is the code implementation of this widget. import pandas as pdimport ipywidgets as widgetsfrom ipywidgets import Layoutdf = pd.read_csv('SF_crimes.csv')unique_cat = df.Category.unique()style = {'description_width': 'initial'}category = widgets.SelectMultiple( options = unique_cat.tolist(), value = ['VANDALISM', 'ASSAULT', 'ROBBERY'], description='Criminal Case', disabled=False, style=style, layout = Layout(width='50%', height='80px')) The arguments that we passed on this SelectMultiple() attribute is the same as before, except that the value and options arguments would be the crime categories instead of districts. import pandas as pd import ipywidgets as widgets from ipywidgets import Layout df = pd.read_csv('SF_crimes.csv') unique_cat = df.Category.unique() style = {'description_width': 'initial'} category = widgets.SelectMultiple( options = unique_cat.tolist(), value = ['VANDALISM', 'ASSAULT', 'ROBBERY'], description='Criminal Case', disabled=False, style=style, layout = Layout(width='50%', height='80px') ) If you run the code cells above, you’ll get the following widget. Next, we want to combine all of the three widgets that we’ve created before to create an interactive visualization. To visualize the crime locations, we can visualize them with a map, since we have the information regarding the latitude and longitude in the dataset. To visualize the dataset into a map, we can use folium library. If you haven’t installed folium yet, you can install it using pip command. pip install folium We can integrate the map with the widgets such that when we make a different selection with the widgets, the visualization will adjust accordingly. First, the value of the slider widget will determine how many crimes in the dataset that we should consider in the visualization. Next, the map should then show the crime categories and the districts based on our selection with the multiple selection widgets. To create additional visualizations, we can also create two bar charts. One bar chart to show how many crimes are there based on the categories that we’ve selected using the widgets. The other chart is to show how many crimes are there in the district that we’ve selected using the widget. Finally, we need to define a function to integrate all of the three widgets with our map visualization and the two bar charts. Below is the complete code implementation to do all of that from start to finish. Now if we call the function update_map in the last code cell of Jupyter Notebook above, we get the interactivity to our map and bar chart visualizations based on the value that we’ve selected in all of the three widgets. Now we’re done with our job with Jupyter Notebook to create interactive visualizations with the help of ipywidgets library! So far, we’ve created interactive visualizations with the help of ipywidgets , matplotlib , and folium library. As of right now, you can proceed to show the visualization in your Jupyter Notebook to other people. However, in most cases, you’ll show the visualization to non-technical people, people who’re not interested to see the chunks of Python code in your notebook and just want to see a clean visualization. Hence, using Jupyter Notebook to show the interactive visualization wouldn’t be the best choice. To transform the visualization on your Jupyter Notebook to a standalone dashboard, we can use Voila. Now if you haven’t installed Voila yet, you can install it using pip command as follows: pip install voila Once you’ve installed Voila, it’s going to be very easy to create a standalone dashboard. All you need to do is go to your terminal or Anaconda prompt, and then type the following format: voila path/to/your/notebook.ipynb Alternatively, you can do so directly in your notebook by clicking the Voila icon in your Jupyter Notebook toolbar. Now if you did either of two steps above, you’ll get the following standalone dashboard. And that’s it! We have transformed the visualizations in our Jupyter Notebook into a standalone dashboard. Now with the same trick you can transform your own visualization with any dataset in Jupyter Notebook to a standalone dashboard. So far, the dashboard that you’ve built with Voila only runs locally in your local computer. It means that you can’t actually share it with other people, unless you lend your computer to them. In order for other people to have access to your dashboard, you need to deploy your dashboard on the cloud, such as AWS, GCP, Azure, or Heroku. In this article, we’re going to use Heroku to deploy our dashboard such that other people can see your dashboard with their own computer. The first step to deploy your dashboard with Heroku is by logging-in to your Heroku account. If you don’t have an account yet, you can sign up to Heroku for free. The next step is to download and install Heroku command line interface (CLI) to your local machine. After Heroku CLI installation, now you need to create two additional files beside your Jupyter notebook file. These files are: requirements.txt: This text file should contain all of the dependencies or libraries that you used in your Jupyter Notebook. As an example, in this article we use folium , numpy , pandas , ipywidgets , matplotlib, and voila libraries. Hence, we need to list all of them in this file. As an addition, since we use Jupyter Notebook, we need to add ipykernel in this file such that Heroku can run the commands in our Jupyter Notebook. Below is what the content of requirements.txt looks like. numpypandasfoliumipywidgetsmatplotlibvoilaipykernel Procfile: This is the file that tells Heroku how and what files are necessary to run your Jupyter Notebook. You can type the following as the content of this file. web: voila --port=$PORT --no-browser --enable_nbextensions=True your_jupyter_notebook_name.ipynb You can create those two files with any text editor you have in your computer, for example Notepad or Notepad++. Next, save those files in the same folder where you save your Jupyter Notebook file. Now open your terminal or command prompt, and then type heroku login in it. This will direct you to a browser page where you’re prompted to log-in with your Heroku account. Next, go to the working directory where you save your Jupyter file, requirements.txt, and Procfile with your command prompt. In the working directory, initialize an empty repository by typing git init. Next, you can create a new app on your Heroku account by typing the following format: heroku create your-app-name . After creating your app, then proceed by typing the following commands in order: git add .git commit -m "Your customized message"git push heroku master Now after you typed git push heroku master , Heroku will start the process to create the app to host your dashboard. After a minute or so, you’ll get a link to your dashboard in the command prompt. The link will be similar with the name of your app. And that’s it! Now you can share the link with other people so that they can see your interactive dashboard. You can see the deployed dashboard for the visualizations in this article here. In case you’re interested to see the Jupyter Notebook used in this article and requirements.txt as well as the Procfile, you can see it here.
[ { "code": null, "e": 472, "s": 171, "text": "With the emergence of BI tools such as PowerBI and Tableau, Jupyter Notebook probably wouldn’t be the first tool that comes up in your mind when you want to create an interactive dashboard. However, thanks to Voila, now it is possible to build an interactive dashboard directly from Jupyter Notebook." }, { "code": null, "e": 740, "s": 472, "text": "In this article, I want to show you the step-by-step guide on how to create interactive plots with Jupyter Notebook, turn them into a standalone dashboard, and then deploy it on the cloud with Heroku so that other people can see your dashboard. So, let’s get started!" }, { "code": null, "e": 906, "s": 740, "text": "In this article, I’m going to use the San Fransisco dataset. The dataset contains more than 150,000 rows of crime history that occurred in San Fransisco during 2016." }, { "code": null, "e": 1062, "s": 906, "text": "As usual, we can load the dataset with Pandas. To get a sense of what the dataset looks like, let’s print out the first five rows of the dataset afterward." }, { "code": null, "e": 1116, "s": 1062, "text": "import numpy as np\nimport pandas as pd\nimport folium\n" }, { "code": null, "e": 1151, "s": 1116, "text": "df = pd.read_csv('SF_crimes.csv')\n" }, { "code": null, "e": 1162, "s": 1151, "text": "df.head()\n" }, { "code": null, "e": 1453, "s": 1165, "text": "Since the purpose of the article is to show how to turn interactive visualizations in your Jupyter Notebook into a standalone dashboard using Voila, then I’m not going to do EDA of this dataset. Let’s jump into creating widgets to add interactivity to the visualizations of this dataset." }, { "code": null, "e": 1801, "s": 1453, "text": "Now that we’ve loaded the data, we can start right away to create widgets. These widgets are essentials to add interactivity to our visualizations. In this article, we’re going to use three widgets: one slider widget and two multiple selection widgets. To create these widgets, we can use ipywidgets library that is available for Jupyter Notebook." }, { "code": null, "e": 2159, "s": 1801, "text": "The first widget that we are going to create is the slider widget. To do this, we can use IntSlider()attribute from ipywidgets. This slider widget will control how many rows of the dataset that Pandas should load. For example, if the slider value is 1000, then Pandas should load the first 1000 rows of the dataset. Below is the code implementation of that." }, { "code": null, "e": 2402, "s": 2159, "text": "import ipywidgets as widgetsimport pandas as pdstyle = {'description_width': 'initial'}limit_case = widgets.IntSlider( value=1000, min=100, max=5000, step=1, description='Max Number of Case:', disabled=False, style=style)" }, { "code": null, "e": 2862, "s": 2402, "text": "In the code above, we passed several arguments into IntSlider()attribute from ipywidgets. The first one is value , which is the default value that will be displayed when we run the code. Next, min and max are the minimum and maximum range values that can be considered in the slider. Meanwhile, step is the value increment or decrement when we move the slider up or down. Finally, we add style argument such that the word in description will not be truncated." }, { "code": null, "e": 3115, "s": 2862, "text": "Next, with interactive()attribute from ipywidgets, we can link up the widget with the variable in which the value we want to interactively change. Now if we change the slider value, we can see that the length of the dataset will be changed accordingly." }, { "code": null, "e": 3371, "s": 3115, "text": "import ipywidgets as widgets\nimport pandas as pd\n\nstyle = {'description_width': 'initial'}\n\nlimit_case = widgets.IntSlider(\n value=1000,\n min=100,\n max=5000,\n step=1,\n description='Max Number of Case:',\n disabled=False,\n style=style)\n" }, { "code": null, "e": 3570, "s": 3371, "text": "def update_df_length(limit):\n \n df = pd.read_csv('SF_crimes.csv')\n df = df.iloc[0:limit, :]\n \n print(\"Number of rows in the dataset that have been successfully loaded:\"+str(len(df)))\n" }, { "code": null, "e": 3627, "s": 3570, "text": "widgets.interactive(update_df_length, limit=limit_case)\n" }, { "code": null, "e": 3741, "s": 3627, "text": "interactive(children=(IntSlider(value=1000, description='Max Number of Case:', max=5000, min=100, style=Slider..." }, { "code": null, "e": 3828, "s": 3744, "text": "If you run the code cells above, you’ll get an interactive slider widget like this." }, { "code": null, "e": 4186, "s": 3828, "text": "Next, let’s create the second widget, which is the multiple selection widget. We can do this by using SelectMultiple()attribute from ipywidgets. With this widget, we have the option to visualize the crime only in particular selection of districts instead of all districts. In order to create this multiple selection widget, below is the code implementation." }, { "code": null, "e": 4555, "s": 4186, "text": "import pandas as pdimport ipywidgets as widgetsfrom ipywidgets import Layoutdf = pd.read_csv('SF_crimes.csv')unique_district = df.PdDistrict.unique()district = widgets.SelectMultiple( options = unique_district.tolist(), value = ['BAYVIEW', 'NORTHERN'], description='District', disabled=False, layout = Layout(width='50%', height='80px', display='flex'))" }, { "code": null, "e": 5036, "s": 4555, "text": "In the code above, we use SelectMultiple() attribute to enable us to pick more than one values of our district variable. The first argument that we should specify is options , which should contain the list of available options of our variable (in our case different kinds of San Fransisco districts). The next one is value , which should contain the variable values that we want to display as default, and then description is for the text field to describe the name of the widget." }, { "code": null, "e": 5121, "s": 5036, "text": "import pandas as pd\nimport ipywidgets as widgets\n\ndf = pd.read_csv('SF_crimes.csv')\n" }, { "code": null, "e": 5163, "s": 5121, "text": "unique_district = df.PdDistrict.unique()\n" }, { "code": null, "e": 5421, "s": 5163, "text": "from ipywidgets import Layout\n\ndistrict = widgets.SelectMultiple(\n options = unique_district.tolist(),\n value = ['BAYVIEW', 'NORTHERN'],\n description='District',\n disabled=False,\n layout = Layout(width='50%', height='80px', display='flex')\n)\n" }, { "code": null, "e": 5431, "s": 5421, "text": "district\n" }, { "code": null, "e": 5545, "s": 5431, "text": "SelectMultiple(description='District', index=(1, 4), layout=Layout(display='flex', height='80px', width='50%')..." }, { "code": null, "e": 5645, "s": 5548, "text": "If you run the code cells above, you’ll get the following interactive multiple selection widget." }, { "code": null, "e": 5910, "s": 5645, "text": "To wrap up, we can create the third widget that is exactly the same as the previous multiple selection widget. The purpose of this widget is to enable us to choose which category of crimes that we want to visualize. Below is the code implementation of this widget." }, { "code": null, "e": 6324, "s": 5910, "text": "import pandas as pdimport ipywidgets as widgetsfrom ipywidgets import Layoutdf = pd.read_csv('SF_crimes.csv')unique_cat = df.Category.unique()style = {'description_width': 'initial'}category = widgets.SelectMultiple( options = unique_cat.tolist(), value = ['VANDALISM', 'ASSAULT', 'ROBBERY'], description='Criminal Case', disabled=False, style=style, layout = Layout(width='50%', height='80px'))" }, { "code": null, "e": 6507, "s": 6324, "text": "The arguments that we passed on this SelectMultiple() attribute is the same as before, except that the value and options arguments would be the crime categories instead of districts." }, { "code": null, "e": 6622, "s": 6507, "text": "import pandas as pd\nimport ipywidgets as widgets\nfrom ipywidgets import Layout\n\ndf = pd.read_csv('SF_crimes.csv')\n" }, { "code": null, "e": 6657, "s": 6622, "text": "unique_cat = df.Category.unique()\n" }, { "code": null, "e": 6939, "s": 6657, "text": "style = {'description_width': 'initial'}\n\ncategory = widgets.SelectMultiple(\n options = unique_cat.tolist(),\n value = ['VANDALISM', 'ASSAULT', 'ROBBERY'],\n description='Criminal Case',\n disabled=False,\n style=style,\n layout = Layout(width='50%', height='80px')\n)\n" }, { "code": null, "e": 7008, "s": 6942, "text": "If you run the code cells above, you’ll get the following widget." }, { "code": null, "e": 7275, "s": 7008, "text": "Next, we want to combine all of the three widgets that we’ve created before to create an interactive visualization. To visualize the crime locations, we can visualize them with a map, since we have the information regarding the latitude and longitude in the dataset." }, { "code": null, "e": 7414, "s": 7275, "text": "To visualize the dataset into a map, we can use folium library. If you haven’t installed folium yet, you can install it using pip command." }, { "code": null, "e": 7433, "s": 7414, "text": "pip install folium" }, { "code": null, "e": 7581, "s": 7433, "text": "We can integrate the map with the widgets such that when we make a different selection with the widgets, the visualization will adjust accordingly." }, { "code": null, "e": 7841, "s": 7581, "text": "First, the value of the slider widget will determine how many crimes in the dataset that we should consider in the visualization. Next, the map should then show the crime categories and the districts based on our selection with the multiple selection widgets." }, { "code": null, "e": 8131, "s": 7841, "text": "To create additional visualizations, we can also create two bar charts. One bar chart to show how many crimes are there based on the categories that we’ve selected using the widgets. The other chart is to show how many crimes are there in the district that we’ve selected using the widget." }, { "code": null, "e": 8258, "s": 8131, "text": "Finally, we need to define a function to integrate all of the three widgets with our map visualization and the two bar charts." }, { "code": null, "e": 8340, "s": 8258, "text": "Below is the complete code implementation to do all of that from start to finish." }, { "code": null, "e": 8561, "s": 8340, "text": "Now if we call the function update_map in the last code cell of Jupyter Notebook above, we get the interactivity to our map and bar chart visualizations based on the value that we’ve selected in all of the three widgets." }, { "code": null, "e": 8685, "s": 8561, "text": "Now we’re done with our job with Jupyter Notebook to create interactive visualizations with the help of ipywidgets library!" }, { "code": null, "e": 8898, "s": 8685, "text": "So far, we’ve created interactive visualizations with the help of ipywidgets , matplotlib , and folium library. As of right now, you can proceed to show the visualization in your Jupyter Notebook to other people." }, { "code": null, "e": 9197, "s": 8898, "text": "However, in most cases, you’ll show the visualization to non-technical people, people who’re not interested to see the chunks of Python code in your notebook and just want to see a clean visualization. Hence, using Jupyter Notebook to show the interactive visualization wouldn’t be the best choice." }, { "code": null, "e": 9387, "s": 9197, "text": "To transform the visualization on your Jupyter Notebook to a standalone dashboard, we can use Voila. Now if you haven’t installed Voila yet, you can install it using pip command as follows:" }, { "code": null, "e": 9405, "s": 9387, "text": "pip install voila" }, { "code": null, "e": 9593, "s": 9405, "text": "Once you’ve installed Voila, it’s going to be very easy to create a standalone dashboard. All you need to do is go to your terminal or Anaconda prompt, and then type the following format:" }, { "code": null, "e": 9627, "s": 9593, "text": "voila path/to/your/notebook.ipynb" }, { "code": null, "e": 9743, "s": 9627, "text": "Alternatively, you can do so directly in your notebook by clicking the Voila icon in your Jupyter Notebook toolbar." }, { "code": null, "e": 9832, "s": 9743, "text": "Now if you did either of two steps above, you’ll get the following standalone dashboard." }, { "code": null, "e": 10068, "s": 9832, "text": "And that’s it! We have transformed the visualizations in our Jupyter Notebook into a standalone dashboard. Now with the same trick you can transform your own visualization with any dataset in Jupyter Notebook to a standalone dashboard." }, { "code": null, "e": 10261, "s": 10068, "text": "So far, the dashboard that you’ve built with Voila only runs locally in your local computer. It means that you can’t actually share it with other people, unless you lend your computer to them." }, { "code": null, "e": 10543, "s": 10261, "text": "In order for other people to have access to your dashboard, you need to deploy your dashboard on the cloud, such as AWS, GCP, Azure, or Heroku. In this article, we’re going to use Heroku to deploy our dashboard such that other people can see your dashboard with their own computer." }, { "code": null, "e": 10706, "s": 10543, "text": "The first step to deploy your dashboard with Heroku is by logging-in to your Heroku account. If you don’t have an account yet, you can sign up to Heroku for free." }, { "code": null, "e": 10806, "s": 10706, "text": "The next step is to download and install Heroku command line interface (CLI) to your local machine." }, { "code": null, "e": 10933, "s": 10806, "text": "After Heroku CLI installation, now you need to create two additional files beside your Jupyter notebook file. These files are:" }, { "code": null, "e": 11423, "s": 10933, "text": "requirements.txt: This text file should contain all of the dependencies or libraries that you used in your Jupyter Notebook. As an example, in this article we use folium , numpy , pandas , ipywidgets , matplotlib, and voila libraries. Hence, we need to list all of them in this file. As an addition, since we use Jupyter Notebook, we need to add ipykernel in this file such that Heroku can run the commands in our Jupyter Notebook. Below is what the content of requirements.txt looks like." }, { "code": null, "e": 11475, "s": 11423, "text": "numpypandasfoliumipywidgetsmatplotlibvoilaipykernel" }, { "code": null, "e": 11639, "s": 11475, "text": "Procfile: This is the file that tells Heroku how and what files are necessary to run your Jupyter Notebook. You can type the following as the content of this file." }, { "code": null, "e": 11736, "s": 11639, "text": "web: voila --port=$PORT --no-browser --enable_nbextensions=True your_jupyter_notebook_name.ipynb" }, { "code": null, "e": 11934, "s": 11736, "text": "You can create those two files with any text editor you have in your computer, for example Notepad or Notepad++. Next, save those files in the same folder where you save your Jupyter Notebook file." }, { "code": null, "e": 12107, "s": 11934, "text": "Now open your terminal or command prompt, and then type heroku login in it. This will direct you to a browser page where you’re prompted to log-in with your Heroku account." }, { "code": null, "e": 12232, "s": 12107, "text": "Next, go to the working directory where you save your Jupyter file, requirements.txt, and Procfile with your command prompt." }, { "code": null, "e": 12425, "s": 12232, "text": "In the working directory, initialize an empty repository by typing git init. Next, you can create a new app on your Heroku account by typing the following format: heroku create your-app-name ." }, { "code": null, "e": 12506, "s": 12425, "text": "After creating your app, then proceed by typing the following commands in order:" }, { "code": null, "e": 12577, "s": 12506, "text": "git add .git commit -m \"Your customized message\"git push heroku master" }, { "code": null, "e": 12827, "s": 12577, "text": "Now after you typed git push heroku master , Heroku will start the process to create the app to host your dashboard. After a minute or so, you’ll get a link to your dashboard in the command prompt. The link will be similar with the name of your app." }, { "code": null, "e": 12936, "s": 12827, "text": "And that’s it! Now you can share the link with other people so that they can see your interactive dashboard." }, { "code": null, "e": 13016, "s": 12936, "text": "You can see the deployed dashboard for the visualizations in this article here." } ]
Sorting a String in C#
Firstly, set a string array. string[] values = { "tim", "amit", "tom", "jack", "saurav"}; Use the Sort() method to sort. Array.Sort(values); Let us see the complete code − Live Demo using System; public class Program { public static void Main() { string[] values = { "tim", "amit", "tom", "jack", "saurav"}; foreach (string value in values) { Console.Write(value); Console.Write(' '); } // sorting Array.Sort(values); Console.WriteLine("\nSorted..."); foreach (string value in values) { Console.Write(value); Console.Write(' '); } Console.WriteLine(); } } tim amit tom jack saurav Sorted... amit jack saurav tim tom
[ { "code": null, "e": 1091, "s": 1062, "text": "Firstly, set a string array." }, { "code": null, "e": 1152, "s": 1091, "text": "string[] values = { \"tim\", \"amit\", \"tom\", \"jack\", \"saurav\"};" }, { "code": null, "e": 1183, "s": 1152, "text": "Use the Sort() method to sort." }, { "code": null, "e": 1203, "s": 1183, "text": "Array.Sort(values);" }, { "code": null, "e": 1234, "s": 1203, "text": "Let us see the complete code −" }, { "code": null, "e": 1245, "s": 1234, "text": " Live Demo" }, { "code": null, "e": 1717, "s": 1245, "text": "using System;\npublic class Program {\n public static void Main() {\n string[] values = { \"tim\", \"amit\", \"tom\", \"jack\", \"saurav\"};\n\n foreach (string value in values) {\n Console.Write(value);\n Console.Write(' ');\n }\n\n // sorting\n Array.Sort(values);\n Console.WriteLine(\"\\nSorted...\");\n foreach (string value in values) {\n Console.Write(value);\n Console.Write(' ');\n }\n Console.WriteLine();\n }\n}" }, { "code": null, "e": 1777, "s": 1717, "text": "tim amit tom jack saurav\nSorted...\namit jack saurav tim tom" } ]
Creating a spam filter using Naive Bayes with TextAnalysis.jl | by Kim Fung | Towards Data Science
Hello! Today I’m gonna tell you more about what I did to make a spam filter using Naive Bayes to detect spam data from this dataset on kaggle by UCI Machine Learning, along with the use of TextAnalysis.jl on Julia. I started off by looking at the docs off TextAnalysis.jl to understand more about how exactly the NaiveBayes Classifier works. using TextAnalysis: NaiveBayesClassifier, fit!, predictm = NaiveBayesClassifier([:legal, :financial])fit!(m, "this is financial doc", :financial)fit!(m, "this is legal doc", :legal)predict(m, "this should be predicted as a legal document") I ran the example from the docs and I learned that the function NaiveBayesClassifier takes in the argument of an array of possible classes that the concerned data could perhaps belong to. In this case, it was :legal and :financial. I also learned that we have train the model by fitting the concerned data with the fit! function where it takes in the arguments of the model itself, the string of data we are trying to train, and the class that data belongs to. The data here is a string, for example “this is financial doc” and the class it belongs to is, in this case, :financial. Finally, I learned that the predict function allows us to enter a string of data and uses the NaiveBayesClassifier algorithm to predict what class the string belongs to, based on the strings of data trained before using the fit! function. The predict function takes in the arguments of the model itself as well as the string of data we are trying to predict. My first approach to the problem was that I thought it would be a good idea to first import all of the data. As I have experience with the packages CSV.jl and DataFrames.jl, I am familiar with the importing of the data. using CSV, DataFramesspamdata = DataFrame(CSV.read("spam.csv"; allowmissing=:none))---------------------------------------------------------------julia> showall(spamdata)5572×5 DataFrame│ Row │ v1 ││ │ String │├──────┼────────┤│ 1 │ ham ││ 2 │ ham ││ 3 │ spam ││ 4 │ ham ││ 5 │ ham ││ 6 │ spam ││ 7 │ ham ││ 8 │ ham ││ 9 │ spam ││ 10 │ spam │ This image below shows the structure of the original .csv file with the data. The csv file has two columns. v2 is the string of the data we want to use to train and v1 is the class of the particular string of data, corresponding to v2. I want a way to loop through every single row of the file and split the ham data in one condition and spam data in another, such that when it comes to training, I will be able to train the ham data using the fit! function, which requires me to specify the class of that data. for row in eachrow(spamdata) if row.v1 == "ham" println("ham") elseif row.v1 == "spam" println("spam") endend This was a success and I ended up having hams and spams being printed! hamspamhamspamhamhamspamspamhamspam⋮ Now that it is out of the way, I can define my model using the NaiveBayesClassifier function. I want to define 2 classes, :ham and :spam. using TextAnalysis: NaiveBayesClassifier, fit!, predictm = NaiveBayesClassifier([:ham, :spam]) Next, I want to start training my model. As we saw from the original .csv file’s structure, v2 is the string we are trying to train. Combining the for loop with the fit! function, I did the following to try and train all the data we have available. using CSV, DataFramesusing TextAnalysis: NaiveBayesClassifier, fit!, predictspamdata = DataFrame(CSV.read("spam.csv"; allowmissing=:none))global m = NaiveBayesClassifier([:ham, :spam])for row in eachrow(spamdata) if row.v1 == "ham" fit!(m, row.v2, :ham) elseif row.v1 == "spam" fit!(m, row.v2, :spam) endend But when I ran that, I got the following error: LoadError: Base.InvalidCharError{Char}('\xe5\xa3') It was then when I realized that the dataset had invalid characters in certain strings in the v2 column. To eliminate this error, we need to filter out the unsupported characters using the following function: filter(isvalid, <string>) for row in eachrow(spamdata) if row.v1 == "ham" fit!(m, filter(isvalid, row.v2), :ham) elseif row.v1 == "spam" fit!(m, filter(isvalid, row.v2), :spam) endend When I replaced the string row.v2 with filter(isvalid, row.v2) and ran the program once again, no errors came up. Therefore the model was successfully trained and so far so good! Nothing was actually printed out in the REPL because there was no error and nothing in the program had anything printed out. To fully test that the model is working, we can try and create a prediction and print out the results of the prediction to see whether the training was really done or not. prediction1 = predict(m, "hello my name is kfung")prediction2 = predict(m, "text 31845 to get a free phone")println(prediction1)println(prediction2) Here I created two predictions, where the first one looks like a ham message (as it doesn’t look suspicious), and a second one that looks like a spam message to test out the model. The results I got are below: Dict(:spam => 0.013170434049325023, :ham => 0.986829565950675)Dict(:spam => 0.9892304346396908, :ham => 0.010769565360309069) As we can tell, the predictions were pretty accurate as the first prediction had a :ham value close to 1 meaning it is most probably a ham message, and the second prediction had a :spam value close to 1 meaning it is most likely a spam message. Exactly what we expected. But for users who are not familiar with dictionaries or Julia syntax, they may be confused as to what the dictionaries above mean. I modified the code so that it checks for the :spam and the :ham values in the dictionary and prints out the class of the bigger value of those two. prediction = predict(m, "hello my name is kfung")if prediction[:spam] > prediction[:ham] println("spam")else println("ham")end As we expected, the results of this program was the string “ham” because the :ham value it predicted was greater than the :spam value, therefore it is more likely to be a ham message. In the end, I wrapped everything in a function that takes a string as an argument so that when you call the function with a string, it will print out either “spam” if the model predicts it as a spam message, or “ham” if the model predicts that it is not a spam message. using CSV, DataFramesusing TextAnalysis: NaiveBayesClassifier, fit!, predictfunction checkspam(msg::String) spamdata = DataFrame(CSV.read("spam.csv"; allowmissing=:none)) m = NaiveBayesClassifier([:ham, :spam]) for row in eachrow(spamdata) if row.v1 == "ham" fit!(m, filter(isvalid, row.v2), :ham) elseif row.v1 == "spam" fit!(m, filter(isvalid, row.v2), :spam) end end prediction = predict(m, msg) if prediction[:spam] > prediction[:ham] println("spam") else println("ham (not spam)") endend In the end I realized how I was training the model every time a classify a message. The makes the program not very efficient at run time because every time we are trying to predict using the model, it has gone through through the 5600 lines of data all over again. Instead, we can bring the modal outside of the function (so that it is run at the start only once) and store the model in a global variable so that afterwards it can just used the pre-trained model stored in the global variable to classify any other messages. using CSV, DataFramesusing TextAnalysis: NaiveBayesClassifier, fit!, predictspamdata = DataFrame(CSV.read("spam.csv"; allowmissing=:none))global m = NaiveBayesClassifier([:ham, :spam])for row in eachrow(spamdata) if row.v1 == "ham" fit!(m, filter(isvalid, row.v2), :ham) elseif row.v1 == "spam" fit!(m, filter(isvalid, row.v2), :spam) endendfunction checkspam(msg::String) prediction = predict(m, msg) if prediction[:spam] > prediction[:ham] println("spam") else println("ham (not spam)") endend Overall, I think this was a very successful attempt at creating a new spam filter. I learnt more about how I could apply Naive Bayes to model independent assumptions for probabilistic classification. Naive Bayes continues to be at the moment a rather popular option for text categorisation, of which this is an example, and can be contrasted to other methods of model training such as logistic regression where the data is conditionally trained. This model has other applications such as sentiment analysis which is what I’ll be focusing on soon in another article, so stay tuned! Thanks so much for reading!
[ { "code": null, "e": 387, "s": 172, "text": "Hello! Today I’m gonna tell you more about what I did to make a spam filter using Naive Bayes to detect spam data from this dataset on kaggle by UCI Machine Learning, along with the use of TextAnalysis.jl on Julia." }, { "code": null, "e": 514, "s": 387, "text": "I started off by looking at the docs off TextAnalysis.jl to understand more about how exactly the NaiveBayes Classifier works." }, { "code": null, "e": 754, "s": 514, "text": "using TextAnalysis: NaiveBayesClassifier, fit!, predictm = NaiveBayesClassifier([:legal, :financial])fit!(m, \"this is financial doc\", :financial)fit!(m, \"this is legal doc\", :legal)predict(m, \"this should be predicted as a legal document\")" }, { "code": null, "e": 942, "s": 754, "text": "I ran the example from the docs and I learned that the function NaiveBayesClassifier takes in the argument of an array of possible classes that the concerned data could perhaps belong to." }, { "code": null, "e": 1336, "s": 942, "text": "In this case, it was :legal and :financial. I also learned that we have train the model by fitting the concerned data with the fit! function where it takes in the arguments of the model itself, the string of data we are trying to train, and the class that data belongs to. The data here is a string, for example “this is financial doc” and the class it belongs to is, in this case, :financial." }, { "code": null, "e": 1695, "s": 1336, "text": "Finally, I learned that the predict function allows us to enter a string of data and uses the NaiveBayesClassifier algorithm to predict what class the string belongs to, based on the strings of data trained before using the fit! function. The predict function takes in the arguments of the model itself as well as the string of data we are trying to predict." }, { "code": null, "e": 1915, "s": 1695, "text": "My first approach to the problem was that I thought it would be a good idea to first import all of the data. As I have experience with the packages CSV.jl and DataFrames.jl, I am familiar with the importing of the data." }, { "code": null, "e": 2323, "s": 1915, "text": "using CSV, DataFramesspamdata = DataFrame(CSV.read(\"spam.csv\"; allowmissing=:none))---------------------------------------------------------------julia> showall(spamdata)5572×5 DataFrame│ Row │ v1 ││ │ String │├──────┼────────┤│ 1 │ ham ││ 2 │ ham ││ 3 │ spam ││ 4 │ ham ││ 5 │ ham ││ 6 │ spam ││ 7 │ ham ││ 8 │ ham ││ 9 │ spam ││ 10 │ spam │" }, { "code": null, "e": 2401, "s": 2323, "text": "This image below shows the structure of the original .csv file with the data." }, { "code": null, "e": 2559, "s": 2401, "text": "The csv file has two columns. v2 is the string of the data we want to use to train and v1 is the class of the particular string of data, corresponding to v2." }, { "code": null, "e": 2835, "s": 2559, "text": "I want a way to loop through every single row of the file and split the ham data in one condition and spam data in another, such that when it comes to training, I will be able to train the ham data using the fit! function, which requires me to specify the class of that data." }, { "code": null, "e": 2968, "s": 2835, "text": "for row in eachrow(spamdata) if row.v1 == \"ham\" println(\"ham\") elseif row.v1 == \"spam\" println(\"spam\") endend" }, { "code": null, "e": 3039, "s": 2968, "text": "This was a success and I ended up having hams and spams being printed!" }, { "code": null, "e": 3076, "s": 3039, "text": "hamspamhamspamhamhamspamspamhamspam⋮" }, { "code": null, "e": 3214, "s": 3076, "text": "Now that it is out of the way, I can define my model using the NaiveBayesClassifier function. I want to define 2 classes, :ham and :spam." }, { "code": null, "e": 3309, "s": 3214, "text": "using TextAnalysis: NaiveBayesClassifier, fit!, predictm = NaiveBayesClassifier([:ham, :spam])" }, { "code": null, "e": 3558, "s": 3309, "text": "Next, I want to start training my model. As we saw from the original .csv file’s structure, v2 is the string we are trying to train. Combining the for loop with the fit! function, I did the following to try and train all the data we have available." }, { "code": null, "e": 3889, "s": 3558, "text": "using CSV, DataFramesusing TextAnalysis: NaiveBayesClassifier, fit!, predictspamdata = DataFrame(CSV.read(\"spam.csv\"; allowmissing=:none))global m = NaiveBayesClassifier([:ham, :spam])for row in eachrow(spamdata) if row.v1 == \"ham\" fit!(m, row.v2, :ham) elseif row.v1 == \"spam\" fit!(m, row.v2, :spam) endend" }, { "code": null, "e": 3988, "s": 3889, "text": "But when I ran that, I got the following error: LoadError: Base.InvalidCharError{Char}('\\xe5\\xa3')" }, { "code": null, "e": 4223, "s": 3988, "text": "It was then when I realized that the dataset had invalid characters in certain strings in the v2 column. To eliminate this error, we need to filter out the unsupported characters using the following function: filter(isvalid, <string>)" }, { "code": null, "e": 4404, "s": 4223, "text": "for row in eachrow(spamdata) if row.v1 == \"ham\" fit!(m, filter(isvalid, row.v2), :ham) elseif row.v1 == \"spam\" fit!(m, filter(isvalid, row.v2), :spam) endend" }, { "code": null, "e": 4583, "s": 4404, "text": "When I replaced the string row.v2 with filter(isvalid, row.v2) and ran the program once again, no errors came up. Therefore the model was successfully trained and so far so good!" }, { "code": null, "e": 4880, "s": 4583, "text": "Nothing was actually printed out in the REPL because there was no error and nothing in the program had anything printed out. To fully test that the model is working, we can try and create a prediction and print out the results of the prediction to see whether the training was really done or not." }, { "code": null, "e": 5029, "s": 4880, "text": "prediction1 = predict(m, \"hello my name is kfung\")prediction2 = predict(m, \"text 31845 to get a free phone\")println(prediction1)println(prediction2)" }, { "code": null, "e": 5210, "s": 5029, "text": "Here I created two predictions, where the first one looks like a ham message (as it doesn’t look suspicious), and a second one that looks like a spam message to test out the model." }, { "code": null, "e": 5239, "s": 5210, "text": "The results I got are below:" }, { "code": null, "e": 5365, "s": 5239, "text": "Dict(:spam => 0.013170434049325023, :ham => 0.986829565950675)Dict(:spam => 0.9892304346396908, :ham => 0.010769565360309069)" }, { "code": null, "e": 5636, "s": 5365, "text": "As we can tell, the predictions were pretty accurate as the first prediction had a :ham value close to 1 meaning it is most probably a ham message, and the second prediction had a :spam value close to 1 meaning it is most likely a spam message. Exactly what we expected." }, { "code": null, "e": 5916, "s": 5636, "text": "But for users who are not familiar with dictionaries or Julia syntax, they may be confused as to what the dictionaries above mean. I modified the code so that it checks for the :spam and the :ham values in the dictionary and prints out the class of the bigger value of those two." }, { "code": null, "e": 6049, "s": 5916, "text": "prediction = predict(m, \"hello my name is kfung\")if prediction[:spam] > prediction[:ham] println(\"spam\")else println(\"ham\")end" }, { "code": null, "e": 6233, "s": 6049, "text": "As we expected, the results of this program was the string “ham” because the :ham value it predicted was greater than the :spam value, therefore it is more likely to be a ham message." }, { "code": null, "e": 6503, "s": 6233, "text": "In the end, I wrapped everything in a function that takes a string as an argument so that when you call the function with a string, it will print out either “spam” if the model predicts it as a spam message, or “ham” if the model predicts that it is not a spam message." }, { "code": null, "e": 7077, "s": 6503, "text": "using CSV, DataFramesusing TextAnalysis: NaiveBayesClassifier, fit!, predictfunction checkspam(msg::String) spamdata = DataFrame(CSV.read(\"spam.csv\"; allowmissing=:none)) m = NaiveBayesClassifier([:ham, :spam]) for row in eachrow(spamdata) if row.v1 == \"ham\" fit!(m, filter(isvalid, row.v2), :ham) elseif row.v1 == \"spam\" fit!(m, filter(isvalid, row.v2), :spam) end end prediction = predict(m, msg) if prediction[:spam] > prediction[:ham] println(\"spam\") else println(\"ham (not spam)\") endend" }, { "code": null, "e": 7602, "s": 7077, "text": "In the end I realized how I was training the model every time a classify a message. The makes the program not very efficient at run time because every time we are trying to predict using the model, it has gone through through the 5600 lines of data all over again. Instead, we can bring the modal outside of the function (so that it is run at the start only once) and store the model in a global variable so that afterwards it can just used the pre-trained model stored in the global variable to classify any other messages." }, { "code": null, "e": 8147, "s": 7602, "text": "using CSV, DataFramesusing TextAnalysis: NaiveBayesClassifier, fit!, predictspamdata = DataFrame(CSV.read(\"spam.csv\"; allowmissing=:none))global m = NaiveBayesClassifier([:ham, :spam])for row in eachrow(spamdata) if row.v1 == \"ham\" fit!(m, filter(isvalid, row.v2), :ham) elseif row.v1 == \"spam\" fit!(m, filter(isvalid, row.v2), :spam) endendfunction checkspam(msg::String) prediction = predict(m, msg) if prediction[:spam] > prediction[:ham] println(\"spam\") else println(\"ham (not spam)\") endend" }, { "code": null, "e": 8728, "s": 8147, "text": "Overall, I think this was a very successful attempt at creating a new spam filter. I learnt more about how I could apply Naive Bayes to model independent assumptions for probabilistic classification. Naive Bayes continues to be at the moment a rather popular option for text categorisation, of which this is an example, and can be contrasted to other methods of model training such as logistic regression where the data is conditionally trained. This model has other applications such as sentiment analysis which is what I’ll be focusing on soon in another article, so stay tuned!" } ]
C++ Memory Library - allocator
It defines the memory models to be used by some parts of the Standard Library, and most specifically, by STL containers. Following is the declaration for std::allocator function. template <class T> class allocator; template <class T> class allocator; T − It contains information about types of elements. In below example explains about std::allocator function. #include <memory> #include <iostream> #include <string> int main() { std::allocator<int> a1; int* a = a1.allocate(10); a[9] = 7; std::cout << a[9] << '\n'; a1.deallocate(a, 10); std::allocator<std::string> a2; decltype(a1)::rebind<std::string>::other a2_1; std::allocator_traits<decltype(a1)>::rebind_alloc<std::string> a2_2; std::string* s = a2.allocate(2); a2.construct(s, "foo"); a2.construct(s + 1, "bar"); std::cout << s[0] << ' ' << s[1] << '\n'; a2.destroy(s); a2.destroy(s + 1); a2.deallocate(s, 2); } Let us compile and run the above program, this will produce the following result − 7 foo bar Print Add Notes Bookmark this page
[ { "code": null, "e": 2724, "s": 2603, "text": "It defines the memory models to be used by some parts of the Standard Library, and most specifically, by STL containers." }, { "code": null, "e": 2782, "s": 2724, "text": "Following is the declaration for std::allocator function." }, { "code": null, "e": 2818, "s": 2782, "text": "template <class T> class allocator;" }, { "code": null, "e": 2854, "s": 2818, "text": "template <class T> class allocator;" }, { "code": null, "e": 2907, "s": 2854, "text": "T − It contains information about types of elements." }, { "code": null, "e": 2964, "s": 2907, "text": "In below example explains about std::allocator function." }, { "code": null, "e": 3531, "s": 2964, "text": "#include <memory>\n#include <iostream>\n#include <string>\n\nint main() {\n std::allocator<int> a1;\n int* a = a1.allocate(10);\n\n a[9] = 7;\n\n std::cout << a[9] << '\\n';\n\n a1.deallocate(a, 10);\n\n std::allocator<std::string> a2;\n\n decltype(a1)::rebind<std::string>::other a2_1;\n\n std::allocator_traits<decltype(a1)>::rebind_alloc<std::string> a2_2;\n\n std::string* s = a2.allocate(2);\n\n a2.construct(s, \"foo\");\n a2.construct(s + 1, \"bar\");\n\n std::cout << s[0] << ' ' << s[1] << '\\n';\n \n a2.destroy(s);\n a2.destroy(s + 1);\n a2.deallocate(s, 2);\n}" }, { "code": null, "e": 3614, "s": 3531, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3625, "s": 3614, "text": "7\nfoo bar\n" }, { "code": null, "e": 3632, "s": 3625, "text": " Print" }, { "code": null, "e": 3643, "s": 3632, "text": " Add Notes" } ]
Get the count of a specific value in MongoDB
To get the count of a specific value in MongoDB, use aggregate(). Let us create a collection with documents − > db.demo210.insertOne( ... { ... details: [ ... { ... ClientName: "Robert" ... }, ... { ... ... lientName: "John Doe" ... }, ... { ... ... ClientName: "Robert" ... }, ... { ... ... ClientName: "Robert" ... }, ... { ... ... ClientName: "David Miller" ... } ... ] ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e3d99ab03d395bdc21346f9") } Display all documents from a collection with the help of find() method − > db.demo210.find(); This will produce the following output − { "_id" : ObjectId("5e3d99ab03d395bdc21346f9"), "details" : [ { "ClientName" : "Robert" }, { "ClientName" : "John Doe" }, { "ClientName" : "Robert" }, { "ClientName" : "Robert" }, { "ClientName" : "David Miller" } ] } Following is the query to get the count of a specific value − > db.demo210.aggregate([ ... { "$match" : { "details.ClientName" : "Robert" } }, ... { "$unwind" : "$details" }, ... { "$match" : { "details.ClientName" : "Robert" } }, ... { "$group" : { "_id" : "$_id", "Size" : { "$sum" : 1 } } }, ... { "$match" : { "Size" : { "$gte" : 2 } } } ...]); This will produce the following output − { "_id" : ObjectId("5e3d99ab03d395bdc21346f9"), "Size" : 3 }
[ { "code": null, "e": 1172, "s": 1062, "text": "To get the count of a specific value in MongoDB, use aggregate(). Let us create a collection with documents −" }, { "code": null, "e": 1681, "s": 1172, "text": "> db.demo210.insertOne(\n... {\n... details: [\n... {\n... ClientName: \"Robert\"\n... },\n... {\n...\n... lientName: \"John Doe\"\n... },\n... {\n...\n... ClientName: \"Robert\"\n... },\n... {\n...\n... ClientName: \"Robert\"\n... },\n... {\n...\n... ClientName: \"David Miller\"\n... }\n... ]\n... }\n...);\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3d99ab03d395bdc21346f9\")\n}" }, { "code": null, "e": 1754, "s": 1681, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1775, "s": 1754, "text": "> db.demo210.find();" }, { "code": null, "e": 1816, "s": 1775, "text": "This will produce the following output −" }, { "code": null, "e": 2034, "s": 1816, "text": "{ \"_id\" : ObjectId(\"5e3d99ab03d395bdc21346f9\"), \"details\" : [ { \"ClientName\" : \"Robert\" }, { \"ClientName\" : \"John Doe\" }, { \"ClientName\" : \"Robert\" }, { \"ClientName\" : \"Robert\" }, { \"ClientName\" : \"David Miller\" } ] }" }, { "code": null, "e": 2096, "s": 2034, "text": "Following is the query to get the count of a specific value −" }, { "code": null, "e": 2393, "s": 2096, "text": "> db.demo210.aggregate([\n... { \"$match\" : { \"details.ClientName\" : \"Robert\" } },\n... { \"$unwind\" : \"$details\" },\n... { \"$match\" : { \"details.ClientName\" : \"Robert\" } },\n... { \"$group\" : { \"_id\" : \"$_id\", \"Size\" : { \"$sum\" : 1 } } },\n... { \"$match\" : { \"Size\" : { \"$gte\" : 2 } } }\n...]);" }, { "code": null, "e": 2434, "s": 2393, "text": "This will produce the following output −" }, { "code": null, "e": 2495, "s": 2434, "text": "{ \"_id\" : ObjectId(\"5e3d99ab03d395bdc21346f9\"), \"Size\" : 3 }" } ]
Python VLC – Creating MediaPlayer object
11 Apr, 2022 In this article we will see how we can create a MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaPlayer object is the basic object in vlc module for playing the video. MediaPlayer class is the basic class it is used to play single video at a time. In order to do this we will use MediaPlayer method Syntax : MediaPlayer(video_uri) Argument : It takes video uri as optional argument Return : It returns MediaPlayer object Below is the implementation Python3 # importing vlc moduleimport vlcimport timeimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # printing type of media player variableprint(type(media_player)) Output : class 'vlc.MediaPlayer' Another example Python3 # importing vlc moduleimport vlcimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer("1.mp4") # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) Output : simranarora5sos Python vlc-library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Apr, 2022" }, { "code": null, "e": 428, "s": 28, "text": "In this article we will see how we can create a MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaPlayer object is the basic object in vlc module for playing the video. MediaPlayer class is the basic class it is used to play single video at a time." }, { "code": null, "e": 601, "s": 428, "text": "In order to do this we will use MediaPlayer method Syntax : MediaPlayer(video_uri) Argument : It takes video uri as optional argument Return : It returns MediaPlayer object" }, { "code": null, "e": 630, "s": 601, "text": "Below is the implementation " }, { "code": null, "e": 638, "s": 630, "text": "Python3" }, { "code": "# importing vlc moduleimport vlcimport timeimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # printing type of media player variableprint(type(media_player))", "e": 826, "s": 638, "text": null }, { "code": null, "e": 835, "s": 826, "text": "Output :" }, { "code": null, "e": 859, "s": 835, "text": "class 'vlc.MediaPlayer'" }, { "code": null, "e": 876, "s": 859, "text": "Another example " }, { "code": null, "e": 884, "s": 876, "text": "Python3" }, { "code": "# importing vlc moduleimport vlcimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer(\"1.mp4\") # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)", "e": 1138, "s": 884, "text": null }, { "code": null, "e": 1148, "s": 1138, "text": "Output : " }, { "code": null, "e": 1164, "s": 1148, "text": "simranarora5sos" }, { "code": null, "e": 1183, "s": 1164, "text": "Python vlc-library" }, { "code": null, "e": 1190, "s": 1183, "text": "Python" } ]
C++ Interview questions based on constructors/ Destructors.
28 Aug, 2018 1. What is destructor?Ans. Destructor is a member function which is called when an object is deleted/destroyed or goes out of scope. class String {private: char* s; int size; public: String(char*); // constructor ~String(); // destructor}; 2. What is the purpose of using a destructor in C++?Ans. The main purpose of destructor is to free all the resources (opened files, opened sockets, database connections, resource locks etc.) which are allocated during your object’s life time. // CPP program to demonstrate destructors.class Geeks {private: // a private-access pointer to integer int* myPrvIntPtr; public: Geeks() { // default constructor myPrvIntPtr = new int(0); // allocate a new integer, place its address in myPrvIntPtr } ~Geeks() { // de-allocate the integer whose address // is stored in myPrvIntPtr delete myPrvIntPtr; }}; 3. What is the use of a constructor?Constructor is a special function having same name as class name. Constructor is called at the time of creating object to your class. Constructor is used to initialize the instance variables of an object while creating it. Constructor is also used to create virtual tables for virtual functions. 4. What if I don’t use copy constructor? Where does it create problem?Please see copy constructor 5. Does C++ compiler create default constructor when we write our own?In C++, compiler by default creates default constructor for every class. But, if we define our own constructor, compiler doesn’t create the default constructor. 6. What is the order of constructor execution in C++?Ans. First base class constructor is executed and then derived class constructor, so execution happens from top to bottom in inheritance tree. 7. What is the order of destructor execution in C++?Ans. Generally derived class destructor, and then base class destructor. Except in case if we are taking a derived class object into a baseclass pointer (or reference variable), and we forget to give virtual keyword for base class destructor. See virtual destructor for details. 8. Can we have virtual destructors? If so what is the use of virtual destructors.Ans. Yes, we can. This is to make sure that the correct class destructor is called at run time. Specifically when we use base class pointer or reference to hold the derived class object. If we don’t have virtual destructor, then it will end up in calling only base class destructor. // CPP program without virtual destructor// causing undefined behavior#include <iostream> using namespace std; class base {public: base() { cout << "Constructing base \n"; } ~base() { cout << "Destructing base \n"; }}; class derived : public base {public: derived() { cout << "Constructing derived \n"; } ~derived() { cout << "Destructing derived \n"; }}; int main(void){ derived* d = new derived(); base* b = d; delete b; getchar(); return 0;} cpp-constructor cpp-destructor C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Aug, 2018" }, { "code": null, "e": 187, "s": 54, "text": "1. What is destructor?Ans. Destructor is a member function which is called when an object is deleted/destroyed or goes out of scope." }, { "code": "class String {private: char* s; int size; public: String(char*); // constructor ~String(); // destructor};", "e": 307, "s": 187, "text": null }, { "code": null, "e": 550, "s": 307, "text": "2. What is the purpose of using a destructor in C++?Ans. The main purpose of destructor is to free all the resources (opened files, opened sockets, database connections, resource locks etc.) which are allocated during your object’s life time." }, { "code": "// CPP program to demonstrate destructors.class Geeks {private: // a private-access pointer to integer int* myPrvIntPtr; public: Geeks() { // default constructor myPrvIntPtr = new int(0); // allocate a new integer, place its address in myPrvIntPtr } ~Geeks() { // de-allocate the integer whose address // is stored in myPrvIntPtr delete myPrvIntPtr; }};", "e": 984, "s": 550, "text": null }, { "code": null, "e": 1316, "s": 984, "text": "3. What is the use of a constructor?Constructor is a special function having same name as class name. Constructor is called at the time of creating object to your class. Constructor is used to initialize the instance variables of an object while creating it. Constructor is also used to create virtual tables for virtual functions." }, { "code": null, "e": 1414, "s": 1316, "text": "4. What if I don’t use copy constructor? Where does it create problem?Please see copy constructor" }, { "code": null, "e": 1645, "s": 1414, "text": "5. Does C++ compiler create default constructor when we write our own?In C++, compiler by default creates default constructor for every class. But, if we define our own constructor, compiler doesn’t create the default constructor." }, { "code": null, "e": 1841, "s": 1645, "text": "6. What is the order of constructor execution in C++?Ans. First base class constructor is executed and then derived class constructor, so execution happens from top to bottom in inheritance tree." }, { "code": null, "e": 2172, "s": 1841, "text": "7. What is the order of destructor execution in C++?Ans. Generally derived class destructor, and then base class destructor. Except in case if we are taking a derived class object into a baseclass pointer (or reference variable), and we forget to give virtual keyword for base class destructor. See virtual destructor for details." }, { "code": null, "e": 2536, "s": 2172, "text": "8. Can we have virtual destructors? If so what is the use of virtual destructors.Ans. Yes, we can. This is to make sure that the correct class destructor is called at run time. Specifically when we use base class pointer or reference to hold the derived class object. If we don’t have virtual destructor, then it will end up in calling only base class destructor." }, { "code": "// CPP program without virtual destructor// causing undefined behavior#include <iostream> using namespace std; class base {public: base() { cout << \"Constructing base \\n\"; } ~base() { cout << \"Destructing base \\n\"; }}; class derived : public base {public: derived() { cout << \"Constructing derived \\n\"; } ~derived() { cout << \"Destructing derived \\n\"; }}; int main(void){ derived* d = new derived(); base* b = d; delete b; getchar(); return 0;}", "e": 3064, "s": 2536, "text": null }, { "code": null, "e": 3080, "s": 3064, "text": "cpp-constructor" }, { "code": null, "e": 3095, "s": 3080, "text": "cpp-destructor" }, { "code": null, "e": 3099, "s": 3095, "text": "C++" }, { "code": null, "e": 3103, "s": 3099, "text": "CPP" } ]
Neo4j Create Node
23 Aug, 2019 In the Neo4j to create node you will have to state CREATE statement. With the help of cypher language it is easy to create nodes, properties and relation between nodes. Let’s create sample node of GeeksforGeesk. You can see the table format, the actual code and the text also by selecting options. Below examples will illustrate the concept more clearly. Example: In this example we will create a node label “GeeksforGeeks” with the “Tag” property that will tell us about the “GeeksforGeeks” that will be property value. To create the node:$ CREATE (a:GeeksforGeeks { Tag : "A Computer Science Portal" }) The prefix a is a variable that will be anything this thing will required to refer later in any statement. After firing the Cypher query you will get something like the below picture.Output: $ CREATE (a:GeeksforGeeks { Tag : "A Computer Science Portal" }) The prefix a is a variable that will be anything this thing will required to refer later in any statement. After firing the Cypher query you will get something like the below picture.Output: Display node:So now you have a created node but the above query does not show you the created node to see the node you need to use RETURN statement like have to fire the below query. Here again we will create a node with 2 properties. Display Created node:$ CREATE (a:GeksforGeeks { Tag : "A Computer Science Portal", Type : "Edutech" }) RETURN a Output:Note: We return the node by using its variable name (in this case a). $ CREATE (a:GeksforGeeks { Tag : "A Computer Science Portal", Type : "Edutech" }) RETURN a Output:Note: We return the node by using its variable name (in this case a). Creating multiple nodes:To create multiple nodes use the CREATE statement and separate the nodes by “, ” coma or you can use multiple time CREATE statement Like the below query. Multiple nodes single Query using coma:$ CREATE (a:GeeksforGeeks { Tag: "A Computer Science Portal"}), (b:W3School { Tag: "We are the Learner"}) RETURN a, b orCREATE (a:GeeksforGeeks { Tag: "A Computer Science Portal"}) CREATE (b:W3School { Tag: "We are the Learner"}) RETURN a, b Output: $ CREATE (a:GeeksforGeeks { Tag: "A Computer Science Portal"}), (b:W3School { Tag: "We are the Learner"}) RETURN a, b or CREATE (a:GeeksforGeeks { Tag: "A Computer Science Portal"}) CREATE (b:W3School { Tag: "We are the Learner"}) RETURN a, b Output: Note: Both the query will gave you same output. DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Aug, 2019" }, { "code": null, "e": 383, "s": 28, "text": "In the Neo4j to create node you will have to state CREATE statement. With the help of cypher language it is easy to create nodes, properties and relation between nodes. Let’s create sample node of GeeksforGeesk. You can see the table format, the actual code and the text also by selecting options. Below examples will illustrate the concept more clearly." }, { "code": null, "e": 549, "s": 383, "text": "Example: In this example we will create a node label “GeeksforGeeks” with the “Tag” property that will tell us about the “GeeksforGeeks” that will be property value." }, { "code": null, "e": 824, "s": 549, "text": "To create the node:$ CREATE (a:GeeksforGeeks { Tag : \"A Computer Science Portal\" })\nThe prefix a is a variable that will be anything this thing will required to refer later in any statement. After firing the Cypher query you will get something like the below picture.Output:" }, { "code": null, "e": 890, "s": 824, "text": "$ CREATE (a:GeeksforGeeks { Tag : \"A Computer Science Portal\" })\n" }, { "code": null, "e": 1081, "s": 890, "text": "The prefix a is a variable that will be anything this thing will required to refer later in any statement. After firing the Cypher query you will get something like the below picture.Output:" }, { "code": null, "e": 1316, "s": 1081, "text": "Display node:So now you have a created node but the above query does not show you the created node to see the node you need to use RETURN statement like have to fire the below query. Here again we will create a node with 2 properties." }, { "code": null, "e": 1506, "s": 1316, "text": "Display Created node:$ CREATE (a:GeksforGeeks { Tag : \"A Computer Science Portal\", Type : \"Edutech\" }) \nRETURN a\nOutput:Note: We return the node by using its variable name (in this case a)." }, { "code": null, "e": 1599, "s": 1506, "text": "$ CREATE (a:GeksforGeeks { Tag : \"A Computer Science Portal\", Type : \"Edutech\" }) \nRETURN a\n" }, { "code": null, "e": 1676, "s": 1599, "text": "Output:Note: We return the node by using its variable name (in this case a)." }, { "code": null, "e": 1854, "s": 1676, "text": "Creating multiple nodes:To create multiple nodes use the CREATE statement and separate the nodes by “, ” coma or you can use multiple time CREATE statement Like the below query." }, { "code": null, "e": 2147, "s": 1854, "text": "Multiple nodes single Query using coma:$ CREATE (a:GeeksforGeeks { Tag: \"A Computer Science Portal\"}), \n(b:W3School { Tag: \"We are the Learner\"}) \nRETURN a, b\norCREATE (a:GeeksforGeeks { Tag: \"A Computer Science Portal\"}) \nCREATE (b:W3School { Tag: \"We are the Learner\"}) \nRETURN a, b\nOutput:" }, { "code": null, "e": 2268, "s": 2147, "text": "$ CREATE (a:GeeksforGeeks { Tag: \"A Computer Science Portal\"}), \n(b:W3School { Tag: \"We are the Learner\"}) \nRETURN a, b\n" }, { "code": null, "e": 2271, "s": 2268, "text": "or" }, { "code": null, "e": 2396, "s": 2271, "text": "CREATE (a:GeeksforGeeks { Tag: \"A Computer Science Portal\"}) \nCREATE (b:W3School { Tag: \"We are the Learner\"}) \nRETURN a, b\n" }, { "code": null, "e": 2404, "s": 2396, "text": "Output:" }, { "code": null, "e": 2452, "s": 2404, "text": "Note: Both the query will gave you same output." }, { "code": null, "e": 2457, "s": 2452, "text": "DBMS" }, { "code": null, "e": 2462, "s": 2457, "text": "DBMS" } ]
enum.IntEnum in Python
22 Apr, 2020 With the help of enum.IntEnum() method, we can get the enumeration based on integer value, if we compare with normal enum based class it will fail by using enum.IntEnum() method. Syntax : enum.IntEnum Return : IntEnum doesn’t have a written type. Example #1 :In this example we can see that by using enum.IntEnum() method, we are able to get the enumeration based on integer value by using this method. # import enum and IntEnumfrom enum import IntEnum # Using enum.IntEnum class author(IntEnum): GEEK = 1 FOR = 2 GEEKS = 3 print(author.FOR == 2) OutPut : True Example #2 : # import enum and IntEnumfrom enum import IntEnum, Enum # Using enum.IntEnum class author(IntEnum): GEEK = 1 FOR = 2 GEEKS = 3 class language(Enum): Python = 1 Java = 2 print(author.GEEK == language.Python) OutPut : False Python-enum Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 207, "s": 28, "text": "With the help of enum.IntEnum() method, we can get the enumeration based on integer value, if we compare with normal enum based class it will fail by using enum.IntEnum() method." }, { "code": null, "e": 229, "s": 207, "text": "Syntax : enum.IntEnum" }, { "code": null, "e": 275, "s": 229, "text": "Return : IntEnum doesn’t have a written type." }, { "code": null, "e": 431, "s": 275, "text": "Example #1 :In this example we can see that by using enum.IntEnum() method, we are able to get the enumeration based on integer value by using this method." }, { "code": "# import enum and IntEnumfrom enum import IntEnum # Using enum.IntEnum class author(IntEnum): GEEK = 1 FOR = 2 GEEKS = 3 print(author.FOR == 2)", "e": 589, "s": 431, "text": null }, { "code": null, "e": 598, "s": 589, "text": "OutPut :" }, { "code": null, "e": 603, "s": 598, "text": "True" }, { "code": null, "e": 616, "s": 603, "text": "Example #2 :" }, { "code": "# import enum and IntEnumfrom enum import IntEnum, Enum # Using enum.IntEnum class author(IntEnum): GEEK = 1 FOR = 2 GEEKS = 3 class language(Enum): Python = 1 Java = 2 print(author.GEEK == language.Python)", "e": 846, "s": 616, "text": null }, { "code": null, "e": 855, "s": 846, "text": "OutPut :" }, { "code": null, "e": 861, "s": 855, "text": "False" }, { "code": null, "e": 873, "s": 861, "text": "Python-enum" }, { "code": null, "e": 880, "s": 873, "text": "Python" } ]
Python – Create dictionary from the list
01 Oct, 2020 Given a list. The task is to convert it to a dictionary with the values as the list element and keys as the concatenation of the given string K and value. Examples: Input : test_list = [“gfg”, “is”, “best”], K = “pref_” Output : {‘pref_gfg’: ‘gfg’, ‘pref_is’: ‘is’, ‘pref_best’: ‘best’} Explanation : Keys constructed after concatenating K. Input : test_list = [“gfg”, “best”], K = “pref_” Output : {‘pref_gfg’: ‘gfg’, ‘pref_best’: ‘best’} Explanation : Keys constructed after concatenating K. Method #1: Using loop This is one of the ways in which this task can be performed. In this, we perform concatenation using + operator to construct keys and values are extracted from list. Python3 # Python3 code to demonstrate working of # Values derived Dictionary keys# Using loop # initializing listtest_list = ["gfg", "is", "best"] # printing original listprint("The original list is : " + str(test_list)) # initializing K K = "def_key_" # using loop to construct new Dictionary# + operator used to concat default key and values res = dict()for ele in test_list: res[K + str(ele)] = ele # printing result print("The constructed Dictionary : " + str(res)) Output: The original list is : [‘gfg’, ‘is’, ‘best’]The constructed Dictionary : {‘def_key_gfg’: ‘gfg’, ‘def_key_is’: ‘is’, ‘def_key_best’: ‘best’} Method #2: Using dictionary comprehension This is yet another way in which this task can be performed. In this, we construct a dictionary using one-liner using dictionary comprehension. Python3 # Python3 code to demonstrate working of # Values derived Dictionary keys# Using dictionary comprehension # initializing listtest_list = ["gfg", "is", "best"] # printing original listprint("The original list is : " + str(test_list)) # initializing K K = "def_key_" # using dictionary comprehension# + operator used to concat default key and values res = {K + str(ele) : ele for ele in test_list} # printing result print("The constructed Dictionary : " + str(res)) Output: The original list is : [‘gfg’, ‘is’, ‘best’]The constructed Dictionary : {‘def_key_gfg’: ‘gfg’, ‘def_key_is’: ‘is’, ‘def_key_best’: ‘best’} Python dictionary-programs Python list-programs Python Python Programs 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() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Oct, 2020" }, { "code": null, "e": 183, "s": 28, "text": "Given a list. The task is to convert it to a dictionary with the values as the list element and keys as the concatenation of the given string K and value." }, { "code": null, "e": 193, "s": 183, "text": "Examples:" }, { "code": null, "e": 369, "s": 193, "text": "Input : test_list = [“gfg”, “is”, “best”], K = “pref_” Output : {‘pref_gfg’: ‘gfg’, ‘pref_is’: ‘is’, ‘pref_best’: ‘best’} Explanation : Keys constructed after concatenating K." }, { "code": null, "e": 523, "s": 369, "text": "Input : test_list = [“gfg”, “best”], K = “pref_” Output : {‘pref_gfg’: ‘gfg’, ‘pref_best’: ‘best’} Explanation : Keys constructed after concatenating K. " }, { "code": null, "e": 545, "s": 523, "text": "Method #1: Using loop" }, { "code": null, "e": 711, "s": 545, "text": "This is one of the ways in which this task can be performed. In this, we perform concatenation using + operator to construct keys and values are extracted from list." }, { "code": null, "e": 719, "s": 711, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Values derived Dictionary keys# Using loop # initializing listtest_list = [\"gfg\", \"is\", \"best\"] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing K K = \"def_key_\" # using loop to construct new Dictionary# + operator used to concat default key and values res = dict()for ele in test_list: res[K + str(ele)] = ele # printing result print(\"The constructed Dictionary : \" + str(res))", "e": 1191, "s": 719, "text": null }, { "code": null, "e": 1199, "s": 1191, "text": "Output:" }, { "code": null, "e": 1339, "s": 1199, "text": "The original list is : [‘gfg’, ‘is’, ‘best’]The constructed Dictionary : {‘def_key_gfg’: ‘gfg’, ‘def_key_is’: ‘is’, ‘def_key_best’: ‘best’}" }, { "code": null, "e": 1381, "s": 1339, "text": "Method #2: Using dictionary comprehension" }, { "code": null, "e": 1525, "s": 1381, "text": "This is yet another way in which this task can be performed. In this, we construct a dictionary using one-liner using dictionary comprehension." }, { "code": null, "e": 1533, "s": 1525, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Values derived Dictionary keys# Using dictionary comprehension # initializing listtest_list = [\"gfg\", \"is\", \"best\"] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing K K = \"def_key_\" # using dictionary comprehension# + operator used to concat default key and values res = {K + str(ele) : ele for ele in test_list} # printing result print(\"The constructed Dictionary : \" + str(res))", "e": 2003, "s": 1533, "text": null }, { "code": null, "e": 2011, "s": 2003, "text": "Output:" }, { "code": null, "e": 2151, "s": 2011, "text": "The original list is : [‘gfg’, ‘is’, ‘best’]The constructed Dictionary : {‘def_key_gfg’: ‘gfg’, ‘def_key_is’: ‘is’, ‘def_key_best’: ‘best’}" }, { "code": null, "e": 2178, "s": 2151, "text": "Python dictionary-programs" }, { "code": null, "e": 2199, "s": 2178, "text": "Python list-programs" }, { "code": null, "e": 2206, "s": 2199, "text": "Python" }, { "code": null, "e": 2222, "s": 2206, "text": "Python Programs" }, { "code": null, "e": 2320, "s": 2222, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2338, "s": 2320, "text": "Python Dictionary" }, { "code": null, "e": 2380, "s": 2338, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2402, "s": 2380, "text": "Enumerate() in Python" }, { "code": null, "e": 2437, "s": 2402, "text": "Read a file line by line in Python" }, { "code": null, "e": 2463, "s": 2437, "text": "Python String | replace()" }, { "code": null, "e": 2506, "s": 2463, "text": "Python program to convert a list to string" }, { "code": null, "e": 2528, "s": 2506, "text": "Defaultdict in Python" }, { "code": null, "e": 2567, "s": 2528, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2605, "s": 2567, "text": "Python | Convert a list to dictionary" } ]
Merge two sorted lists (in-place)
24 Jun, 2022 Given two sorted lists, merge them so as to produce a combined sorted list (without using extra space).Examples: Input : head1: 5->7->9 head2: 4->6->8 Output : 4->5->6->7->8->9 Explanation: The output list is in sorted order. Input : head1: 1->3->5->7 head2: 2->4 Output : 1->2->3->4->5->7 Explanation: The output list is in sorted order. There are different discussed different solutions in post below. Merge two sorted linked lists Method 1 (Recursive) Approach: The recursive solution can be formed, given the linked lists are sorted. Compare the head of both linked lists.Find the smaller node among the two head nodes. The current element will be the smaller node among two head nodes.The rest elements of both lists will appear after that.Now run a recursive function with parameters, the next node of the smaller element, and the other head.The recursive function will return the next smaller element linked with rest of the sorted element. Now point the next of current element to that, i.e curr_ele->next=recursivefunction()Handle some corner cases. If both the heads are NULL return null.If one head is null return the other. Compare the head of both linked lists. Find the smaller node among the two head nodes. The current element will be the smaller node among two head nodes. The rest elements of both lists will appear after that. Now run a recursive function with parameters, the next node of the smaller element, and the other head. The recursive function will return the next smaller element linked with rest of the sorted element. Now point the next of current element to that, i.e curr_ele->next=recursivefunction() Handle some corner cases. If both the heads are NULL return null.If one head is null return the other. If both the heads are NULL return null. If one head is null return the other. C++ C Java Python3 C# Javascript // C++ program to merge two sorted linked lists// in-place.#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* next;}; // Function to create newNode in a linkedlistNode* newNode(int key){ struct Node* temp = new Node; temp->data = key; temp->next = NULL; return temp;} // A utility function to print linked listvoid printList(Node* node){ while (node != NULL) { cout << node->data << " "; node = node->next; }} // Merges two given lists in-place. This function// mainly compares head nodes and calls mergeUtil()Node* merge(Node* h1, Node* h2){ if (!h1) return h2; if (!h2) return h1; // start with the linked list // whose head data is the least if (h1->data < h2->data) { h1->next = merge(h1->next, h2); return h1; } else { h2->next = merge(h1, h2->next); return h2; }} // Driver programint main(){ Node* head1 = newNode(1); head1->next = newNode(3); head1->next->next = newNode(5); // 1->3->5 LinkedList created Node* head2 = newNode(0); head2->next = newNode(2); head2->next->next = newNode(4); // 0->2->4 LinkedList created Node* mergedhead = merge(head1, head2); printList(mergedhead); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // C program to merge two sorted linked lists// in-place.#include <stdio.h>#include <stdlib.h> typedef struct Node { int data; struct Node* next;} Node; // Function to create newNode in a linkedlistNode* newNode(int key){ struct Node* temp = (Node*)malloc(sizeof(Node)); temp->data = key; temp->next = NULL; return temp;} // A utility function to print linked listvoid printList(Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} // Merges two given lists in-place. This function// mainly compares head nodes and calls mergeUtil()Node* merge(Node* h1, Node* h2){ if (!h1) return h2; if (!h2) return h1; // start with the linked list // whose head data is the least if (h1->data < h2->data) { h1->next = merge(h1->next, h2); return h1; } else { h2->next = merge(h1, h2->next); return h2; }} // Driver programint main(){ Node* head1 = newNode(1); head1->next = newNode(3); head1->next->next = newNode(5); // 1->3->5 LinkedList created Node* head2 = newNode(0); head2->next = newNode(2); head2->next->next = newNode(4); // 0->2->4 LinkedList created Node* mergedhead = merge(head1, head2); printList(mergedhead); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Java program to merge two sorted// linked lists in-place.class GFG { static class Node { int data; Node next; }; // Function to create newNode in a linkedlist static Node newNode(int key) { Node temp = new Node(); temp.data = key; temp.next = null; return temp; } // A utility function to print linked list static void printList(Node node) { while (node != null) { System.out.printf("%d ", node.data); node = node.next; } } // Merges two given lists in-place. This function // mainly compares head nodes and calls mergeUtil() static Node merge(Node h1, Node h2) { if (h1 == null) return h2; if (h2 == null) return h1; // start with the linked list // whose head data is the least if (h1.data < h2.data) { h1.next = merge(h1.next, h2); return h1; } else { h2.next = merge(h1, h2.next); return h2; } } // Driver program public static void main(String args[]) { Node head1 = newNode(1); head1.next = newNode(3); head1.next.next = newNode(5); // 1.3.5 LinkedList created Node head2 = newNode(0); head2.next = newNode(2); head2.next.next = newNode(4); // 0.2.4 LinkedList created Node mergedhead = merge(head1, head2); printList(mergedhead); }} // This code is contributed by Arnab Kundu # Python3 program to merge two # sorted linked lists in-place.import math class Node: def __init__(self, data): self.data = data self.next = None # Function to create newNode in a linkedlistdef newNode( key): temp = Node(key) temp.data = key temp.next = None return temp # A utility function to print linked listdef printList( node): while (node != None): print(node.data, end = " ") node = node.next # Merges two given lists in-place. # This function mainly compares # head nodes and calls mergeUtil()def merge( h1, h2): if (h1 == None): return h2 if (h2 == None): return h1 # start with the linked list # whose head data is the least if (h1.data < h2.data): h1.next = merge(h1.next, h2) return h1 else: h2.next = merge(h1, h2.next) return h2 # Driver Codeif __name__=='__main__': head1 = newNode(1) head1.next = newNode(3) head1.next.next = newNode(5) # 1.3.5 LinkedList created head2 = newNode(0) head2.next = newNode(2) head2.next.next = newNode(4) # 0.2.4 LinkedList created mergedhead = merge(head1, head2) printList(mergedhead) # This code is contributed by Srathore // C# program to merge two sorted// linked lists in-place.using System; class GFG { public class Node { public int data; public Node next; }; // Function to create newNode in a linkedlist static Node newNode(int key) { Node temp = new Node(); temp.data = key; temp.next = null; return temp; } // A utility function to print linked list static void printList(Node node) { while (node != null) { Console.Write("{0} ", node.data); node = node.next; } } // Merges two given lists in-place. This function // mainly compares head nodes and calls mergeUtil() static Node merge(Node h1, Node h2) { if (h1 == null) return h2; if (h2 == null) return h1; // start with the linked list // whose head data is the least if (h1.data < h2.data) { h1.next = merge(h1.next, h2); return h1; } else { h2.next = merge(h1, h2.next); return h2; } } // Driver code public static void Main(String[] args) { Node head1 = newNode(1); head1.next = newNode(3); head1.next.next = newNode(5); // 1.3.5 LinkedList created Node head2 = newNode(0); head2.next = newNode(2); head2.next.next = newNode(4); // 0.2.4 LinkedList created Node mergedhead = merge(head1, head2); printList(mergedhead); }} // This code has been contributed by 29AjayKumar <script>// javascript program to merge two sorted// linked lists in-place. class Node { constructor(){ this.data = 0; this.next = null; } } // Function to create newNode in a linkedlist function newNode(key) { temp = new Node(); temp.data = key; temp.next = null; return temp; } // A utility function to print linked list function printList( node) { while (node != null) { document.write(node.data+" "); node = node.next; } } // Merges two given lists in-place. This function // mainly compares head nodes and calls mergeUtil() function merge( h1, h2) { if (h1 == null) return h2; if (h2 == null) return h1; // start with the linked list // whose head data is the least if (h1.data < h2.data) { h1.next = merge(h1.next, h2); return h1; } else { h2.next = merge(h1, h2.next); return h2; } } // Driver program head1 = newNode(1); head1.next = newNode(3); head1.next.next = newNode(5); // 1.3.5 LinkedList created head2 = newNode(0); head2.next = newNode(2); head2.next.next = newNode(4); // 0.2.4 LinkedList created mergedhead = merge(head1, head2); printList(mergedhead); // This code contributed by umadevi9616</script> Output: 0 1 2 3 4 5 Complexity Analysis: Time complexity:O(n). Only one traversal of the linked lists are needed. Auxiliary Space:O(n). If the recursive stack space is taken into consideration. Method 2 (Iterative) Approach: This approach is very similar to the above recursive approach. Traverse the list from start to end.If the head node of second list lies in between two nodes of the first list, insert it there and make the next node of second list the head. Continue this until there is no node left in both lists, i.e. both the lists are traversed.If the first list has reached end while traversing, point the next node to the head of second list. Traverse the list from start to end. If the head node of second list lies in between two nodes of the first list, insert it there and make the next node of second list the head. Continue this until there is no node left in both lists, i.e. both the lists are traversed. If the first list has reached end while traversing, point the next node to the head of second list. Note: Compare both the lists where the list with a smaller head value is the first list. C++ C Java Python C# Javascript // C++ program to merge two sorted linked lists// in-place.#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* next;}; // Function to create newNode in a linkedliststruct Node* newNode(int key){ struct Node* temp = new Node; temp->data = key; temp->next = NULL; return temp;} // A utility function to print linked listvoid printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} // Merges two lists with headers as h1 and h2.// It assumes that h1's data is smaller than// or equal to h2's data.struct Node* mergeUtil(struct Node* h1, struct Node* h2){ // if only one node in first list // simply point its head to second list if (!h1->next) { h1->next = h2; return h1; } // Initialize current and next pointers of // both lists struct Node *curr1 = h1, *next1 = h1->next; struct Node *curr2 = h2, *next2 = h2->next; while (next1 && curr2) { // if curr2 lies in between curr1 and next1 // then do curr1->curr2->next1 if ((curr2->data) >= (curr1->data) && (curr2->data) <= (next1->data)) { next2 = curr2->next; curr1->next = curr2; curr2->next = next1; // now let curr1 and curr2 to point // to their immediate next pointers curr1 = curr2; curr2 = next2; } else { // if more nodes in first list if (next1->next) { next1 = next1->next; curr1 = curr1->next; } // else point the last node of first list // to the remaining nodes of second list else { next1->next = curr2; return h1; } } } return h1;} // Merges two given lists in-place. This function// mainly compares head nodes and calls mergeUtil()struct Node* merge(struct Node* h1, struct Node* h2){ if (!h1) return h2; if (!h2) return h1; // start with the linked list // whose head data is the least if (h1->data < h2->data) return mergeUtil(h1, h2); else return mergeUtil(h2, h1);} // Driver programint main(){ struct Node* head1 = newNode(1); head1->next = newNode(3); head1->next->next = newNode(5); // 1->3->5 LinkedList created struct Node* head2 = newNode(0); head2->next = newNode(2); head2->next->next = newNode(4); // 0->2->4 LinkedList created struct Node* mergedhead = merge(head1, head2); printList(mergedhead); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // C program to merge two sorted linked lists// in-place.#include <stdio.h>#include <stdlib.h> typedef struct Node { int data; struct Node* next;} Node; // Function to create newNode in a linkedlistNode* newNode(int key){ Node* temp = (Node *)malloc(sizeof(Node)); temp->data = key; temp->next = NULL; return temp;} // A utility function to print linked listvoid printList(Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} // Merges two lists with headers as h1 and h2.// It assumes that h1's data is smaller than// or equal to h2's data.struct Node* mergeUtil(Node* h1, Node* h2){ // if only one node in first list // simply point its head to second list if (!h1->next) { h1->next = h2; return h1; } // Initialize current and next pointers of both lists Node *curr1 = h1, *next1 = h1->next; Node *curr2 = h2, *next2 = h2->next; while (next1 && curr2) { // if curr2 lies in between curr1 and next1 // then do curr1->curr2->next1 if ((curr2->data) >= (curr1->data) && (curr2->data) <= (next1->data)) { next2 = curr2->next; curr1->next = curr2; curr2->next = next1; // now let curr1 and curr2 to point // to their immediate next pointers curr1 = curr2; curr2 = next2; } else { // if more nodes in first list if (next1->next) { next1 = next1->next; curr1 = curr1->next; } // else point the last node of first list // to the remaining nodes of second list else { next1->next = curr2; return h1; } } } return h1;} // Merges two given lists in-place. This function// mainly compares head nodes and calls mergeUtil()Node* merge(Node* h1, Node* h2){ if (!h1) return h2; if (!h2) return h1; // start with the linked list // whose head data is the least if (h1->data < h2->data) return mergeUtil(h1, h2); else return mergeUtil(h2, h1);} // Driver programint main(){ Node* head1 = newNode(1); head1->next = newNode(3); head1->next->next = newNode(5); // 1->3->5 LinkedList created Node* head2 = newNode(0); head2->next = newNode(2); head2->next->next = newNode(4); // 0->2->4 LinkedList created Node* mergedhead = merge(head1, head2); printList(mergedhead); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Java program to merge two sorted// linked lists in-place.class GfG { static class Node { int data; Node next; } // Function to create newNode in a linkedlist static Node newNode(int key) { Node temp = new Node(); temp.data = key; temp.next = null; return temp; } // A utility function to print linked list static void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } // Merges two lists with headers as h1 and h2. // It assumes that h1's data is smaller than // or equal to h2's data. static Node mergeUtil(Node h1, Node h2) { // if only one node in first list // simply point its head to second list if (h1.next == null) { h1.next = h2; return h1; } // Initialize current and next pointers of // both lists Node curr1 = h1, next1 = h1.next; Node curr2 = h2, next2 = h2.next; while (next1 != null && curr2 != null) { // if curr2 lies in between curr1 and next1 // then do curr1->curr2->next1 if ((curr2.data) >= (curr1.data) && (curr2.data) <= (next1.data)) { next2 = curr2.next; curr1.next = curr2; curr2.next = next1; // now let curr1 and curr2 to point // to their immediate next pointers curr1 = curr2; curr2 = next2; } else { // if more nodes in first list if (next1.next != null) { next1 = next1.next; curr1 = curr1.next; } // else point the last node of first list // to the remaining nodes of second list else { next1.next = curr2; return h1; } } } return h1; } // Merges two given lists in-place. This function // mainly compares head nodes and calls mergeUtil() static Node merge(Node h1, Node h2) { if (h1 == null) return h2; if (h2 == null) return h1; // start with the linked list // whose head data is the least if (h1.data < h2.data) return mergeUtil(h1, h2); else return mergeUtil(h2, h1); } // Driver code public static void main(String[] args) { Node head1 = newNode(1); head1.next = newNode(3); head1.next.next = newNode(5); // 1->3->5 LinkedList created Node head2 = newNode(0); head2.next = newNode(2); head2.next.next = newNode(4); // 0->2->4 LinkedList created Node mergedhead = merge(head1, head2); printList(mergedhead); }} // This code is contributed by// prerna saini # Python program to merge two sorted linked lists# in-place. # Linked List node class Node: def __init__(self, data): self.data = data self.next = None # Function to create newNode in a linkedlistdef newNode(key): temp = Node(0) temp.data = key temp.next = None return temp # A utility function to print linked listdef printList(node): while (node != None) : print( node.data, end =" ") node = node.next # Merges two lists with headers as h1 and h2.# It assumes that h1's data is smaller than# or equal to h2's data.def mergeUtil(h1, h2): # if only one node in first list # simply point its head to second list if (h1.next == None) : h1.next = h2 return h1 # Initialize current and next pointers of # both lists curr1 = h1 next1 = h1.next curr2 = h2 next2 = h2.next while (next1 != None and curr2 != None): # if curr2 lies in between curr1 and next1 # then do curr1.curr2.next1 if ((curr2.data) >= (curr1.data) and (curr2.data) <= (next1.data)) : next2 = curr2.next curr1.next = curr2 curr2.next = next1 # now let curr1 and curr2 to point # to their immediate next pointers curr1 = curr2 curr2 = next2 else : # if more nodes in first list if (next1.next) : next1 = next1.next curr1 = curr1.next # else point the last node of first list # to the remaining nodes of second list else : next1.next = curr2 return h1 return h1 # Merges two given lists in-place. This function# mainly compares head nodes and calls mergeUtil()def merge( h1, h2): if (h1 == None): return h2 if (h2 == None): return h1 # start with the linked list # whose head data is the least if (h1.data < h2.data): return mergeUtil(h1, h2) else: return mergeUtil(h2, h1) # Driver program head1 = newNode(1)head1.next = newNode(3)head1.next.next = newNode(5) # 1.3.5 LinkedList created head2 = newNode(0)head2.next = newNode(2)head2.next.next = newNode(4) # 0.2.4 LinkedList created mergedhead = merge(head1, head2) printList(mergedhead) # This code is contributed by Arnab Kundu // C# program to merge two sorted// linked lists in-place.using System; class GfG { public class Node { public int data; public Node next; } // Function to create newNode in a linkedlist static Node newNode(int key) { Node temp = new Node(); temp.data = key; temp.next = null; return temp; } // A utility function to print linked list static void printList(Node node) { while (node != null) { Console.Write(node.data + " "); node = node.next; } } // Merges two lists with headers as h1 and h2. // It assumes that h1's data is smaller than // or equal to h2's data. static Node mergeUtil(Node h1, Node h2) { // if only one node in first list // simply point its head to second list if (h1.next == null) { h1.next = h2; return h1; } // Initialize current and next pointers of // both lists Node curr1 = h1, next1 = h1.next; Node curr2 = h2, next2 = h2.next; while (next1 != null && curr2 != null) { // if curr2 lies in between curr1 and next1 // then do curr1->curr2->next1 if ((curr2.data) >= (curr1.data) && (curr2.data) <= (next1.data)) { next2 = curr2.next; curr1.next = curr2; curr2.next = next1; // now let curr1 and curr2 to point // to their immediate next pointers curr1 = curr2; curr2 = next2; } else { // if more nodes in first list if (next1.next != null) { next1 = next1.next; curr1 = curr1.next; } // else point the last node of first list // to the remaining nodes of second list else { next1.next = curr2; return h1; } } } return h1; } // Merges two given lists in-place. This function // mainly compares head nodes and calls mergeUtil() static Node merge(Node h1, Node h2) { if (h1 == null) return h2; if (h2 == null) return h1; // start with the linked list // whose head data is the least if (h1.data < h2.data) return mergeUtil(h1, h2); else return mergeUtil(h2, h1); } // Driver code public static void Main(String[] args) { Node head1 = newNode(1); head1.next = newNode(3); head1.next.next = newNode(5); // 1->3->5 LinkedList created Node head2 = newNode(0); head2.next = newNode(2); head2.next.next = newNode(4); // 0->2->4 LinkedList created Node mergedhead = merge(head1, head2); printList(mergedhead); }} /* This code contributed by PrinciRaj1992 */ <script> // JavaScript program to merge two sorted// linked lists in-place.class Node { constructor() { this.data = 0; this.next = null; }} // Function to create newNode in a linkedlist function newNode(key) { var temp = new Node(); temp.data = key; temp.next = null; return temp; } // A utility function to print linked list function printList(node) { while (node != null) { document.write(node.data + " "); node = node.next; } } // Merges two lists with headers as h1 and h2. // It assumes that h1's data is smaller than // or equal to h2's data. function mergeUtil(h1, h2) { // if only one node in first list // simply point its head to second list if (h1.next == null) { h1.next = h2; return h1; } // Initialize current and next pointers of // both lists var curr1 = h1, next1 = h1.next; var curr2 = h2, next2 = h2.next; while (next1 != null && curr2 != null) { // if curr2 lies in between curr1 and next1 // then do curr1->curr2->next1 if ((curr2.data) >= (curr1.data) && (curr2.data) <= (next1.data)) { next2 = curr2.next; curr1.next = curr2; curr2.next = next1; // now let curr1 and curr2 to point // to their immediate next pointers curr1 = curr2; curr2 = next2; } else { // if more nodes in first list if (next1.next != null) { next1 = next1.next; curr1 = curr1.next; } // else point the last node of first list // to the remaining nodes of second list else { next1.next = curr2; return h1; } } } return h1; } // Merges two given lists in-place. This function // mainly compares head nodes and calls mergeUtil() function merge(h1, h2) { if (h1 == null) return h2; if (h2 == null) return h1; // start with the linked list // whose head data is the least if (h1.data < h2.data) return mergeUtil(h1, h2); else return mergeUtil(h2, h1); } // Driver code var head1 = newNode(1); head1.next = newNode(3); head1.next.next = newNode(5); // 1->3->5 LinkedList created var head2 = newNode(0); head2.next = newNode(2); head2.next.next = newNode(4); // 0->2->4 LinkedList created var mergedhead = merge(head1, head2); printList(mergedhead); // This code contributed by gauravrajput1 </script> Output: 0 1 2 3 4 5 Complexity Analysis: Time complexity:O(n). As only one traversal of the linked lists is needed. Auxiliary Space:O(1). As there is no space required. This article is contributed by Mandula Vikitha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. prerna saini princiraj1992 andrew1234 29AjayKumar mrityunjoy gp6 sapnasingh4991 umadevi9616 GauravRajput1 arorakashish0911 adityakumar129 Accolite Amazon Belzabar Brocade FactSet Flipkart MakeMyTrip Microsoft OATS Systems Oracle Samsung Synopsys Linked List Flipkart Accolite Amazon Microsoft Samsung FactSet MakeMyTrip Oracle Brocade Synopsys OATS Systems Belzabar Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Jun, 2022" }, { "code": null, "e": 169, "s": 54, "text": "Given two sorted lists, merge them so as to produce a combined sorted list (without using extra space).Examples: " }, { "code": null, "e": 413, "s": 169, "text": "Input : head1: 5->7->9\n head2: 4->6->8 \nOutput : 4->5->6->7->8->9\nExplanation: The output list is in sorted order.\n\nInput : head1: 1->3->5->7\n head2: 2->4\nOutput : 1->2->3->4->5->7\nExplanation: The output list is in sorted order." }, { "code": null, "e": 511, "s": 415, "text": "There are different discussed different solutions in post below. Merge two sorted linked lists " }, { "code": null, "e": 532, "s": 511, "text": "Method 1 (Recursive)" }, { "code": null, "e": 617, "s": 532, "text": "Approach: The recursive solution can be formed, given the linked lists are sorted. " }, { "code": null, "e": 1215, "s": 617, "text": "Compare the head of both linked lists.Find the smaller node among the two head nodes. The current element will be the smaller node among two head nodes.The rest elements of both lists will appear after that.Now run a recursive function with parameters, the next node of the smaller element, and the other head.The recursive function will return the next smaller element linked with rest of the sorted element. Now point the next of current element to that, i.e curr_ele->next=recursivefunction()Handle some corner cases. If both the heads are NULL return null.If one head is null return the other." }, { "code": null, "e": 1254, "s": 1215, "text": "Compare the head of both linked lists." }, { "code": null, "e": 1369, "s": 1254, "text": "Find the smaller node among the two head nodes. The current element will be the smaller node among two head nodes." }, { "code": null, "e": 1425, "s": 1369, "text": "The rest elements of both lists will appear after that." }, { "code": null, "e": 1529, "s": 1425, "text": "Now run a recursive function with parameters, the next node of the smaller element, and the other head." }, { "code": null, "e": 1715, "s": 1529, "text": "The recursive function will return the next smaller element linked with rest of the sorted element. Now point the next of current element to that, i.e curr_ele->next=recursivefunction()" }, { "code": null, "e": 1818, "s": 1715, "text": "Handle some corner cases. If both the heads are NULL return null.If one head is null return the other." }, { "code": null, "e": 1858, "s": 1818, "text": "If both the heads are NULL return null." }, { "code": null, "e": 1896, "s": 1858, "text": "If one head is null return the other." }, { "code": null, "e": 1902, "s": 1898, "text": "C++" }, { "code": null, "e": 1904, "s": 1902, "text": "C" }, { "code": null, "e": 1909, "s": 1904, "text": "Java" }, { "code": null, "e": 1917, "s": 1909, "text": "Python3" }, { "code": null, "e": 1920, "s": 1917, "text": "C#" }, { "code": null, "e": 1931, "s": 1920, "text": "Javascript" }, { "code": "// C++ program to merge two sorted linked lists// in-place.#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* next;}; // Function to create newNode in a linkedlistNode* newNode(int key){ struct Node* temp = new Node; temp->data = key; temp->next = NULL; return temp;} // A utility function to print linked listvoid printList(Node* node){ while (node != NULL) { cout << node->data << \" \"; node = node->next; }} // Merges two given lists in-place. This function// mainly compares head nodes and calls mergeUtil()Node* merge(Node* h1, Node* h2){ if (!h1) return h2; if (!h2) return h1; // start with the linked list // whose head data is the least if (h1->data < h2->data) { h1->next = merge(h1->next, h2); return h1; } else { h2->next = merge(h1, h2->next); return h2; }} // Driver programint main(){ Node* head1 = newNode(1); head1->next = newNode(3); head1->next->next = newNode(5); // 1->3->5 LinkedList created Node* head2 = newNode(0); head2->next = newNode(2); head2->next->next = newNode(4); // 0->2->4 LinkedList created Node* mergedhead = merge(head1, head2); printList(mergedhead); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 3279, "s": 1931, "text": null }, { "code": "// C program to merge two sorted linked lists// in-place.#include <stdio.h>#include <stdlib.h> typedef struct Node { int data; struct Node* next;} Node; // Function to create newNode in a linkedlistNode* newNode(int key){ struct Node* temp = (Node*)malloc(sizeof(Node)); temp->data = key; temp->next = NULL; return temp;} // A utility function to print linked listvoid printList(Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} // Merges two given lists in-place. This function// mainly compares head nodes and calls mergeUtil()Node* merge(Node* h1, Node* h2){ if (!h1) return h2; if (!h2) return h1; // start with the linked list // whose head data is the least if (h1->data < h2->data) { h1->next = merge(h1->next, h2); return h1; } else { h2->next = merge(h1, h2->next); return h2; }} // Driver programint main(){ Node* head1 = newNode(1); head1->next = newNode(3); head1->next->next = newNode(5); // 1->3->5 LinkedList created Node* head2 = newNode(0); head2->next = newNode(2); head2->next->next = newNode(4); // 0->2->4 LinkedList created Node* mergedhead = merge(head1, head2); printList(mergedhead); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 4651, "s": 3279, "text": null }, { "code": "// Java program to merge two sorted// linked lists in-place.class GFG { static class Node { int data; Node next; }; // Function to create newNode in a linkedlist static Node newNode(int key) { Node temp = new Node(); temp.data = key; temp.next = null; return temp; } // A utility function to print linked list static void printList(Node node) { while (node != null) { System.out.printf(\"%d \", node.data); node = node.next; } } // Merges two given lists in-place. This function // mainly compares head nodes and calls mergeUtil() static Node merge(Node h1, Node h2) { if (h1 == null) return h2; if (h2 == null) return h1; // start with the linked list // whose head data is the least if (h1.data < h2.data) { h1.next = merge(h1.next, h2); return h1; } else { h2.next = merge(h1, h2.next); return h2; } } // Driver program public static void main(String args[]) { Node head1 = newNode(1); head1.next = newNode(3); head1.next.next = newNode(5); // 1.3.5 LinkedList created Node head2 = newNode(0); head2.next = newNode(2); head2.next.next = newNode(4); // 0.2.4 LinkedList created Node mergedhead = merge(head1, head2); printList(mergedhead); }} // This code is contributed by Arnab Kundu", "e": 6187, "s": 4651, "text": null }, { "code": "# Python3 program to merge two # sorted linked lists in-place.import math class Node: def __init__(self, data): self.data = data self.next = None # Function to create newNode in a linkedlistdef newNode( key): temp = Node(key) temp.data = key temp.next = None return temp # A utility function to print linked listdef printList( node): while (node != None): print(node.data, end = \" \") node = node.next # Merges two given lists in-place. # This function mainly compares # head nodes and calls mergeUtil()def merge( h1, h2): if (h1 == None): return h2 if (h2 == None): return h1 # start with the linked list # whose head data is the least if (h1.data < h2.data): h1.next = merge(h1.next, h2) return h1 else: h2.next = merge(h1, h2.next) return h2 # Driver Codeif __name__=='__main__': head1 = newNode(1) head1.next = newNode(3) head1.next.next = newNode(5) # 1.3.5 LinkedList created head2 = newNode(0) head2.next = newNode(2) head2.next.next = newNode(4) # 0.2.4 LinkedList created mergedhead = merge(head1, head2) printList(mergedhead) # This code is contributed by Srathore", "e": 7425, "s": 6187, "text": null }, { "code": "// C# program to merge two sorted// linked lists in-place.using System; class GFG { public class Node { public int data; public Node next; }; // Function to create newNode in a linkedlist static Node newNode(int key) { Node temp = new Node(); temp.data = key; temp.next = null; return temp; } // A utility function to print linked list static void printList(Node node) { while (node != null) { Console.Write(\"{0} \", node.data); node = node.next; } } // Merges two given lists in-place. This function // mainly compares head nodes and calls mergeUtil() static Node merge(Node h1, Node h2) { if (h1 == null) return h2; if (h2 == null) return h1; // start with the linked list // whose head data is the least if (h1.data < h2.data) { h1.next = merge(h1.next, h2); return h1; } else { h2.next = merge(h1, h2.next); return h2; } } // Driver code public static void Main(String[] args) { Node head1 = newNode(1); head1.next = newNode(3); head1.next.next = newNode(5); // 1.3.5 LinkedList created Node head2 = newNode(0); head2.next = newNode(2); head2.next.next = newNode(4); // 0.2.4 LinkedList created Node mergedhead = merge(head1, head2); printList(mergedhead); }} // This code has been contributed by 29AjayKumar", "e": 8988, "s": 7425, "text": null }, { "code": "<script>// javascript program to merge two sorted// linked lists in-place. class Node { constructor(){ this.data = 0; this.next = null; } } // Function to create newNode in a linkedlist function newNode(key) { temp = new Node(); temp.data = key; temp.next = null; return temp; } // A utility function to print linked list function printList( node) { while (node != null) { document.write(node.data+\" \"); node = node.next; } } // Merges two given lists in-place. This function // mainly compares head nodes and calls mergeUtil() function merge( h1, h2) { if (h1 == null) return h2; if (h2 == null) return h1; // start with the linked list // whose head data is the least if (h1.data < h2.data) { h1.next = merge(h1.next, h2); return h1; } else { h2.next = merge(h1, h2.next); return h2; } } // Driver program head1 = newNode(1); head1.next = newNode(3); head1.next.next = newNode(5); // 1.3.5 LinkedList created head2 = newNode(0); head2.next = newNode(2); head2.next.next = newNode(4); // 0.2.4 LinkedList created mergedhead = merge(head1, head2); printList(mergedhead); // This code contributed by umadevi9616</script>", "e": 10450, "s": 8988, "text": null }, { "code": null, "e": 10460, "s": 10450, "text": "Output: " }, { "code": null, "e": 10473, "s": 10460, "text": "0 1 2 3 4 5 " }, { "code": null, "e": 10495, "s": 10473, "text": "Complexity Analysis: " }, { "code": null, "e": 10568, "s": 10495, "text": "Time complexity:O(n). Only one traversal of the linked lists are needed." }, { "code": null, "e": 10648, "s": 10568, "text": "Auxiliary Space:O(n). If the recursive stack space is taken into consideration." }, { "code": null, "e": 10669, "s": 10648, "text": "Method 2 (Iterative)" }, { "code": null, "e": 10743, "s": 10669, "text": "Approach: This approach is very similar to the above recursive approach. " }, { "code": null, "e": 11111, "s": 10743, "text": "Traverse the list from start to end.If the head node of second list lies in between two nodes of the first list, insert it there and make the next node of second list the head. Continue this until there is no node left in both lists, i.e. both the lists are traversed.If the first list has reached end while traversing, point the next node to the head of second list." }, { "code": null, "e": 11148, "s": 11111, "text": "Traverse the list from start to end." }, { "code": null, "e": 11381, "s": 11148, "text": "If the head node of second list lies in between two nodes of the first list, insert it there and make the next node of second list the head. Continue this until there is no node left in both lists, i.e. both the lists are traversed." }, { "code": null, "e": 11481, "s": 11381, "text": "If the first list has reached end while traversing, point the next node to the head of second list." }, { "code": null, "e": 11571, "s": 11481, "text": "Note: Compare both the lists where the list with a smaller head value is the first list. " }, { "code": null, "e": 11575, "s": 11571, "text": "C++" }, { "code": null, "e": 11577, "s": 11575, "text": "C" }, { "code": null, "e": 11582, "s": 11577, "text": "Java" }, { "code": null, "e": 11589, "s": 11582, "text": "Python" }, { "code": null, "e": 11592, "s": 11589, "text": "C#" }, { "code": null, "e": 11603, "s": 11592, "text": "Javascript" }, { "code": "// C++ program to merge two sorted linked lists// in-place.#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* next;}; // Function to create newNode in a linkedliststruct Node* newNode(int key){ struct Node* temp = new Node; temp->data = key; temp->next = NULL; return temp;} // A utility function to print linked listvoid printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} // Merges two lists with headers as h1 and h2.// It assumes that h1's data is smaller than// or equal to h2's data.struct Node* mergeUtil(struct Node* h1, struct Node* h2){ // if only one node in first list // simply point its head to second list if (!h1->next) { h1->next = h2; return h1; } // Initialize current and next pointers of // both lists struct Node *curr1 = h1, *next1 = h1->next; struct Node *curr2 = h2, *next2 = h2->next; while (next1 && curr2) { // if curr2 lies in between curr1 and next1 // then do curr1->curr2->next1 if ((curr2->data) >= (curr1->data) && (curr2->data) <= (next1->data)) { next2 = curr2->next; curr1->next = curr2; curr2->next = next1; // now let curr1 and curr2 to point // to their immediate next pointers curr1 = curr2; curr2 = next2; } else { // if more nodes in first list if (next1->next) { next1 = next1->next; curr1 = curr1->next; } // else point the last node of first list // to the remaining nodes of second list else { next1->next = curr2; return h1; } } } return h1;} // Merges two given lists in-place. This function// mainly compares head nodes and calls mergeUtil()struct Node* merge(struct Node* h1, struct Node* h2){ if (!h1) return h2; if (!h2) return h1; // start with the linked list // whose head data is the least if (h1->data < h2->data) return mergeUtil(h1, h2); else return mergeUtil(h2, h1);} // Driver programint main(){ struct Node* head1 = newNode(1); head1->next = newNode(3); head1->next->next = newNode(5); // 1->3->5 LinkedList created struct Node* head2 = newNode(0); head2->next = newNode(2); head2->next->next = newNode(4); // 0->2->4 LinkedList created struct Node* mergedhead = merge(head1, head2); printList(mergedhead); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 14286, "s": 11603, "text": null }, { "code": "// C program to merge two sorted linked lists// in-place.#include <stdio.h>#include <stdlib.h> typedef struct Node { int data; struct Node* next;} Node; // Function to create newNode in a linkedlistNode* newNode(int key){ Node* temp = (Node *)malloc(sizeof(Node)); temp->data = key; temp->next = NULL; return temp;} // A utility function to print linked listvoid printList(Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} // Merges two lists with headers as h1 and h2.// It assumes that h1's data is smaller than// or equal to h2's data.struct Node* mergeUtil(Node* h1, Node* h2){ // if only one node in first list // simply point its head to second list if (!h1->next) { h1->next = h2; return h1; } // Initialize current and next pointers of both lists Node *curr1 = h1, *next1 = h1->next; Node *curr2 = h2, *next2 = h2->next; while (next1 && curr2) { // if curr2 lies in between curr1 and next1 // then do curr1->curr2->next1 if ((curr2->data) >= (curr1->data) && (curr2->data) <= (next1->data)) { next2 = curr2->next; curr1->next = curr2; curr2->next = next1; // now let curr1 and curr2 to point // to their immediate next pointers curr1 = curr2; curr2 = next2; } else { // if more nodes in first list if (next1->next) { next1 = next1->next; curr1 = curr1->next; } // else point the last node of first list // to the remaining nodes of second list else { next1->next = curr2; return h1; } } } return h1;} // Merges two given lists in-place. This function// mainly compares head nodes and calls mergeUtil()Node* merge(Node* h1, Node* h2){ if (!h1) return h2; if (!h2) return h1; // start with the linked list // whose head data is the least if (h1->data < h2->data) return mergeUtil(h1, h2); else return mergeUtil(h2, h1);} // Driver programint main(){ Node* head1 = newNode(1); head1->next = newNode(3); head1->next->next = newNode(5); // 1->3->5 LinkedList created Node* head2 = newNode(0); head2->next = newNode(2); head2->next->next = newNode(4); // 0->2->4 LinkedList created Node* mergedhead = merge(head1, head2); printList(mergedhead); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 16896, "s": 14286, "text": null }, { "code": "// Java program to merge two sorted// linked lists in-place.class GfG { static class Node { int data; Node next; } // Function to create newNode in a linkedlist static Node newNode(int key) { Node temp = new Node(); temp.data = key; temp.next = null; return temp; } // A utility function to print linked list static void printList(Node node) { while (node != null) { System.out.print(node.data + \" \"); node = node.next; } } // Merges two lists with headers as h1 and h2. // It assumes that h1's data is smaller than // or equal to h2's data. static Node mergeUtil(Node h1, Node h2) { // if only one node in first list // simply point its head to second list if (h1.next == null) { h1.next = h2; return h1; } // Initialize current and next pointers of // both lists Node curr1 = h1, next1 = h1.next; Node curr2 = h2, next2 = h2.next; while (next1 != null && curr2 != null) { // if curr2 lies in between curr1 and next1 // then do curr1->curr2->next1 if ((curr2.data) >= (curr1.data) && (curr2.data) <= (next1.data)) { next2 = curr2.next; curr1.next = curr2; curr2.next = next1; // now let curr1 and curr2 to point // to their immediate next pointers curr1 = curr2; curr2 = next2; } else { // if more nodes in first list if (next1.next != null) { next1 = next1.next; curr1 = curr1.next; } // else point the last node of first list // to the remaining nodes of second list else { next1.next = curr2; return h1; } } } return h1; } // Merges two given lists in-place. This function // mainly compares head nodes and calls mergeUtil() static Node merge(Node h1, Node h2) { if (h1 == null) return h2; if (h2 == null) return h1; // start with the linked list // whose head data is the least if (h1.data < h2.data) return mergeUtil(h1, h2); else return mergeUtil(h2, h1); } // Driver code public static void main(String[] args) { Node head1 = newNode(1); head1.next = newNode(3); head1.next.next = newNode(5); // 1->3->5 LinkedList created Node head2 = newNode(0); head2.next = newNode(2); head2.next.next = newNode(4); // 0->2->4 LinkedList created Node mergedhead = merge(head1, head2); printList(mergedhead); }} // This code is contributed by// prerna saini", "e": 19841, "s": 16896, "text": null }, { "code": "# Python program to merge two sorted linked lists# in-place. # Linked List node class Node: def __init__(self, data): self.data = data self.next = None # Function to create newNode in a linkedlistdef newNode(key): temp = Node(0) temp.data = key temp.next = None return temp # A utility function to print linked listdef printList(node): while (node != None) : print( node.data, end =\" \") node = node.next # Merges two lists with headers as h1 and h2.# It assumes that h1's data is smaller than# or equal to h2's data.def mergeUtil(h1, h2): # if only one node in first list # simply point its head to second list if (h1.next == None) : h1.next = h2 return h1 # Initialize current and next pointers of # both lists curr1 = h1 next1 = h1.next curr2 = h2 next2 = h2.next while (next1 != None and curr2 != None): # if curr2 lies in between curr1 and next1 # then do curr1.curr2.next1 if ((curr2.data) >= (curr1.data) and (curr2.data) <= (next1.data)) : next2 = curr2.next curr1.next = curr2 curr2.next = next1 # now let curr1 and curr2 to point # to their immediate next pointers curr1 = curr2 curr2 = next2 else : # if more nodes in first list if (next1.next) : next1 = next1.next curr1 = curr1.next # else point the last node of first list # to the remaining nodes of second list else : next1.next = curr2 return h1 return h1 # Merges two given lists in-place. This function# mainly compares head nodes and calls mergeUtil()def merge( h1, h2): if (h1 == None): return h2 if (h2 == None): return h1 # start with the linked list # whose head data is the least if (h1.data < h2.data): return mergeUtil(h1, h2) else: return mergeUtil(h2, h1) # Driver program head1 = newNode(1)head1.next = newNode(3)head1.next.next = newNode(5) # 1.3.5 LinkedList created head2 = newNode(0)head2.next = newNode(2)head2.next.next = newNode(4) # 0.2.4 LinkedList created mergedhead = merge(head1, head2) printList(mergedhead) # This code is contributed by Arnab Kundu", "e": 22226, "s": 19841, "text": null }, { "code": "// C# program to merge two sorted// linked lists in-place.using System; class GfG { public class Node { public int data; public Node next; } // Function to create newNode in a linkedlist static Node newNode(int key) { Node temp = new Node(); temp.data = key; temp.next = null; return temp; } // A utility function to print linked list static void printList(Node node) { while (node != null) { Console.Write(node.data + \" \"); node = node.next; } } // Merges two lists with headers as h1 and h2. // It assumes that h1's data is smaller than // or equal to h2's data. static Node mergeUtil(Node h1, Node h2) { // if only one node in first list // simply point its head to second list if (h1.next == null) { h1.next = h2; return h1; } // Initialize current and next pointers of // both lists Node curr1 = h1, next1 = h1.next; Node curr2 = h2, next2 = h2.next; while (next1 != null && curr2 != null) { // if curr2 lies in between curr1 and next1 // then do curr1->curr2->next1 if ((curr2.data) >= (curr1.data) && (curr2.data) <= (next1.data)) { next2 = curr2.next; curr1.next = curr2; curr2.next = next1; // now let curr1 and curr2 to point // to their immediate next pointers curr1 = curr2; curr2 = next2; } else { // if more nodes in first list if (next1.next != null) { next1 = next1.next; curr1 = curr1.next; } // else point the last node of first list // to the remaining nodes of second list else { next1.next = curr2; return h1; } } } return h1; } // Merges two given lists in-place. This function // mainly compares head nodes and calls mergeUtil() static Node merge(Node h1, Node h2) { if (h1 == null) return h2; if (h2 == null) return h1; // start with the linked list // whose head data is the least if (h1.data < h2.data) return mergeUtil(h1, h2); else return mergeUtil(h2, h1); } // Driver code public static void Main(String[] args) { Node head1 = newNode(1); head1.next = newNode(3); head1.next.next = newNode(5); // 1->3->5 LinkedList created Node head2 = newNode(0); head2.next = newNode(2); head2.next.next = newNode(4); // 0->2->4 LinkedList created Node mergedhead = merge(head1, head2); printList(mergedhead); }} /* This code contributed by PrinciRaj1992 */", "e": 25207, "s": 22226, "text": null }, { "code": "<script> // JavaScript program to merge two sorted// linked lists in-place.class Node { constructor() { this.data = 0; this.next = null; }} // Function to create newNode in a linkedlist function newNode(key) { var temp = new Node(); temp.data = key; temp.next = null; return temp; } // A utility function to print linked list function printList(node) { while (node != null) { document.write(node.data + \" \"); node = node.next; } } // Merges two lists with headers as h1 and h2. // It assumes that h1's data is smaller than // or equal to h2's data. function mergeUtil(h1, h2) { // if only one node in first list // simply point its head to second list if (h1.next == null) { h1.next = h2; return h1; } // Initialize current and next pointers of // both lists var curr1 = h1, next1 = h1.next; var curr2 = h2, next2 = h2.next; while (next1 != null && curr2 != null) { // if curr2 lies in between curr1 and next1 // then do curr1->curr2->next1 if ((curr2.data) >= (curr1.data) && (curr2.data) <= (next1.data)) { next2 = curr2.next; curr1.next = curr2; curr2.next = next1; // now let curr1 and curr2 to point // to their immediate next pointers curr1 = curr2; curr2 = next2; } else { // if more nodes in first list if (next1.next != null) { next1 = next1.next; curr1 = curr1.next; } // else point the last node of first list // to the remaining nodes of second list else { next1.next = curr2; return h1; } } } return h1; } // Merges two given lists in-place. This function // mainly compares head nodes and calls mergeUtil() function merge(h1, h2) { if (h1 == null) return h2; if (h2 == null) return h1; // start with the linked list // whose head data is the least if (h1.data < h2.data) return mergeUtil(h1, h2); else return mergeUtil(h2, h1); } // Driver code var head1 = newNode(1); head1.next = newNode(3); head1.next.next = newNode(5); // 1->3->5 LinkedList created var head2 = newNode(0); head2.next = newNode(2); head2.next.next = newNode(4); // 0->2->4 LinkedList created var mergedhead = merge(head1, head2); printList(mergedhead); // This code contributed by gauravrajput1 </script>", "e": 28086, "s": 25207, "text": null }, { "code": null, "e": 28096, "s": 28086, "text": "Output: " }, { "code": null, "e": 28109, "s": 28096, "text": "0 1 2 3 4 5 " }, { "code": null, "e": 28132, "s": 28109, "text": "Complexity Analysis: " }, { "code": null, "e": 28207, "s": 28132, "text": "Time complexity:O(n). As only one traversal of the linked lists is needed." }, { "code": null, "e": 28260, "s": 28207, "text": "Auxiliary Space:O(1). As there is no space required." }, { "code": null, "e": 28684, "s": 28260, "text": "This article is contributed by Mandula Vikitha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 28697, "s": 28684, "text": "prerna saini" }, { "code": null, "e": 28711, "s": 28697, "text": "princiraj1992" }, { "code": null, "e": 28722, "s": 28711, "text": "andrew1234" }, { "code": null, "e": 28734, "s": 28722, "text": "29AjayKumar" }, { "code": null, "e": 28745, "s": 28734, "text": "mrityunjoy" }, { "code": null, "e": 28749, "s": 28745, "text": "gp6" }, { "code": null, "e": 28764, "s": 28749, "text": "sapnasingh4991" }, { "code": null, "e": 28776, "s": 28764, "text": "umadevi9616" }, { "code": null, "e": 28790, "s": 28776, "text": "GauravRajput1" }, { "code": null, "e": 28807, "s": 28790, "text": "arorakashish0911" }, { "code": null, "e": 28822, "s": 28807, "text": "adityakumar129" }, { "code": null, "e": 28831, "s": 28822, "text": "Accolite" }, { "code": null, "e": 28838, "s": 28831, "text": "Amazon" }, { "code": null, "e": 28847, "s": 28838, "text": "Belzabar" }, { "code": null, "e": 28855, "s": 28847, "text": "Brocade" }, { "code": null, "e": 28863, "s": 28855, "text": "FactSet" }, { "code": null, "e": 28872, "s": 28863, "text": "Flipkart" }, { "code": null, "e": 28883, "s": 28872, "text": "MakeMyTrip" }, { "code": null, "e": 28893, "s": 28883, "text": "Microsoft" }, { "code": null, "e": 28906, "s": 28893, "text": "OATS Systems" }, { "code": null, "e": 28913, "s": 28906, "text": "Oracle" }, { "code": null, "e": 28921, "s": 28913, "text": "Samsung" }, { "code": null, "e": 28930, "s": 28921, "text": "Synopsys" }, { "code": null, "e": 28942, "s": 28930, "text": "Linked List" }, { "code": null, "e": 28951, "s": 28942, "text": "Flipkart" }, { "code": null, "e": 28960, "s": 28951, "text": "Accolite" }, { "code": null, "e": 28967, "s": 28960, "text": "Amazon" }, { "code": null, "e": 28977, "s": 28967, "text": "Microsoft" }, { "code": null, "e": 28985, "s": 28977, "text": "Samsung" }, { "code": null, "e": 28993, "s": 28985, "text": "FactSet" }, { "code": null, "e": 29004, "s": 28993, "text": "MakeMyTrip" }, { "code": null, "e": 29011, "s": 29004, "text": "Oracle" }, { "code": null, "e": 29019, "s": 29011, "text": "Brocade" }, { "code": null, "e": 29028, "s": 29019, "text": "Synopsys" }, { "code": null, "e": 29041, "s": 29028, "text": "OATS Systems" }, { "code": null, "e": 29050, "s": 29041, "text": "Belzabar" }, { "code": null, "e": 29062, "s": 29050, "text": "Linked List" } ]
How to make a grouped boxplot graph in matplotlib?
To make a grouped boxplot graph in matplotlib, we can take the following steps − Import matplotlib.pyplot and seaborn. Set the figure size and adjust the padding between and around the subplots. Load an example Seaborn dataset from the online repository. Make a boxplot with male and female group in a single day. To display the figure, use show() method. import seaborn as sns import matplotlib.pyplot as plt # Set the figure size plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True # Import a Seaborn dataset data = sns.load_dataset('tips') # Create a grouped boxplot sns.boxplot(x=data['day'], y=data['total_bill'], hue=data['sex']) plt.show() It will produce the following output
[ { "code": null, "e": 1143, "s": 1062, "text": "To make a grouped boxplot graph in matplotlib, we can take the following steps −" }, { "code": null, "e": 1181, "s": 1143, "text": "Import matplotlib.pyplot and seaborn." }, { "code": null, "e": 1257, "s": 1181, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1317, "s": 1257, "text": "Load an example Seaborn dataset from the online repository." }, { "code": null, "e": 1376, "s": 1317, "text": "Make a boxplot with male and female group in a single day." }, { "code": null, "e": 1418, "s": 1376, "text": "To display the figure, use show() method." }, { "code": null, "e": 1749, "s": 1418, "text": "import seaborn as sns\nimport matplotlib.pyplot as plt\n\n# Set the figure size\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\n# Import a Seaborn dataset\ndata = sns.load_dataset('tips')\n\n# Create a grouped boxplot\nsns.boxplot(x=data['day'], y=data['total_bill'], hue=data['sex'])\n\n\nplt.show()" }, { "code": null, "e": 1786, "s": 1749, "text": "It will produce the following output" } ]
DateTimeOffset.FromUnixTimeMilliseconds() Method in C# - GeeksforGeeks
28 Feb, 2019 DateTimeOffset.FromUnixTimeMilliseconds(Int64) Method is used to convert a Unix time expressed as the number of milliseconds which have elapsed since 1970-01-01T00:00:00Z to a DateTimeOffset value. Syntax: public static DateTimeOffset FromUnixTimeMilliseconds (long milliseconds); Here, it takes a Unix time, expressed as the number of milliseconds that have elapsed since 1970-01-01T00:00:00Z (January 1, 1970, at 12:00 AM UTC). For Unix times before this date, its value is negative. Return Value: This method returns a date and time value that represents the same moment in time as the Unix time. Exception: This method will give ArgumentOutOfRangeException if milliseconds is less than -62,135,596,800,000 or milliseconds is greater than 253,402,300,799,999. Below programs illustrate the use of DateTimeOffset.FromUnixTimeMilliseconds(Int64) Method: Example 1: // C# program to demonstrate the// DateTimeOffset.FromUnixTimeMilliseconds(Int64)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // Converts a Unix time expressed as // the number of milliseconds that // have elapsed since 1970-01-01T00:00:00Z // to a DateTimeOffset value. // instance using AddYears() method DateTimeOffset value = DateTimeOffset.FromUnixTimeMilliseconds(100000); // Display the time Console.WriteLine("DateTimeOffset is {0}", value); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} DateTimeOffset is 01/01/1970 00:01:40 +00:00 Example 2: For ArgumentOutOfRangeException // C# program to demonstrate the// DateTimeOffset.FromUnixTimeMilliseconds(Int64)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // Converts a Unix time expressed as the // number of milliseconds that have elapsed // since 1970-01-01T00:00:00Z to a DateTimeOffset // value instance using AddYears() method DateTimeOffset value = DateTimeOffset.FromUnixTimeMilliseconds(253502300799999); // Display the time Console.WriteLine("DateTimeOffset is {0}", value); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} Exception Thrown: System.ArgumentOutOfRangeException Reference: https://docs.microsoft.com/en-us/dotnet/api/system.datetimeoffset.fromunixtimemilliseconds?view=netframework-4.7.2 CSharp-DateTimeOffset-Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? C# | List Class C# | Inheritance Partial Classes in C# Convert String to Character Array in C# Lambda Expressions in C# Difference between Hashtable and Dictionary in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n28 Feb, 2019" }, { "code": null, "e": 24500, "s": 24302, "text": "DateTimeOffset.FromUnixTimeMilliseconds(Int64) Method is used to convert a Unix time expressed as the number of milliseconds which have elapsed since 1970-01-01T00:00:00Z to a DateTimeOffset value." }, { "code": null, "e": 24583, "s": 24500, "text": "Syntax: public static DateTimeOffset FromUnixTimeMilliseconds (long milliseconds);" }, { "code": null, "e": 24788, "s": 24583, "text": "Here, it takes a Unix time, expressed as the number of milliseconds that have elapsed since 1970-01-01T00:00:00Z (January 1, 1970, at 12:00 AM UTC). For Unix times before this date, its value is negative." }, { "code": null, "e": 24902, "s": 24788, "text": "Return Value: This method returns a date and time value that represents the same moment in time as the Unix time." }, { "code": null, "e": 25065, "s": 24902, "text": "Exception: This method will give ArgumentOutOfRangeException if milliseconds is less than -62,135,596,800,000 or milliseconds is greater than 253,402,300,799,999." }, { "code": null, "e": 25157, "s": 25065, "text": "Below programs illustrate the use of DateTimeOffset.FromUnixTimeMilliseconds(Int64) Method:" }, { "code": null, "e": 25168, "s": 25157, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// DateTimeOffset.FromUnixTimeMilliseconds(Int64)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // Converts a Unix time expressed as // the number of milliseconds that // have elapsed since 1970-01-01T00:00:00Z // to a DateTimeOffset value. // instance using AddYears() method DateTimeOffset value = DateTimeOffset.FromUnixTimeMilliseconds(100000); // Display the time Console.WriteLine(\"DateTimeOffset is {0}\", value); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 25998, "s": 25168, "text": null }, { "code": null, "e": 26044, "s": 25998, "text": "DateTimeOffset is 01/01/1970 00:01:40 +00:00\n" }, { "code": null, "e": 26087, "s": 26044, "text": "Example 2: For ArgumentOutOfRangeException" }, { "code": "// C# program to demonstrate the// DateTimeOffset.FromUnixTimeMilliseconds(Int64)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // Converts a Unix time expressed as the // number of milliseconds that have elapsed // since 1970-01-01T00:00:00Z to a DateTimeOffset // value instance using AddYears() method DateTimeOffset value = DateTimeOffset.FromUnixTimeMilliseconds(253502300799999); // Display the time Console.WriteLine(\"DateTimeOffset is {0}\", value); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 26911, "s": 26087, "text": null }, { "code": null, "e": 26965, "s": 26911, "text": "Exception Thrown: System.ArgumentOutOfRangeException\n" }, { "code": null, "e": 26976, "s": 26965, "text": "Reference:" }, { "code": null, "e": 27091, "s": 26976, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetimeoffset.fromunixtimemilliseconds?view=netframework-4.7.2" }, { "code": null, "e": 27120, "s": 27091, "text": "CSharp-DateTimeOffset-Struct" }, { "code": null, "e": 27134, "s": 27120, "text": "CSharp-method" }, { "code": null, "e": 27137, "s": 27134, "text": "C#" }, { "code": null, "e": 27235, "s": 27137, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27258, "s": 27235, "text": "Extension Method in C#" }, { "code": null, "e": 27286, "s": 27258, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27326, "s": 27286, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27369, "s": 27326, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27385, "s": 27369, "text": "C# | List Class" }, { "code": null, "e": 27402, "s": 27385, "text": "C# | Inheritance" }, { "code": null, "e": 27424, "s": 27402, "text": "Partial Classes in C#" }, { "code": null, "e": 27464, "s": 27424, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 27489, "s": 27464, "text": "Lambda Expressions in C#" } ]
CSS | var() Function - GeeksforGeeks
18 Dec, 2018 The var() function in CSS is used to insert a value for custom property. Syntax: var( custom_property, value ) Parameters: This function accepts two parameters which are listed below: custom_property: It is the required parameter. The name of custom property must start with two dashes(–). value: It is optional parameter. It is used if custom property is invalid. Below program illustrates the var() function in CSS: Program: <!-- HTML code to describes var() function in CSS --><!DOCTYPE html><html> <head> <title>var() function</title> <style> :root { --main-bg-color: Green; } /* Use of var() function */ .gfg1 { background-color: var(--main-bg-color); padding:10px; } .gfg2 { background-color: var(--main-bg-color); padding: 5px; } h1 { color:green; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>var() function</h2> <div class = "gfg1">GeeksforGeeks</div><br> <div class = "gfg2">A computer science portal for geeks</div> </body></html> Output: Supported Browsers: The browser supported by var() function are listed below: Google Chrome 49.0 Edge 15.0 Firefox 31.0 Safari 9.1 Opera 36.0 CSS-Functions CSS Web Technologies 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 update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28046, "s": 28018, "text": "\n18 Dec, 2018" }, { "code": null, "e": 28119, "s": 28046, "text": "The var() function in CSS is used to insert a value for custom property." }, { "code": null, "e": 28127, "s": 28119, "text": "Syntax:" }, { "code": null, "e": 28157, "s": 28127, "text": "var( custom_property, value )" }, { "code": null, "e": 28230, "s": 28157, "text": "Parameters: This function accepts two parameters which are listed below:" }, { "code": null, "e": 28336, "s": 28230, "text": "custom_property: It is the required parameter. The name of custom property must start with two dashes(–)." }, { "code": null, "e": 28411, "s": 28336, "text": "value: It is optional parameter. It is used if custom property is invalid." }, { "code": null, "e": 28464, "s": 28411, "text": "Below program illustrates the var() function in CSS:" }, { "code": null, "e": 28473, "s": 28464, "text": "Program:" }, { "code": "<!-- HTML code to describes var() function in CSS --><!DOCTYPE html><html> <head> <title>var() function</title> <style> :root { --main-bg-color: Green; } /* Use of var() function */ .gfg1 { background-color: var(--main-bg-color); padding:10px; } .gfg2 { background-color: var(--main-bg-color); padding: 5px; } h1 { color:green; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>var() function</h2> <div class = \"gfg1\">GeeksforGeeks</div><br> <div class = \"gfg2\">A computer science portal for geeks</div> </body></html> ", "e": 29345, "s": 28473, "text": null }, { "code": null, "e": 29353, "s": 29345, "text": "Output:" }, { "code": null, "e": 29431, "s": 29353, "text": "Supported Browsers: The browser supported by var() function are listed below:" }, { "code": null, "e": 29450, "s": 29431, "text": "Google Chrome 49.0" }, { "code": null, "e": 29460, "s": 29450, "text": "Edge 15.0" }, { "code": null, "e": 29473, "s": 29460, "text": "Firefox 31.0" }, { "code": null, "e": 29484, "s": 29473, "text": "Safari 9.1" }, { "code": null, "e": 29495, "s": 29484, "text": "Opera 36.0" }, { "code": null, "e": 29509, "s": 29495, "text": "CSS-Functions" }, { "code": null, "e": 29513, "s": 29509, "text": "CSS" }, { "code": null, "e": 29530, "s": 29513, "text": "Web Technologies" }, { "code": null, "e": 29628, "s": 29530, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29637, "s": 29628, "text": "Comments" }, { "code": null, "e": 29650, "s": 29637, "text": "Old Comments" }, { "code": null, "e": 29712, "s": 29650, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29762, "s": 29712, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 29810, "s": 29762, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 29868, "s": 29810, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 29918, "s": 29868, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 29960, "s": 29918, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29993, "s": 29960, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30036, "s": 29993, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30098, "s": 30036, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Adjusted Coefficient of Determination in R Programming - GeeksforGeeks
11 Oct, 2020 Prerequisite: Multiple Linear Regression using R A well-fitting regression model produces predicted values close to the observed data values. The mean model, which uses the mean for every predicted value, commonly would be used if there were no informative predictor variables. The fit of a proposed regression model should therefore be better than the fit of the mean model. The three most common statistical measures used to evaluate regression model fit are: Coefficient of determination (R2), Adjusted R2 Root Mean Squared Error (RMSE)Overall F-test Coefficient of determination (R2), Adjusted R2 Root Mean Squared Error (RMSE) Overall F-test So in this article let’s discuss the adjusted coefficient of determination or adjusted R2 in R programming. Much like the coefficient of the determination itself, R2adj describes the variance of the response variable y, which may be predicted on the basis of the independent feature variables, x. However, two important distinctions: R2adj takes into account the number of variables in the data set. It penalizes for data points that do not fit the regression model developed.An implication of the above statement would be that R2adj, unlike R2 does not increase continually with an increase in feature variables (due to change in its mathematical calculation) and, does not take into consideration independent variables that don’t affect the feature variable. This protects the model against overfitting. R2adj takes into account the number of variables in the data set. It penalizes for data points that do not fit the regression model developed. An implication of the above statement would be that R2adj, unlike R2 does not increase continually with an increase in feature variables (due to change in its mathematical calculation) and, does not take into consideration independent variables that don’t affect the feature variable. This protects the model against overfitting. This measure is therefore more suited for multiple regression models than R2, which works only for the simple linear regression model. where, n: number of data points k: number of variables excluding the outcome R2: coefficient of determination Input: A data set of 20 records of trees with labels height,girth and volume. Structure of the data set is given below. Model 1: This model considers height and volume to predict girth Model 2: This model considers only volume to predict girth Output: Model 1: R-squared: 0.9518, Adjusted R-squared: 0.9461 Model 2: R-squared: 0.9494, Adjusted R-squared: 0.9466 Explanation of results: Model 1 considers the label height as a variable that determines girth, which is not at all always true and hence, considers an irrelevant label in the model. The results of R-squared suggest Model 1 has a better fit, which is evidently not true. The metric adjusted R-squared, which is greater for Model 2 mitigates this anomaly. It is very easy to find out the Adjusted Coefficient of Determination in the R language. The steps to follow are: Make a data frame in R. Calculate the multiple linear regression model and save it in a new variable. The so calculated new variable’s summary has an adjusted coefficient of determination or adjusted R-squared parameter that needs to be extracted. Example: R # R program to illustrate# Adj Coefficient of determination # Creating a dataframesample_data <- data.frame(col1 = c(10, 20, 30, 40, 50), col2 = c(1, 2, 3, 2, 2), col3 = c(10, 20, 30, 20, 25)) # multiple regression model # where col1, col2 are featuressample_model <- lm(col3~col1 + col2, data = sample_data) # Extracting Adj R-squared parameter # from summary summary(sample_model)$adj.r.squared Output: [1] 0.9318182 Picked R Data-science R Machine-Learning R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? R - if statement Replace Specific Characters in String in R How to import an Excel File into R ? Time Series Analysis in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n11 Oct, 2020" }, { "code": null, "e": 25291, "s": 25242, "text": "Prerequisite: Multiple Linear Regression using R" }, { "code": null, "e": 25704, "s": 25291, "text": "A well-fitting regression model produces predicted values close to the observed data values. The mean model, which uses the mean for every predicted value, commonly would be used if there were no informative predictor variables. The fit of a proposed regression model should therefore be better than the fit of the mean model. The three most common statistical measures used to evaluate regression model fit are:" }, { "code": null, "e": 25796, "s": 25704, "text": "Coefficient of determination (R2), Adjusted R2 Root Mean Squared Error (RMSE)Overall F-test" }, { "code": null, "e": 25844, "s": 25796, "text": "Coefficient of determination (R2), Adjusted R2 " }, { "code": null, "e": 25875, "s": 25844, "text": "Root Mean Squared Error (RMSE)" }, { "code": null, "e": 25890, "s": 25875, "text": "Overall F-test" }, { "code": null, "e": 26225, "s": 25890, "text": "So in this article let’s discuss the adjusted coefficient of determination or adjusted R2 in R programming. Much like the coefficient of the determination itself, R2adj describes the variance of the response variable y, which may be predicted on the basis of the independent feature variables, x. However, two important distinctions:" }, { "code": null, "e": 26698, "s": 26225, "text": "R2adj takes into account the number of variables in the data set. It penalizes for data points that do not fit the regression model developed.An implication of the above statement would be that R2adj, unlike R2 does not increase continually with an increase in feature variables (due to change in its mathematical calculation) and, does not take into consideration independent variables that don’t affect the feature variable. This protects the model against overfitting." }, { "code": null, "e": 26842, "s": 26698, "text": "R2adj takes into account the number of variables in the data set. It penalizes for data points that do not fit the regression model developed." }, { "code": null, "e": 27172, "s": 26842, "text": "An implication of the above statement would be that R2adj, unlike R2 does not increase continually with an increase in feature variables (due to change in its mathematical calculation) and, does not take into consideration independent variables that don’t affect the feature variable. This protects the model against overfitting." }, { "code": null, "e": 27307, "s": 27172, "text": "This measure is therefore more suited for multiple regression models than R2, which works only for the simple linear regression model." }, { "code": null, "e": 27314, "s": 27307, "text": "where," }, { "code": null, "e": 27339, "s": 27314, "text": "n: number of data points" }, { "code": null, "e": 27384, "s": 27339, "text": "k: number of variables excluding the outcome" }, { "code": null, "e": 27417, "s": 27384, "text": "R2: coefficient of determination" }, { "code": null, "e": 27537, "s": 27417, "text": "Input: A data set of 20 records of trees with labels height,girth and volume. Structure of the data set is given below." }, { "code": null, "e": 27602, "s": 27537, "text": "Model 1: This model considers height and volume to predict girth" }, { "code": null, "e": 27661, "s": 27602, "text": "Model 2: This model considers only volume to predict girth" }, { "code": null, "e": 27669, "s": 27661, "text": "Output:" }, { "code": null, "e": 27792, "s": 27669, "text": "Model 1: R-squared: 0.9518, Adjusted R-squared: 0.9461 \nModel 2: R-squared: 0.9494, Adjusted R-squared: 0.9466 \n" }, { "code": null, "e": 28147, "s": 27792, "text": "Explanation of results: Model 1 considers the label height as a variable that determines girth, which is not at all always true and hence, considers an irrelevant label in the model. The results of R-squared suggest Model 1 has a better fit, which is evidently not true. The metric adjusted R-squared, which is greater for Model 2 mitigates this anomaly." }, { "code": null, "e": 28261, "s": 28147, "text": "It is very easy to find out the Adjusted Coefficient of Determination in the R language. The steps to follow are:" }, { "code": null, "e": 28285, "s": 28261, "text": "Make a data frame in R." }, { "code": null, "e": 28363, "s": 28285, "text": "Calculate the multiple linear regression model and save it in a new variable." }, { "code": null, "e": 28509, "s": 28363, "text": "The so calculated new variable’s summary has an adjusted coefficient of determination or adjusted R-squared parameter that needs to be extracted." }, { "code": null, "e": 28518, "s": 28509, "text": "Example:" }, { "code": null, "e": 28520, "s": 28518, "text": "R" }, { "code": "# R program to illustrate# Adj Coefficient of determination # Creating a dataframesample_data <- data.frame(col1 = c(10, 20, 30, 40, 50), col2 = c(1, 2, 3, 2, 2), col3 = c(10, 20, 30, 20, 25)) # multiple regression model # where col1, col2 are featuressample_model <- lm(col3~col1 + col2, data = sample_data) # Extracting Adj R-squared parameter # from summary summary(sample_model)$adj.r.squared", "e": 28989, "s": 28520, "text": null }, { "code": null, "e": 28997, "s": 28989, "text": "Output:" }, { "code": null, "e": 29012, "s": 28997, "text": "[1] 0.9318182\n" }, { "code": null, "e": 29019, "s": 29012, "text": "Picked" }, { "code": null, "e": 29034, "s": 29019, "text": "R Data-science" }, { "code": null, "e": 29053, "s": 29034, "text": "R Machine-Learning" }, { "code": null, "e": 29064, "s": 29053, "text": "R Language" }, { "code": null, "e": 29162, "s": 29064, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29214, "s": 29162, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29252, "s": 29214, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29287, "s": 29252, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29345, "s": 29287, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29394, "s": 29345, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29444, "s": 29394, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 29461, "s": 29444, "text": "R - if statement" }, { "code": null, "e": 29504, "s": 29461, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29541, "s": 29504, "text": "How to import an Excel File into R ?" } ]
Spring JdbcTemplate CRUD Example | Spring JDBC Example
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, I am going to show you how to implement Spring JdbcTemplate Example with all CRUD operations. The JdbcTemplate is a central class in Spring JDBC Framework, it is responsible for the creation of connections and releasing the resources. It is also responsible to perform the basic JDBC workflow, creating statements and executing the statements. Database : CREATE TABLE `customer` ( `custid` int(11) NOT NULL, `custname` varchar(255) DEFAULT NULL, `city` varchar(255) DEFAULT NULL, PRIMARY KEY (`custid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 Project Structure: Recommended: SpringBoot With JdbcTemplate CRUD Operations Example pom.xml <dependencies> <!-- Spring and Transactions --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring-framework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring-framework.version}</version> </dependency> <!-- Spring JDBC Support --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring-framework.version}</version> </dependency> <!-- MySQL Driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.0.5</version> </dependency> <!-- Logging with SLF4J & LogBack --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> <scope>runtime</scope> </dependency> </dependencies> Spring configuration file : spring configuration.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <bean id="db" class="com.onlinetutorialspoint.business.DemoBean"> <property name="customerDAO" ref="customerDAO" /> </bean> <bean id="customerDAO" class="com.onlinetutorialspoint.dao.CustomerDAOImpl"> <property name="jdbcTemplate" ref="jdbcTemplate" /> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <constructor-arg ref="dataSource" /> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/onlinetutorialspoint"/> <property name="username" value="otp"/> <property name="password" value="123456"/> </bean> </beans> Spring Beans : Proving CRUD services to the repository. package com.onlinetutorialspoint.business; import org.springframework.beans.factory.annotation.Autowired; import com.onlinetutorialspoint.dao.CustomerDAO; import com.onlinetutorialspoint.dto.Customer; public class DemoBean { @Autowired private CustomerDAO customerDAO; public void setCustomerDAO(CustomerDAO customerDAO) { this.customerDAO = customerDAO; } public void insertCustomer(int cid, String custName, String addr) { Customer customer = new Customer(); customer.setCustomerId(cid); customer.setCustomerName(custName); customer.setCustomerAddress(addr); int res = customerDAO.insert(customer); System.out.println(res + ": Records inserted"); } public int deleteCustomer(int customerId) { return customerDAO.deleteCustomer(customerId); } public Customer selectCustomer(int customerId) { return customerDAO.selectCustomer(customerId); } public void updateCustomer(Customer customer) { customerDAO.updateCustomer(customer); } } DAO Classes : CustomerDAO.java package com.onlinetutorialspoint.dao; import com.onlinetutorialspoint.dto.Customer; public interface CustomerDAO { Customer selectCustomer(int cistomerId); int insert(Customer c); int deleteCustomer(int customerId); void updateCustomer(Customer customer); } CustomerDAOImpl.java Containing all CRUD operation implementations. package com.onlinetutorialspoint.dao; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.ResultSetExtractor; import com.onlinetutorialspoint.dto.Customer; public class CustomerDAOImpl implements CustomerDAO { private JdbcTemplate jdbcTemplate; public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public int insert(Customer c) { int custId = c.getCustomerId(); String name = c.getCustomerName(); String address = c.getCustomerAddress(); int rows = jdbcTemplate.update("insert into customer values(?,?,?)", custId, name, address); return rows; } @Override public int deleteCustomer(int customerId) { String query = "DELETE from customer where custid=?"; return jdbcTemplate.update(query, new Object[] { Integer.valueOf(customerId) }); } @Override public void updateCustomer(Customer customer) { String query = "UPDATE customer SET custname=?,city=? WHERE custid=?"; jdbcTemplate.update(query, new Object[] { customer.getCustomerName(), customer.getCustomerAddress(), Integer.valueOf(customer.getCustomerId()) }); } @Override public Customer selectCustomer(int customerId) { final Customer customer = new Customer(); String quer = "SELECT * FROM customer WHERE custid='" + customerId + "'"; return (Customer) jdbcTemplate.query(quer, new ResultSetExtractor & amp; amp; amp; lt; Customer & amp; amp; amp; gt; () { public Customer extractData(ResultSet rs) throws SQLException, DataAccessException { if (rs.next()) { customer.setCustomerId(rs.getInt(1)); customer.setCustomerName(rs.getString(2)); customer.setCustomerAddress(rs.getString(3)); } return customer; } }); } } Customer.java package com.onlinetutorialspoint.dto; public class Customer { private int customerId; private String customerName; private String customerAddress; public int getCustomerId() { return customerId; } public void setCustomerId(int customerId) { this.customerId = customerId; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public String getCustomerAddress() { return customerAddress; } public void setCustomerAddress(String customerAddress) { this.customerAddress = customerAddress; } } Done! Let’s test our Spring JdbcTemplate example: Main.java import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.onlinetutorialspoint.business.DemoBean; import com.onlinetutorialspoint.dto.Customer; public class Main { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml"); DemoBean demo = (DemoBean) context.getBean("db"); // Inserting Data into customer table.. demo.insertCustomer(1, "chandra", "Hyd"); // Selecting data from customer table Customer customer = demo.selectCustomer(1); System.out.println("Inserted Customer Name : " + customer.getCustomerName()); // updating customer data in customer table.. Customer customer2 = new Customer(); customer2.setCustomerId(1); customer2.setCustomerAddress("Vizag"); customer2.setCustomerName("shekhar"); demo.updateCustomer(customer2); // Deleting customer data from customer table.. int count = demo.deleteCustomer(1); < br / > System.out.println(count > 0 ? "Deleted Successfully" : "No Records found"); } } Create MySQL table JDBCTemplate Happy Learning 🙂 Spring JdbcTemplate CRUD Example File size: 21 KB Downloads: 3264 Spring Boot JdbcTemplate CRUD Operations Mysql Types of Spring Bean Scopes Example How to enable Swagger in Spring Boot Application Spring Boot H2 Database + JDBC Template Example Spring Boot Redis Data Example CRUD Operations Spring boot exception handling rest service (CRUD) operations Spring Boot PostgreSQL DB CRUD Example @Qualifier annotation example in Spring Spring Java Configuration Example Spring Collection Dependency List Example Spring Boot Actuator Database Health Check Hibernate Named Query with Example Spring Bean Autowire By Constructor Example Spring Collection Map Dependency Example Spring Bean Autowire ByName Example Spring Boot JdbcTemplate CRUD Operations Mysql Types of Spring Bean Scopes Example How to enable Swagger in Spring Boot Application Spring Boot H2 Database + JDBC Template Example Spring Boot Redis Data Example CRUD Operations Spring boot exception handling rest service (CRUD) operations Spring Boot PostgreSQL DB CRUD Example @Qualifier annotation example in Spring Spring Java Configuration Example Spring Collection Dependency List Example Spring Boot Actuator Database Health Check Hibernate Named Query with Example Spring Bean Autowire By Constructor Example Spring Collection Map Dependency Example Spring Bean Autowire ByName Example Yashwant December 27, 2016 at 2:40 pm - Reply Nice tutorial 🙂 DKM February 17, 2017 at 9:14 pm - Reply Good one for beginners. Simple. Manoj Kumar Nirala April 12, 2017 at 9:27 am - Reply Hi Chandrashekhar, a really good example to start with. Could you please post an example with Spring mvc, Apache Tiles, JdbcTemplate with CRUD operations ? Thanks kavita October 5, 2017 at 8:42 am - Reply Hi, nice example, but where are the view file, could please send me the code on this email id : kavita11.kavita22@gmail.com Yashwant December 27, 2016 at 2:40 pm - Reply Nice tutorial 🙂 Nice tutorial 🙂 DKM February 17, 2017 at 9:14 pm - Reply Good one for beginners. Simple. Good one for beginners. Simple. Manoj Kumar Nirala April 12, 2017 at 9:27 am - Reply Hi Chandrashekhar, a really good example to start with. Could you please post an example with Spring mvc, Apache Tiles, JdbcTemplate with CRUD operations ? Thanks Hi Chandrashekhar, a really good example to start with. Could you please post an example with Spring mvc, Apache Tiles, JdbcTemplate with CRUD operations ? Thanks kavita October 5, 2017 at 8:42 am - Reply Hi, nice example, but where are the view file, could please send me the code on this email id : kavita11.kavita22@gmail.com Hi, nice example, but where are the view file, could please send me the code on this email id : kavita11.kavita22@gmail.com
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 510, "s": 398, "text": "In this tutorial, I am going to show you how to implement Spring JdbcTemplate Example with all CRUD operations." }, { "code": null, "e": 760, "s": 510, "text": "The JdbcTemplate is a central class in Spring JDBC Framework, it is responsible for the creation of connections and releasing the resources. It is also responsible to perform the basic JDBC workflow, creating statements and executing the statements." }, { "code": null, "e": 771, "s": 760, "text": "Database :" }, { "code": null, "e": 958, "s": 771, "text": "CREATE TABLE `customer` (\n`custid` int(11) NOT NULL,\n`custname` varchar(255) DEFAULT NULL,\n`city` varchar(255) DEFAULT NULL,\nPRIMARY KEY (`custid`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1" }, { "code": null, "e": 977, "s": 958, "text": "Project Structure:" }, { "code": null, "e": 1043, "s": 977, "text": "Recommended: SpringBoot With JdbcTemplate CRUD Operations Example" }, { "code": null, "e": 1051, "s": 1043, "text": "pom.xml" }, { "code": null, "e": 2480, "s": 1051, "text": "<dependencies>\n <!-- Spring and Transactions -->\n <dependency>\n <groupId>org.springframework</groupId>\n <artifactId>spring-context</artifactId>\n <version>${spring-framework.version}</version>\n </dependency>\n <dependency>\n <groupId>org.springframework</groupId>\n <artifactId>spring-tx</artifactId>\n <version>${spring-framework.version}</version>\n </dependency>\n \n <!-- Spring JDBC Support -->\n <dependency>\n <groupId>org.springframework</groupId>\n <artifactId>spring-jdbc</artifactId>\n <version>${spring-framework.version}</version>\n </dependency>\n \n <!-- MySQL Driver -->\n <dependency>\n <groupId>mysql</groupId>\n <artifactId>mysql-connector-java</artifactId>\n <version>5.0.5</version>\n </dependency>\n \n <!-- Logging with SLF4J & LogBack -->\n <dependency>\n <groupId>org.slf4j</groupId>\n <artifactId>slf4j-api</artifactId>\n <version>${slf4j.version}</version>\n <scope>compile</scope>\n </dependency>\n <dependency>\n <groupId>ch.qos.logback</groupId>\n <artifactId>logback-classic</artifactId>\n <version>${logback.version}</version>\n <scope>runtime</scope>\n </dependency>\n </dependencies>" }, { "code": null, "e": 2508, "s": 2480, "text": "Spring configuration file :" }, { "code": null, "e": 2533, "s": 2508, "text": "spring configuration.xml" }, { "code": null, "e": 3997, "s": 2533, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:context=\"http://www.springframework.org/schema/context\"\n xmlns:jdbc=\"http://www.springframework.org/schema/jdbc\"\n xsi:schemaLocation=\"http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd\n http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd\n http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd\">\n <bean id=\"db\" class=\"com.onlinetutorialspoint.business.DemoBean\">\n <property name=\"customerDAO\" ref=\"customerDAO\" />\n </bean>\n <bean id=\"customerDAO\" class=\"com.onlinetutorialspoint.dao.CustomerDAOImpl\">\n <property name=\"jdbcTemplate\" ref=\"jdbcTemplate\" />\n </bean>\n <bean id=\"jdbcTemplate\" class=\"org.springframework.jdbc.core.JdbcTemplate\">\n <constructor-arg ref=\"dataSource\" />\n </bean>\n <bean id=\"dataSource\" class=\"org.springframework.jdbc.datasource.DriverManagerDataSource\"> \n <property name=\"driverClassName\" value=\"com.mysql.jdbc.Driver\"/>\n <property name=\"url\" value=\"jdbc:mysql://localhost:3306/onlinetutorialspoint\"/>\n <property name=\"username\" value=\"otp\"/>\n <property name=\"password\" value=\"123456\"/>\n </bean>\n</beans>" }, { "code": null, "e": 4012, "s": 3997, "text": "Spring Beans :" }, { "code": null, "e": 4053, "s": 4012, "text": "Proving CRUD services to the repository." }, { "code": null, "e": 5122, "s": 4053, "text": "package com.onlinetutorialspoint.business;\n\nimport org.springframework.beans.factory.annotation.Autowired;\n\nimport com.onlinetutorialspoint.dao.CustomerDAO;\nimport com.onlinetutorialspoint.dto.Customer;\n\npublic class DemoBean {\n @Autowired\n private CustomerDAO customerDAO;\n\n public void setCustomerDAO(CustomerDAO customerDAO) {\n this.customerDAO = customerDAO;\n }\n\n public void insertCustomer(int cid, String custName, String addr) {\n Customer customer = new Customer();\n customer.setCustomerId(cid);\n customer.setCustomerName(custName);\n customer.setCustomerAddress(addr);\n int res = customerDAO.insert(customer);\n System.out.println(res + \": Records inserted\");\n }\n\n public int deleteCustomer(int customerId) {\n return customerDAO.deleteCustomer(customerId);\n }\n\n public Customer selectCustomer(int customerId) {\n return customerDAO.selectCustomer(customerId);\n }\n\n public void updateCustomer(Customer customer) {\n customerDAO.updateCustomer(customer);\n }\n\n}" }, { "code": null, "e": 5136, "s": 5122, "text": "DAO Classes :" }, { "code": null, "e": 5153, "s": 5136, "text": "CustomerDAO.java" }, { "code": null, "e": 5432, "s": 5153, "text": "package com.onlinetutorialspoint.dao;\n\nimport com.onlinetutorialspoint.dto.Customer;\n\npublic interface CustomerDAO {\n Customer selectCustomer(int cistomerId);\n\n int insert(Customer c);\n\n int deleteCustomer(int customerId);\n\n void updateCustomer(Customer customer);\n}" }, { "code": null, "e": 5453, "s": 5432, "text": "CustomerDAOImpl.java" }, { "code": null, "e": 5500, "s": 5453, "text": "Containing all CRUD operation implementations." }, { "code": null, "e": 7771, "s": 5500, "text": "package com.onlinetutorialspoint.dao;\n\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\n\nimport org.springframework.dao.DataAccessException;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.jdbc.core.ResultSetExtractor;\n\nimport com.onlinetutorialspoint.dto.Customer;\n\npublic class CustomerDAOImpl implements CustomerDAO {\n\n private JdbcTemplate jdbcTemplate;\n\n public JdbcTemplate getJdbcTemplate() {\n return jdbcTemplate;\n }\n\n public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {\n this.jdbcTemplate = jdbcTemplate;\n }\n\n @Override\n public int insert(Customer c) {\n int custId = c.getCustomerId();\n String name = c.getCustomerName();\n String address = c.getCustomerAddress();\n int rows = jdbcTemplate.update(\"insert into customer values(?,?,?)\", custId, name, address);\n\n return rows;\n }\n\n @Override\n public int deleteCustomer(int customerId) {\n String query = \"DELETE from customer where custid=?\";\n return jdbcTemplate.update(query, new Object[] {\n Integer.valueOf(customerId)\n });\n\n }\n\n @Override\n public void updateCustomer(Customer customer) {\n String query = \"UPDATE customer SET custname=?,city=? WHERE custid=?\";\n jdbcTemplate.update(query,\n new Object[] {\n customer.getCustomerName(), customer.getCustomerAddress(), Integer.valueOf(customer.getCustomerId())\n });\n\n }\n\n @Override\n public Customer selectCustomer(int customerId) {\n final Customer customer = new Customer();\n String quer = \"SELECT * FROM customer WHERE custid='\" + customerId + \"'\";\n return (Customer) jdbcTemplate.query(quer, new ResultSetExtractor & amp; amp; amp; lt; Customer & amp; amp; amp; gt;\n () {\n public Customer extractData(ResultSet rs) throws SQLException, DataAccessException {\n if (rs.next()) {\n customer.setCustomerId(rs.getInt(1));\n customer.setCustomerName(rs.getString(2));\n customer.setCustomerAddress(rs.getString(3));\n }\n return customer;\n }\n });\n }\n\n}" }, { "code": null, "e": 7785, "s": 7771, "text": "Customer.java" }, { "code": null, "e": 8476, "s": 7785, "text": "package com.onlinetutorialspoint.dto;\n\npublic class Customer {\n private int customerId;\n private String customerName;\n private String customerAddress;\n public int getCustomerId() {\n return customerId;\n }\n public void setCustomerId(int customerId) {\n this.customerId = customerId;\n }\n public String getCustomerName() {\n return customerName;\n }\n public void setCustomerName(String customerName) {\n this.customerName = customerName;\n }\n public String getCustomerAddress() {\n return customerAddress;\n }\n public void setCustomerAddress(String customerAddress) {\n this.customerAddress = customerAddress;\n }\n\n}" }, { "code": null, "e": 8482, "s": 8476, "text": "Done!" }, { "code": null, "e": 8526, "s": 8482, "text": "Let’s test our Spring JdbcTemplate example:" }, { "code": null, "e": 8536, "s": 8526, "text": "Main.java" }, { "code": null, "e": 9753, "s": 8536, "text": "import org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\nimport com.onlinetutorialspoint.business.DemoBean;\nimport com.onlinetutorialspoint.dto.Customer;\n\npublic class Main {\n\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"applicationcontext.xml\");\n DemoBean demo = (DemoBean) context.getBean(\"db\");\n\n // Inserting Data into customer table..\n\n demo.insertCustomer(1, \"chandra\", \"Hyd\");\n\n // Selecting data from customer table\n Customer customer = demo.selectCustomer(1);\n System.out.println(\"Inserted Customer Name : \" + customer.getCustomerName());\n\n // updating customer data in customer table..\n Customer customer2 = new Customer();\n customer2.setCustomerId(1);\n customer2.setCustomerAddress(\"Vizag\");\n customer2.setCustomerName(\"shekhar\");\n\n demo.updateCustomer(customer2);\n\n // Deleting customer data from customer table..\n\n int count = demo.deleteCustomer(1); < br / >\n System.out.println(count > 0 ? \"Deleted Successfully\" : \"No Records found\");\n\n }\n\n}" }, { "code": null, "e": 9772, "s": 9753, "text": "Create MySQL table" }, { "code": null, "e": 9785, "s": 9772, "text": "JDBCTemplate" }, { "code": null, "e": 9802, "s": 9785, "text": "Happy Learning 🙂" }, { "code": null, "e": 9872, "s": 9802, "text": "\n\nSpring JdbcTemplate CRUD Example\n\nFile size: 21 KB\nDownloads: 3264\n" }, { "code": null, "e": 10517, "s": 9872, "text": "\nSpring Boot JdbcTemplate CRUD Operations Mysql\nTypes of Spring Bean Scopes Example\nHow to enable Swagger in Spring Boot Application\nSpring Boot H2 Database + JDBC Template Example\nSpring Boot Redis Data Example CRUD Operations\nSpring boot exception handling rest service (CRUD) operations\nSpring Boot PostgreSQL DB CRUD Example\n@Qualifier annotation example in Spring\nSpring Java Configuration Example\nSpring Collection Dependency List Example\nSpring Boot Actuator Database Health Check\nHibernate Named Query with Example\nSpring Bean Autowire By Constructor Example\nSpring Collection Map Dependency Example\nSpring Bean Autowire ByName Example\n" }, { "code": null, "e": 10564, "s": 10517, "text": "Spring Boot JdbcTemplate CRUD Operations Mysql" }, { "code": null, "e": 10600, "s": 10564, "text": "Types of Spring Bean Scopes Example" }, { "code": null, "e": 10649, "s": 10600, "text": "How to enable Swagger in Spring Boot Application" }, { "code": null, "e": 10697, "s": 10649, "text": "Spring Boot H2 Database + JDBC Template Example" }, { "code": null, "e": 10744, "s": 10697, "text": "Spring Boot Redis Data Example CRUD Operations" }, { "code": null, "e": 10806, "s": 10744, "text": "Spring boot exception handling rest service (CRUD) operations" }, { "code": null, "e": 10845, "s": 10806, "text": "Spring Boot PostgreSQL DB CRUD Example" }, { "code": null, "e": 10885, "s": 10845, "text": "@Qualifier annotation example in Spring" }, { "code": null, "e": 10919, "s": 10885, "text": "Spring Java Configuration Example" }, { "code": null, "e": 10961, "s": 10919, "text": "Spring Collection Dependency List Example" }, { "code": null, "e": 11004, "s": 10961, "text": "Spring Boot Actuator Database Health Check" }, { "code": null, "e": 11039, "s": 11004, "text": "Hibernate Named Query with Example" }, { "code": null, "e": 11083, "s": 11039, "text": "Spring Bean Autowire By Constructor Example" }, { "code": null, "e": 11124, "s": 11083, "text": "Spring Collection Map Dependency Example" }, { "code": null, "e": 11160, "s": 11124, "text": "Spring Bean Autowire ByName Example" }, { "code": null, "e": 11723, "s": 11160, "text": "\n\n\n\n\n\nYashwant\nDecember 27, 2016 at 2:40 pm - Reply \n\nNice tutorial 🙂\n\n\n\n\n\n\n\n\n\nDKM\nFebruary 17, 2017 at 9:14 pm - Reply \n\nGood one for beginners. Simple.\n\n\n\n\n\n\n\n\n\nManoj Kumar Nirala\nApril 12, 2017 at 9:27 am - Reply \n\nHi Chandrashekhar, a really good example to start with. Could you please post an example with Spring mvc, Apache Tiles, JdbcTemplate with CRUD operations ?\nThanks\n\n\n\n\n\n\n\n\n\nkavita\nOctober 5, 2017 at 8:42 am - Reply \n\nHi,\nnice example, but where are the view file,\ncould please send me the code on this email id : kavita11.kavita22@gmail.com\n\n\n\n\n" }, { "code": null, "e": 11796, "s": 11723, "text": "\n\n\n\n\nYashwant\nDecember 27, 2016 at 2:40 pm - Reply \n\nNice tutorial 🙂\n\n\n\n" }, { "code": null, "e": 11812, "s": 11796, "text": "Nice tutorial 🙂" }, { "code": null, "e": 11896, "s": 11812, "text": "\n\n\n\n\nDKM\nFebruary 17, 2017 at 9:14 pm - Reply \n\nGood one for beginners. Simple.\n\n\n\n" }, { "code": null, "e": 11928, "s": 11896, "text": "Good one for beginners. Simple." }, { "code": null, "e": 12155, "s": 11928, "text": "\n\n\n\n\nManoj Kumar Nirala\nApril 12, 2017 at 9:27 am - Reply \n\nHi Chandrashekhar, a really good example to start with. Could you please post an example with Spring mvc, Apache Tiles, JdbcTemplate with CRUD operations ?\nThanks\n\n\n\n" }, { "code": null, "e": 12311, "s": 12155, "text": "Hi Chandrashekhar, a really good example to start with. Could you please post an example with Spring mvc, Apache Tiles, JdbcTemplate with CRUD operations ?" }, { "code": null, "e": 12318, "s": 12311, "text": "Thanks" }, { "code": null, "e": 12495, "s": 12318, "text": "\n\n\n\n\nkavita\nOctober 5, 2017 at 8:42 am - Reply \n\nHi,\nnice example, but where are the view file,\ncould please send me the code on this email id : kavita11.kavita22@gmail.com\n\n\n\n" } ]
C++ Program to Decode a Message Encoded Using Playfair Cipher
In this scheme, pairs of letters are encrypted, instead of single letters as in the case of simple substitution cipher. In playfair cipher, initially a key table is created. The key table is a 5×5 grid of alphabets that acts as the key for encrypting the plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet (usually J) is omitted from the table as we need only 25 alphabets instead of 26. If the plaintext contains J, then it is replaced by I. The sender and the receiver deicide on a particular key, say ‘tutorials’. In a key table, the first characters (going left to right) in the table is the phrase, excluding the duplicate letters. The rest of the table will be filled with the remaining letters of the alphabet, in natural order. The key table works out to be − First, a plaintext message is split into pairs of two letters (digraphs). If there is an odd number of letters, a Z is added to the last letter. Let us consider that, we want to encrypt the message “hide money”. It will be written as − HI DE MO NE YZ The rules of encryption are − If both the letters are in the same column, take the letter below each one (going back to the top if at the bottom)‘H’ and ‘I’ are in same column, hence take letter below them to replace. HI → QC If both the letters are in the same column, take the letter below each one (going back to the top if at the bottom)‘H’ and ‘I’ are in same column, hence take letter below them to replace. HI → QC If both letters are in the same row, take the letter to the right of each one (going back to the left if at the farthest right)‘D’ and ‘E’ are in same row, hence take letter to the right of them to replace. DE → EF If both letters are in the same row, take the letter to the right of each one (going back to the left if at the farthest right)‘D’ and ‘E’ are in same row, hence take letter to the right of them to replace. DE → EF If neither of the preceding two rules are true, form a rectangle with the two letters and take the letters on the horizontal opposite corner of the rectangle. If neither of the preceding two rules are true, form a rectangle with the two letters and take the letters on the horizontal opposite corner of the rectangle. Using these rules, the result of the encryption of ‘hide money’ with the key of ‘tutorials’ would be − QC EF NU MF ZV Decrypting the Playfair cipher is as simple as doing the same process in reverse. Receiver has the same key and can create the same key table, and then decrypt any messages made using that key. Here is a C++ program is given to encode a message using Playfair Cipher. Begin Function void play( int dir ) For it = msg.begin() to it != msg.end() If ( getPos( *it++, j, k ) ) If ( getPos( *it, p, q) ) If ( j == p ) nmsg+= getChar( j, k + dir ) nmsg += getChar( p, q + dir ) else if( k == q ) nmsg += getChar( j + dir, k ) nmsg += getChar( p + dir, q ) else nmsg += getChar( p, k ) nmsg += getChar( j, q ) done done done msg = nmsg done End #include <iostream> #include <string> using namespace std; class playfair { public: string msg; char n[5][5]; void play( string k, string t, bool m, bool e ) { createEncoder( k, m ); getText( t, m, e ); if( e ) play( 1 ); else play( -1 ); print(); } private: void play( int dir ) { int j,k,p,q; string nmsg; for( string::const_iterator it = msg.begin(); it != msg.end(); it++ ) { if( getPos( *it++, j, k ) ) if( getPos( *it, p, q) ) { //for same row if( j == p ) { nmsg+= getChar( j, k + dir ); nmsg += getChar( p, q + dir ); } //for same column else if( k == q ) { nmsg += getChar( j + dir, k ); nmsg += getChar( p + dir, q ); } else { nmsg += getChar( p, k ); nmsg += getChar( j, q ); } } } msg = nmsg; } void print() //print the solution { cout << "\n\n Solution:" << endl; string::iterator it = msg.begin(); int count = 0; while( it != msg.end() ) { cout << *it; it++; cout << *it << " "; it++; if( ++count >= 26 ) cout << endl; count = 0; } cout << endl << endl; } char getChar( int a, int b ) { //get the characters return n[ (b + 5) % 5 ][ (a + 5) % 5 ]; } bool getPos( char l, int &c, int &d ) { //get the position for( int y = 0; y < 5; y++ ) for( int x = 0; x < 5; x++ ) if( n[y][x] == l ) { c = x; d= y; return true; } return false; } void getText( string t, bool m, bool e ) { //get the original message for( string::iterator it = t.begin(); it != t.end(); it++ ) { //to choose J = I or no Q in the alphabet. *it = toupper( *it ); if( *it < 65 || *it > 90 ) continue; if( *it == 'J' && m ) *it = 'I'; else if( *it == 'Q' && !m ) continue; msg += *it; } if( e ) { string nmsg = ""; size_t len = msg.length(); for( size_t x = 0; x < len; x += 2 ) { nmsg += msg[x]; if( x + 1 < len ) { if( msg[x] == msg[x + 1] ) nmsg += 'X'; nmsg += msg[x + 1]; } } msg = nmsg; } if( msg.length() & 1 ) msg += 'X'; } void createEncoder( string key, bool m ) { //creation of the key table if( key.length() < 1 ) key= "KEYWORD"; key += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string s= ""; for( string::iterator it = key.begin(); it != key.end(); it++ ) { *it = toupper( *it ); if( *it < 65 || *it > 90 ) continue; if( ( *it == 'J' && m ) || ( *it == 'Q' && !m ) ) continue; if( s.find( *it ) == -1 ) s += *it; } copy( s.begin(), s.end(), &n[0][0] ); } }; int main( int argc, char* argv[] ) { string k, i, msg; bool m, c; cout << "Encrpty or Decypt? "; getline( cin, i ); c = ( i[0] == 'e' || i[0] == 'E' ); cout << "Enter a key: "; getline( cin, k); cout << "I <-> J (Y/N): "; getline( cin, i ); m = ( i[0] == 'y' || i[0] == 'Y' ); cout << "Enter the message: "; getline( cin, msg ); playfair pf; pf.play( k, msg,m, c ); return system( "pause" ); } Encrpty or Decypt? d Enter a key: players I <-> J (Y/N): y Enter the message: OK GC GC MZ MQ CF YA RL QH OM Solution: TH IS IS TU TO RI AL SP OI NT
[ { "code": null, "e": 1182, "s": 1062, "text": "In this scheme, pairs of letters are encrypted, instead of single letters as in the case of simple substitution cipher." }, { "code": null, "e": 1536, "s": 1182, "text": "In playfair cipher, initially a key table is created. The key table is a 5×5 grid of alphabets that acts as the key for encrypting the plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet (usually J) is omitted from the table as we need only 25 alphabets instead of 26. If the plaintext contains J, then it is replaced by I." }, { "code": null, "e": 1861, "s": 1536, "text": "The sender and the receiver deicide on a particular key, say ‘tutorials’. In a key table, the first characters (going left to right) in the table is the phrase, excluding the duplicate letters. The rest of the table will be filled with the remaining letters of the alphabet, in natural order. The key table works out to be −" }, { "code": null, "e": 2097, "s": 1861, "text": "First, a plaintext message is split into pairs of two letters (digraphs). If there is an odd number of letters, a Z is added to the last letter. Let us consider that, we want to encrypt the message “hide money”. It will be written as −" }, { "code": null, "e": 2112, "s": 2097, "text": "HI DE MO NE YZ" }, { "code": null, "e": 2142, "s": 2112, "text": "The rules of encryption are −" }, { "code": null, "e": 2338, "s": 2142, "text": "If both the letters are in the same column, take the letter below each one (going back to the top if at the bottom)‘H’ and ‘I’ are in same column, hence take letter below them to replace. HI → QC" }, { "code": null, "e": 2534, "s": 2338, "text": "If both the letters are in the same column, take the letter below each one (going back to the top if at the bottom)‘H’ and ‘I’ are in same column, hence take letter below them to replace. HI → QC" }, { "code": null, "e": 2749, "s": 2534, "text": "If both letters are in the same row, take the letter to the right of each one (going back to the left if at the farthest right)‘D’ and ‘E’ are in same row, hence take letter to the right of them to replace. DE → EF" }, { "code": null, "e": 2964, "s": 2749, "text": "If both letters are in the same row, take the letter to the right of each one (going back to the left if at the farthest right)‘D’ and ‘E’ are in same row, hence take letter to the right of them to replace. DE → EF" }, { "code": null, "e": 3123, "s": 2964, "text": "If neither of the preceding two rules are true, form a rectangle with the two letters and take the letters on the horizontal opposite corner of the rectangle." }, { "code": null, "e": 3282, "s": 3123, "text": "If neither of the preceding two rules are true, form a rectangle with the two letters and take the letters on the horizontal opposite corner of the rectangle." }, { "code": null, "e": 3385, "s": 3282, "text": "Using these rules, the result of the encryption of ‘hide money’ with the key of ‘tutorials’ would be −" }, { "code": null, "e": 3400, "s": 3385, "text": "QC EF NU MF ZV" }, { "code": null, "e": 3594, "s": 3400, "text": "Decrypting the Playfair cipher is as simple as doing the same process in reverse. Receiver has the same key and can create the same key table, and then decrypt any messages made using that key." }, { "code": null, "e": 3668, "s": 3594, "text": "Here is a C++ program is given to encode a message using Playfair Cipher." }, { "code": null, "e": 4167, "s": 3668, "text": "Begin\nFunction void play( int dir )\nFor it = msg.begin() to it != msg.end()\n If ( getPos( *it++, j, k ) )\n If ( getPos( *it, p, q) )\n If ( j == p )\n nmsg+= getChar( j, k + dir )\n nmsg += getChar( p, q + dir )\n else if( k == q )\n nmsg += getChar( j + dir, k )\n nmsg += getChar( p + dir, q )\n else\n nmsg += getChar( p, k )\n nmsg += getChar( j, q )\n done\n done\n done\n msg = nmsg\ndone\nEnd" }, { "code": null, "e": 7701, "s": 4167, "text": "#include <iostream>\n#include <string>\nusing namespace std;\nclass playfair {\n public:\n string msg; char n[5][5];\n void play( string k, string t, bool m, bool e ) {\n createEncoder( k, m );\n getText( t, m, e );\n if( e )\n play( 1 );\n else\n play( -1 );\n print();\n }\n private:\n void play( int dir ) {\n int j,k,p,q;\n string nmsg;\n for( string::const_iterator it = msg.begin(); it != msg.end(); it++ ) {\n if( getPos( *it++, j, k ) )\n if( getPos( *it, p, q) ) {\n //for same row\n if( j == p ) {\n nmsg+= getChar( j, k + dir );\n nmsg += getChar( p, q + dir );\n }\n //for same column\n else if( k == q ) {\n nmsg += getChar( j + dir, k );\n nmsg += getChar( p + dir, q );\n } else {\n nmsg += getChar( p, k );\n nmsg += getChar( j, q );\n }\n }\n }\n msg = nmsg;\n }\n void print() //print the solution {\n cout << \"\\n\\n Solution:\" << endl;\n string::iterator it = msg.begin(); int count = 0;\n while( it != msg.end() ) {\n cout << *it;\n it++;\n cout << *it << \" \";\n it++;\n if( ++count >= 26 )\n cout << endl;\n count = 0;\n }\n cout << endl << endl;\n }\n char getChar( int a, int b ) { //get the characters\n return n[ (b + 5) % 5 ][ (a + 5) % 5 ];\n }\n bool getPos( char l, int &c, int &d ) { //get the position\n for( int y = 0; y < 5; y++ )\n for( int x = 0; x < 5; x++ )\n if( n[y][x] == l ) {\n c = x;\n d= y;\n return true;\n }\n return false;\n }\n void getText( string t, bool m, bool e ) { //get the original message\n for( string::iterator it = t.begin(); it != t.end(); it++ ) {\n //to choose J = I or no Q in the alphabet.\n *it = toupper( *it );\n if( *it < 65 || *it > 90 )\n continue;\n if( *it == 'J' && m )\n *it = 'I';\n else if( *it == 'Q' && !m )\n continue;\n msg += *it;\n } if( e ) {\n string nmsg = \"\"; size_t len = msg.length();\n for( size_t x = 0; x < len; x += 2 ) {\n nmsg += msg[x];\n if( x + 1 < len ) {\n if( msg[x] == msg[x + 1] ) nmsg += 'X';\n nmsg += msg[x + 1];\n }\n }\n msg = nmsg;\n }\n if( msg.length() & 1 )\n msg += 'X';\n }\n void createEncoder( string key, bool m ) { //creation of the key table\n if( key.length() < 1 )\n key= \"KEYWORD\";\n key += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n string s= \"\";\n for( string::iterator it = key.begin(); it != key.end(); it++ ) {\n *it = toupper( *it );\n if( *it < 65 || *it > 90 )\n continue;\n if( ( *it == 'J' && m ) || ( *it == 'Q' && !m ) )\n continue;\n if( s.find( *it ) == -1 )\n s += *it;\n }\n copy( s.begin(), s.end(), &n[0][0] );\n }\n};\nint main( int argc, char* argv[] ) {\n string k, i, msg;\n bool m, c;\n cout << \"Encrpty or Decypt? \";\n getline( cin, i );\n c = ( i[0] == 'e' || i[0] == 'E' );\n cout << \"Enter a key: \";\n getline( cin, k);\n cout << \"I <-> J (Y/N): \";\n getline( cin, i );\n m = ( i[0] == 'y' || i[0] == 'Y' );\n cout << \"Enter the message: \";\n getline( cin, msg );\n playfair pf;\n pf.play( k, msg,m, c );\n return system( \"pause\" );\n}" }, { "code": null, "e": 7850, "s": 7701, "text": "Encrpty or Decypt? d\nEnter a key: players\nI <-> J (Y/N): y\nEnter the message: OK GC GC MZ MQ CF YA RL QH OM\n\nSolution:\nTH IS IS TU TO RI AL SP OI NT" } ]
Difference between Method Overriding and Method Hiding in C#
19 Mar, 2019 Method Overriding is a technique that allows the invoking of functions from another class (base class) in the derived class. Creating a method in the derived class with the same signature as a method in the base class is called Method Overriding.In simple words, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature and the same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class. Example: // C# program to illustrate the // Method overriding conceptusing System; // Base classclass My_Parent { // virtual method public virtual void display() { Console.WriteLine("My new parent class.. !"); }} // Derived classclass My_Child : My_Parent { // Here display method is overridden public override void display() { Console.WriteLine("My new child class.. !"); }} class GFG { // Main Method public static void Main() { My_Parent obj; // Creating object of the base class obj = new My_Parent(); // Invoking method of the base class obj.display(); // Creating object of the derived class obj = new My_Child(); // Invoking method of derived class obj.display(); }} Output: My new parent class.. ! My new child class.. ! In Method Hiding, you can hide the implementation of the methods of a base class from the derived class using the new keyword. Or in other words, in method hiding, you can redefine the method of the base class in the derived class by using the new keyword. Example: // C# program to illustrate the// concept of method hidingusing System; // Base Classpublic class My_Parent { public void show() { Console.WriteLine("This is my parent class."); }} // Derived Classpublic class My_Child : My_Parent { // Hide the method of base class // Using new keyword public new void show() { Console.WriteLine("This is my child class."); }} public class GFG { // Main method static public void Main() { // Creating the object of // the derived class My_Child obj = new My_Child(); // Access the method of derived class obj.show(); }} Output: This is my child class. CSharp-Inheritance CSharp-OOP C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n19 Mar, 2019" }, { "code": null, "e": 728, "s": 53, "text": "Method Overriding is a technique that allows the invoking of functions from another class (base class) in the derived class. Creating a method in the derived class with the same signature as a method in the base class is called Method Overriding.In simple words, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature and the same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class." }, { "code": null, "e": 737, "s": 728, "text": "Example:" }, { "code": "// C# program to illustrate the // Method overriding conceptusing System; // Base classclass My_Parent { // virtual method public virtual void display() { Console.WriteLine(\"My new parent class.. !\"); }} // Derived classclass My_Child : My_Parent { // Here display method is overridden public override void display() { Console.WriteLine(\"My new child class.. !\"); }} class GFG { // Main Method public static void Main() { My_Parent obj; // Creating object of the base class obj = new My_Parent(); // Invoking method of the base class obj.display(); // Creating object of the derived class obj = new My_Child(); // Invoking method of derived class obj.display(); }}", "e": 1534, "s": 737, "text": null }, { "code": null, "e": 1542, "s": 1534, "text": "Output:" }, { "code": null, "e": 1590, "s": 1542, "text": "My new parent class.. !\nMy new child class.. !\n" }, { "code": null, "e": 1847, "s": 1590, "text": "In Method Hiding, you can hide the implementation of the methods of a base class from the derived class using the new keyword. Or in other words, in method hiding, you can redefine the method of the base class in the derived class by using the new keyword." }, { "code": null, "e": 1856, "s": 1847, "text": "Example:" }, { "code": "// C# program to illustrate the// concept of method hidingusing System; // Base Classpublic class My_Parent { public void show() { Console.WriteLine(\"This is my parent class.\"); }} // Derived Classpublic class My_Child : My_Parent { // Hide the method of base class // Using new keyword public new void show() { Console.WriteLine(\"This is my child class.\"); }} public class GFG { // Main method static public void Main() { // Creating the object of // the derived class My_Child obj = new My_Child(); // Access the method of derived class obj.show(); }}", "e": 2508, "s": 1856, "text": null }, { "code": null, "e": 2516, "s": 2508, "text": "Output:" }, { "code": null, "e": 2540, "s": 2516, "text": "This is my child class." }, { "code": null, "e": 2559, "s": 2540, "text": "CSharp-Inheritance" }, { "code": null, "e": 2570, "s": 2559, "text": "CSharp-OOP" }, { "code": null, "e": 2573, "s": 2570, "text": "C#" } ]
Fix “Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]” in Android Studio
16 Jun, 2021 Implementation is a dependency configuration used for library declaration and was introduced in the Android Gradle Plugin 3.0 by Google. Implementation dependencies are declared in this configuration which is internal and not meant for consumer exposure. The main reason for “Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]”” error is that the Gradle cannot recognize the implementation configuration. In this article, we will be discussing 5 different methods to solve this error. Method 1: Update to the latest Gradle version Method 2: Change “implementation” to “compile” Method 3: Move dependencies to module build.gradle Method 4: Change apply plugin: “java” to “java-library” Method 5: Change “implementationSdkVersion” to “compileSdkVersion” In case you are using the “implementation” configuration in an older version of Gradle, the Gradle will not recognize it and throw this error. Hence updating Gradle and Gradle build plugin to the latest version can help solve this issue. Step 1: Navigate to app > Gradle Script > build.gradle (Project: app). Now inside the “dependencies” block, update the classpath to the latest version of the Gradle build plugin. dependencies { classpath "com.android.tools.build:gradle:4.0.2" } Step 2: Now navigate to app > Gradle Script > gradle-wrapper.properties and update the “distributionUrl” to the latest version of Gradle. After adding this code sync your project to solve this issue. distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip If you are using the “implementation” configuration in a Gradle Plugin version less than 3.0, the Gradle will not recognize it and will throw this error. Hence changing “implementation” to “compile” would work. Navigate to app > Gradle Script > build.gradle (Module:app). Inside the dependencies block change “implementation” to “compile“, “testImplementation” to “testCompile” and “androidTestImplementation” to “androidTestCompile“. dependencies { compile fileTree(dir: "libs", include: ["*.jar"]) compile 'androidx.appcompat:appcompat:1.3.0' compile 'androidx.constraintlayout:constraintlayout:2.0.4' compile 'com.google.firebase:firebase-database:20.0.0' compile 'com.google.firebase:firebase-analytics' compile platform('com.google.firebase:firebase-bom:28.0.1') compile 'com.google.android.material:material:1.3.0' compile 'com.google.android:flexbox:2.0.1' compile 'androidx.cardview:cardview:1.0.0' compile 'com.google.firebase:firebase-storage:20.0.0' testCompile 'junit:junit:4.12' androidTestCompile 'androidx.test.ext:junit:1.1.2' androidTestCompile 'androidx.test.espresso:espresso-core:3.3.0' } In Android Studio, there is two build.gradle files. One is for the Project level and another one for the Module level. If application dependencies are added in the Project level build.gradle file, it throws the error “Could not find implementation() method”. Adding these dependencies into the module build.gradle can help solve this issue. The Java Library plugin expands the capabilities of the Java plugin by providing specific knowledge about Java libraries. Change the code inside the Module level build.gradle from apply plugin: 'java' to apply plugin: 'java-library' After adding this code sync your project to solve this issue. The version of the compiler used while building the app is determined by the “compileSdkVersion” while there is no such method as “implementationSdkVersion” in Gradle. Hence changing “implementationSdkVersion” to “compileSdkVersion” can solve this issue. Navigate to app > Gradle Script > build.gradle (Module:app). Change the code from android { implementationSdkVersion 30 ....... } to android { compileSdkVersion 30 ....... } After adding this code sync your project to solve this issue. Android-Studio Picked Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jun, 2021" }, { "code": null, "e": 557, "s": 28, "text": "Implementation is a dependency configuration used for library declaration and was introduced in the Android Gradle Plugin 3.0 by Google. Implementation dependencies are declared in this configuration which is internal and not meant for consumer exposure. The main reason for “Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]”” error is that the Gradle cannot recognize the implementation configuration. In this article, we will be discussing 5 different methods to solve this error." }, { "code": null, "e": 603, "s": 557, "text": "Method 1: Update to the latest Gradle version" }, { "code": null, "e": 650, "s": 603, "text": "Method 2: Change “implementation” to “compile”" }, { "code": null, "e": 701, "s": 650, "text": "Method 3: Move dependencies to module build.gradle" }, { "code": null, "e": 757, "s": 701, "text": "Method 4: Change apply plugin: “java” to “java-library”" }, { "code": null, "e": 824, "s": 757, "text": "Method 5: Change “implementationSdkVersion” to “compileSdkVersion”" }, { "code": null, "e": 1063, "s": 824, "text": "In case you are using the “implementation” configuration in an older version of Gradle, the Gradle will not recognize it and throw this error. Hence updating Gradle and Gradle build plugin to the latest version can help solve this issue. " }, { "code": null, "e": 1244, "s": 1063, "text": "Step 1: Navigate to app > Gradle Script > build.gradle (Project: app). Now inside the “dependencies” block, update the classpath to the latest version of the Gradle build plugin. " }, { "code": null, "e": 1310, "s": 1244, "text": "dependencies { classpath \"com.android.tools.build:gradle:4.0.2\" }" }, { "code": null, "e": 1511, "s": 1310, "text": "Step 2: Now navigate to app > Gradle Script > gradle-wrapper.properties and update the “distributionUrl” to the latest version of Gradle. After adding this code sync your project to solve this issue. " }, { "code": null, "e": 1591, "s": 1511, "text": "distributionUrl=https\\://services.gradle.org/distributions/gradle-6.1.1-all.zip" }, { "code": null, "e": 2027, "s": 1591, "text": "If you are using the “implementation” configuration in a Gradle Plugin version less than 3.0, the Gradle will not recognize it and will throw this error. Hence changing “implementation” to “compile” would work. Navigate to app > Gradle Script > build.gradle (Module:app). Inside the dependencies block change “implementation” to “compile“, “testImplementation” to “testCompile” and “androidTestImplementation” to “androidTestCompile“. " }, { "code": null, "e": 2754, "s": 2027, "text": "dependencies {\n compile fileTree(dir: \"libs\", include: [\"*.jar\"])\n compile 'androidx.appcompat:appcompat:1.3.0'\n compile 'androidx.constraintlayout:constraintlayout:2.0.4'\n compile 'com.google.firebase:firebase-database:20.0.0'\n compile 'com.google.firebase:firebase-analytics'\n compile platform('com.google.firebase:firebase-bom:28.0.1')\n compile 'com.google.android.material:material:1.3.0'\n compile 'com.google.android:flexbox:2.0.1'\n compile 'androidx.cardview:cardview:1.0.0'\n compile 'com.google.firebase:firebase-storage:20.0.0'\n testCompile 'junit:junit:4.12'\n androidTestCompile 'androidx.test.ext:junit:1.1.2'\n androidTestCompile 'androidx.test.espresso:espresso-core:3.3.0'\n}" }, { "code": null, "e": 3095, "s": 2754, "text": "In Android Studio, there is two build.gradle files. One is for the Project level and another one for the Module level. If application dependencies are added in the Project level build.gradle file, it throws the error “Could not find implementation() method”. Adding these dependencies into the module build.gradle can help solve this issue." }, { "code": null, "e": 3276, "s": 3095, "text": "The Java Library plugin expands the capabilities of the Java plugin by providing specific knowledge about Java libraries. Change the code inside the Module level build.gradle from " }, { "code": null, "e": 3297, "s": 3276, "text": "apply plugin: 'java'" }, { "code": null, "e": 3301, "s": 3297, "text": "to " }, { "code": null, "e": 3330, "s": 3301, "text": "apply plugin: 'java-library'" }, { "code": null, "e": 3393, "s": 3330, "text": "After adding this code sync your project to solve this issue. " }, { "code": null, "e": 3731, "s": 3393, "text": "The version of the compiler used while building the app is determined by the “compileSdkVersion” while there is no such method as “implementationSdkVersion” in Gradle. Hence changing “implementationSdkVersion” to “compileSdkVersion” can solve this issue. Navigate to app > Gradle Script > build.gradle (Module:app). Change the code from" }, { "code": null, "e": 3788, "s": 3731, "text": "android {\n implementationSdkVersion 30\n .......\n }" }, { "code": null, "e": 3791, "s": 3788, "text": "to" }, { "code": null, "e": 3841, "s": 3791, "text": "android {\n compileSdkVersion 30\n .......\n }" }, { "code": null, "e": 3904, "s": 3841, "text": "After adding this code sync your project to solve this issue. " }, { "code": null, "e": 3919, "s": 3904, "text": "Android-Studio" }, { "code": null, "e": 3926, "s": 3919, "text": "Picked" }, { "code": null, "e": 3934, "s": 3926, "text": "Android" }, { "code": null, "e": 3942, "s": 3934, "text": "Android" } ]
turtle.onscreenclick() function in Python
26 Jul, 2020 The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. This function is used to bind fun to a mouse-click event on canvas. Syntax : turtle.onscreenclick(fun, btn=1, add=None) Parameters: Below is the implementation of the above method with an example : Python3 # import packagesimport turtleimport random # global colorscol = ['red', 'yellow', 'green', 'blue', 'white', 'black', 'orange', 'pink'] # method to call on screen click def fxn(x, y): global col ind = random.randint(0, 7) # set screen color randomly sc.bgcolor(col[ind]) # set screensc = turtle.Screen()sc.setup(400, 300) # call method on screen clickturtle.onscreenclick(fxn) Output : Here we can find that whenever the user clicks (yellow-colored dot on arrow) on screen it changes the background color of the turtle graphics window randomly. Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n26 Jul, 2020" }, { "code": null, "e": 270, "s": 53, "text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support." }, { "code": null, "e": 338, "s": 270, "text": "This function is used to bind fun to a mouse-click event on canvas." }, { "code": null, "e": 347, "s": 338, "text": "Syntax :" }, { "code": null, "e": 391, "s": 347, "text": "turtle.onscreenclick(fun, btn=1, add=None)\n" }, { "code": null, "e": 403, "s": 391, "text": "Parameters:" }, { "code": null, "e": 605, "s": 539, "text": "Below is the implementation of the above method with an example :" }, { "code": null, "e": 613, "s": 605, "text": "Python3" }, { "code": "# import packagesimport turtleimport random # global colorscol = ['red', 'yellow', 'green', 'blue', 'white', 'black', 'orange', 'pink'] # method to call on screen click def fxn(x, y): global col ind = random.randint(0, 7) # set screen color randomly sc.bgcolor(col[ind]) # set screensc = turtle.Screen()sc.setup(400, 300) # call method on screen clickturtle.onscreenclick(fxn)", "e": 1021, "s": 613, "text": null }, { "code": null, "e": 1030, "s": 1021, "text": "Output :" }, { "code": null, "e": 1190, "s": 1030, "text": "Here we can find that whenever the user clicks (yellow-colored dot on arrow) on screen it changes the background color of the turtle graphics window randomly." }, { "code": null, "e": 1204, "s": 1190, "text": "Python-turtle" }, { "code": null, "e": 1211, "s": 1204, "text": "Python" } ]
Python – Filter float strings from String list
29 Nov, 2019 Sometimes, while working with Python list, we can have a problem in which we need to separate the float values from valid strings. But problem arises when float values are in form of strings. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loop + Exception HandlingThe combination of above functionalities can be used to perform this task. In this, we loop through each element and try to convert each string into float value, if it’s a success, means it’s a float, else it raises a ValueError and we can get desired string. # Python3 code to demonstrate working of# Filter float strings from String list# using loop + Exception Handling # initialize list test_list = ['gfg', '45.45', 'is', '87.5', 'best', '90.34'] # printing original list print("The original list : " + str(test_list)) # Filter float strings from String list# using loop + Exception Handlingres = []for ele in test_list: try: float(ele) except ValueError: res.append(ele) # printing resultprint("String list after filtering floats : " + str(res)) The original list : ['gfg', '45.45', 'is', '87.5', 'best', '90.34'] String list after filtering floats : ['gfg', 'is', 'best'] Method #2 : Using regex + list comprehensionThe combination of above functionalities can perform this task. In this, we perform the task of filtering using regex created and list comprehension is used to iterate over the list and apply the filter. # Python3 code to demonstrate working of# Filter float strings from String list# using regex + list comprehensionimport re # initialize list test_list = ['gfg', '45.45', 'is', '87.5', 'best', '90.34'] # printing original list print("The original list : " + str(test_list)) # Filter float strings from String list# using regex + list comprehensiontemp = re.compile(r'\d+(?:\.\d*)')res = [ele for ele in test_list if not temp.match(ele)] # printing resultprint("String list after filtering floats : " + str(res)) The original list : ['gfg', '45.45', 'is', '87.5', 'best', '90.34'] String list after filtering floats : ['gfg', 'is', 'best'] Python list-programs Python Python Programs 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() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2019" }, { "code": null, "e": 284, "s": 28, "text": "Sometimes, while working with Python list, we can have a problem in which we need to separate the float values from valid strings. But problem arises when float values are in form of strings. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 587, "s": 284, "text": "Method #1 : Using loop + Exception HandlingThe combination of above functionalities can be used to perform this task. In this, we loop through each element and try to convert each string into float value, if it’s a success, means it’s a float, else it raises a ValueError and we can get desired string." }, { "code": "# Python3 code to demonstrate working of# Filter float strings from String list# using loop + Exception Handling # initialize list test_list = ['gfg', '45.45', 'is', '87.5', 'best', '90.34'] # printing original list print(\"The original list : \" + str(test_list)) # Filter float strings from String list# using loop + Exception Handlingres = []for ele in test_list: try: float(ele) except ValueError: res.append(ele) # printing resultprint(\"String list after filtering floats : \" + str(res))", "e": 1102, "s": 587, "text": null }, { "code": null, "e": 1230, "s": 1102, "text": "The original list : ['gfg', '45.45', 'is', '87.5', 'best', '90.34']\nString list after filtering floats : ['gfg', 'is', 'best']\n" }, { "code": null, "e": 1480, "s": 1232, "text": "Method #2 : Using regex + list comprehensionThe combination of above functionalities can perform this task. In this, we perform the task of filtering using regex created and list comprehension is used to iterate over the list and apply the filter." }, { "code": "# Python3 code to demonstrate working of# Filter float strings from String list# using regex + list comprehensionimport re # initialize list test_list = ['gfg', '45.45', 'is', '87.5', 'best', '90.34'] # printing original list print(\"The original list : \" + str(test_list)) # Filter float strings from String list# using regex + list comprehensiontemp = re.compile(r'\\d+(?:\\.\\d*)')res = [ele for ele in test_list if not temp.match(ele)] # printing resultprint(\"String list after filtering floats : \" + str(res))", "e": 1995, "s": 1480, "text": null }, { "code": null, "e": 2123, "s": 1995, "text": "The original list : ['gfg', '45.45', 'is', '87.5', 'best', '90.34']\nString list after filtering floats : ['gfg', 'is', 'best']\n" }, { "code": null, "e": 2144, "s": 2123, "text": "Python list-programs" }, { "code": null, "e": 2151, "s": 2144, "text": "Python" }, { "code": null, "e": 2167, "s": 2151, "text": "Python Programs" }, { "code": null, "e": 2265, "s": 2167, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2283, "s": 2265, "text": "Python Dictionary" }, { "code": null, "e": 2325, "s": 2283, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2347, "s": 2325, "text": "Enumerate() in Python" }, { "code": null, "e": 2382, "s": 2347, "text": "Read a file line by line in Python" }, { "code": null, "e": 2408, "s": 2382, "text": "Python String | replace()" }, { "code": null, "e": 2451, "s": 2408, "text": "Python program to convert a list to string" }, { "code": null, "e": 2473, "s": 2451, "text": "Defaultdict in Python" }, { "code": null, "e": 2512, "s": 2473, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2550, "s": 2512, "text": "Python | Convert a list to dictionary" } ]
Program for class interval arithmetic mean
07 May, 2021 Given a class interval and frequency distribution and the task is to find Arithmetic mean. In case of frequency distribution the raw data is arranged by intervals having corresponding frequencies. So if we are interested to find arithmetic mean of the data having class interval we must know the mid variable x. This variable can be calculated by using mid point of interval. Let lower limit of interval are lower_limit[] = {1, 6, 11, 16, 21} Upper limit of interval are upper_limit[] = {5, 10, 15, 20, 25} and frequency freq[] = {10, 20, 30, 40, 50} are given.Where mid(x) = (lower[i] + upper[i]) / 2; and mean = (freq[0] * mid[0] + freq[1] * mid[1] + . . . + freq[n – 1] * mid[n – 1]) / (freq[0] + freq[1] + . . . + freq[n-1])= 2450 / 150 = 16.3333 Examples: Input : lower_limit[] = {1, 6, 11, 16, 21} upper_limit[] = {5, 10, 15, 20, 25} freq[] = {10, 20, 30, 40, 50} Output : 16.3333 Input : lower_limit[] = {10, 20, 30, 40, 50} upper_limit[] = {19, 29, 39, 49, 59} freq[] = {15, 20, 30, 35, 40} Output : 38.6429 C++ Java Python3 C# PHP Javascript // CPP program to find class interval// arithmetic mean.#include <bits/stdc++.h>using namespace std; // Function to find class interval arithmetic mean.float mean(int lower_limit[], int upper_limit[], int freq[], int n){ float mid[n]; float sum = 0, freqSum = 0; // calculate sum of frequency and sum of // multiplication of interval mid value // and frequency. for (int i = 0; i < n; i++) { mid[i] = (lower_limit[i] + upper_limit[i]) / 2; sum = sum + mid[i] * freq[i]; freqSum = freqSum + freq[i]; } return sum / freqSum;} // Driver functionint main(){ int lower_limit[] = { 1, 6, 11, 16, 21 }; int upper_limit[] = { 5, 10, 15, 20, 25 }; int freq[] = { 10, 20, 30, 40, 50 }; int n = sizeof(freq) / sizeof(freq[0]); cout << mean(lower_limit, upper_limit, freq, n); return 0;} // java program to find// class intervalimport java.io.*; class GFG { // Function to find class // interval arithmetic mean. static float mean(int lower_limit[], int upper_limit[], int freq[], int n) { float mid[] = new float[n]; float sum = 0, freqSum = 0; // calculate sum of frequency and sum of // multiplication of interval mid value // and frequency. for (int i = 0; i < n; i++) { mid[i] = (lower_limit[i] + upper_limit[i]) / 2; sum = sum + mid[i] * freq[i]; freqSum = freqSum + freq[i]; } return sum / freqSum; } // Driver function public static void main (String[] args) { int lower_limit[] = { 1, 6, 11, 16, 21 }; int upper_limit[] = { 5, 10, 15, 20, 25 }; int freq[] = { 10, 20, 30, 40, 50 }; int n = freq.length; mean(lower_limit, upper_limit, freq, n); System.out.println(mean(lower_limit, upper_limit, freq, n)); }} // This code is contributed by vt_m # Python 3 program to find class interval# arithmetic mean. # Function to find class interval# arithmetic mean.def mean(lower_limit, upper_limit, freq, n): mid = [0.0] * n sum = 0 freqSum = 0 # calculate sum of frequency and # sum of multiplication of interval # mid value and frequency. for i in range( 0, n): mid[i] = ((lower_limit[i] + upper_limit[i]) / 2) sum = sum + mid[i] * freq[i] freqSum = freqSum + freq[i] return sum / freqSum # Driver functionlower_limit = [ 1, 6, 11, 16, 21 ]upper_limit = [ 5, 10, 15, 20, 25 ]freq = [10, 20, 30, 40, 50]n = len(freq)print(round(mean(lower_limit, upper_limit, freq, n), 4)) # This code is contributed by# Smitha Dinesh Semwal // C# program to find// class intervalusing System; class GFG { // Function to find class // interval arithmetic mean. static float mean(int []lower_limit, int []upper_limit, int []freq, int n) { float []mid = new float[n]; float sum = 0, freqSum = 0; // calculate sum of frequency and sum of // multiplication of interval mid value // and frequency. for (int i = 0; i < n; i++) { mid[i] = (lower_limit[i] + upper_limit[i]) / 2; sum = sum + mid[i] * freq[i]; freqSum = freqSum + freq[i]; } return sum / freqSum; } // Driver function public static void Main () { int []lower_limit = { 1, 6, 11, 16, 21 }; int []upper_limit = { 5, 10, 15, 20, 25 }; int []freq = { 10, 20, 30, 40, 50 }; int n = freq.Length; mean(lower_limit, upper_limit, freq, n); Console.WriteLine(mean(lower_limit, upper_limit, freq, n)); }} // This code is contributed by vt_m <?php// PHP program to find class interval// arithmetic mean. // Function to find class interval// arithmetic mean.function mean( $lower_limit, $upper_limit, $freq, $n){ $mid = array(); $sum = 0; $freqSum = 0; // calculate sum of frequency and // sum of multiplication of interval // mid value and frequency. for ( $i = 0; $i <$n; $i++) { $mid[$i] = ($lower_limit[$i] + $upper_limit[$i]) / 2; $sum = $sum + $mid[$i] * $freq[$i]; $freqSum = $freqSum + $freq[$i]; } return $sum / $freqSum;} // Driver function$lower_limit = array( 1, 6, 11, 16, 21 );$upper_limit = array( 5, 10, 15, 20, 25 );$freq = array( 10, 20, 30, 40, 50 );$n = count($freq); echo mean($lower_limit, $upper_limit, $freq, $n); // This code is contributed by anuj_67.?> <script> // JavaScript program to find// class interval // Function to find class // interval arithmetic mean. function mean(lower_limit, upper_limit, freq, n) { let mid = []; let sum = 0, freqSum = 0; // calculate sum of frequency and sum of // multiplication of interval mid value // and frequency. for (let i = 0; i < n; i++) { mid[i] = (lower_limit[i] + upper_limit[i]) / 2; sum = sum + mid[i] * freq[i]; freqSum = freqSum + freq[i]; } return sum / freqSum; } // Driver Code let lower_limit = [ 1, 6, 11, 16, 21 ]; let upper_limit = [ 5, 10, 15, 20, 25 ]; let freq = [ 10, 20, 30, 40, 50 ]; let n = freq.length; mean(lower_limit, upper_limit, freq, n); document.write(mean(lower_limit, upper_limit, freq, n)); // This code is contributed by chinmoy1997pal.</script> Output: 16.3333 Smitha Dinesh Semwal vt_m chinmoy1997pal arorakashish0911 statistical-algorithms Algorithms Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Hash Functions and list/types of Hash functions How to Start Learning DSA? Complete Roadmap To Learn DSA From Scratch Minimum cost to reach the top of the floor by climbing stairs Difference between NP hard and NP complete problem Binary Search In JavaScript Algorithms Design Techniques What is Hashing | A Complete Tutorial Print all shortest paths between given source and destination in an undirected graph
[ { "code": null, "e": 52, "s": 24, "text": "\n07 May, 2021" }, { "code": null, "e": 428, "s": 52, "text": "Given a class interval and frequency distribution and the task is to find Arithmetic mean. In case of frequency distribution the raw data is arranged by intervals having corresponding frequencies. So if we are interested to find arithmetic mean of the data having class interval we must know the mid variable x. This variable can be calculated by using mid point of interval." }, { "code": null, "e": 805, "s": 428, "text": "Let lower limit of interval are lower_limit[] = {1, 6, 11, 16, 21} Upper limit of interval are upper_limit[] = {5, 10, 15, 20, 25} and frequency freq[] = {10, 20, 30, 40, 50} are given.Where mid(x) = (lower[i] + upper[i]) / 2; and mean = (freq[0] * mid[0] + freq[1] * mid[1] + . . . + freq[n – 1] * mid[n – 1]) / (freq[0] + freq[1] + . . . + freq[n-1])= 2450 / 150 = 16.3333 " }, { "code": null, "e": 817, "s": 805, "text": "Examples: " }, { "code": null, "e": 1105, "s": 817, "text": "Input : lower_limit[] = {1, 6, 11, 16, 21}\n upper_limit[] = {5, 10, 15, 20, 25}\n freq[] = {10, 20, 30, 40, 50}\nOutput : 16.3333\n\nInput : lower_limit[] = {10, 20, 30, 40, 50}\n upper_limit[] = {19, 29, 39, 49, 59}\n freq[] = {15, 20, 30, 35, 40}\nOutput : 38.6429" }, { "code": null, "e": 1109, "s": 1105, "text": "C++" }, { "code": null, "e": 1114, "s": 1109, "text": "Java" }, { "code": null, "e": 1122, "s": 1114, "text": "Python3" }, { "code": null, "e": 1125, "s": 1122, "text": "C#" }, { "code": null, "e": 1129, "s": 1125, "text": "PHP" }, { "code": null, "e": 1140, "s": 1129, "text": "Javascript" }, { "code": "// CPP program to find class interval// arithmetic mean.#include <bits/stdc++.h>using namespace std; // Function to find class interval arithmetic mean.float mean(int lower_limit[], int upper_limit[], int freq[], int n){ float mid[n]; float sum = 0, freqSum = 0; // calculate sum of frequency and sum of // multiplication of interval mid value // and frequency. for (int i = 0; i < n; i++) { mid[i] = (lower_limit[i] + upper_limit[i]) / 2; sum = sum + mid[i] * freq[i]; freqSum = freqSum + freq[i]; } return sum / freqSum;} // Driver functionint main(){ int lower_limit[] = { 1, 6, 11, 16, 21 }; int upper_limit[] = { 5, 10, 15, 20, 25 }; int freq[] = { 10, 20, 30, 40, 50 }; int n = sizeof(freq) / sizeof(freq[0]); cout << mean(lower_limit, upper_limit, freq, n); return 0;}", "e": 2026, "s": 1140, "text": null }, { "code": "// java program to find// class intervalimport java.io.*; class GFG { // Function to find class // interval arithmetic mean. static float mean(int lower_limit[], int upper_limit[], int freq[], int n) { float mid[] = new float[n]; float sum = 0, freqSum = 0; // calculate sum of frequency and sum of // multiplication of interval mid value // and frequency. for (int i = 0; i < n; i++) { mid[i] = (lower_limit[i] + upper_limit[i]) / 2; sum = sum + mid[i] * freq[i]; freqSum = freqSum + freq[i]; } return sum / freqSum; } // Driver function public static void main (String[] args) { int lower_limit[] = { 1, 6, 11, 16, 21 }; int upper_limit[] = { 5, 10, 15, 20, 25 }; int freq[] = { 10, 20, 30, 40, 50 }; int n = freq.length; mean(lower_limit, upper_limit, freq, n); System.out.println(mean(lower_limit, upper_limit, freq, n)); }} // This code is contributed by vt_m", "e": 3134, "s": 2026, "text": null }, { "code": "# Python 3 program to find class interval# arithmetic mean. # Function to find class interval# arithmetic mean.def mean(lower_limit, upper_limit, freq, n): mid = [0.0] * n sum = 0 freqSum = 0 # calculate sum of frequency and # sum of multiplication of interval # mid value and frequency. for i in range( 0, n): mid[i] = ((lower_limit[i] + upper_limit[i]) / 2) sum = sum + mid[i] * freq[i] freqSum = freqSum + freq[i] return sum / freqSum # Driver functionlower_limit = [ 1, 6, 11, 16, 21 ]upper_limit = [ 5, 10, 15, 20, 25 ]freq = [10, 20, 30, 40, 50]n = len(freq)print(round(mean(lower_limit, upper_limit, freq, n), 4)) # This code is contributed by# Smitha Dinesh Semwal", "e": 3953, "s": 3134, "text": null }, { "code": "// C# program to find// class intervalusing System; class GFG { // Function to find class // interval arithmetic mean. static float mean(int []lower_limit, int []upper_limit, int []freq, int n) { float []mid = new float[n]; float sum = 0, freqSum = 0; // calculate sum of frequency and sum of // multiplication of interval mid value // and frequency. for (int i = 0; i < n; i++) { mid[i] = (lower_limit[i] + upper_limit[i]) / 2; sum = sum + mid[i] * freq[i]; freqSum = freqSum + freq[i]; } return sum / freqSum; } // Driver function public static void Main () { int []lower_limit = { 1, 6, 11, 16, 21 }; int []upper_limit = { 5, 10, 15, 20, 25 }; int []freq = { 10, 20, 30, 40, 50 }; int n = freq.Length; mean(lower_limit, upper_limit, freq, n); Console.WriteLine(mean(lower_limit, upper_limit, freq, n)); }} // This code is contributed by vt_m", "e": 5078, "s": 3953, "text": null }, { "code": "<?php// PHP program to find class interval// arithmetic mean. // Function to find class interval// arithmetic mean.function mean( $lower_limit, $upper_limit, $freq, $n){ $mid = array(); $sum = 0; $freqSum = 0; // calculate sum of frequency and // sum of multiplication of interval // mid value and frequency. for ( $i = 0; $i <$n; $i++) { $mid[$i] = ($lower_limit[$i] + $upper_limit[$i]) / 2; $sum = $sum + $mid[$i] * $freq[$i]; $freqSum = $freqSum + $freq[$i]; } return $sum / $freqSum;} // Driver function$lower_limit = array( 1, 6, 11, 16, 21 );$upper_limit = array( 5, 10, 15, 20, 25 );$freq = array( 10, 20, 30, 40, 50 );$n = count($freq); echo mean($lower_limit, $upper_limit, $freq, $n); // This code is contributed by anuj_67.?>", "e": 5944, "s": 5078, "text": null }, { "code": "<script> // JavaScript program to find// class interval // Function to find class // interval arithmetic mean. function mean(lower_limit, upper_limit, freq, n) { let mid = []; let sum = 0, freqSum = 0; // calculate sum of frequency and sum of // multiplication of interval mid value // and frequency. for (let i = 0; i < n; i++) { mid[i] = (lower_limit[i] + upper_limit[i]) / 2; sum = sum + mid[i] * freq[i]; freqSum = freqSum + freq[i]; } return sum / freqSum; } // Driver Code let lower_limit = [ 1, 6, 11, 16, 21 ]; let upper_limit = [ 5, 10, 15, 20, 25 ]; let freq = [ 10, 20, 30, 40, 50 ]; let n = freq.length; mean(lower_limit, upper_limit, freq, n); document.write(mean(lower_limit, upper_limit, freq, n)); // This code is contributed by chinmoy1997pal.</script>", "e": 6963, "s": 5944, "text": null }, { "code": null, "e": 6972, "s": 6963, "text": "Output: " }, { "code": null, "e": 6980, "s": 6972, "text": "16.3333" }, { "code": null, "e": 7003, "s": 6982, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 7008, "s": 7003, "text": "vt_m" }, { "code": null, "e": 7023, "s": 7008, "text": "chinmoy1997pal" }, { "code": null, "e": 7040, "s": 7023, "text": "arorakashish0911" }, { "code": null, "e": 7063, "s": 7040, "text": "statistical-algorithms" }, { "code": null, "e": 7074, "s": 7063, "text": "Algorithms" }, { "code": null, "e": 7085, "s": 7074, "text": "Algorithms" }, { "code": null, "e": 7183, "s": 7085, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7250, "s": 7183, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 7298, "s": 7250, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 7325, "s": 7298, "text": "How to Start Learning DSA?" }, { "code": null, "e": 7368, "s": 7325, "text": "Complete Roadmap To Learn DSA From Scratch" }, { "code": null, "e": 7430, "s": 7368, "text": "Minimum cost to reach the top of the floor by climbing stairs" }, { "code": null, "e": 7481, "s": 7430, "text": "Difference between NP hard and NP complete problem" }, { "code": null, "e": 7509, "s": 7481, "text": "Binary Search In JavaScript" }, { "code": null, "e": 7538, "s": 7509, "text": "Algorithms Design Techniques" }, { "code": null, "e": 7576, "s": 7538, "text": "What is Hashing | A Complete Tutorial" } ]
id() function in Python
25 Nov, 2017 Introductionid() is an inbuilt function in Python.Syntax: id(object) As we can see the function accepts a single parameter and is used to return the identity of an object. This identity has to be unique and constant for this object during the lifetime. Two objects with non-overlapping lifetimes may have the same id() value. If we relate this to C, then they are actually the memory address, here in Python it is the unique id. This function is generally used internally in Python. Examples: The output is the identity of the object passed. This is random but when running in the same program, it generates unique and same identity. Input : id(1025) Output : 140365829447504 Output varies with different runs Input : id("geek") Output : 139793848214784 # This program shows various identitiesstr1 = "geek"print(id(str1)) str2 = "geek"print(id(str2)) # This will return Trueprint(id(str1) == id(str2)) # Use in Listslist1 = ["aakash", "priya", "abdul"]print(id(list1[0]))print(id(list1[2])) # This returns falseprint(id(list1[0])==id(list1[2])) Output: 140252505691448 140252505691448 True 140252505691840 140252505739928 False Python-Built-in-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n25 Nov, 2017" }, { "code": null, "e": 111, "s": 53, "text": "Introductionid() is an inbuilt function in Python.Syntax:" }, { "code": null, "e": 122, "s": 111, "text": "id(object)" }, { "code": null, "e": 536, "s": 122, "text": "As we can see the function accepts a single parameter and is used to return the identity of an object. This identity has to be unique and constant for this object during the lifetime. Two objects with non-overlapping lifetimes may have the same id() value. If we relate this to C, then they are actually the memory address, here in Python it is the unique id. This function is generally used internally in Python." }, { "code": null, "e": 546, "s": 536, "text": "Examples:" }, { "code": null, "e": 814, "s": 546, "text": "The output is the identity of the \nobject passed. This is random but \nwhen running in the same program, \nit generates unique and same identity. \n\nInput : id(1025)\nOutput : 140365829447504\nOutput varies with different runs\n\nInput : id(\"geek\")\nOutput : 139793848214784\n" }, { "code": "# This program shows various identitiesstr1 = \"geek\"print(id(str1)) str2 = \"geek\"print(id(str2)) # This will return Trueprint(id(str1) == id(str2)) # Use in Listslist1 = [\"aakash\", \"priya\", \"abdul\"]print(id(list1[0]))print(id(list1[2])) # This returns falseprint(id(list1[0])==id(list1[2]))", "e": 1109, "s": 814, "text": null }, { "code": null, "e": 1117, "s": 1109, "text": "Output:" }, { "code": null, "e": 1193, "s": 1117, "text": "140252505691448\n140252505691448\nTrue\n140252505691840\n140252505739928\nFalse\n" }, { "code": null, "e": 1219, "s": 1193, "text": "Python-Built-in-functions" }, { "code": null, "e": 1226, "s": 1219, "text": "Python" } ]
How to input or read a Character, Word and a Sentence from user in C?
21 Sep, 2021 C is a procedural programming language. It was initially developed by Dennis Ritchie as a system programming language to write an operating system. The main features of the C language include low-level access to memory, a simple set of keywords, and a clean style, these features make C language suitable for system programmings like operating systems or compiler development. This article focuses on how to take a character, a string, and a sentence as input in C. Reading a Character in C Problem Statement#1: Write a C program to read a single character as input in C. Syntax- scanf("%c", &charVariable); Approach- scanf() needs to know the memory location of a variable in order to store the input from the user.So, the ampersand will be used in front of the variable (here ch) to know the address of a variable.Here using %c format specifier, the compiler can understand that character type of data is in a variable when taking input using the scanf() function scanf() needs to know the memory location of a variable in order to store the input from the user. So, the ampersand will be used in front of the variable (here ch) to know the address of a variable. Here using %c format specifier, the compiler can understand that character type of data is in a variable when taking input using the scanf() function C // C program to implement// the above approach#include <stdio.h> // Driver codeint main(){ char ch; // Read a char type variable, // store in "ch" scanf("%c", &ch); printf("Output : %c", ch); return 0;} Reading a Word in C Problem Statement#2: Write a C program to read words as input from the user. Syntax- scanf("%s", stringvariable); Approach- First, initialize the char array of size ( greater than are equal to the length of word).Then, use %s format specifier to take the string using the scanf() function. First, initialize the char array of size ( greater than are equal to the length of word). Then, use %s format specifier to take the string using the scanf() function. C // C Program to implement// the above approach#include <stdio.h> // Driver codeint main(){ char word[100]; // word is treated as a pointer // to the first element of array scanf("%s", word); printf("Output : %s", word); return 0;} Note: An array name itself indicates its address. word == &word[0], these are both the same.It’s because the variable name word points to the first element of the array. So, there is no need to mention ampersand in scanf(). Reading a Sentence in C Problem Statement#3: Write a C program to read sentences as input from the user. Method 1- scanf() doesn’t store the white space character in a string variable.It only reads characters other than white spaces and stores them in the specified character array until it encounters a white-space character. scanf() doesn’t store the white space character in a string variable. It only reads characters other than white spaces and stores them in the specified character array until it encounters a white-space character. Syntax- scanf("%[^\n]s", sen) C // C program to implement// the above approach#include <stdio.h> // Driver codeint main(){ char sen[100]; scanf("%[^\n]s", sen); printf("Output : %s", sen); return 0;} scanf(“%[^\n]s”, sen) means to read a string including spaces until the next line is received or to read string until line break i.e. \n is encountered and store it on an array named “sen”. Here, %[ ] is the scanset specifier.scanf will process only those characters which are part of scanset.If the first character of the scanset is ‘^’, then the specifier will stop reading after the first occurrence of that character.^\n stands for taking input until a newline isn’t encountered. Here, %[ ] is the scanset specifier. scanf will process only those characters which are part of scanset. If the first character of the scanset is ‘^’, then the specifier will stop reading after the first occurrence of that character. ^\n stands for taking input until a newline isn’t encountered. C // C program to implement// the above approach#include <stdio.h> // Driver codeint main(){ char sen[100]; scanf("%[^f]s", sen); printf("Output : %s", sen); return 0;} It’ll stop reading after the first occurrence of that character f (specified in the scanset). Method 2- Using fgets Note- gets() never checks the maximum limit of input characters. Hence they may cause undefined behavior and probably lead to buffer overflow error which eventually causes the program to crash. Hence, it is advisable not to use the gets function to read strings. To overcome the above limitation, fgets can be used. Syntax- char *fgets(char *str, int size, FILE *stream) C // C program to implement// the above approach#include <stdio.h>#define BUFFSIZE 25 // Driver codeint main(){ char sen[BUFFSIZE]; fgets(sen, BUFFSIZE, stdin); printf("Output : %s", sen); return 0;} Blogathon-2021 c-input-output Blogathon C Language Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Connect Python with SQL Database? How to Import JSON Data into SQL Server? Data Mining - Cluster Analysis Explain the purpose of render() in ReactJS How to build a basic CRUD app with Node.js and ReactJS ? std::sort() in C++ STL Bitwise Operators in C/C++ Arrays in C/C++ Substring in C++ Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Sep, 2021" }, { "code": null, "e": 518, "s": 52, "text": "C is a procedural programming language. It was initially developed by Dennis Ritchie as a system programming language to write an operating system. The main features of the C language include low-level access to memory, a simple set of keywords, and a clean style, these features make C language suitable for system programmings like operating systems or compiler development. This article focuses on how to take a character, a string, and a sentence as input in C." }, { "code": null, "e": 543, "s": 518, "text": "Reading a Character in C" }, { "code": null, "e": 624, "s": 543, "text": "Problem Statement#1: Write a C program to read a single character as input in C." }, { "code": null, "e": 632, "s": 624, "text": "Syntax-" }, { "code": null, "e": 660, "s": 632, "text": "scanf(\"%c\", &charVariable);" }, { "code": null, "e": 670, "s": 660, "text": "Approach-" }, { "code": null, "e": 1018, "s": 670, "text": "scanf() needs to know the memory location of a variable in order to store the input from the user.So, the ampersand will be used in front of the variable (here ch) to know the address of a variable.Here using %c format specifier, the compiler can understand that character type of data is in a variable when taking input using the scanf() function" }, { "code": null, "e": 1117, "s": 1018, "text": "scanf() needs to know the memory location of a variable in order to store the input from the user." }, { "code": null, "e": 1218, "s": 1117, "text": "So, the ampersand will be used in front of the variable (here ch) to know the address of a variable." }, { "code": null, "e": 1368, "s": 1218, "text": "Here using %c format specifier, the compiler can understand that character type of data is in a variable when taking input using the scanf() function" }, { "code": null, "e": 1370, "s": 1368, "text": "C" }, { "code": "// C program to implement// the above approach#include <stdio.h> // Driver codeint main(){ char ch; // Read a char type variable, // store in \"ch\" scanf(\"%c\", &ch); printf(\"Output : %c\", ch); return 0;}", "e": 1594, "s": 1370, "text": null }, { "code": null, "e": 1614, "s": 1594, "text": "Reading a Word in C" }, { "code": null, "e": 1691, "s": 1614, "text": "Problem Statement#2: Write a C program to read words as input from the user." }, { "code": null, "e": 1699, "s": 1691, "text": "Syntax-" }, { "code": null, "e": 1728, "s": 1699, "text": "scanf(\"%s\", stringvariable);" }, { "code": null, "e": 1738, "s": 1728, "text": "Approach-" }, { "code": null, "e": 1904, "s": 1738, "text": "First, initialize the char array of size ( greater than are equal to the length of word).Then, use %s format specifier to take the string using the scanf() function." }, { "code": null, "e": 1994, "s": 1904, "text": "First, initialize the char array of size ( greater than are equal to the length of word)." }, { "code": null, "e": 2071, "s": 1994, "text": "Then, use %s format specifier to take the string using the scanf() function." }, { "code": null, "e": 2073, "s": 2071, "text": "C" }, { "code": "// C Program to implement// the above approach#include <stdio.h> // Driver codeint main(){ char word[100]; // word is treated as a pointer // to the first element of array scanf(\"%s\", word); printf(\"Output : %s\", word); return 0;}", "e": 2325, "s": 2073, "text": null }, { "code": null, "e": 2550, "s": 2325, "text": "Note: An array name itself indicates its address. word == &word[0], these are both the same.It’s because the variable name word points to the first element of the array. So, there is no need to mention ampersand in scanf()." }, { "code": null, "e": 2574, "s": 2550, "text": "Reading a Sentence in C" }, { "code": null, "e": 2655, "s": 2574, "text": "Problem Statement#3: Write a C program to read sentences as input from the user." }, { "code": null, "e": 2665, "s": 2655, "text": "Method 1-" }, { "code": null, "e": 2877, "s": 2665, "text": "scanf() doesn’t store the white space character in a string variable.It only reads characters other than white spaces and stores them in the specified character array until it encounters a white-space character." }, { "code": null, "e": 2947, "s": 2877, "text": "scanf() doesn’t store the white space character in a string variable." }, { "code": null, "e": 3090, "s": 2947, "text": "It only reads characters other than white spaces and stores them in the specified character array until it encounters a white-space character." }, { "code": null, "e": 3098, "s": 3090, "text": "Syntax-" }, { "code": null, "e": 3120, "s": 3098, "text": "scanf(\"%[^\\n]s\", sen)" }, { "code": null, "e": 3122, "s": 3120, "text": "C" }, { "code": "// C program to implement// the above approach#include <stdio.h> // Driver codeint main(){ char sen[100]; scanf(\"%[^\\n]s\", sen); printf(\"Output : %s\", sen); return 0;}", "e": 3303, "s": 3122, "text": null }, { "code": null, "e": 3493, "s": 3303, "text": "scanf(“%[^\\n]s”, sen) means to read a string including spaces until the next line is received or to read string until line break i.e. \\n is encountered and store it on an array named “sen”." }, { "code": null, "e": 3788, "s": 3493, "text": "Here, %[ ] is the scanset specifier.scanf will process only those characters which are part of scanset.If the first character of the scanset is ‘^’, then the specifier will stop reading after the first occurrence of that character.^\\n stands for taking input until a newline isn’t encountered." }, { "code": null, "e": 3825, "s": 3788, "text": "Here, %[ ] is the scanset specifier." }, { "code": null, "e": 3893, "s": 3825, "text": "scanf will process only those characters which are part of scanset." }, { "code": null, "e": 4022, "s": 3893, "text": "If the first character of the scanset is ‘^’, then the specifier will stop reading after the first occurrence of that character." }, { "code": null, "e": 4086, "s": 4022, "text": "^\\n stands for taking input until a newline isn’t encountered." }, { "code": null, "e": 4088, "s": 4086, "text": "C" }, { "code": "// C program to implement// the above approach#include <stdio.h> // Driver codeint main(){ char sen[100]; scanf(\"%[^f]s\", sen); printf(\"Output : %s\", sen); return 0;}", "e": 4268, "s": 4088, "text": null }, { "code": null, "e": 4362, "s": 4268, "text": "It’ll stop reading after the first occurrence of that character f (specified in the scanset)." }, { "code": null, "e": 4384, "s": 4362, "text": "Method 2- Using fgets" }, { "code": null, "e": 4700, "s": 4384, "text": "Note- gets() never checks the maximum limit of input characters. Hence they may cause undefined behavior and probably lead to buffer overflow error which eventually causes the program to crash. Hence, it is advisable not to use the gets function to read strings. To overcome the above limitation, fgets can be used." }, { "code": null, "e": 4708, "s": 4700, "text": "Syntax-" }, { "code": null, "e": 4755, "s": 4708, "text": "char *fgets(char *str, int size, FILE *stream)" }, { "code": null, "e": 4757, "s": 4755, "text": "C" }, { "code": "// C program to implement// the above approach#include <stdio.h>#define BUFFSIZE 25 // Driver codeint main(){ char sen[BUFFSIZE]; fgets(sen, BUFFSIZE, stdin); printf(\"Output : %s\", sen); return 0;}", "e": 4968, "s": 4757, "text": null }, { "code": null, "e": 4983, "s": 4968, "text": "Blogathon-2021" }, { "code": null, "e": 4998, "s": 4983, "text": "c-input-output" }, { "code": null, "e": 5008, "s": 4998, "text": "Blogathon" }, { "code": null, "e": 5019, "s": 5008, "text": "C Language" }, { "code": null, "e": 5027, "s": 5019, "text": "Strings" }, { "code": null, "e": 5035, "s": 5027, "text": "Strings" }, { "code": null, "e": 5133, "s": 5035, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5174, "s": 5133, "text": "How to Connect Python with SQL Database?" }, { "code": null, "e": 5215, "s": 5174, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 5246, "s": 5215, "text": "Data Mining - Cluster Analysis" }, { "code": null, "e": 5289, "s": 5246, "text": "Explain the purpose of render() in ReactJS" }, { "code": null, "e": 5346, "s": 5289, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 5369, "s": 5346, "text": "std::sort() in C++ STL" }, { "code": null, "e": 5396, "s": 5369, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 5412, "s": 5396, "text": "Arrays in C/C++" }, { "code": null, "e": 5429, "s": 5412, "text": "Substring in C++" } ]
Minimize modulo operations to make given Array a permutation of [1, N]
15 Feb, 2022 Given an array arr[] of size N, the task is to find the minimum number of operations required to make the array a permutation of numbers in range [1, N] where, in each operation, an element at any index i can be replaced by arr[i]%k (k = any value greater than 0). Return -1 if the array cannot be made a permutation of numbers in range [1, N]. Examples: Input: arr [] = {1, 7}, N = 2Output: 1Explanation: The only possible sequence of operations which minimizes the no of operations isChoose i = 1, k = 5. Perform arr[1] = arr[1] % 5 = 2. Input: arr [] = {1,5,4}, N = 3Output: -1Explanation: It is impossible to obtain a permutation of integers from 1 to N. Approach: The problem can be solved on the basis of the following observation. x % y < (x/2) if x ≥ y, andx % y = x if x < y. As bigger is x, the longer the range of values that can be obtained after one mod operation. So try to, assign smaller arr[i] to smaller numbers in the resulting permutation. Although, if arr[i] satisfies 1 ≤ arr[i] ≤ N, just leave it there and use it in the resulting permutation.if multiple arr[i] satisfy the same condition and have the same value, just choose one. Let’s suppose in the optimal solution, l is changed to m and n to l for some n > l > m (l, m, n are values, not indices). Then keeping l intact and changing n to m uses 1 less operation. And, if it is possible to change n to l, then it must be possible to change n to m. Follow the steps mentioned below to implement the approach: Sort the array. If 1 ≤ arr[i] ≤ N and it is the first occurrence of the element with value arr[i], leave it there. Else, let the current least unassigned value in the resulting permutation be x:If x < arr[i]/2, assign the current element to value x and add the number of operations by 1.Else, output −1 directly. If x < arr[i]/2, assign the current element to value x and add the number of operations by 1. Else, output −1 directly. Below is the implementation of the above approach. C++ Java C# Python3 Javascript // C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Function to find minimum operations// used to make permutation of 1 to Nvoid minoperation(vector<int> arr, int N){ set<int> st; vector<int> rem; // Storing one instance of every element // from 1 to N for (int i = 1; i <= N; i++) { st.insert(i); } for (int i = 0; i < N; i++) { if (st.find(arr[i]) != st.end()) st.erase(arr[i]); else rem.push_back(arr[i]); } // Sorting in descending order sort(rem.begin(), rem.end()); reverse(rem.begin(), rem.end()); int pt = 0; bool flag = false; for (auto& x : rem) { auto it = st.end(); it--; int p = (*it); if (p > (x - 1) / 2) { flag = true; break; } st.erase(it); } if (flag) { // Not possible to make permutation. cout << "-1"; } else { // Minimum number of operation required. cout << rem.size(); }} // Driver codeint main(){ int N = 3; vector<int> arr = { 1, 5, 4 }; minoperation(arr, N); return 0;} // Java code to implement above approachimport java.util.*;class GFG{ // Function to find minimum operations // used to make permutation of 1 to N static void minoperation(int[] arr, int N) { HashSet<Integer> st = new HashSet<Integer>(); Vector<Integer> rem = new Vector<Integer>(); // Storing one instance of every element // from 1 to N for (int i = 1; i <= N; i++) { st.add(i); } for (int i = 0; i < N; i++) { if (st.contains(arr[i])) st.remove(arr[i]); else rem.add(arr[i]); } // Sorting in descending order Collections.sort(rem,Collections.reverseOrder()); boolean flag = false; for (int x : rem) { int it = st.size(); it--; int p = new ArrayList<>(st).get(it); if (p > (x - 1) / 2) { flag = true; break; } st.remove(it); } if (flag) { // Not possible to make permutation. System.out.print("-1"); } else { // Minimum number of operation required. System.out.print(rem.size()); } } // Driver code public static void main(String[] args) { int N = 3; int[] arr = { 1, 5, 4 }; minoperation(arr, N); }} // This code is contributed by 29AjayKumar // C# code to implement above approachusing System;using System.Collections.Generic;class GFG{ // Function to find minimum operations // used to make permutation of 1 to N static void minoperation(int[] arr, int N) { HashSet<int> st = new HashSet<int>(); List<int> rem = new List<int>(); // Storing one instance of every element // from 1 to N for (int i = 1; i <= N; i++) { st.Add(i); } for (int i = 0; i < N; i++) { if (st.Contains(arr[i])) st.Remove(arr[i]); else rem.Add(arr[i]); } // Sorting in descending order rem.Sort(); rem.Reverse(); bool flag = false; foreach (int x in rem) { int it = st.Count; it--; int p = new List<int>(st)[it]; if (p > (x - 1) / 2) { flag = true; break; } st.Remove(it); } if (flag) { // Not possible to make permutation. Console.Write("-1"); } else { // Minimum number of operation required. Console.Write(rem.Count); } } // Driver code public static void Main() { int N = 3; int[] arr = { 1, 5, 4 }; minoperation(arr, N); }} // This code is contributed by Saurabh jaiswal # Python 3 code to implement above approach # Function to find minimum operations# used to make permutation of 1 to Ndef minoperation(arr, N): st = set([]) rem = [] # Storing one instance of every element # from 1 to N for i in range(1, N + 1): st.add(i) for i in range(N): if (arr[i] in st): st.remove(arr[i]) else: rem.append(arr[i]) # Sorting in descending order rem.sort() rem.reverse() pt = 0 flag = False for x in rem: it = len(st) it -= 1 p = list(st)[it] if (p > (x - 1) / 2): flag = True break st.remove(it) if (flag): # Not possible to make permutation. print("-1") else: # Minimum number of operation required. print(len(rem)) # Driver codeif __name__ == "__main__": N = 3 arr = [1, 5, 4] minoperation(arr, N) # This code is contributed by ukasp. <script> // JavaScript code for the above approach // Function to find minimum operations // used to make permutation of 1 to N function minoperation(arr, N) { let st = new Set(); let rem = []; // Storing one instance of every element // from 1 to N for (let i = 1; i <= N; i++) { st.add(i); } for (let i = 0; i < N; i++) { if (st.has(arr[i])) st.delete(arr[i]); else rem.push(arr[i]); } // Sorting in descending order rem.sort(function (a, b) { return b - a }) rem.reverse(); let pt = 0; let flag = false; for (let x of rem) { let it = [...st].pop(); let p = (it); if (p > Math.floor((x - 1) / 2)) { flag = true; break; } st.delete(it); } if (flag) { // Not possible to make permutation. document.write(-1) } else { // Minimum number of operation required. document.write(rem.size) } } // Driver code let N = 3; let arr = [1, 5, 4]; minoperation(arr, N); // This code is contributed by Potta Lokesh </script> -1 Time Complexity: O(N * logN)Auxiliary Space: O(N) lokeshpotta20 ukasp 29AjayKumar _saurabh_jaiswal germanshephered48 Binary Search Arrays Greedy Sorting Arrays Greedy Sorting Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Subset Sum Problem | DP-25 Introduction to Data Structures Python | Using 2D arrays/lists the right way Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Write a program to print all permutations of a given string Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Feb, 2022" }, { "code": null, "e": 373, "s": 28, "text": "Given an array arr[] of size N, the task is to find the minimum number of operations required to make the array a permutation of numbers in range [1, N] where, in each operation, an element at any index i can be replaced by arr[i]%k (k = any value greater than 0). Return -1 if the array cannot be made a permutation of numbers in range [1, N]." }, { "code": null, "e": 383, "s": 373, "text": "Examples:" }, { "code": null, "e": 569, "s": 383, "text": "Input: arr [] = {1, 7}, N = 2Output: 1Explanation: The only possible sequence of operations which minimizes the no of operations isChoose i = 1, k = 5. Perform arr[1] = arr[1] % 5 = 2. " }, { "code": null, "e": 688, "s": 569, "text": "Input: arr [] = {1,5,4}, N = 3Output: -1Explanation: It is impossible to obtain a permutation of integers from 1 to N." }, { "code": null, "e": 767, "s": 688, "text": "Approach: The problem can be solved on the basis of the following observation." }, { "code": null, "e": 815, "s": 767, "text": "x % y < (x/2) if x ≥ y, andx % y = x if x < y." }, { "code": null, "e": 990, "s": 815, "text": "As bigger is x, the longer the range of values that can be obtained after one mod operation. So try to, assign smaller arr[i] to smaller numbers in the resulting permutation." }, { "code": null, "e": 1455, "s": 990, "text": "Although, if arr[i] satisfies 1 ≤ arr[i] ≤ N, just leave it there and use it in the resulting permutation.if multiple arr[i] satisfy the same condition and have the same value, just choose one. Let’s suppose in the optimal solution, l is changed to m and n to l for some n > l > m (l, m, n are values, not indices). Then keeping l intact and changing n to m uses 1 less operation. And, if it is possible to change n to l, then it must be possible to change n to m." }, { "code": null, "e": 1515, "s": 1455, "text": "Follow the steps mentioned below to implement the approach:" }, { "code": null, "e": 1531, "s": 1515, "text": "Sort the array." }, { "code": null, "e": 1630, "s": 1531, "text": "If 1 ≤ arr[i] ≤ N and it is the first occurrence of the element with value arr[i], leave it there." }, { "code": null, "e": 1828, "s": 1630, "text": "Else, let the current least unassigned value in the resulting permutation be x:If x < arr[i]/2, assign the current element to value x and add the number of operations by 1.Else, output −1 directly." }, { "code": null, "e": 1922, "s": 1828, "text": "If x < arr[i]/2, assign the current element to value x and add the number of operations by 1." }, { "code": null, "e": 1948, "s": 1922, "text": "Else, output −1 directly." }, { "code": null, "e": 1999, "s": 1948, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 2003, "s": 1999, "text": "C++" }, { "code": null, "e": 2008, "s": 2003, "text": "Java" }, { "code": null, "e": 2011, "s": 2008, "text": "C#" }, { "code": null, "e": 2019, "s": 2011, "text": "Python3" }, { "code": null, "e": 2030, "s": 2019, "text": "Javascript" }, { "code": "// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Function to find minimum operations// used to make permutation of 1 to Nvoid minoperation(vector<int> arr, int N){ set<int> st; vector<int> rem; // Storing one instance of every element // from 1 to N for (int i = 1; i <= N; i++) { st.insert(i); } for (int i = 0; i < N; i++) { if (st.find(arr[i]) != st.end()) st.erase(arr[i]); else rem.push_back(arr[i]); } // Sorting in descending order sort(rem.begin(), rem.end()); reverse(rem.begin(), rem.end()); int pt = 0; bool flag = false; for (auto& x : rem) { auto it = st.end(); it--; int p = (*it); if (p > (x - 1) / 2) { flag = true; break; } st.erase(it); } if (flag) { // Not possible to make permutation. cout << \"-1\"; } else { // Minimum number of operation required. cout << rem.size(); }} // Driver codeint main(){ int N = 3; vector<int> arr = { 1, 5, 4 }; minoperation(arr, N); return 0;}", "e": 3180, "s": 2030, "text": null }, { "code": "// Java code to implement above approachimport java.util.*;class GFG{ // Function to find minimum operations // used to make permutation of 1 to N static void minoperation(int[] arr, int N) { HashSet<Integer> st = new HashSet<Integer>(); Vector<Integer> rem = new Vector<Integer>(); // Storing one instance of every element // from 1 to N for (int i = 1; i <= N; i++) { st.add(i); } for (int i = 0; i < N; i++) { if (st.contains(arr[i])) st.remove(arr[i]); else rem.add(arr[i]); } // Sorting in descending order Collections.sort(rem,Collections.reverseOrder()); boolean flag = false; for (int x : rem) { int it = st.size(); it--; int p = new ArrayList<>(st).get(it); if (p > (x - 1) / 2) { flag = true; break; } st.remove(it); } if (flag) { // Not possible to make permutation. System.out.print(\"-1\"); } else { // Minimum number of operation required. System.out.print(rem.size()); } } // Driver code public static void main(String[] args) { int N = 3; int[] arr = { 1, 5, 4 }; minoperation(arr, N); }} // This code is contributed by 29AjayKumar", "e": 4396, "s": 3180, "text": null }, { "code": "// C# code to implement above approachusing System;using System.Collections.Generic;class GFG{ // Function to find minimum operations // used to make permutation of 1 to N static void minoperation(int[] arr, int N) { HashSet<int> st = new HashSet<int>(); List<int> rem = new List<int>(); // Storing one instance of every element // from 1 to N for (int i = 1; i <= N; i++) { st.Add(i); } for (int i = 0; i < N; i++) { if (st.Contains(arr[i])) st.Remove(arr[i]); else rem.Add(arr[i]); } // Sorting in descending order rem.Sort(); rem.Reverse(); bool flag = false; foreach (int x in rem) { int it = st.Count; it--; int p = new List<int>(st)[it]; if (p > (x - 1) / 2) { flag = true; break; } st.Remove(it); } if (flag) { // Not possible to make permutation. Console.Write(\"-1\"); } else { // Minimum number of operation required. Console.Write(rem.Count); } } // Driver code public static void Main() { int N = 3; int[] arr = { 1, 5, 4 }; minoperation(arr, N); }} // This code is contributed by Saurabh jaiswal", "e": 5610, "s": 4396, "text": null }, { "code": "# Python 3 code to implement above approach # Function to find minimum operations# used to make permutation of 1 to Ndef minoperation(arr, N): st = set([]) rem = [] # Storing one instance of every element # from 1 to N for i in range(1, N + 1): st.add(i) for i in range(N): if (arr[i] in st): st.remove(arr[i]) else: rem.append(arr[i]) # Sorting in descending order rem.sort() rem.reverse() pt = 0 flag = False for x in rem: it = len(st) it -= 1 p = list(st)[it] if (p > (x - 1) / 2): flag = True break st.remove(it) if (flag): # Not possible to make permutation. print(\"-1\") else: # Minimum number of operation required. print(len(rem)) # Driver codeif __name__ == \"__main__\": N = 3 arr = [1, 5, 4] minoperation(arr, N) # This code is contributed by ukasp.", "e": 6561, "s": 5610, "text": null }, { "code": "<script> // JavaScript code for the above approach // Function to find minimum operations // used to make permutation of 1 to N function minoperation(arr, N) { let st = new Set(); let rem = []; // Storing one instance of every element // from 1 to N for (let i = 1; i <= N; i++) { st.add(i); } for (let i = 0; i < N; i++) { if (st.has(arr[i])) st.delete(arr[i]); else rem.push(arr[i]); } // Sorting in descending order rem.sort(function (a, b) { return b - a }) rem.reverse(); let pt = 0; let flag = false; for (let x of rem) { let it = [...st].pop(); let p = (it); if (p > Math.floor((x - 1) / 2)) { flag = true; break; } st.delete(it); } if (flag) { // Not possible to make permutation. document.write(-1) } else { // Minimum number of operation required. document.write(rem.size) } } // Driver code let N = 3; let arr = [1, 5, 4]; minoperation(arr, N); // This code is contributed by Potta Lokesh </script>", "e": 8044, "s": 6561, "text": null }, { "code": null, "e": 8050, "s": 8047, "text": "-1" }, { "code": null, "e": 8102, "s": 8052, "text": "Time Complexity: O(N * logN)Auxiliary Space: O(N)" }, { "code": null, "e": 8118, "s": 8104, "text": "lokeshpotta20" }, { "code": null, "e": 8124, "s": 8118, "text": "ukasp" }, { "code": null, "e": 8136, "s": 8124, "text": "29AjayKumar" }, { "code": null, "e": 8153, "s": 8136, "text": "_saurabh_jaiswal" }, { "code": null, "e": 8171, "s": 8153, "text": "germanshephered48" }, { "code": null, "e": 8185, "s": 8171, "text": "Binary Search" }, { "code": null, "e": 8192, "s": 8185, "text": "Arrays" }, { "code": null, "e": 8199, "s": 8192, "text": "Greedy" }, { "code": null, "e": 8207, "s": 8199, "text": "Sorting" }, { "code": null, "e": 8214, "s": 8207, "text": "Arrays" }, { "code": null, "e": 8221, "s": 8214, "text": "Greedy" }, { "code": null, "e": 8229, "s": 8221, "text": "Sorting" }, { "code": null, "e": 8243, "s": 8229, "text": "Binary Search" }, { "code": null, "e": 8341, "s": 8243, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8364, "s": 8341, "text": "Introduction to Arrays" }, { "code": null, "e": 8420, "s": 8364, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 8447, "s": 8420, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 8479, "s": 8447, "text": "Introduction to Data Structures" }, { "code": null, "e": 8524, "s": 8479, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 8575, "s": 8524, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 8626, "s": 8575, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 8686, "s": 8626, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 8744, "s": 8686, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" } ]
Java - String concat() Method
This method appends one String to the end of another. The method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method. Here is the syntax of this method − public String concat(String s) Here is the detail of parameters − s − the String that is concatenated to the end of this String. s − the String that is concatenated to the end of this String. This methods returns a string that represents the concatenation of this object's characters followed by the string argument's characters. This methods returns a string that represents the concatenation of this object's characters followed by the string argument's characters. public class Test { public static void main(String args[]) { String s = "Strings are immutable"; s = s.concat(" all the time"); System.out.println(s); } } This will produce the following result − Strings are immutable all the time
[ { "code": null, "e": 2709, "s": 2511, "text": "This method appends one String to the end of another. The method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method." }, { "code": null, "e": 2745, "s": 2709, "text": "Here is the syntax of this method −" }, { "code": null, "e": 2777, "s": 2745, "text": "public String concat(String s)\n" }, { "code": null, "e": 2812, "s": 2777, "text": "Here is the detail of parameters −" }, { "code": null, "e": 2875, "s": 2812, "text": "s − the String that is concatenated to the end of this String." }, { "code": null, "e": 2938, "s": 2875, "text": "s − the String that is concatenated to the end of this String." }, { "code": null, "e": 3076, "s": 2938, "text": "This methods returns a string that represents the concatenation of this object's characters followed by the string argument's characters." }, { "code": null, "e": 3214, "s": 3076, "text": "This methods returns a string that represents the concatenation of this object's characters followed by the string argument's characters." }, { "code": null, "e": 3394, "s": 3214, "text": "public class Test {\n\n public static void main(String args[]) {\n String s = \"Strings are immutable\";\n s = s.concat(\" all the time\");\n System.out.println(s);\n }\n}" }, { "code": null, "e": 3435, "s": 3394, "text": "This will produce the following result −" } ]
Database Connectivity using C/C++
In this section, you will learn how to use SQLite in C/C++ programs. Before you start using SQLite in our C/C++ programs, you need to make sure that you have SQLite library set up on the machine. You can check the SQLite Installation chapter to understand the installation process. Following are important C/C++ SQLite interface routines, which can suffice your requirement to work with SQLite database from your C/C++ program. If you are looking for a more sophisticated application, then you can look into SQLite official documentation. sqlite3_open(const char *filename, sqlite3 **ppDb) sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char **errmsg) sqlite3_close(sqlite3*) Following C code segment shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned. #include <stdio.h> #include <sqlite3.h> int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stderr, "Opened database successfully\n"); } sqlite3_close(db); } $gcc test.c -l sqlite3 $./a.out Opened database successfully Following C code segment will be used to create a table in the previously created database − #include <stdio.h> #include <stdlib.h> #include <sqlite3.h> static int callback(void *NotUsed, int argc, char **argv, char **azColName) { int i; for(i = 0; i<argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stdout, "Opened database successfully\n"); } /* Create SQL statement */ sql = "CREATE TABLE COMPANY(" \ "ID INT PRIMARY KEY NOT NULL," \ "NAME TEXT NOT NULL," \ "AGE INT NOT NULL," \ "ADDRESS CHAR(50)," \ "SALARY REAL );"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); if( rc != SQLITE_OK ) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Table created successfully\n"); } sqlite3_close(db); return 0; } -rwxr-xr-x. 1 root root 9567 May 8 02:31 a.out -rw-r--r--. 1 root root 1207 May 8 02:31 test.c -rw-r--r--. 1 root root 3072 May 8 02:31 test.db Following C code segment shows how you can create records in COMPANY table created in the above example – #include <stdio.h> #include <stdlib.h> #include <sqlite3.h> static int callback(void *NotUsed, int argc, char **argv, char **azColName) { int i; for(i = 0; i<argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stderr, "Opened database successfully\n"); } /* Create SQL statement */ sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " \ "VALUES (1, 'Paul', 32, 'California', 20000.00 ); " \ "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " \ "VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); " \ "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \ "VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );" \ "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \ "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); if( rc != SQLITE_OK ) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Records created successfully\n"); } sqlite3_close(db); return 0; } Opened database successfully Records created successfully Before proceeding with actual example to fetch records, let us look at some detail about the callback function, which we are using in our examples. This callback provides a way to obtain results from SELECT statements. It has the following declaration – typedef int (*sqlite3_callback)( void*, /* Data provided in the 4th argument of sqlite3_exec() */ int, /* The number of columns in row */ char**, /* An array of strings representing fields in the row */ char** /* An array of strings representing column names */ ); If the above callback is provided in sqlite_exec() routine as the third argument, SQLite will call this callback function for each record processed in each SELECT statement executed within the SQL argument. Following C code segment shows how you can fetch and display records from the COMPANY table created in the above example – #include <stdio.h> #include <stdlib.h> #include <sqlite3.h> static int callback(void *data, int argc, char **argv, char **azColName) { int i; fprintf(stderr, "%s: ", (const char*)data); for(i = 0; i<argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; const char* data = "Callback function called"; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stderr, "Opened database successfully\n"); } /* Create SQL statement */ sql = "SELECT * from COMPANY"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Operation done successfully\n"); } sqlite3_close(db); return 0; } Opened database successfully Callback function called: ID = 1 NAME = Paul AGE = 32 ADDRESS = California SALARY = 20000.0 Callback function called: ID = 2 NAME = Allen AGE = 25 ADDRESS = Texas SALARY = 15000.0 Callback function called: ID = 3 NAME = Teddy AGE = 23 ADDRESS = Norway SALARY = 20000.0 Callback function called: ID = 4 NAME = Mark AGE = 25 ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully
[ { "code": null, "e": 1256, "s": 1187, "text": "In this section, you will learn how to use SQLite in C/C++ programs." }, { "code": null, "e": 1469, "s": 1256, "text": "Before you start using SQLite in our C/C++ programs, you need to make sure that you have SQLite library set up on the machine. You can check the SQLite Installation chapter to understand the installation process." }, { "code": null, "e": 1726, "s": 1469, "text": "Following are important C/C++ SQLite interface routines, which can suffice your requirement to work with SQLite database from your C/C++ program. If you are looking for a more sophisticated application, then you can look into SQLite official documentation." }, { "code": null, "e": 1777, "s": 1726, "text": "sqlite3_open(const char *filename, sqlite3 **ppDb)" }, { "code": null, "e": 1861, "s": 1777, "text": "sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char **errmsg)" }, { "code": null, "e": 1885, "s": 1861, "text": "sqlite3_close(sqlite3*)" }, { "code": null, "e": 2060, "s": 1885, "text": "Following C code segment shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned." }, { "code": null, "e": 2423, "s": 2060, "text": "#include <stdio.h>\n#include <sqlite3.h>\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n rc = sqlite3_open(\"test.db\", &db);\n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stderr, \"Opened database successfully\\n\");\n }\n sqlite3_close(db);\n}" }, { "code": null, "e": 2484, "s": 2423, "text": "$gcc test.c -l sqlite3\n$./a.out\nOpened database successfully" }, { "code": null, "e": 2577, "s": 2484, "text": "Following C code segment will be used to create a table in the previously created database −" }, { "code": null, "e": 3711, "s": 2577, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h>\nstatic int callback(void *NotUsed, int argc, char **argv, char **azColName) {\n int i;\n for(i = 0; i<argc; i++) {\n printf(\"%s = %s\\n\", azColName[i], argv[i] ? argv[i] : \"NULL\");\n }\n printf(\"\\n\");\n return 0;\n}\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n char *sql;\n /* Open database */\n rc = sqlite3_open(\"test.db\", &db);\n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stdout, \"Opened database successfully\\n\");\n }\n /* Create SQL statement */\n sql = \"CREATE TABLE COMPANY(\" \\\n \"ID INT PRIMARY KEY NOT NULL,\" \\\n \"NAME TEXT NOT NULL,\" \\\n \"AGE INT NOT NULL,\" \\\n \"ADDRESS CHAR(50),\" \\\n \"SALARY REAL );\";\n /* Execute SQL statement */\n rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);\n if( rc != SQLITE_OK ) {\n fprintf(stderr, \"SQL error: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n } else {\n fprintf(stdout, \"Table created successfully\\n\");\n }\n sqlite3_close(db);\n return 0;\n}" }, { "code": null, "e": 3855, "s": 3711, "text": "-rwxr-xr-x. 1 root root 9567 May 8 02:31 a.out\n-rw-r--r--. 1 root root 1207 May 8 02:31 test.c\n-rw-r--r--. 1 root root 3072 May 8 02:31 test.db" }, { "code": null, "e": 3961, "s": 3855, "text": "Following C code segment shows how you can create records in COMPANY table created in the above example –" }, { "code": null, "e": 5384, "s": 3961, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h>\nstatic int callback(void *NotUsed, int argc, char **argv, char **azColName) {\n int i;\n for(i = 0; i<argc; i++) {\n printf(\"%s = %s\\n\", azColName[i], argv[i] ? argv[i] : \"NULL\");\n }\n printf(\"\\n\");\n return 0;\n}\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n char *sql;\n /* Open database */\n rc = sqlite3_open(\"test.db\", &db);\n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stderr, \"Opened database successfully\\n\");\n }\n /* Create SQL statement */\n sql = \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \" \\\n \"VALUES (1, 'Paul', 32, 'California', 20000.00 ); \" \\\n \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \" \\\n \"VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); \" \\\n \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\" \\\n \"VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );\" \\\n \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\" \\\n \"VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );\";\n /* Execute SQL statement */\n rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);\n if( rc != SQLITE_OK ) {\n fprintf(stderr, \"SQL error: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n } else {\n fprintf(stdout, \"Records created successfully\\n\");\n }\n sqlite3_close(db);\n return 0;\n}" }, { "code": null, "e": 5442, "s": 5384, "text": "Opened database successfully\nRecords created successfully" }, { "code": null, "e": 5696, "s": 5442, "text": "Before proceeding with actual example to fetch records, let us look at some detail about the callback function, which we are using in our examples. This callback provides a way to obtain results from SELECT statements. It has the following declaration –" }, { "code": null, "e": 5973, "s": 5696, "text": "typedef int (*sqlite3_callback)(\n void*, /* Data provided in the 4th argument of sqlite3_exec() */\n int, /* The number of columns in row */\n char**, /* An array of strings representing fields in the row */\n char** /* An array of strings representing column names */\n);" }, { "code": null, "e": 6180, "s": 5973, "text": "If the above callback is provided in sqlite_exec() routine as the third argument, SQLite will call this callback function for each record processed in each SELECT statement executed within the SQL argument." }, { "code": null, "e": 6303, "s": 6180, "text": "Following C code segment shows how you can fetch and display records from the COMPANY table created in the above example –" }, { "code": null, "e": 7392, "s": 6303, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h>\nstatic int callback(void *data, int argc, char **argv, char **azColName) {\n int i;\n fprintf(stderr, \"%s: \", (const char*)data);\n for(i = 0; i<argc; i++) {\n printf(\"%s = %s\\n\", azColName[i], argv[i] ? argv[i] : \"NULL\");\n }\n printf(\"\\n\");\n return 0;\n}\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n char *sql;\n const char* data = \"Callback function called\";\n /* Open database */\n rc = sqlite3_open(\"test.db\", &db);\n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stderr, \"Opened database successfully\\n\");\n }\n /* Create SQL statement */\n sql = \"SELECT * from COMPANY\";\n /* Execute SQL statement */\n rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);\n if( rc != SQLITE_OK ) {\n fprintf(stderr, \"SQL error: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n } else {\n fprintf(stdout, \"Operation done successfully\\n\");\n }\n sqlite3_close(db);\n return 0;\n}" }, { "code": null, "e": 7809, "s": 7392, "text": "Opened database successfully\nCallback function called: ID = 1\nNAME = Paul\nAGE = 32\nADDRESS = California\nSALARY = 20000.0\nCallback function called: ID = 2\nNAME = Allen\nAGE = 25\nADDRESS = Texas\nSALARY = 15000.0\nCallback function called: ID = 3\nNAME = Teddy\nAGE = 23\nADDRESS = Norway\nSALARY = 20000.0\nCallback function called: ID = 4\nNAME = Mark\nAGE = 25\nADDRESS = Rich-Mond\nSALARY = 65000.0\nOperation done successfully" } ]
Python – os.pardir() method with example
18 May, 2020 In Python, OS module provides various functions to interact with the operating system. This module comes under the Python standard utility module, so there is no need to install it manually. os.pardir is a constant string used by the operating system to refer to the parent directory. This method is also available via os.path.pardir() Note: os.pardir is ‘.. for UNIX based OS and ‘::‘ for Mac OS. Syntax: os.pardir Return type: a string that refers to the parent directory. # Python program to demonstrate# os.pardir import os # prints .. by defaultprint(os.pardir) Output: .. Example 2: Let’s print the parent of current working directory. # Python program to demonstrate# os.pardir import os # current working directorypath = os.getcwd()print("Current Directory:", path) # parent directoryparent = os.path.join(path, os.pardir) # prints parent directoryprint("\nParent Directory:", os.path.abspath(parent)) Output: Current Directory: /home/geeks/Desktop/gfg Parent Directory: /home/geeks/Desktop Example 3: Getting the parent of specified path. # Python program to demonstrate# os.pardir import os # pathpath = "your/path/for/parent/directory"print("Path:", path) # parentparent = os.path.join(path, os.pardir) # prints the relative file path # for the current directory (parent)print("\nParent:", os.path.relpath(parent)) Output: Path: your/path/for/parent/directory Parent: your/path/for/parent nishkarsh146 Python directory-program python-os-module Python Python Programs 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() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n18 May, 2020" }, { "code": null, "e": 219, "s": 28, "text": "In Python, OS module provides various functions to interact with the operating system. This module comes under the Python standard utility module, so there is no need to install it manually." }, { "code": null, "e": 364, "s": 219, "text": "os.pardir is a constant string used by the operating system to refer to the parent directory. This method is also available via os.path.pardir()" }, { "code": null, "e": 426, "s": 364, "text": "Note: os.pardir is ‘.. for UNIX based OS and ‘::‘ for Mac OS." }, { "code": null, "e": 444, "s": 426, "text": "Syntax: os.pardir" }, { "code": null, "e": 503, "s": 444, "text": "Return type: a string that refers to the parent directory." }, { "code": "# Python program to demonstrate# os.pardir import os # prints .. by defaultprint(os.pardir)", "e": 597, "s": 503, "text": null }, { "code": null, "e": 605, "s": 597, "text": "Output:" }, { "code": null, "e": 609, "s": 605, "text": "..\n" }, { "code": null, "e": 674, "s": 609, "text": " Example 2: Let’s print the parent of current working directory." }, { "code": "# Python program to demonstrate# os.pardir import os # current working directorypath = os.getcwd()print(\"Current Directory:\", path) # parent directoryparent = os.path.join(path, os.pardir) # prints parent directoryprint(\"\\nParent Directory:\", os.path.abspath(parent))", "e": 950, "s": 674, "text": null }, { "code": null, "e": 958, "s": 950, "text": "Output:" }, { "code": null, "e": 1041, "s": 958, "text": "Current Directory: /home/geeks/Desktop/gfg\n\nParent Directory: /home/geeks/Desktop\n" }, { "code": null, "e": 1091, "s": 1041, "text": " Example 3: Getting the parent of specified path." }, { "code": "# Python program to demonstrate# os.pardir import os # pathpath = \"your/path/for/parent/directory\"print(\"Path:\", path) # parentparent = os.path.join(path, os.pardir) # prints the relative file path # for the current directory (parent)print(\"\\nParent:\", os.path.relpath(parent))", "e": 1377, "s": 1091, "text": null }, { "code": null, "e": 1385, "s": 1377, "text": "Output:" }, { "code": null, "e": 1453, "s": 1385, "text": "Path: your/path/for/parent/directory\n\nParent: your/path/for/parent\n" }, { "code": null, "e": 1466, "s": 1453, "text": "nishkarsh146" }, { "code": null, "e": 1491, "s": 1466, "text": "Python directory-program" }, { "code": null, "e": 1508, "s": 1491, "text": "python-os-module" }, { "code": null, "e": 1515, "s": 1508, "text": "Python" }, { "code": null, "e": 1531, "s": 1515, "text": "Python Programs" }, { "code": null, "e": 1629, "s": 1531, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1647, "s": 1629, "text": "Python Dictionary" }, { "code": null, "e": 1689, "s": 1647, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1711, "s": 1689, "text": "Enumerate() in Python" }, { "code": null, "e": 1746, "s": 1711, "text": "Read a file line by line in Python" }, { "code": null, "e": 1772, "s": 1746, "text": "Python String | replace()" }, { "code": null, "e": 1815, "s": 1772, "text": "Python program to convert a list to string" }, { "code": null, "e": 1837, "s": 1815, "text": "Defaultdict in Python" }, { "code": null, "e": 1876, "s": 1837, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1914, "s": 1876, "text": "Python | Convert a list to dictionary" } ]
Java Program to Search for a File in a Directory
21 Oct, 2020 Searching files in Java can be performed using the File class and FilenameFilter interface. The FilenameFilter interface is used to filter files from the list of files. This interface has a method boolean accept(File dir, String name) that is implemented to find the desired files from the list returned by the java.io.File.list() method. This method is very useful when we want to find files with a specific extension within a folder. First Approach Create a class MyFilenameFilter which implements the FilenameFilter interface and overrides the accept() method of FilenameFilter interface.The accept() method takes two arguments of which the first one is the directory name and the second one is the filename.The accept() method returns true if the filename starts with the specified initials else returns false.The class FindFile contains the main method which accepts the user input like the desired directory to search and the initials of the file to search.The directory object of File class is initiated with the director name and the filter object of MyFilenameFilter class is initiated with the initials provided by the user.The list() method is invoked on the dir object which returns an array of files that satisfy the condition.The array is iterated over and the name of the required files are printed to the output screen. Create a class MyFilenameFilter which implements the FilenameFilter interface and overrides the accept() method of FilenameFilter interface. The accept() method takes two arguments of which the first one is the directory name and the second one is the filename. The accept() method returns true if the filename starts with the specified initials else returns false. The class FindFile contains the main method which accepts the user input like the desired directory to search and the initials of the file to search. The directory object of File class is initiated with the director name and the filter object of MyFilenameFilter class is initiated with the initials provided by the user. The list() method is invoked on the dir object which returns an array of files that satisfy the condition. The array is iterated over and the name of the required files are printed to the output screen. Code Implementation Java // Java Program to Search for a File in a Directoryimport java.io.*; // MyFilenameFilter class implements FilenameFilter// interfaceclass MyFilenameFilter implements FilenameFilter { String initials; // constructor to initialize object public MyFilenameFilter(String initials) { this.initials = initials; } // overriding the accept method of FilenameFilter // interface public boolean accept(File dir, String name) { return name.startsWith(initials); }} public class Main { public static void main(String[] args) { // Create an object of the File class // Replace the file path with path of the directory File directory = new File("/home/user/"); // Create an object of Class MyFilenameFilter // Constructor with name of file which is being // searched MyFilenameFilter filter = new MyFilenameFilter("file.cpp"); // store all names with same name // with/without extension String[] flist = directory.list(filter); // Empty array if (flist == null) { System.out.println( "Empty directory or directory does not exists."); } else { // Print all files with same name in directory // as provided in object of MyFilenameFilter // class for (int i = 0; i < flist.length; i++) { System.out.println(flist[i]+" found"); } } }} Output file.cpp found Second Approach The list() method is called on the dir object of the File class and the list of files in the ‘flist’ array.Each file in the ‘flist’ array is checked against the required filename.If a match is found it is printed on the screen. The list() method is called on the dir object of the File class and the list of files in the ‘flist’ array. Each file in the ‘flist’ array is checked against the required filename. If a match is found it is printed on the screen. This method is a bit different from the previous one as the user needs to specify the exact name of the file in this case. Code Implementation Java // Java Program to Search for a File in a Directoryimport java.io.File; public class Main { public static void main(String[] argv) throws Exception { // Create an object of the File class // Replace the file path with path of the directory File directory = new File("/home/user/"); // store all names with same name // with/without extension String[] flist = directory.list(); int flag = 0; if (flist == null) { System.out.println("Empty directory."); } else { // Linear search in the array for (int i = 0; i < flist.length; i++) { String filename = flist[i]; if (filename.equalsIgnoreCase("file.cpp")) { System.out.println(filename + " found"); flag = 1; } } } if (flag == 0) { System.out.println("File Not Found"); } }} Output file.cpp found Java-File Class Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Oct, 2020" }, { "code": null, "e": 464, "s": 28, "text": "Searching files in Java can be performed using the File class and FilenameFilter interface. The FilenameFilter interface is used to filter files from the list of files. This interface has a method boolean accept(File dir, String name) that is implemented to find the desired files from the list returned by the java.io.File.list() method. This method is very useful when we want to find files with a specific extension within a folder." }, { "code": null, "e": 479, "s": 464, "text": "First Approach" }, { "code": null, "e": 1365, "s": 479, "text": "Create a class MyFilenameFilter which implements the FilenameFilter interface and overrides the accept() method of FilenameFilter interface.The accept() method takes two arguments of which the first one is the directory name and the second one is the filename.The accept() method returns true if the filename starts with the specified initials else returns false.The class FindFile contains the main method which accepts the user input like the desired directory to search and the initials of the file to search.The directory object of File class is initiated with the director name and the filter object of MyFilenameFilter class is initiated with the initials provided by the user.The list() method is invoked on the dir object which returns an array of files that satisfy the condition.The array is iterated over and the name of the required files are printed to the output screen." }, { "code": null, "e": 1506, "s": 1365, "text": "Create a class MyFilenameFilter which implements the FilenameFilter interface and overrides the accept() method of FilenameFilter interface." }, { "code": null, "e": 1627, "s": 1506, "text": "The accept() method takes two arguments of which the first one is the directory name and the second one is the filename." }, { "code": null, "e": 1731, "s": 1627, "text": "The accept() method returns true if the filename starts with the specified initials else returns false." }, { "code": null, "e": 1881, "s": 1731, "text": "The class FindFile contains the main method which accepts the user input like the desired directory to search and the initials of the file to search." }, { "code": null, "e": 2053, "s": 1881, "text": "The directory object of File class is initiated with the director name and the filter object of MyFilenameFilter class is initiated with the initials provided by the user." }, { "code": null, "e": 2161, "s": 2053, "text": "The list() method is invoked on the dir object which returns an array of files that satisfy the condition." }, { "code": null, "e": 2257, "s": 2161, "text": "The array is iterated over and the name of the required files are printed to the output screen." }, { "code": null, "e": 2277, "s": 2257, "text": "Code Implementation" }, { "code": null, "e": 2282, "s": 2277, "text": "Java" }, { "code": "// Java Program to Search for a File in a Directoryimport java.io.*; // MyFilenameFilter class implements FilenameFilter// interfaceclass MyFilenameFilter implements FilenameFilter { String initials; // constructor to initialize object public MyFilenameFilter(String initials) { this.initials = initials; } // overriding the accept method of FilenameFilter // interface public boolean accept(File dir, String name) { return name.startsWith(initials); }} public class Main { public static void main(String[] args) { // Create an object of the File class // Replace the file path with path of the directory File directory = new File(\"/home/user/\"); // Create an object of Class MyFilenameFilter // Constructor with name of file which is being // searched MyFilenameFilter filter = new MyFilenameFilter(\"file.cpp\"); // store all names with same name // with/without extension String[] flist = directory.list(filter); // Empty array if (flist == null) { System.out.println( \"Empty directory or directory does not exists.\"); } else { // Print all files with same name in directory // as provided in object of MyFilenameFilter // class for (int i = 0; i < flist.length; i++) { System.out.println(flist[i]+\" found\"); } } }}", "e": 3791, "s": 2282, "text": null }, { "code": null, "e": 3800, "s": 3793, "text": "Output" }, { "code": null, "e": 3816, "s": 3800, "text": "file.cpp found\n" }, { "code": null, "e": 3832, "s": 3816, "text": "Second Approach" }, { "code": null, "e": 4060, "s": 3832, "text": "The list() method is called on the dir object of the File class and the list of files in the ‘flist’ array.Each file in the ‘flist’ array is checked against the required filename.If a match is found it is printed on the screen." }, { "code": null, "e": 4168, "s": 4060, "text": "The list() method is called on the dir object of the File class and the list of files in the ‘flist’ array." }, { "code": null, "e": 4241, "s": 4168, "text": "Each file in the ‘flist’ array is checked against the required filename." }, { "code": null, "e": 4290, "s": 4241, "text": "If a match is found it is printed on the screen." }, { "code": null, "e": 4414, "s": 4290, "text": "This method is a bit different from the previous one as the user needs to specify the exact name of the file in this case. " }, { "code": null, "e": 4434, "s": 4414, "text": "Code Implementation" }, { "code": null, "e": 4439, "s": 4434, "text": "Java" }, { "code": "// Java Program to Search for a File in a Directoryimport java.io.File; public class Main { public static void main(String[] argv) throws Exception { // Create an object of the File class // Replace the file path with path of the directory File directory = new File(\"/home/user/\"); // store all names with same name // with/without extension String[] flist = directory.list(); int flag = 0; if (flist == null) { System.out.println(\"Empty directory.\"); } else { // Linear search in the array for (int i = 0; i < flist.length; i++) { String filename = flist[i]; if (filename.equalsIgnoreCase(\"file.cpp\")) { System.out.println(filename + \" found\"); flag = 1; } } } if (flag == 0) { System.out.println(\"File Not Found\"); } }}", "e": 5410, "s": 4439, "text": null }, { "code": null, "e": 5419, "s": 5412, "text": "Output" }, { "code": null, "e": 5435, "s": 5419, "text": "file.cpp found\n" }, { "code": null, "e": 5451, "s": 5435, "text": "Java-File Class" }, { "code": null, "e": 5456, "s": 5451, "text": "Java" }, { "code": null, "e": 5470, "s": 5456, "text": "Java Programs" }, { "code": null, "e": 5475, "s": 5470, "text": "Java" } ]
Docopt module in Python
10 Jul, 2020 Docopt is a command line interface description module. It helps you define a interface for a command-line application and generates parser for it. The interface message in docopt is a formalized help message. You can install docopt module in various ways, pip is one of the best ways to install docopt. $pip install docopt Note: docopt is tested with Python 2.5, 2.6, 2.7, 3.2, 3.3 and PyPy as well. docopt is most commonly used to display the help messages and it is invoked with -h or –help option. You can import and call this module with the following command. from docopt import docopt docopt(doc, argv = None, version = None, help = True, options = False) Parameters of the module is as shown below : doc : It is a docstring (__doc__) that contains the help message. argv : It is an optional argument vector contains list of strings. version : It is an optional argument mentioning the version of the program. help : Responsible for displaying the help message. It is True by default. options_first : This doesn’t allow the mixing of positional arguments and optional arguments. By default it is False. docopt gives you strong control over your help page and it consists of the usage keyword which is case-insensitive that is followed by your program_name. A usage pattern can be described with various elements as mentioned below : usage ='''Usage : program_name.py command --option program_name.py [optional argument] program_name.py --another-option =<argument> program_name.py (--option1 | --option2 ) program_name.py <argument>... ''' < argument > argument : The element starting with “<” and ending with “>” is called a positional argument. It is position sensitive. –option -o: The element starting with “–” or “-” are called as long or short option. It can either be mentioned as --option or -o. -h, --help Display help -o, --option Display options -l, --all List all -q, --quit exit --version Version 3.6.1 [optional argument] : The element starting with “[” and ending with “]” is called an optional argument. It is considered optionally. < argument >... : The ellipsis “...” is used when the element present to the left can be repeated more than once. (required arguments) : The elements starting with “(” and ending with “)” is a required element. (--option1 | --option2) says that either of –option1 or –option2 is required. Example : # filename ='docopt_example.py" usage ='''Usage: docopt_example.py [(<name1>|<name2>)] <name3>... docopt_example.py mov <name1> <name2> docopt_example.py (--h|--q) [<name1> -l] docopt_example.py --version Options: -l, --all List all. -q, --quit exit. --version Version 3.6.1 -h --help Show this screen. --version Show version. --speed =<kn> Speed in knots [default: 10]. --moored Moored (anchored) mine. --drifting Drifting mine. ''' from docopt import docoptargs = docopt(usage)print(args) Output : python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jul, 2020" }, { "code": null, "e": 237, "s": 28, "text": "Docopt is a command line interface description module. It helps you define a interface for a command-line application and generates parser for it. The interface message in docopt is a formalized help message." }, { "code": null, "e": 331, "s": 237, "text": "You can install docopt module in various ways, pip is one of the best ways to install docopt." }, { "code": null, "e": 351, "s": 331, "text": "$pip install docopt" }, { "code": null, "e": 428, "s": 351, "text": "Note: docopt is tested with Python 2.5, 2.6, 2.7, 3.2, 3.3 and PyPy as well." }, { "code": null, "e": 593, "s": 428, "text": "docopt is most commonly used to display the help messages and it is invoked with -h or –help option. You can import and call this module with the following command." }, { "code": "from docopt import docopt docopt(doc, argv = None, version = None, help = True, options = False)", "e": 697, "s": 593, "text": null }, { "code": null, "e": 742, "s": 697, "text": "Parameters of the module is as shown below :" }, { "code": null, "e": 808, "s": 742, "text": "doc : It is a docstring (__doc__) that contains the help message." }, { "code": null, "e": 875, "s": 808, "text": "argv : It is an optional argument vector contains list of strings." }, { "code": null, "e": 951, "s": 875, "text": "version : It is an optional argument mentioning the version of the program." }, { "code": null, "e": 1026, "s": 951, "text": "help : Responsible for displaying the help message. It is True by default." }, { "code": null, "e": 1144, "s": 1026, "text": "options_first : This doesn’t allow the mixing of positional arguments and optional arguments. By default it is False." }, { "code": null, "e": 1374, "s": 1144, "text": "docopt gives you strong control over your help page and it consists of the usage keyword which is case-insensitive that is followed by your program_name. A usage pattern can be described with various elements as mentioned below :" }, { "code": "usage ='''Usage : program_name.py command --option program_name.py [optional argument] program_name.py --another-option =<argument> program_name.py (--option1 | --option2 ) program_name.py <argument>... '''", "e": 1589, "s": 1374, "text": null }, { "code": null, "e": 1722, "s": 1589, "text": "< argument > argument : The element starting with “<” and ending with “>” is called a positional argument. It is position sensitive." }, { "code": null, "e": 1853, "s": 1722, "text": "–option -o: The element starting with “–” or “-” are called as long or short option. It can either be mentioned as --option or -o." }, { "code": null, "e": 1997, "s": 1853, "text": " -h, --help Display help\n -o, --option Display options\n -l, --all List all\n -q, --quit exit\n --version Version 3.6.1 \n" }, { "code": null, "e": 2130, "s": 1997, "text": "[optional argument] : The element starting with “[” and ending with “]” is called an optional argument. It is considered optionally." }, { "code": null, "e": 2244, "s": 2130, "text": "< argument >... : The ellipsis “...” is used when the element present to the left can be repeated more than once." }, { "code": null, "e": 2419, "s": 2244, "text": "(required arguments) : The elements starting with “(” and ending with “)” is a required element. (--option1 | --option2) says that either of –option1 or –option2 is required." }, { "code": null, "e": 2429, "s": 2419, "text": "Example :" }, { "code": "# filename ='docopt_example.py\" usage ='''Usage: docopt_example.py [(<name1>|<name2>)] <name3>... docopt_example.py mov <name1> <name2> docopt_example.py (--h|--q) [<name1> -l] docopt_example.py --version Options: -l, --all List all. -q, --quit exit. --version Version 3.6.1 -h --help Show this screen. --version Show version. --speed =<kn> Speed in knots [default: 10]. --moored Moored (anchored) mine. --drifting Drifting mine. ''' from docopt import docoptargs = docopt(usage)print(args)", "e": 2992, "s": 2429, "text": null }, { "code": null, "e": 3001, "s": 2992, "text": "Output :" }, { "code": null, "e": 3016, "s": 3001, "text": "python-modules" }, { "code": null, "e": 3023, "s": 3016, "text": "Python" }, { "code": null, "e": 3121, "s": 3023, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3153, "s": 3121, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3180, "s": 3153, "text": "Python Classes and Objects" }, { "code": null, "e": 3201, "s": 3180, "text": "Python OOPs Concepts" }, { "code": null, "e": 3224, "s": 3201, "text": "Introduction To PYTHON" }, { "code": null, "e": 3280, "s": 3224, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3311, "s": 3280, "text": "Python | os.path.join() method" }, { "code": null, "e": 3353, "s": 3311, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3395, "s": 3353, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3434, "s": 3395, "text": "Python | Get unique values from a list" } ]
plotly.express.line_3d() function in Python
17 Jul, 2020 Plotly library of Python can be very useful for data visualization and understanding the data simply and easily. Plotly graph objects are a high-level interface to plotly which are easy to use. This function is used to create a 3D line plot and can be used with pandas dataframes. Each row of dataframe is represented by a symbol mark in 3D space in the line plot. Syntax: plotly.express.line_3d(data_frame=None, x=None, y=None, z=None, color=None, line_dash=None, text=None, line_group=None, hover_name=None, hover_data=None, title=None, template=None, width=None, height=None) Parameters: data_frame: DataFrame or array-like or dict needs to be passed for column names. x, y, z: This parameters is either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the x, y and z axis in cartesian coordinates respectively. color: This parameters assign color to marks. line_dash: This parameter is used to assign dash-patterns to lines. line_group: This parameter is used to group rows of data_frame into lines. hover_name: Values from this column or array_like appear in bold in the hover tooltip. hover_data: This parameter is used to appear in the hover tooltip or tuples with a bool or formatting string as first element, and list-like data to appear in hover as second element Values from these columns appear as extra data in the hover tooltip. Example 1: Python3 import plotly.express as px df = px.data.tips() plot = px.line_3d(df, x = 'time', y = 'day', z = 'sex')plot.show() Output: Example 2: Python3 import plotly.express as px df = px.data.tips() plot = px.line_3d(df, x = 'time', y = 'day', z = 'sex', color = 'time')plot.show() Output: Example 3: Python3 # Python program to demonstrate scatter# plot import plotly.express as px df = px.data.tips() plot = px.line_3d(df, x = 'day', y = 'total_bill', z = 'sex', color = 'time', line_group = 'sex')plot.show() Output: Python Plotly express-class Python-Plotly Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jul, 2020" }, { "code": null, "e": 222, "s": 28, "text": "Plotly library of Python can be very useful for data visualization and understanding the data simply and easily. Plotly graph objects are a high-level interface to plotly which are easy to use." }, { "code": null, "e": 393, "s": 222, "text": "This function is used to create a 3D line plot and can be used with pandas dataframes. Each row of dataframe is represented by a symbol mark in 3D space in the line plot." }, { "code": null, "e": 607, "s": 393, "text": "Syntax: plotly.express.line_3d(data_frame=None, x=None, y=None, z=None, color=None, line_dash=None, text=None, line_group=None, hover_name=None, hover_data=None, title=None, template=None, width=None, height=None)" }, { "code": null, "e": 619, "s": 607, "text": "Parameters:" }, { "code": null, "e": 700, "s": 619, "text": "data_frame: DataFrame or array-like or dict needs to be passed for column names." }, { "code": null, "e": 940, "s": 700, "text": "x, y, z: This parameters is either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the x, y and z axis in cartesian coordinates respectively." }, { "code": null, "e": 986, "s": 940, "text": "color: This parameters assign color to marks." }, { "code": null, "e": 1054, "s": 986, "text": "line_dash: This parameter is used to assign dash-patterns to lines." }, { "code": null, "e": 1129, "s": 1054, "text": "line_group: This parameter is used to group rows of data_frame into lines." }, { "code": null, "e": 1217, "s": 1129, "text": "hover_name: Values from this column or array_like appear in bold in the hover tooltip." }, { "code": null, "e": 1469, "s": 1217, "text": "hover_data: This parameter is used to appear in the hover tooltip or tuples with a bool or formatting string as first element, and list-like data to appear in hover as second element Values from these columns appear as extra data in the hover tooltip." }, { "code": null, "e": 1480, "s": 1469, "text": "Example 1:" }, { "code": null, "e": 1488, "s": 1480, "text": "Python3" }, { "code": "import plotly.express as px df = px.data.tips() plot = px.line_3d(df, x = 'time', y = 'day', z = 'sex')plot.show()", "e": 1646, "s": 1488, "text": null }, { "code": null, "e": 1654, "s": 1646, "text": "Output:" }, { "code": null, "e": 1665, "s": 1654, "text": "Example 2:" }, { "code": null, "e": 1673, "s": 1665, "text": "Python3" }, { "code": "import plotly.express as px df = px.data.tips() plot = px.line_3d(df, x = 'time', y = 'day', z = 'sex', color = 'time')plot.show()", "e": 1858, "s": 1673, "text": null }, { "code": null, "e": 1866, "s": 1858, "text": "Output:" }, { "code": null, "e": 1877, "s": 1866, "text": "Example 3:" }, { "code": null, "e": 1885, "s": 1877, "text": "Python3" }, { "code": "# Python program to demonstrate scatter# plot import plotly.express as px df = px.data.tips() plot = px.line_3d(df, x = 'day', y = 'total_bill', z = 'sex', color = 'time', line_group = 'sex')plot.show()", "e": 2174, "s": 1885, "text": null }, { "code": null, "e": 2182, "s": 2174, "text": "Output:" }, { "code": null, "e": 2210, "s": 2182, "text": "Python Plotly express-class" }, { "code": null, "e": 2224, "s": 2210, "text": "Python-Plotly" }, { "code": null, "e": 2231, "s": 2224, "text": "Python" } ]