title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
string at() in C++ - GeeksforGeeks
08 Jul, 2021 std::string::at can be used to extract characters by characters from a given string. It supports two different syntaxes both having similar parameters: Syntax 1: char& string::at (size_type idx) Syntax 2: const char& string::at (size_type idx) const idx : index number Both forms return the character that has the index idx (the first character has index 0). For all strings, an index greater than or equal to length() as value is invalid. If the caller ensures that the index is valid, she can use operator [], which is faster. Return value : Returns character at the specified position in the string. Exception : Passing an invalid index (less than 0 or greater than or equal to size()) throws an out_of_range exception. CPP // CPP code to demonstrate std::string::at #include <iostream>using namespace std; // Function to demonstrate std::string::atvoid atDemo(string str){ cout << str.at(5); // Below line throws out of // range exception as 16 > length() // cout << str.at(16);} // Driver codeint main(){ string str("GeeksForGeeks"); atDemo(str); return 0;} Output: F Application std::string::at can be used for extracting characters from string. Here is the simple code for the same. CPP // CPP code to extract characters from a given string #include <iostream>using namespace std; // Function to demonstrate std::string::atvoid extractChar(string str){ char ch; // Calculating the length of string int l = str.length(); for (int i = 0; i < l; i++) { ch = str.at(i); cout << ch << " "; }} // Driver codeint main(){ string str("GeeksForGeeks"); extractChar(str); return 0;} Output: G e e k s F o r G e e k s This article is contributed by Pushpanjali Chauhan. 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. anikaseth98 cpp-strings-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Virtual Function in C++ Bitwise Operators in C/C++ Templates in C++ with Examples Constructors in C++ Operator Overloading in C++ Socket Programming in C/C++ Object Oriented Programming in C++
[ { "code": null, "e": 25632, "s": 25604, "text": "\n08 Jul, 2021" }, { "code": null, "e": 25796, "s": 25632, "text": "std::string::at can be used to extract characters by characters from a given string. It supports two different syntaxes both having similar parameters: Syntax 1: " }, { "code": null, "e": 25829, "s": 25796, "text": "char& string::at (size_type idx)" }, { "code": null, "e": 25841, "s": 25829, "text": "Syntax 2: " }, { "code": null, "e": 26363, "s": 25841, "text": "const char& string::at (size_type idx) const\n\nidx : index number\nBoth forms return the character that has the index idx (the first character has index 0).\nFor all strings, an index greater than or equal to length() as value is invalid.\nIf the caller ensures that the index is valid, she can use operator [], which is faster.\n\nReturn value : Returns character at the specified position in the string.\n\nException : Passing an invalid index (less than 0 \nor greater than or equal to size()) throws an out_of_range exception." }, { "code": null, "e": 26369, "s": 26365, "text": "CPP" }, { "code": "// CPP code to demonstrate std::string::at #include <iostream>using namespace std; // Function to demonstrate std::string::atvoid atDemo(string str){ cout << str.at(5); // Below line throws out of // range exception as 16 > length() // cout << str.at(16);} // Driver codeint main(){ string str(\"GeeksForGeeks\"); atDemo(str); return 0;}", "e": 26727, "s": 26369, "text": null }, { "code": null, "e": 26737, "s": 26727, "text": "Output: " }, { "code": null, "e": 26739, "s": 26737, "text": "F" }, { "code": null, "e": 26753, "s": 26741, "text": "Application" }, { "code": null, "e": 26860, "s": 26753, "text": "std::string::at can be used for extracting characters from string. Here is the simple code for the same. " }, { "code": null, "e": 26864, "s": 26860, "text": "CPP" }, { "code": "// CPP code to extract characters from a given string #include <iostream>using namespace std; // Function to demonstrate std::string::atvoid extractChar(string str){ char ch; // Calculating the length of string int l = str.length(); for (int i = 0; i < l; i++) { ch = str.at(i); cout << ch << \" \"; }} // Driver codeint main(){ string str(\"GeeksForGeeks\"); extractChar(str); return 0;}", "e": 27288, "s": 26864, "text": null }, { "code": null, "e": 27298, "s": 27288, "text": "Output: " }, { "code": null, "e": 27325, "s": 27298, "text": "G e e k s F o r G e e k s " }, { "code": null, "e": 27753, "s": 27325, "text": "This article is contributed by Pushpanjali Chauhan. 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": 27765, "s": 27753, "text": "anikaseth98" }, { "code": null, "e": 27785, "s": 27765, "text": "cpp-strings-library" }, { "code": null, "e": 27789, "s": 27785, "text": "STL" }, { "code": null, "e": 27793, "s": 27789, "text": "C++" }, { "code": null, "e": 27797, "s": 27793, "text": "STL" }, { "code": null, "e": 27801, "s": 27797, "text": "CPP" }, { "code": null, "e": 27899, "s": 27801, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27918, "s": 27899, "text": "Inheritance in C++" }, { "code": null, "e": 27961, "s": 27918, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 27985, "s": 27961, "text": "C++ Classes and Objects" }, { "code": null, "e": 28009, "s": 27985, "text": "Virtual Function in C++" }, { "code": null, "e": 28036, "s": 28009, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 28067, "s": 28036, "text": "Templates in C++ with Examples" }, { "code": null, "e": 28087, "s": 28067, "text": "Constructors in C++" }, { "code": null, "e": 28115, "s": 28087, "text": "Operator Overloading in C++" }, { "code": null, "e": 28143, "s": 28115, "text": "Socket Programming in C/C++" } ]
Detection of a specific color(blue here) using OpenCV with Python - GeeksforGeeks
31 Dec, 2021 The following code in python uses OpenCV library which is employed for image processing techniques. The program allows the detection of a specific color in a live stream video content. A video is composed of infinite frames at different time instants. We will detect the colour of every frame one by one. The code will only compile in linux environment. Make sure that openCV is installed in your system before you run the program. For installation: Run the command following on your terminal to install it from the Ubuntu or Debian repository. sudo apt-get install libopencv-dev python-opencv OR In order to download OpenCV from the official site run the following command: bash install-opencv.sh on your terminal. Type your sudo password and you will have installed OpenCV. This operation may take a long time due to the packages to be installed and the compilation process. To install numpy just use the command: sudo pip install numpy Python3 # Python program for Detection of a # specific color(blue here) using OpenCV with Pythonimport cv2import numpy as np # Webcamera no 0 is used to capture the framescap = cv2.VideoCapture(0) # This drives the program into an infinite loop.while(1): # Captures the live stream frame-by-frame _, frame = cap.read() # Converts images from BGR to HSV hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) lower_blue = np.array([110,50,50]) upper_blue = np.array([130,255,255]) # Here we are defining range of bluecolor in HSV # This creates a mask of blue coloured # objects found in the frame. mask = cv2.inRange(hsv, lower_blue, upper_blue) # The bitwise and of the frame and mask is done so # that only the blue coloured objects are highlighted # and stored in res res = cv2.bitwise_and(frame,frame, mask= mask) cv2.imshow('frame',frame) cv2.imshow('mask',mask) cv2.imshow('res',res) # This displays the frame, mask # and res which we created in 3 separate windows. k = cv2.waitKey(5) & 0xFF if k == 27: break # Destroys all of the HighGUI windows.cv2.destroyAllWindows() # release the captured framecap.release() Explanation of Code: Camera Settings: In order to perform runtime operations, the device’s web-camera is used. To capture a video, we need to create a VideoCapture object. Its argument can be either the device index or the name of a video file. The device index is just the number to specify which camera. Normally one camera will be connected, so we simply pass 0. You can select the second camera by passing 1 and so on. After that, you can capture frame-by-frame. But in the end, don’t forget to release the capture. Moreover, if anyone wants to apply this color detection technique on any image it can be done with little modifications in the code which I’ll discuss later. Capturing frames: The infinite loop is used so that the web camera captures the frames in every instance and is open during the entire course of the program. After capturing the live stream frame by frame we are converting each frame in BGR color space(the default one) to HSV color space. There are more than 150 color-space conversion methods available in OpenCV. But we will look into only two which are most widely used ones, BGR to Gray and BGR to HSV. For color conversion, we use the function cv2.cvtColor(input_image, flag) where flag determines the type of conversion. For BGR to HSV, we use the flag cv2.COLOR_BGR2HSV. Now we know how to convert BGR images to HSV, we can use this to extract a colored object. In HSV, it is more easier to represent a color than RGB color-space. In specifying the range, we have specified the range of blue color. Whereas you can enter the range of any colour you wish. Masking technique: The mask is basically creating some specific region of the image following certain rules. Here we are creating a mask that comprises of an object in blue color. After that, I have used a bitwise_and on the input image and the threshold image so that only the blue coloured objects are highlighted and stored in res. We then display the frame, res, and mask on 3 separate windows using imshow function. Display the frame: As imshow() is a function of HighGui it is required to call waitKey regularly, in order to process its event loop. The function waitKey() waits for key event for a “delay” (here, 5 milliseconds). If you don’t call waitKey, HighGui cannot process windows events like redraw, resizing, input event, etc. So just call it, even with a 1ms delay . Summarizing the process: Take each frame of the video.Convert each frame from BGR to HSV color-space.Threshold the HSV image for a range of blue color. Take each frame of the video.Convert each frame from BGR to HSV color-space.Threshold the HSV image for a range of blue color. Take each frame of the video. Convert each frame from BGR to HSV color-space. Threshold the HSV image for a range of blue color. This article is contributed by Pratima Upadhyay. 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. Geek_Dev surindertarika1234 kumaripunam984122 OpenCV GBlog Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar GET and POST requests using Python Top 10 Projects For Beginners To Practice HTML and CSS Skills Types of Software Testing Working with csv files in Python Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25995, "s": 25967, "text": "\n31 Dec, 2021" }, { "code": null, "e": 26351, "s": 25995, "text": "The following code in python uses OpenCV library which is employed for image processing techniques. The program allows the detection of a specific color in a live stream video content. A video is composed of infinite frames at different time instants. We will detect the colour of every frame one by one. The code will only compile in linux environment. " }, { "code": null, "e": 26448, "s": 26351, "text": "Make sure that openCV is installed in your system before you run the program. For installation: " }, { "code": null, "e": 26543, "s": 26448, "text": "Run the command following on your terminal to install it from the Ubuntu or Debian repository." }, { "code": null, "e": 26592, "s": 26543, "text": "sudo apt-get install libopencv-dev python-opencv" }, { "code": null, "e": 26673, "s": 26592, "text": "OR In order to download OpenCV from the official site run the following command:" }, { "code": null, "e": 26696, "s": 26673, "text": "bash install-opencv.sh" }, { "code": null, "e": 26876, "s": 26696, "text": "on your terminal. Type your sudo password and you will have installed OpenCV. This operation may take a long time due to the packages to be installed and the compilation process." }, { "code": null, "e": 26917, "s": 26876, "text": "To install numpy just use the command: " }, { "code": null, "e": 26940, "s": 26917, "text": "sudo pip install numpy" }, { "code": null, "e": 26950, "s": 26942, "text": "Python3" }, { "code": "# Python program for Detection of a # specific color(blue here) using OpenCV with Pythonimport cv2import numpy as np # Webcamera no 0 is used to capture the framescap = cv2.VideoCapture(0) # This drives the program into an infinite loop.while(1): # Captures the live stream frame-by-frame _, frame = cap.read() # Converts images from BGR to HSV hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) lower_blue = np.array([110,50,50]) upper_blue = np.array([130,255,255]) # Here we are defining range of bluecolor in HSV # This creates a mask of blue coloured # objects found in the frame. mask = cv2.inRange(hsv, lower_blue, upper_blue) # The bitwise and of the frame and mask is done so # that only the blue coloured objects are highlighted # and stored in res res = cv2.bitwise_and(frame,frame, mask= mask) cv2.imshow('frame',frame) cv2.imshow('mask',mask) cv2.imshow('res',res) # This displays the frame, mask # and res which we created in 3 separate windows. k = cv2.waitKey(5) & 0xFF if k == 27: break # Destroys all of the HighGUI windows.cv2.destroyAllWindows() # release the captured framecap.release()", "e": 28147, "s": 26950, "text": null }, { "code": null, "e": 28169, "s": 28147, "text": "Explanation of Code: " }, { "code": null, "e": 28826, "s": 28169, "text": "Camera Settings: In order to perform runtime operations, the device’s web-camera is used. To capture a video, we need to create a VideoCapture object. Its argument can be either the device index or the name of a video file. The device index is just the number to specify which camera. Normally one camera will be connected, so we simply pass 0. You can select the second camera by passing 1 and so on. After that, you can capture frame-by-frame. But in the end, don’t forget to release the capture. Moreover, if anyone wants to apply this color detection technique on any image it can be done with little modifications in the code which I’ll discuss later." }, { "code": null, "e": 29739, "s": 28826, "text": "Capturing frames: The infinite loop is used so that the web camera captures the frames in every instance and is open during the entire course of the program. After capturing the live stream frame by frame we are converting each frame in BGR color space(the default one) to HSV color space. There are more than 150 color-space conversion methods available in OpenCV. But we will look into only two which are most widely used ones, BGR to Gray and BGR to HSV. For color conversion, we use the function cv2.cvtColor(input_image, flag) where flag determines the type of conversion. For BGR to HSV, we use the flag cv2.COLOR_BGR2HSV. Now we know how to convert BGR images to HSV, we can use this to extract a colored object. In HSV, it is more easier to represent a color than RGB color-space. In specifying the range, we have specified the range of blue color. Whereas you can enter the range of any colour you wish." }, { "code": null, "e": 30160, "s": 29739, "text": "Masking technique: The mask is basically creating some specific region of the image following certain rules. Here we are creating a mask that comprises of an object in blue color. After that, I have used a bitwise_and on the input image and the threshold image so that only the blue coloured objects are highlighted and stored in res. We then display the frame, res, and mask on 3 separate windows using imshow function." }, { "code": null, "e": 30522, "s": 30160, "text": "Display the frame: As imshow() is a function of HighGui it is required to call waitKey regularly, in order to process its event loop. The function waitKey() waits for key event for a “delay” (here, 5 milliseconds). If you don’t call waitKey, HighGui cannot process windows events like redraw, resizing, input event, etc. So just call it, even with a 1ms delay ." }, { "code": null, "e": 30674, "s": 30522, "text": "Summarizing the process: Take each frame of the video.Convert each frame from BGR to HSV color-space.Threshold the HSV image for a range of blue color." }, { "code": null, "e": 30801, "s": 30674, "text": "Take each frame of the video.Convert each frame from BGR to HSV color-space.Threshold the HSV image for a range of blue color." }, { "code": null, "e": 30831, "s": 30801, "text": "Take each frame of the video." }, { "code": null, "e": 30879, "s": 30831, "text": "Convert each frame from BGR to HSV color-space." }, { "code": null, "e": 30930, "s": 30879, "text": "Threshold the HSV image for a range of blue color." }, { "code": null, "e": 31355, "s": 30930, "text": "This article is contributed by Pratima Upadhyay. 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": 31364, "s": 31355, "text": "Geek_Dev" }, { "code": null, "e": 31383, "s": 31364, "text": "surindertarika1234" }, { "code": null, "e": 31401, "s": 31383, "text": "kumaripunam984122" }, { "code": null, "e": 31408, "s": 31401, "text": "OpenCV" }, { "code": null, "e": 31414, "s": 31408, "text": "GBlog" }, { "code": null, "e": 31421, "s": 31414, "text": "Python" }, { "code": null, "e": 31519, "s": 31421, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31544, "s": 31519, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 31579, "s": 31544, "text": "GET and POST requests using Python" }, { "code": null, "e": 31641, "s": 31579, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31667, "s": 31641, "text": "Types of Software Testing" }, { "code": null, "e": 31700, "s": 31667, "text": "Working with csv files in Python" }, { "code": null, "e": 31728, "s": 31700, "text": "Read JSON file using Python" }, { "code": null, "e": 31778, "s": 31728, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 31800, "s": 31778, "text": "Python map() function" } ]
Dealing with class imbalanced image datasets using the Focal Tversky Loss | by Robin Vinod | Towards Data Science
Class imbalanced datasets is a frequent problem experienced when trying to train segmentation networks. The first time I trained an image segmentation model, I was getting over 96% accuracy straight off the bat. Either I unknowingly made the biggest breakthrough since the inception of the first CNN, or there was something wrong with my approach. I quickly realised that the pixels to be segmented accounted for a very small percentage of the total pixels in the image. All the model had to do was predict a fully black image (a.k.a no segmentation) and it was rewarded with over 90% accuracy. This is a common problem encountered in most image segmentation tasks, where the background class is much larger than the other classes. In this story, I go through the techniques used to deal with class imbalanced problems and why the Focal Tverky Loss might be the best option for you. Losses that deal with class imbalanceWhat is the Tversky Index?Focal Tversky LossConclusion Losses that deal with class imbalance What is the Tversky Index? Focal Tversky Loss Conclusion a. Weighted Binary Cross Entropy Once of the losses typically used to deal with class imbalance is the weighted binary cross entropy. The crux of the normal binary cross entropy is that it considers all pixels equally when calculating the loss. In a mask where 90% of the pixels are 0s and only 10% are 1, the network receives receives a low loss even if it misses all the 1s, which means the network is not learning anything. Weighted binary cross entropy (WBCE) attempts to solve this by weighting the positive class. For every class 1 predicted by the network, BCE adds log(p) to the loss while WBCE adds β log(p) to the loss. Hence, if β > 1, class 1 is weighted higher, meaning the network is less likely to ignore it (lesser false negatives). Conversely, if β < 1, class 0 is weighted higher, meaning there will be lesser false positives. By controlling, the value of β, you can reduce the problem of class imbalance by weighting the smaller class higher. However, the optimal value of β is hard to ascertain and requires many rounds of trial and error. Pros: Simple smooth loss surface that is fast in training Cons: Difficult to optimise and find the sweet spot b. Dice Coefficient The Dice Coefficient is well-known for being the go-to evaluation metric for image segmentation, but it can also serve as a loss function. Although not as widely used as other loss functions like binary cross entropy, the dice coefficient does wonders when it comes to class imbalance. Unlike BCE, dice coefficient only considers the segmentation class and not the background class. The pixels are classified as True Positive (TP), False Negative (FN) and False Positive (FP). The dice coefficient is a measure of overlap of the predicted mask and the groundtruth. Since it does not account for the background class, it cannot dominate over the smaller segmentation class. The dice coefficient outputs a score in the range [0,1] where 1 is a perfect overlap. Thus, (1-DSC) can be used as a loss function. Considering the maximisation of the dice coefficient is the goal of the network, using it directly as a loss function can yield good results, since it works well with class imbalanced data by design. However, one of the pitfalls of the dice coefficient is the potential for exploding gradients. Early in the training, the dice coefficient is close to 0, which can cause instability in training due to exploding gradients as a result of the network making large changes to weights. However, this is easily manageable using batch normalisation and ReLUs. Pros: Easy solution to class imbalance without having to manually optimise any parameters Cons: Potential for gradient explosion, and generally slower to train than BCE The Tversky Index (TI) is a asymmetric similarity measure that is a generalisation of the dice coefficient and the Jaccard index. The tversky index adds two parameters, α and β, where α + β = 1. In the case where α = β = 0.5, it simplifies into the dice coefficient. It simplifies to the Jaccard index if α = β = 1. By setting the value of α > β, you can penalise false negatives more. This becomes useful in highly imbalanced datasets where the additional level of control over the loss function yields better small scale segmentations than the normal dice coefficient. Although the tversky index is only a simple improvement over the dice coefficient, it can prove useful in edge cases where you need a finer level of control. In the paper, Tversky loss function for image segmentation using 3D fully convolutional deep networks by Salehi et al., the tversky loss was used to obtain the most desirable performance for multiple sclerosis lesion segmentation, a typically class imbalanced problem. The Focal Tversky Loss (FTL) is a generalisation of the tversky loss. The non-linear nature of the loss gives you control over how the loss behaves at different values of the tversky index obtained. γ is a parameter that controls the non-linearity of the loss. As γ tends to positive ∞, the gradient of the loss tends to ∞ as the Tversky Index (TI) tends to 1. As γ tends to 0, the gradient of the loss tends to 0 as TI tends to 1. Essentially, with a value of γ < 1, the gradient of the loss is higher for examples where TI > 0.5, forcing the model to focus on such examples. This behaviour can be useful towards the end of training as the model is still incentivised to learn even though TI is nearing convergence. However, at the same time, it will weight easier examples higher during the early stages of training, which can lead to poor learning. In the case of class imbalance, the FTL becomes useful when γ > 1. This results in a higher loss gradient for examples where TI < 0.5. This forces the model to focus on harder examples, especially small scale segmentations which usually receive low TI scores. In the image above, the blue line is the standard tversky loss. The purple line shows the higher gradient and higher loss when TI > 0.5 while the green line shows higher loss when TI < 0.5. The table above is extracted from the paper, A Novel Focal Tversky loss function with improved Attention U-Net for lesion segmentation. In the BUS dataset, the FTL showed significant improvements in all categories. In the ISIC dataset, although the overall dice coefficient was the highest, the model did not have the highest precision or recall. Although models trained with FTL may not have the outright highest precision or recall, it is important to note that the balance between precision and recall was best when trained with FTL, which shows that the objective of tackling class imbalance was satisfied. The end result is the best overall dice coefficient. The Focal Tversky Loss is an easy drop in solution to deal with class imbalance. Although the best parameter values will take some trial and error to determine, you should see good results with the following: α = 0.7, β = 0.3, γ = 3/4 Keras Implementation To get the full implementation of a U-Net with attention, recurrence and inception layers pre-implemented, please check https://github.com/robinvvinod/unet/.
[ { "code": null, "e": 519, "s": 171, "text": "Class imbalanced datasets is a frequent problem experienced when trying to train segmentation networks. The first time I trained an image segmentation model, I was getting over 96% accuracy straight off the bat. Either I unknowingly made the biggest breakthrough since the inception of the first CNN, or there was something wrong with my approach." }, { "code": null, "e": 903, "s": 519, "text": "I quickly realised that the pixels to be segmented accounted for a very small percentage of the total pixels in the image. All the model had to do was predict a fully black image (a.k.a no segmentation) and it was rewarded with over 90% accuracy. This is a common problem encountered in most image segmentation tasks, where the background class is much larger than the other classes." }, { "code": null, "e": 1054, "s": 903, "text": "In this story, I go through the techniques used to deal with class imbalanced problems and why the Focal Tverky Loss might be the best option for you." }, { "code": null, "e": 1146, "s": 1054, "text": "Losses that deal with class imbalanceWhat is the Tversky Index?Focal Tversky LossConclusion" }, { "code": null, "e": 1184, "s": 1146, "text": "Losses that deal with class imbalance" }, { "code": null, "e": 1211, "s": 1184, "text": "What is the Tversky Index?" }, { "code": null, "e": 1230, "s": 1211, "text": "Focal Tversky Loss" }, { "code": null, "e": 1241, "s": 1230, "text": "Conclusion" }, { "code": null, "e": 1274, "s": 1241, "text": "a. Weighted Binary Cross Entropy" }, { "code": null, "e": 1668, "s": 1274, "text": "Once of the losses typically used to deal with class imbalance is the weighted binary cross entropy. The crux of the normal binary cross entropy is that it considers all pixels equally when calculating the loss. In a mask where 90% of the pixels are 0s and only 10% are 1, the network receives receives a low loss even if it misses all the 1s, which means the network is not learning anything." }, { "code": null, "e": 1761, "s": 1668, "text": "Weighted binary cross entropy (WBCE) attempts to solve this by weighting the positive class." }, { "code": null, "e": 1871, "s": 1761, "text": "For every class 1 predicted by the network, BCE adds log(p) to the loss while WBCE adds β log(p) to the loss." }, { "code": null, "e": 2086, "s": 1871, "text": "Hence, if β > 1, class 1 is weighted higher, meaning the network is less likely to ignore it (lesser false negatives). Conversely, if β < 1, class 0 is weighted higher, meaning there will be lesser false positives." }, { "code": null, "e": 2301, "s": 2086, "text": "By controlling, the value of β, you can reduce the problem of class imbalance by weighting the smaller class higher. However, the optimal value of β is hard to ascertain and requires many rounds of trial and error." }, { "code": null, "e": 2359, "s": 2301, "text": "Pros: Simple smooth loss surface that is fast in training" }, { "code": null, "e": 2411, "s": 2359, "text": "Cons: Difficult to optimise and find the sweet spot" }, { "code": null, "e": 2431, "s": 2411, "text": "b. Dice Coefficient" }, { "code": null, "e": 2717, "s": 2431, "text": "The Dice Coefficient is well-known for being the go-to evaluation metric for image segmentation, but it can also serve as a loss function. Although not as widely used as other loss functions like binary cross entropy, the dice coefficient does wonders when it comes to class imbalance." }, { "code": null, "e": 2908, "s": 2717, "text": "Unlike BCE, dice coefficient only considers the segmentation class and not the background class. The pixels are classified as True Positive (TP), False Negative (FN) and False Positive (FP)." }, { "code": null, "e": 3236, "s": 2908, "text": "The dice coefficient is a measure of overlap of the predicted mask and the groundtruth. Since it does not account for the background class, it cannot dominate over the smaller segmentation class. The dice coefficient outputs a score in the range [0,1] where 1 is a perfect overlap. Thus, (1-DSC) can be used as a loss function." }, { "code": null, "e": 3436, "s": 3236, "text": "Considering the maximisation of the dice coefficient is the goal of the network, using it directly as a loss function can yield good results, since it works well with class imbalanced data by design." }, { "code": null, "e": 3789, "s": 3436, "text": "However, one of the pitfalls of the dice coefficient is the potential for exploding gradients. Early in the training, the dice coefficient is close to 0, which can cause instability in training due to exploding gradients as a result of the network making large changes to weights. However, this is easily manageable using batch normalisation and ReLUs." }, { "code": null, "e": 3879, "s": 3789, "text": "Pros: Easy solution to class imbalance without having to manually optimise any parameters" }, { "code": null, "e": 3958, "s": 3879, "text": "Cons: Potential for gradient explosion, and generally slower to train than BCE" }, { "code": null, "e": 4088, "s": 3958, "text": "The Tversky Index (TI) is a asymmetric similarity measure that is a generalisation of the dice coefficient and the Jaccard index." }, { "code": null, "e": 4274, "s": 4088, "text": "The tversky index adds two parameters, α and β, where α + β = 1. In the case where α = β = 0.5, it simplifies into the dice coefficient. It simplifies to the Jaccard index if α = β = 1." }, { "code": null, "e": 4529, "s": 4274, "text": "By setting the value of α > β, you can penalise false negatives more. This becomes useful in highly imbalanced datasets where the additional level of control over the loss function yields better small scale segmentations than the normal dice coefficient." }, { "code": null, "e": 4687, "s": 4529, "text": "Although the tversky index is only a simple improvement over the dice coefficient, it can prove useful in edge cases where you need a finer level of control." }, { "code": null, "e": 4956, "s": 4687, "text": "In the paper, Tversky loss function for image segmentation using 3D fully convolutional deep networks by Salehi et al., the tversky loss was used to obtain the most desirable performance for multiple sclerosis lesion segmentation, a typically class imbalanced problem." }, { "code": null, "e": 5155, "s": 4956, "text": "The Focal Tversky Loss (FTL) is a generalisation of the tversky loss. The non-linear nature of the loss gives you control over how the loss behaves at different values of the tversky index obtained." }, { "code": null, "e": 5388, "s": 5155, "text": "γ is a parameter that controls the non-linearity of the loss. As γ tends to positive ∞, the gradient of the loss tends to ∞ as the Tversky Index (TI) tends to 1. As γ tends to 0, the gradient of the loss tends to 0 as TI tends to 1." }, { "code": null, "e": 5808, "s": 5388, "text": "Essentially, with a value of γ < 1, the gradient of the loss is higher for examples where TI > 0.5, forcing the model to focus on such examples. This behaviour can be useful towards the end of training as the model is still incentivised to learn even though TI is nearing convergence. However, at the same time, it will weight easier examples higher during the early stages of training, which can lead to poor learning." }, { "code": null, "e": 6068, "s": 5808, "text": "In the case of class imbalance, the FTL becomes useful when γ > 1. This results in a higher loss gradient for examples where TI < 0.5. This forces the model to focus on harder examples, especially small scale segmentations which usually receive low TI scores." }, { "code": null, "e": 6258, "s": 6068, "text": "In the image above, the blue line is the standard tversky loss. The purple line shows the higher gradient and higher loss when TI > 0.5 while the green line shows higher loss when TI < 0.5." }, { "code": null, "e": 6394, "s": 6258, "text": "The table above is extracted from the paper, A Novel Focal Tversky loss function with improved Attention U-Net for lesion segmentation." }, { "code": null, "e": 6605, "s": 6394, "text": "In the BUS dataset, the FTL showed significant improvements in all categories. In the ISIC dataset, although the overall dice coefficient was the highest, the model did not have the highest precision or recall." }, { "code": null, "e": 6922, "s": 6605, "text": "Although models trained with FTL may not have the outright highest precision or recall, it is important to note that the balance between precision and recall was best when trained with FTL, which shows that the objective of tackling class imbalance was satisfied. The end result is the best overall dice coefficient." }, { "code": null, "e": 7131, "s": 6922, "text": "The Focal Tversky Loss is an easy drop in solution to deal with class imbalance. Although the best parameter values will take some trial and error to determine, you should see good results with the following:" }, { "code": null, "e": 7157, "s": 7131, "text": "α = 0.7, β = 0.3, γ = 3/4" }, { "code": null, "e": 7178, "s": 7157, "text": "Keras Implementation" } ]
Perfect Square factors of a Number - GeeksforGeeks
30 May, 2021 Given an integer N, the task is to find the number of factors of N which are a perfect square. Examples: Input: N = 100 Output: 4 Explanation: There are four factors of 100 (1, 4, 25, 100) that are perfect square.Input: N = 900 Output: 8 Explanation: There are eight factors of 900 (1, 4, 9, 25, 36, 100, 225, 900) that are perfect square. Naive Approach: The simplest approach to solve this problem is to find all possible factors of the given number N and for each factor, check if the factor is a perfect square or not. For every factor found to be so, increase count. Print the final count. Time Complexity: O(N) Auxiliary Space: O(1)Efficient Approach: The following observations need to be made to optimize the above approach:The number of factors for a number is given by: Factors of N = (1 + a1)*(1 + a2)*(1 + a3)*..*(1 + an) where a1, a2, a3, ..., an are the count of distinct prime factors of N. In a perfect square, the count of distinct prime factors must be divisible by 2. Therefore, the count of factors that are a perfect square is given by: Factors of N that are perfect square = (1 + a1/2)*(1 + a2/2)*...*(1 + an/2) where a1, a2, a3, ..., an are the count of distinct prime factors of N. Illustration: The prime factors of N = 100 are 2, 2, 5, 5. Therefore, the number of factors that are perfect square are (1 + 2/2) * (1 + 2/2) = 4. The factors are 1, 4, 25, 100. Therefore, find the count of prime factors and apply the above formula to find the count of factors that are a perfect square.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function that returns the count of// factors that are perfect squaresint noOfFactors(int N){ if (N == 1) return 1; // Stores the count of number // of times a prime number // divides N. int count = 0; // Stores the number of factors // that are perfect square int ans = 1; // Count number of 2's // that divides N while (N % 2 == 0) { count++; N = N / 2; } // Calculate ans according // to above formula ans *= (count / 2 + 1); // Check for all the possible // numbers that can divide it for (int i = 3; i * i <= N; i = i + 2) { count = 0; // Check the number of // times prime number // i divides it while (N % i == 0) { count++; N = N / i; } // Calculate ans according // to above formula ans *= (count / 2 + 1); } // Return final count return ans;} // Driver Codeint main(){ int N = 100; cout << noOfFactors(N); return 0;} // Java program to implement// the above approachimport java.util.*; class GFG{ // Function that returns the count of// factors that are perfect squaresstatic int noOfFactors(int N){ if (N == 1) return 1; // Stores the count of number // of times a prime number // divides N. int count = 0; // Stores the number of factors // that are perfect square int ans = 1; // Count number of 2's // that divides N while (N % 2 == 0) { count++; N = N / 2; } // Calculate ans according // to above formula ans *= (count / 2 + 1); // Check for all the possible // numbers that can divide it for(int i = 3; i * i <= N; i = i + 2) { count = 0; // Check the number of // times prime number // i divides it while (N % i == 0) { count++; N = N / i; } // Calculate ans according // to above formula ans *= (count / 2 + 1); } // Return final count return ans;} // Driver Codepublic static void main(String[] args){ int N = 100; System.out.print(noOfFactors(N));}} // This code is contributed by 29AjayKumar # Python3 program to implement# the above approach # Function that returns the count of# factors that are perfect squaresdef noOfFactors(N): if (N == 1): return 1 # Stores the count of number # of times a prime number # divides N. count = 0 # Stores the number of factors # that are perfect square ans = 1 # Count number of 2's # that divides N while (N % 2 == 0): count += 1 N = N // 2 # Calculate ans according # to above formula ans *= (count // 2 + 1) # Check for all the possible # numbers that can divide it i = 3 while i * i <= N: count = 0 # Check the number of # times prime number # i divides it while (N % i == 0): count += 1 N = N // i # Calculate ans according # to above formula ans *= (count // 2 + 1) i += 2 # Return final count return ans # Driver Codeif __name__ == "__main__": N = 100 print(noOfFactors(N)) # This code is contributed by chitranayal // C# program to implement// the above approachusing System; class GFG{ // Function that returns the count of// factors that are perfect squaresstatic int noOfFactors(int N){ if (N == 1) return 1; // Stores the count of number // of times a prime number // divides N. int count = 0; // Stores the number of factors // that are perfect square int ans = 1; // Count number of 2's // that divides N while (N % 2 == 0) { count++; N = N / 2; } // Calculate ans according // to above formula ans *= (count / 2 + 1); // Check for all the possible // numbers that can divide it for(int i = 3; i * i <= N; i = i + 2) { count = 0; // Check the number of // times prime number // i divides it while (N % i == 0) { count++; N = N / i; } // Calculate ans according // to above formula ans *= (count / 2 + 1); } // Return final count return ans;} // Driver Codepublic static void Main(String[] args){ int N = 100; Console.Write(noOfFactors(N));}} // This code is contributed by PrinciRaj1992 <script> // Javascript program for// the above approach // Function that returns the count of// factors that are perfect squaresfunction noOfFactors(N){ if (N == 1) return 1; // Stores the count of number // of times a prime number // divides N. let count = 0; // Stores the number of factors // that are perfect square let ans = 1; // Count number of 2's // that divides N while (N % 2 == 0) { count++; N = N / 2; } // Calculate ans according // to above formula ans *= (count / 2 + 1); // Check for all the possible // numbers that can divide it for(let i = 3; i * i <= N; i = i + 2) { count = 0; // Check the number of // times prime number // i divides it while (N % i == 0) { count++; N = N / i; } // Calculate ans according // to above formula ans *= (count / 2 + 1); } // Return final count return ans;} // Driver Code let N = 100; document.write(noOfFactors(N)); </script> 4 Time Complexity: Space Complexity: O(1) ukasp 29AjayKumar princiraj1992 target_2 suman_1729 Maths maths-perfect-square school-programming Competitive Programming Greedy Mathematical Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Prefix Sum Array - Implementation and Applications in Competitive Programming Ordered Set and GNU C++ PBDS Modulo 10^9+7 (1000000007) Bits manipulation (Important tactics) What is Competitive Programming and How to Prepare for It? Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Program for array rotation Write a program to print all permutations of a given string
[ { "code": null, "e": 26169, "s": 26141, "text": "\n30 May, 2021" }, { "code": null, "e": 26264, "s": 26169, "text": "Given an integer N, the task is to find the number of factors of N which are a perfect square." }, { "code": null, "e": 26276, "s": 26264, "text": "Examples: " }, { "code": null, "e": 26513, "s": 26276, "text": "Input: N = 100 Output: 4 Explanation: There are four factors of 100 (1, 4, 25, 100) that are perfect square.Input: N = 900 Output: 8 Explanation: There are eight factors of 900 (1, 4, 9, 25, 36, 100, 225, 900) that are perfect square. " }, { "code": null, "e": 26955, "s": 26513, "text": "Naive Approach: The simplest approach to solve this problem is to find all possible factors of the given number N and for each factor, check if the factor is a perfect square or not. For every factor found to be so, increase count. Print the final count. Time Complexity: O(N) Auxiliary Space: O(1)Efficient Approach: The following observations need to be made to optimize the above approach:The number of factors for a number is given by: " }, { "code": null, "e": 27083, "s": 26955, "text": "Factors of N = (1 + a1)*(1 + a2)*(1 + a3)*..*(1 + an) where a1, a2, a3, ..., an are the count of distinct prime factors of N. " }, { "code": null, "e": 27235, "s": 27083, "text": "In a perfect square, the count of distinct prime factors must be divisible by 2. Therefore, the count of factors that are a perfect square is given by:" }, { "code": null, "e": 27385, "s": 27235, "text": "Factors of N that are perfect square = (1 + a1/2)*(1 + a2/2)*...*(1 + an/2) where a1, a2, a3, ..., an are the count of distinct prime factors of N. " }, { "code": null, "e": 27401, "s": 27385, "text": "Illustration: " }, { "code": null, "e": 27567, "s": 27401, "text": "The prime factors of N = 100 are 2, 2, 5, 5. Therefore, the number of factors that are perfect square are (1 + 2/2) * (1 + 2/2) = 4. The factors are 1, 4, 25, 100. " }, { "code": null, "e": 27745, "s": 27567, "text": "Therefore, find the count of prime factors and apply the above formula to find the count of factors that are a perfect square.Below is the implementation of the above approach: " }, { "code": null, "e": 27749, "s": 27745, "text": "C++" }, { "code": null, "e": 27754, "s": 27749, "text": "Java" }, { "code": null, "e": 27762, "s": 27754, "text": "Python3" }, { "code": null, "e": 27765, "s": 27762, "text": "C#" }, { "code": null, "e": 27776, "s": 27765, "text": "Javascript" }, { "code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function that returns the count of// factors that are perfect squaresint noOfFactors(int N){ if (N == 1) return 1; // Stores the count of number // of times a prime number // divides N. int count = 0; // Stores the number of factors // that are perfect square int ans = 1; // Count number of 2's // that divides N while (N % 2 == 0) { count++; N = N / 2; } // Calculate ans according // to above formula ans *= (count / 2 + 1); // Check for all the possible // numbers that can divide it for (int i = 3; i * i <= N; i = i + 2) { count = 0; // Check the number of // times prime number // i divides it while (N % i == 0) { count++; N = N / i; } // Calculate ans according // to above formula ans *= (count / 2 + 1); } // Return final count return ans;} // Driver Codeint main(){ int N = 100; cout << noOfFactors(N); return 0;}", "e": 28894, "s": 27776, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Function that returns the count of// factors that are perfect squaresstatic int noOfFactors(int N){ if (N == 1) return 1; // Stores the count of number // of times a prime number // divides N. int count = 0; // Stores the number of factors // that are perfect square int ans = 1; // Count number of 2's // that divides N while (N % 2 == 0) { count++; N = N / 2; } // Calculate ans according // to above formula ans *= (count / 2 + 1); // Check for all the possible // numbers that can divide it for(int i = 3; i * i <= N; i = i + 2) { count = 0; // Check the number of // times prime number // i divides it while (N % i == 0) { count++; N = N / i; } // Calculate ans according // to above formula ans *= (count / 2 + 1); } // Return final count return ans;} // Driver Codepublic static void main(String[] args){ int N = 100; System.out.print(noOfFactors(N));}} // This code is contributed by 29AjayKumar", "e": 30078, "s": 28894, "text": null }, { "code": "# Python3 program to implement# the above approach # Function that returns the count of# factors that are perfect squaresdef noOfFactors(N): if (N == 1): return 1 # Stores the count of number # of times a prime number # divides N. count = 0 # Stores the number of factors # that are perfect square ans = 1 # Count number of 2's # that divides N while (N % 2 == 0): count += 1 N = N // 2 # Calculate ans according # to above formula ans *= (count // 2 + 1) # Check for all the possible # numbers that can divide it i = 3 while i * i <= N: count = 0 # Check the number of # times prime number # i divides it while (N % i == 0): count += 1 N = N // i # Calculate ans according # to above formula ans *= (count // 2 + 1) i += 2 # Return final count return ans # Driver Codeif __name__ == \"__main__\": N = 100 print(noOfFactors(N)) # This code is contributed by chitranayal", "e": 31137, "s": 30078, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Function that returns the count of// factors that are perfect squaresstatic int noOfFactors(int N){ if (N == 1) return 1; // Stores the count of number // of times a prime number // divides N. int count = 0; // Stores the number of factors // that are perfect square int ans = 1; // Count number of 2's // that divides N while (N % 2 == 0) { count++; N = N / 2; } // Calculate ans according // to above formula ans *= (count / 2 + 1); // Check for all the possible // numbers that can divide it for(int i = 3; i * i <= N; i = i + 2) { count = 0; // Check the number of // times prime number // i divides it while (N % i == 0) { count++; N = N / i; } // Calculate ans according // to above formula ans *= (count / 2 + 1); } // Return final count return ans;} // Driver Codepublic static void Main(String[] args){ int N = 100; Console.Write(noOfFactors(N));}} // This code is contributed by PrinciRaj1992", "e": 32312, "s": 31137, "text": null }, { "code": "<script> // Javascript program for// the above approach // Function that returns the count of// factors that are perfect squaresfunction noOfFactors(N){ if (N == 1) return 1; // Stores the count of number // of times a prime number // divides N. let count = 0; // Stores the number of factors // that are perfect square let ans = 1; // Count number of 2's // that divides N while (N % 2 == 0) { count++; N = N / 2; } // Calculate ans according // to above formula ans *= (count / 2 + 1); // Check for all the possible // numbers that can divide it for(let i = 3; i * i <= N; i = i + 2) { count = 0; // Check the number of // times prime number // i divides it while (N % i == 0) { count++; N = N / i; } // Calculate ans according // to above formula ans *= (count / 2 + 1); } // Return final count return ans;} // Driver Code let N = 100; document.write(noOfFactors(N)); </script>", "e": 33414, "s": 32312, "text": null }, { "code": null, "e": 33416, "s": 33414, "text": "4" }, { "code": null, "e": 33457, "s": 33416, "text": "Time Complexity: Space Complexity: O(1) " }, { "code": null, "e": 33463, "s": 33457, "text": "ukasp" }, { "code": null, "e": 33475, "s": 33463, "text": "29AjayKumar" }, { "code": null, "e": 33489, "s": 33475, "text": "princiraj1992" }, { "code": null, "e": 33498, "s": 33489, "text": "target_2" }, { "code": null, "e": 33509, "s": 33498, "text": "suman_1729" }, { "code": null, "e": 33515, "s": 33509, "text": "Maths" }, { "code": null, "e": 33536, "s": 33515, "text": "maths-perfect-square" }, { "code": null, "e": 33555, "s": 33536, "text": "school-programming" }, { "code": null, "e": 33579, "s": 33555, "text": "Competitive Programming" }, { "code": null, "e": 33586, "s": 33579, "text": "Greedy" }, { "code": null, "e": 33599, "s": 33586, "text": "Mathematical" }, { "code": null, "e": 33606, "s": 33599, "text": "Greedy" }, { "code": null, "e": 33619, "s": 33606, "text": "Mathematical" }, { "code": null, "e": 33717, "s": 33619, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33795, "s": 33717, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 33824, "s": 33795, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 33851, "s": 33824, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 33889, "s": 33851, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 33948, "s": 33889, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 33999, "s": 33948, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 34050, "s": 33999, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 34108, "s": 34050, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 34135, "s": 34108, "text": "Program for array rotation" } ]
Features of C++ 20 - GeeksforGeeks
31 Dec, 2020 C++ has a tradition of introducing new improvements and features in every 3 years in the form of a standard. With the last standard having released in 2017 as C++ 17, C++20 is going to be the latest standard. Below ere are some major features in C++ 20: C++ Concepts library 3-way comparisons Map contains Range-based for loop New identifiers ( import, module) Calendar and time zone library std::string functions Array bounded/unbounded std::to_array Likely and unlikely attributes The concepts library provides definitions of fundamental library concepts that can be used to perform compile-time validation of template arguments and perform function dispatch based on properties of types. These concepts provide a base for educational reasoning in programs. This section has around 15 concepts that should be self-explanatory. These concepts express relationships between types, type classifications, and fundamental type properties. Defined in header <concepts> Defined in namespace std integral: Specifies that a type is an integral type. signed_integral: Specifies that a type is an integral type that is signed. unsigned_integral: Specifies that a type is an integral type that is unsigned. floating_point: Specifies that a type is a floating-point type. same_as: Specifies that a type is the same as another type. derived_from: Specifies that a type is derived from another type. convertible_to: Specifies that a type is implicitly convertible to another type. common_with: Specifies that two types share a common type. Syntax: template<class T>concept integral = is_integral_v<T>; template<class T>concept signed_integral = integral<T> && is_signed_v<T>; template<class T>concept unsigned_integral = integral<T> && !signed_integral<T>; template<class T>concept floating_point = is_floating_point_v<T>; The three-way comparison operator expressions is of the form: lhs <=> rhs The spaceship operator looks like <=> and its official C++ name is the 3-way comparison operator. It is called so because it is used by comparing two objects, then comparing that result with 0: (x <=> y) < 0 is true if x < y (x <=> y) > 0 is true if x > y (x <=> y) == 0 is true if x and y are equal/equivalent. The 3-way comparison operator not only let express orderings and equality between objects but also the characteristics of the relations. The spaceship operator is a very welcome addition to C++. It gives us more expressiveness in how to define our relations, allows us to write less code to define them, and avoids some performance pitfalls of manually implementing some comparison operators in terms of others. Program 1: C++ // C++ program to illustrate the// above concepts#include <bits/stdc++.h>#include <compare>using namespace std; // Driver Codeint main(){ int a = 91, b = 110; auto ans1 = a <= > b; if (ans1 < 0) { cout << "a < b\n"; } else if (ans1 == 0) { cout << "a == b\n"; } else if (ans1 > 0) { cout << "a > b\n"; } vector<int> v1{ 3, 6, 9 }; vector<int> v2{ 3, 6, 9 }; auto ans2 = v1 <= > v2; if (ans2 < 0) { cout << "v1 < v2\n"; } else if (ans2 == 0) { cout << "v1 == v2\n"; } else if (ans2 > 0) { cout << "v1 > v2\n"; } cout << endl;} Output: Syntax: std::map<Key, T, Compare, Allocator>::contains std::set<T>::contains It gives a much easier way to check if a key is present in the associative container(set or map) in C++20. It replaces the find built-in function. Program 2: C++ // C++ program to illustrate the// above concepts#include <iostream>#include <map> // Driver Codeint main(){ // Map std::map<int, char> M = { { 1, 'a' }, { 2, 'b' } }; // Check if M has key 2 if (M.contains(2)) { std::cout << "Found\n"; } else { std::cout << "Not found\n"; } return 0;} Output: The range-based for loop changed in C++17 to allow the begin() and end() expressions to be of different types and in C++20, an init-statement is introduced for initializing the variables in the loop-scope. It allows us to initialize the container we wish to loop through in the range-declaration itself. Syntax: for (init-statement(optional) range_declaration : range_expression) { /* loop body */} Program 3: C++ // C++ program to illustrate the// above concepts#include <iostream>using namespace std; // Driver Codeint main(){ for (std::vector v{ 1, 2, 3 }; auto& e : v) { std::cout << e; }} Output: Modules help to divide large amounts of code into logical parts. Modules promise faster compile times, isolation of macros, and make header files redundant. They express the logical structure of the code and helps in getting rid of the ugly macro workaround. Modules are orthogonal to namespaces. It makes no difference in which order you import a module. Modules enable you to express the logical structure of your code. You can explicitly specify names that should be exported or not. Additionally, you can bundle a few modules into a bigger module and you can provide them as a logical package. With modules, there is now no need to separate your source code into an interface and an implementation part. Program 4: C++ // C++ program to illustrate the// above concepts// helloworld.cpp module declarationexport module helloworld; // Import declarationimport<iostream>; // Export declarationexport void hello(){ std::cout << "Hello world!\n";} C++ // main.cpp import declarationimport helloworld; // Driver Codeint main(){ hello();} Output: The chrono library of C++ 11/14 was extended with a calendar and time-zone feature. The calendar consists of types, which represent a year, a month, a day of a weekday, or n-th weekday of a month. These elementary types can be combined with complex types such for example year_month, year_month_day, year_month_day_last, years_month_weekday, and year_month_weekday_last. The operator “/” is overloaded for the convenient specification of time points. Additionally, we will get with C++20 new literals: d for a day and y for a year. Due to the extended chrono library, the following functions are easy to implement: Get the last day of a month. Get the number of days between two dates. Printing the current time in various time-zones. Syntax: Defined in header <chrono> Defined in namespace std::chrono Example: auto date1 = 2020y/sep/8; auto date2 = 21d/oct/2018; auto date3 = jan/27/2019; ends_with(“suffix”): Checks if the string ends with the given suffix.starts_with(“prefix”) :Checks if the string view starts with the given prefix. Program 5: C++ // C++ program to illustrate the// above concepts#include <iostream>using namespace std; // Driver Codeint main(){ std::string str = "GeeksforGeeks"; // Check string str starts_with Geeks if (str.starts_with("Geeks")) { std::cout << "true" << endl; } else { std::cout << "false" << endl; } // Check string str ends_with Geeks if (str.ends_with("for")) { std::cout << "true" << endl; } else { std::cout << "false" << endl; }} Output: It checks whether T is an array type of unknown bound and provides the member constant value which is equal to true, if T is an array type of unknown bound. Otherwise, value is equal to false. It checks whether T is an array type of known bound and provides the member constant value which is equal to true, if T is an array type of known bound. Otherwise, value is equal to false. Program 6: C++ // C++ program to illustrate the// above concepts#include <iostream>#include <type_traits> // Class Aclass A {}; // Driver Codeint main(){ std::cout << std::is_unbounded_array_v<A> << '\n'; std::cout << std::is_unbounded_array_v<A[3]> << '\n'; std::cout << std::is_unbounded_array_v<int[]> << '\n'; std::cout << std::is_unbounded_array_v<int> << '\n'; std::cout << std::is_bounded_array_v<A> << '\n'; std::cout << std::is_bounded_array_v<A[3]> << '\n'; std::cout << std::is_bounded_array_v<float> << '\n'; std::cout << std::is_bounded_array_v<int> << '\n';} Output: It converts the given array/”array-like” object to an std::array. It creates an std::array from the one-dimensional built-in array a. The elements of the std::array is copy-initialized from the corresponding element of a. Copying or moving a multidimensional built-in array is not supported. Program 7: C++ // C++ program to illustrate the// above concepts#include <iostream>using namespace std; // Driver Codeint main(){ // Returns std::array<char, 5> std::to_array("Geeks"); std::to_array<int>( { 1, 2, 3 }); int a[] = { 1, 2, 3 }; // Returns std::array<int, 3>` std::to_array(a);} It provides a hint to the Optimizer that the labeled statement is likely/unlikely to have its body executed. Both attributes allow giving the Optimizer a hint, whether the path of execution is more or less likely. Program 8: C++ // C++ program to illustrate the// above concepts#include <iostream>using namespace std; // Driver Codeint main(){ int n = 40; [[likely]] if (n < 100) { cout << n * 2; } [[unlikely]] while (n > 100) { n = n / 2; cout << n << endl; } n = 500; [[likely]] if (n < 100) { cout << n * 2; } [[unlikely]] while (n > 100) { n = n / 2; cout << n << endl; } return 0;} References: C++ 20, CPP Reference. C++-References Articles C++ C++ Programs Programming Language CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexity and Space Complexity Docker - COPY Instruction Time complexities of different data structures SQL | Date functions Difference between Class and Object Vector in C++ STL Arrays in C/C++ Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL)
[ { "code": null, "e": 25665, "s": 25637, "text": "\n31 Dec, 2020" }, { "code": null, "e": 25919, "s": 25665, "text": "C++ has a tradition of introducing new improvements and features in every 3 years in the form of a standard. With the last standard having released in 2017 as C++ 17, C++20 is going to be the latest standard. Below ere are some major features in C++ 20:" }, { "code": null, "e": 25940, "s": 25919, "text": "C++ Concepts library" }, { "code": null, "e": 25958, "s": 25940, "text": "3-way comparisons" }, { "code": null, "e": 25971, "s": 25958, "text": "Map contains" }, { "code": null, "e": 25992, "s": 25971, "text": "Range-based for loop" }, { "code": null, "e": 26026, "s": 25992, "text": "New identifiers ( import, module)" }, { "code": null, "e": 26057, "s": 26026, "text": "Calendar and time zone library" }, { "code": null, "e": 26079, "s": 26057, "text": "std::string functions" }, { "code": null, "e": 26103, "s": 26079, "text": "Array bounded/unbounded" }, { "code": null, "e": 26117, "s": 26103, "text": "std::to_array" }, { "code": null, "e": 26148, "s": 26117, "text": "Likely and unlikely attributes" }, { "code": null, "e": 26425, "s": 26148, "text": "The concepts library provides definitions of fundamental library concepts that can be used to perform compile-time validation of template arguments and perform function dispatch based on properties of types. These concepts provide a base for educational reasoning in programs." }, { "code": null, "e": 26601, "s": 26425, "text": "This section has around 15 concepts that should be self-explanatory. These concepts express relationships between types, type classifications, and fundamental type properties." }, { "code": null, "e": 26656, "s": 26601, "text": "Defined in header <concepts>\nDefined in namespace std\n" }, { "code": null, "e": 26709, "s": 26656, "text": "integral: Specifies that a type is an integral type." }, { "code": null, "e": 26784, "s": 26709, "text": "signed_integral: Specifies that a type is an integral type that is signed." }, { "code": null, "e": 26863, "s": 26784, "text": "unsigned_integral: Specifies that a type is an integral type that is unsigned." }, { "code": null, "e": 26927, "s": 26863, "text": "floating_point: Specifies that a type is a floating-point type." }, { "code": null, "e": 26987, "s": 26927, "text": "same_as: Specifies that a type is the same as another type." }, { "code": null, "e": 27053, "s": 26987, "text": "derived_from: Specifies that a type is derived from another type." }, { "code": null, "e": 27134, "s": 27053, "text": "convertible_to: Specifies that a type is implicitly convertible to another type." }, { "code": null, "e": 27193, "s": 27134, "text": "common_with: Specifies that two types share a common type." }, { "code": null, "e": 27201, "s": 27193, "text": "Syntax:" }, { "code": null, "e": 27255, "s": 27201, "text": "template<class T>concept integral = is_integral_v<T>;" }, { "code": null, "e": 27329, "s": 27255, "text": "template<class T>concept signed_integral = integral<T> && is_signed_v<T>;" }, { "code": null, "e": 27410, "s": 27329, "text": "template<class T>concept unsigned_integral = integral<T> && !signed_integral<T>;" }, { "code": null, "e": 27477, "s": 27410, "text": "template<class T>concept floating_point = is_floating_point_v<T>; " }, { "code": null, "e": 27539, "s": 27477, "text": "The three-way comparison operator expressions is of the form:" }, { "code": null, "e": 27553, "s": 27539, "text": "lhs <=> rhs \n" }, { "code": null, "e": 27747, "s": 27553, "text": "The spaceship operator looks like <=> and its official C++ name is the 3-way comparison operator. It is called so because it is used by comparing two objects, then comparing that result with 0:" }, { "code": null, "e": 27867, "s": 27747, "text": "(x <=> y) < 0 is true if x < y\n(x <=> y) > 0 is true if x > y\n(x <=> y) == 0 is true if x and y are equal/equivalent.\n\n" }, { "code": null, "e": 28279, "s": 27867, "text": "The 3-way comparison operator not only let express orderings and equality between objects but also the characteristics of the relations. The spaceship operator is a very welcome addition to C++. It gives us more expressiveness in how to define our relations, allows us to write less code to define them, and avoids some performance pitfalls of manually implementing some comparison operators in terms of others." }, { "code": null, "e": 28290, "s": 28279, "text": "Program 1:" }, { "code": null, "e": 28294, "s": 28290, "text": "C++" }, { "code": "// C++ program to illustrate the// above concepts#include <bits/stdc++.h>#include <compare>using namespace std; // Driver Codeint main(){ int a = 91, b = 110; auto ans1 = a <= > b; if (ans1 < 0) { cout << \"a < b\\n\"; } else if (ans1 == 0) { cout << \"a == b\\n\"; } else if (ans1 > 0) { cout << \"a > b\\n\"; } vector<int> v1{ 3, 6, 9 }; vector<int> v2{ 3, 6, 9 }; auto ans2 = v1 <= > v2; if (ans2 < 0) { cout << \"v1 < v2\\n\"; } else if (ans2 == 0) { cout << \"v1 == v2\\n\"; } else if (ans2 > 0) { cout << \"v1 > v2\\n\"; } cout << endl;}", "e": 28929, "s": 28294, "text": null }, { "code": null, "e": 28937, "s": 28929, "text": "Output:" }, { "code": null, "e": 28945, "s": 28937, "text": "Syntax:" }, { "code": null, "e": 28992, "s": 28945, "text": "std::map<Key, T, Compare, Allocator>::contains" }, { "code": null, "e": 29014, "s": 28992, "text": "std::set<T>::contains" }, { "code": null, "e": 29161, "s": 29014, "text": "It gives a much easier way to check if a key is present in the associative container(set or map) in C++20. It replaces the find built-in function." }, { "code": null, "e": 29172, "s": 29161, "text": "Program 2:" }, { "code": null, "e": 29176, "s": 29172, "text": "C++" }, { "code": "// C++ program to illustrate the// above concepts#include <iostream>#include <map> // Driver Codeint main(){ // Map std::map<int, char> M = { { 1, 'a' }, { 2, 'b' } }; // Check if M has key 2 if (M.contains(2)) { std::cout << \"Found\\n\"; } else { std::cout << \"Not found\\n\"; } return 0;}", "e": 29533, "s": 29176, "text": null }, { "code": null, "e": 29541, "s": 29533, "text": "Output:" }, { "code": null, "e": 29845, "s": 29541, "text": "The range-based for loop changed in C++17 to allow the begin() and end() expressions to be of different types and in C++20, an init-statement is introduced for initializing the variables in the loop-scope. It allows us to initialize the container we wish to loop through in the range-declaration itself." }, { "code": null, "e": 29853, "s": 29845, "text": "Syntax:" }, { "code": null, "e": 29950, "s": 29853, "text": "for (init-statement(optional) range_declaration : range_expression) { /* loop body */}" }, { "code": null, "e": 29961, "s": 29950, "text": "Program 3:" }, { "code": null, "e": 29965, "s": 29961, "text": "C++" }, { "code": "// C++ program to illustrate the// above concepts#include <iostream>using namespace std; // Driver Codeint main(){ for (std::vector v{ 1, 2, 3 }; auto& e : v) { std::cout << e; }}", "e": 30161, "s": 29965, "text": null }, { "code": null, "e": 30169, "s": 30161, "text": "Output:" }, { "code": null, "e": 30326, "s": 30169, "text": "Modules help to divide large amounts of code into logical parts. Modules promise faster compile times, isolation of macros, and make header files redundant." }, { "code": null, "e": 30525, "s": 30326, "text": "They express the logical structure of the code and helps in getting rid of the ugly macro workaround. Modules are orthogonal to namespaces. It makes no difference in which order you import a module." }, { "code": null, "e": 30767, "s": 30525, "text": "Modules enable you to express the logical structure of your code. You can explicitly specify names that should be exported or not. Additionally, you can bundle a few modules into a bigger module and you can provide them as a logical package." }, { "code": null, "e": 30877, "s": 30767, "text": "With modules, there is now no need to separate your source code into an interface and an implementation part." }, { "code": null, "e": 30888, "s": 30877, "text": "Program 4:" }, { "code": null, "e": 30892, "s": 30888, "text": "C++" }, { "code": "// C++ program to illustrate the// above concepts// helloworld.cpp module declarationexport module helloworld; // Import declarationimport<iostream>; // Export declarationexport void hello(){ std::cout << \"Hello world!\\n\";}", "e": 31121, "s": 30892, "text": null }, { "code": null, "e": 31125, "s": 31121, "text": "C++" }, { "code": "// main.cpp import declarationimport helloworld; // Driver Codeint main(){ hello();}", "e": 31214, "s": 31125, "text": null }, { "code": null, "e": 31222, "s": 31214, "text": "Output:" }, { "code": null, "e": 31754, "s": 31222, "text": "The chrono library of C++ 11/14 was extended with a calendar and time-zone feature. The calendar consists of types, which represent a year, a month, a day of a weekday, or n-th weekday of a month. These elementary types can be combined with complex types such for example year_month, year_month_day, year_month_day_last, years_month_weekday, and year_month_weekday_last. The operator “/” is overloaded for the convenient specification of time points. Additionally, we will get with C++20 new literals: d for a day and y for a year." }, { "code": null, "e": 31837, "s": 31754, "text": "Due to the extended chrono library, the following functions are easy to implement:" }, { "code": null, "e": 31866, "s": 31837, "text": "Get the last day of a month." }, { "code": null, "e": 31908, "s": 31866, "text": "Get the number of days between two dates." }, { "code": null, "e": 31957, "s": 31908, "text": "Printing the current time in various time-zones." }, { "code": null, "e": 31965, "s": 31957, "text": "Syntax:" }, { "code": null, "e": 32026, "s": 31965, "text": "Defined in header <chrono>\nDefined in namespace std::chrono\n" }, { "code": null, "e": 32035, "s": 32026, "text": "Example:" }, { "code": null, "e": 32115, "s": 32035, "text": "auto date1 = 2020y/sep/8;\nauto date2 = 21d/oct/2018;\nauto date3 = jan/27/2019;\n" }, { "code": null, "e": 32263, "s": 32115, "text": "ends_with(“suffix”): Checks if the string ends with the given suffix.starts_with(“prefix”) :Checks if the string view starts with the given prefix." }, { "code": null, "e": 32274, "s": 32263, "text": "Program 5:" }, { "code": null, "e": 32278, "s": 32274, "text": "C++" }, { "code": "// C++ program to illustrate the// above concepts#include <iostream>using namespace std; // Driver Codeint main(){ std::string str = \"GeeksforGeeks\"; // Check string str starts_with Geeks if (str.starts_with(\"Geeks\")) { std::cout << \"true\" << endl; } else { std::cout << \"false\" << endl; } // Check string str ends_with Geeks if (str.ends_with(\"for\")) { std::cout << \"true\" << endl; } else { std::cout << \"false\" << endl; }}", "e": 32773, "s": 32278, "text": null }, { "code": null, "e": 32781, "s": 32773, "text": "Output:" }, { "code": null, "e": 32974, "s": 32781, "text": "It checks whether T is an array type of unknown bound and provides the member constant value which is equal to true, if T is an array type of unknown bound. Otherwise, value is equal to false." }, { "code": null, "e": 33163, "s": 32974, "text": "It checks whether T is an array type of known bound and provides the member constant value which is equal to true, if T is an array type of known bound. Otherwise, value is equal to false." }, { "code": null, "e": 33174, "s": 33163, "text": "Program 6:" }, { "code": null, "e": 33178, "s": 33174, "text": "C++" }, { "code": "// C++ program to illustrate the// above concepts#include <iostream>#include <type_traits> // Class Aclass A {}; // Driver Codeint main(){ std::cout << std::is_unbounded_array_v<A> << '\\n'; std::cout << std::is_unbounded_array_v<A[3]> << '\\n'; std::cout << std::is_unbounded_array_v<int[]> << '\\n'; std::cout << std::is_unbounded_array_v<int> << '\\n'; std::cout << std::is_bounded_array_v<A> << '\\n'; std::cout << std::is_bounded_array_v<A[3]> << '\\n'; std::cout << std::is_bounded_array_v<float> << '\\n'; std::cout << std::is_bounded_array_v<int> << '\\n';}", "e": 33764, "s": 33178, "text": null }, { "code": null, "e": 33772, "s": 33764, "text": "Output:" }, { "code": null, "e": 34064, "s": 33772, "text": "It converts the given array/”array-like” object to an std::array. It creates an std::array from the one-dimensional built-in array a. The elements of the std::array is copy-initialized from the corresponding element of a. Copying or moving a multidimensional built-in array is not supported." }, { "code": null, "e": 34075, "s": 34064, "text": "Program 7:" }, { "code": null, "e": 34079, "s": 34075, "text": "C++" }, { "code": "// C++ program to illustrate the// above concepts#include <iostream>using namespace std; // Driver Codeint main(){ // Returns std::array<char, 5> std::to_array(\"Geeks\"); std::to_array<int>( { 1, 2, 3 }); int a[] = { 1, 2, 3 }; // Returns std::array<int, 3>` std::to_array(a);}", "e": 34388, "s": 34079, "text": null }, { "code": null, "e": 34602, "s": 34388, "text": "It provides a hint to the Optimizer that the labeled statement is likely/unlikely to have its body executed. Both attributes allow giving the Optimizer a hint, whether the path of execution is more or less likely." }, { "code": null, "e": 34613, "s": 34602, "text": "Program 8:" }, { "code": null, "e": 34617, "s": 34613, "text": "C++" }, { "code": "// C++ program to illustrate the// above concepts#include <iostream>using namespace std; // Driver Codeint main(){ int n = 40; [[likely]] if (n < 100) { cout << n * 2; } [[unlikely]] while (n > 100) { n = n / 2; cout << n << endl; } n = 500; [[likely]] if (n < 100) { cout << n * 2; } [[unlikely]] while (n > 100) { n = n / 2; cout << n << endl; } return 0;}", "e": 35044, "s": 34617, "text": null }, { "code": null, "e": 35079, "s": 35044, "text": "References: C++ 20, CPP Reference." }, { "code": null, "e": 35094, "s": 35079, "text": "C++-References" }, { "code": null, "e": 35103, "s": 35094, "text": "Articles" }, { "code": null, "e": 35107, "s": 35103, "text": "C++" }, { "code": null, "e": 35120, "s": 35107, "text": "C++ Programs" }, { "code": null, "e": 35141, "s": 35120, "text": "Programming Language" }, { "code": null, "e": 35145, "s": 35141, "text": "CPP" }, { "code": null, "e": 35243, "s": 35145, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35280, "s": 35243, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 35306, "s": 35280, "text": "Docker - COPY Instruction" }, { "code": null, "e": 35353, "s": 35306, "text": "Time complexities of different data structures" }, { "code": null, "e": 35374, "s": 35353, "text": "SQL | Date functions" }, { "code": null, "e": 35410, "s": 35374, "text": "Difference between Class and Object" }, { "code": null, "e": 35428, "s": 35410, "text": "Vector in C++ STL" }, { "code": null, "e": 35444, "s": 35428, "text": "Arrays in C/C++" }, { "code": null, "e": 35490, "s": 35444, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 35509, "s": 35490, "text": "Inheritance in C++" } ]
Cross Join in LINQ - GeeksforGeeks
01 Jan, 2020 In LINQ, the cross join is a process in which the elements of two sequences are combined with each other means the element of first sequence or collection is combined with the elements of another sequence or collection without any key selection or any filtering condition and the number of elements present in the resulting sequence is equal to the product of the elements in the two source sequences or collections. Or in other words, we can say that cross join will produce a Cartesian product. Cross join is also known as full join. In cross join, we do not require on keyword which specifies the condition for joining. Let us discuss this concept with the help of given examples: Example 1: // C# program to illustrate the concept// of the cross joinusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_lang { get; set; } public int dpt_id { get; set; }} // Employee department detailspublic class Department { public int dpt_id { get; set; } public string emp_dept { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() { emp_id = 101, emp_name = "Amit", emp_lang = "Java", dpt_id = 1 }, new Employee() { emp_id = 102, emp_name = "Mohit", emp_lang = "C#", dpt_id = 2 }, new Employee() { emp_id = 103, emp_name = "Sona", emp_lang = "Java", dpt_id = 1 }, new Employee() { emp_id = 104, emp_name = "Lana", emp_lang = "C++", dpt_id = 3 }, new Employee() { emp_id = 105, emp_name = "Roma", emp_lang = "C#", dpt_id = 2 }, }; List<Department> Dpt = new List<Department>() { new Department() { dpt_id = 1, emp_dept = "Designing" }, new Department() { dpt_id = 2, emp_dept = "Development" }, new Department() { dpt_id = 3, emp_dept = "JE" }, }; // Implementing Cross join using query syntax var res = from first in emp from second in Dpt select new { Employee_name = first.emp_name, Department_name = second.emp_dept }; // Display result foreach(var val in res) { Console.WriteLine(" Employee Name: {0} || Department Name: {1}", val.Employee_name, val.Department_name); } }} Output: Employee Name: Amit || Department Name: Designing Employee Name: Amit || Department Name: Development Employee Name: Amit || Department Name: JE Employee Name: Mohit || Department Name: Designing Employee Name: Mohit || Department Name: Development Employee Name: Mohit || Department Name: JE Employee Name: Sona || Department Name: Designing Employee Name: Sona || Department Name: Development Employee Name: Sona || Department Name: JE Employee Name: Lana || Department Name: Designing Employee Name: Lana || Department Name: Development Employee Name: Lana || Department Name: JE Employee Name: Roma || Department Name: Designing Employee Name: Roma || Department Name: Development Employee Name: Roma || Department Name: JE Example 2: // C# program to illustrate the concept// of cross joinusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_lang { get; set; } public int dpt_id { get; set; }} // Employee department detailspublic class Department { public int dpt_id { get; set; } public string emp_dept { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() { emp_id = 101, emp_name = "Amit", emp_lang = "Java", dpt_id = 1 }, new Employee() { emp_id = 102, emp_name = "Mohit", emp_lang = "C#", dpt_id = 2 }, }; List<Department> Dpt = new List<Department>() { new Department() { dpt_id = 1, emp_dept = "Designing" }, new Department() { dpt_id = 2, emp_dept = "Development" }, }; // Implementing Cross join using // SelectMany method and lambda // expression var res_1 = Dpt.SelectMany(e => emp,(x, y) => new { Department_name = x.emp_dept, Employee_name = y.emp_name}); // Display result foreach(var val in res_1) { Console.WriteLine(" Department Name: {0} || Employee Name: {1}", val.Department_name, val.Employee_name); } // Implementing Cross join using // Join method and lambda expression var res_2 = Dpt.Join(emp, x => true, y => true, (x, y) => new { Department_name = x.emp_dept, Employee_name = y.emp_name}); Console.WriteLine(); // Display result foreach(var val in res_2) { Console.WriteLine(" Department Name: {0} || Employee Name: {1}", val.Department_name, val.Employee_name); } }} Output: Department Name: Designing || Employee Name: Amit Department Name: Designing || Employee Name: Mohit Department Name: Development || Employee Name: Amit Department Name: Development || Employee Name: Mohit Department Name: Designing || Employee Name: Amit Department Name: Designing || Employee Name: Mohit Department Name: Development || Employee Name: Amit Department Name: Development || Employee Name: Mohit CSharp LINQ 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 C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Lambda Expressions in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n01 Jan, 2020" }, { "code": null, "e": 26170, "s": 25547, "text": "In LINQ, the cross join is a process in which the elements of two sequences are combined with each other means the element of first sequence or collection is combined with the elements of another sequence or collection without any key selection or any filtering condition and the number of elements present in the resulting sequence is equal to the product of the elements in the two source sequences or collections. Or in other words, we can say that cross join will produce a Cartesian product. Cross join is also known as full join. In cross join, we do not require on keyword which specifies the condition for joining." }, { "code": null, "e": 26231, "s": 26170, "text": "Let us discuss this concept with the help of given examples:" }, { "code": null, "e": 26242, "s": 26231, "text": "Example 1:" }, { "code": "// C# program to illustrate the concept// of the cross joinusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_lang { get; set; } public int dpt_id { get; set; }} // Employee department detailspublic class Department { public int dpt_id { get; set; } public string emp_dept { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() { emp_id = 101, emp_name = \"Amit\", emp_lang = \"Java\", dpt_id = 1 }, new Employee() { emp_id = 102, emp_name = \"Mohit\", emp_lang = \"C#\", dpt_id = 2 }, new Employee() { emp_id = 103, emp_name = \"Sona\", emp_lang = \"Java\", dpt_id = 1 }, new Employee() { emp_id = 104, emp_name = \"Lana\", emp_lang = \"C++\", dpt_id = 3 }, new Employee() { emp_id = 105, emp_name = \"Roma\", emp_lang = \"C#\", dpt_id = 2 }, }; List<Department> Dpt = new List<Department>() { new Department() { dpt_id = 1, emp_dept = \"Designing\" }, new Department() { dpt_id = 2, emp_dept = \"Development\" }, new Department() { dpt_id = 3, emp_dept = \"JE\" }, }; // Implementing Cross join using query syntax var res = from first in emp from second in Dpt select new { Employee_name = first.emp_name, Department_name = second.emp_dept }; // Display result foreach(var val in res) { Console.WriteLine(\" Employee Name: {0} || Department Name: {1}\", val.Employee_name, val.Department_name); } }}", "e": 28384, "s": 26242, "text": null }, { "code": null, "e": 28392, "s": 28384, "text": "Output:" }, { "code": null, "e": 29136, "s": 28392, "text": " Employee Name: Amit || Department Name: Designing\n Employee Name: Amit || Department Name: Development\n Employee Name: Amit || Department Name: JE\n Employee Name: Mohit || Department Name: Designing\n Employee Name: Mohit || Department Name: Development\n Employee Name: Mohit || Department Name: JE\n Employee Name: Sona || Department Name: Designing\n Employee Name: Sona || Department Name: Development\n Employee Name: Sona || Department Name: JE\n Employee Name: Lana || Department Name: Designing\n Employee Name: Lana || Department Name: Development\n Employee Name: Lana || Department Name: JE\n Employee Name: Roma || Department Name: Designing\n Employee Name: Roma || Department Name: Development\n Employee Name: Roma || Department Name: JE\n" }, { "code": null, "e": 29147, "s": 29136, "text": "Example 2:" }, { "code": "// C# program to illustrate the concept// of cross joinusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_lang { get; set; } public int dpt_id { get; set; }} // Employee department detailspublic class Department { public int dpt_id { get; set; } public string emp_dept { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() { emp_id = 101, emp_name = \"Amit\", emp_lang = \"Java\", dpt_id = 1 }, new Employee() { emp_id = 102, emp_name = \"Mohit\", emp_lang = \"C#\", dpt_id = 2 }, }; List<Department> Dpt = new List<Department>() { new Department() { dpt_id = 1, emp_dept = \"Designing\" }, new Department() { dpt_id = 2, emp_dept = \"Development\" }, }; // Implementing Cross join using // SelectMany method and lambda // expression var res_1 = Dpt.SelectMany(e => emp,(x, y) => new { Department_name = x.emp_dept, Employee_name = y.emp_name}); // Display result foreach(var val in res_1) { Console.WriteLine(\" Department Name: {0} || Employee Name: {1}\", val.Department_name, val.Employee_name); } // Implementing Cross join using // Join method and lambda expression var res_2 = Dpt.Join(emp, x => true, y => true, (x, y) => new { Department_name = x.emp_dept, Employee_name = y.emp_name}); Console.WriteLine(); // Display result foreach(var val in res_2) { Console.WriteLine(\" Department Name: {0} || Employee Name: {1}\", val.Department_name, val.Employee_name); } }}", "e": 31407, "s": 29147, "text": null }, { "code": null, "e": 31415, "s": 31407, "text": "Output:" }, { "code": null, "e": 31837, "s": 31415, "text": " Department Name: Designing || Employee Name: Amit\n Department Name: Designing || Employee Name: Mohit\n Department Name: Development || Employee Name: Amit\n Department Name: Development || Employee Name: Mohit\n\n Department Name: Designing || Employee Name: Amit\n Department Name: Designing || Employee Name: Mohit\n Department Name: Development || Employee Name: Amit\n Department Name: Development || Employee Name: Mohit\n" }, { "code": null, "e": 31849, "s": 31837, "text": "CSharp LINQ" }, { "code": null, "e": 31852, "s": 31849, "text": "C#" }, { "code": null, "e": 31950, "s": 31852, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31973, "s": 31950, "text": "Extension Method in C#" }, { "code": null, "e": 32001, "s": 31973, "text": "HashSet in C# with Examples" }, { "code": null, "e": 32018, "s": 32001, "text": "C# | Inheritance" }, { "code": null, "e": 32040, "s": 32018, "text": "Partial Classes in C#" }, { "code": null, "e": 32069, "s": 32040, "text": "C# | Generics - Introduction" }, { "code": null, "e": 32109, "s": 32069, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 32132, "s": 32109, "text": "Switch Statement in C#" }, { "code": null, "e": 32172, "s": 32132, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 32215, "s": 32172, "text": "C# | How to insert an element in an Array?" } ]
Sorting array of strings (or words) using Trie | Set-2 (Handling Duplicates) - GeeksforGeeks
09 Jul, 2021 Given an array of strings, print them in alphabetical (dictionary) order. If there are duplicates in input array, we need to print all the occurrences.Examples: Input : arr[] = { "abc", "xyz", "abcd", "bcd", "abc" } Output : abc abc abcd bcd xyz Input : arr[] = { "geeks", "for", "geeks", "a", "portal", "to", "learn" } Output : a for geeks geeks learn portal to Prerequisite: Trie | (Insert and Search). Approach: In the previous post array of strings is being sorted, printing only single occurrence of duplicate strings. In this post all occurrences of duplicate strings are printed in lexicographic order. To print the strings in alphabetical order we have to first insert them in the trie and then perform preorder traversal to print in alphabetical order. The nodes of trie contain an index[] array which stores the index position of all the strings of arr[] ending at that node. Except for trie’s leaf node all the other nodes have size 0 for the index[] array.Below is the implementation of the above approach. C++ Java C# Python3 Javascript // C++ implementation to sort an array// of strings using Trie#include <bits/stdc++.h>using namespace std; const int MAX_CHAR = 26; struct Trie { // 'index' vectors size is greater than // 0 when node/ is a leaf node, otherwise // size is 0; vector<int> index; Trie* child[MAX_CHAR]; /*to make new trie*/ Trie() { // initializing fields for (int i = 0; i < MAX_CHAR; i++) child[i] = NULL; }}; // function to insert a string in trievoid insert(Trie* root, string str, int index){ Trie* node = root; for (int i = 0; i < str.size(); i++) { // taking ascii value to find index of // child node char ind = str[i] - 'a'; // making a new path if not already if (!node->child[ind]) node->child[ind] = new Trie(); // go to next node node = node->child[ind]; } // Mark leaf (end of string) and store // index of 'str' in index[] (node->index).push_back(index);} // function for preorder traversal of trievoid preorder(Trie* node, string arr[]){ // if node is empty if (node == NULL) return; for (int i = 0; i < MAX_CHAR; i++) { if (node->child[i] != NULL) { // if leaf node then print all the strings // for (node->child[i]->index).size() > 0) for (int j = 0; j < (node->child[i]->index).size(); j++) cout << arr[node->child[i]->index[j]] << " "; preorder(node->child[i], arr); } }} // function to sort an array// of strings using Trievoid printSorted(string arr[], int n){ Trie* root = new Trie(); // insert all strings of dictionary into trie for (int i = 0; i < n; i++) insert(root, arr[i], i); // print strings in lexicographic order preorder(root, arr);} // Driver program to test aboveint main(){ string arr[] = { "abc", "xyz", "abcd", "bcd", "abc" }; int n = sizeof(arr) / sizeof(arr[0]); printSorted(arr, n); return 0;} // Java implementation// to sort an array of// strings using Trieimport java.util.*; class Trie { private Node rootNode; /*to make new trie*/ Trie() { rootNode = null; } // function to insert // a string in trie void insert(String key, int index) { // making a new path // if not already if (rootNode == null) { rootNode = new Node(); } Node currentNode = rootNode; for (int i = 0;i < key.length();i++) { char keyChar = key.charAt(i); if (currentNode.getChild(keyChar) == null) { currentNode.addChild(keyChar); } // go to next node currentNode = currentNode.getChild(keyChar); } // Mark leaf (end of string) // and store index of 'str' // in index[] currentNode.addIndex(index); } void traversePreorder(String[] array) { traversePreorder(rootNode, array); } // function for preorder // traversal of trie private void traversePreorder(Node node, String[] array) { if (node == null) { return; } if (node.getIndices().size() > 0) { for (int index : node.getIndices()) { System.out.print(array[index] + " "); } } for (char index = 'a';index <= 'z';index++) { traversePreorder(node.getChild(index), array); } } private static class Node { private Node[] children; private List<Integer> indices; Node() { children = new Node[26]; indices = new ArrayList<>(0); } Node getChild(char index) { if (index < 'a' || index > 'z') { return null; } return children[index - 'a']; } void addChild(char index) { if (index < 'a' || index > 'z') { return; } Node node = new Node(); children[index - 'a'] = node; } List<Integer> getIndices() { return indices; } void addIndex(int index) { indices.add(index); } }} class SortStrings { // Driver program public static void main(String[] args) { String[] array = { "abc", "xyz", "abcd", "bcd", "abc" }; printInSortedOrder(array); } // function to sort an array // of strings using Trie private static void printInSortedOrder(String[] array) { Trie trie = new Trie(); for (int i = 0;i < array.length;i++) { trie.insert(array[i], i); } trie.traversePreorder(array); }} // Contributed by Harikrishnan Rajan // C# implementation// to sort an array of// strings using Trieusing System;using System.Collections.Generic; public class Trie{ public Node rootNode; /* to make new trie*/ public Trie() { rootNode = null; } // function to insert // a string in trie public void insert(String key, int index) { // making a new path // if not already if (rootNode == null) { rootNode = new Node(); } Node currentNode = rootNode; for (int i = 0;i < key.Length;i++) { char keyChar = key[i]; if (currentNode.getChild(keyChar) == null) { currentNode.addChild(keyChar); } // go to next node currentNode = currentNode.getChild(keyChar); } // Mark leaf (end of string) // and store index of 'str' // in index[] currentNode.addIndex(index); } public void traversePreorder(String[] array) { traversePreorder(rootNode, array); } // function for preorder // traversal of trie public void traversePreorder(Node node, String[] array) { if (node == null) { return; } if (node.getIndices().Count > 0) { foreach (int index in node.getIndices()) { Console.Write(array[index] + " "); } } for (char index = 'a';index <= 'z';index++) { traversePreorder(node.getChild(index), array); } } public class Node { public Node[] children; public List<int> indices; public Node() { children = new Node[26]; indices = new List<int>(0); } public Node getChild(char index) { if (index < 'a' || index > 'z') { return null; } return children[index - 'a']; } public void addChild(char index) { if (index < 'a' || index > 'z') { return; } Node node = new Node(); children[index - 'a'] = node; } public List<int> getIndices() { return indices; } public void addIndex(int index) { indices.Add(index); } }} public class SortStrings{ // Driver code public static void Main(String[] args) { String[] array = { "abc", "xyz", "abcd", "bcd", "abc" }; printInSortedOrder(array); } // function to sort an array // of strings using Trie static void printInSortedOrder(String[] array) { Trie trie = new Trie(); for (int i = 0;i < array.Length;i++) { trie.insert(array[i], i); } trie.traversePreorder(array); }} // This code has been contributed by 29AjayKumar # Python implementation to sort an array# of strings using Triefrom typing import ListMAX_CHAR = 26class Trie: def __init__(self) -> None: # 'index' vectors size is greater than # 0 when node/ is a leaf node, otherwise # size is 0; self.index = [] self.child = [None for _ in range(MAX_CHAR)] # function to insert a string in triedef insert(root: Trie, string: str, index: int) -> None: node = root for i in range(len(string)): # taking ascii value to find index of # child node ind = ord(string[i]) - ord('a') # making a new path if not already if (node.child[ind] == None): node.child[ind] = Trie() # go to next node node = node.child[ind] # Mark leaf (end of string) and store # index of 'str' in index[] (node.index).append(index) # function for preorder traversal of triedef preorder(node: Trie, arr: List[str]) -> None: # if node is empty if (node == None): return for i in range(MAX_CHAR): if (node.child[i] != None): # if leaf node then print all the strings # for (node.child[i].index).size() > 0) for j in range(len(node.child[i].index)): print(arr[node.child[i].index[j]], end = " ") preorder(node.child[i], arr) # function to sort an array# of strings using Triedef printSorted(arr: List[str], n: int) -> None: root = Trie() # insert all strings of dictionary into trie for i in range(n): insert(root, arr[i], i) # print strings in lexicographic order preorder(root, arr) # Driver program to test aboveif __name__ == "__main__": arr = ["abc", "xyz", "abcd", "bcd", "abc"] n = len(arr) printSorted(arr, n) # This code is contributed by sanjeev2552 <script> // JavaScript implementation// to sort an array of// strings using Trie let rootNode=null; // function to insert // a string in triefunction insert(key,index){ // making a new path // if not already if (rootNode == null) { rootNode = new Node(); } let currentNode = rootNode; for (let i = 0;i < key.length;i++) { let keyChar = key[i]; if (currentNode.getChild(keyChar) == null) { currentNode.addChild(keyChar); } // go to next node currentNode = currentNode.getChild(keyChar); } // Mark leaf (end of string) // and store index of 'str' // in index[] currentNode.addIndex(index);} // function for preorder // traversal of triefunction traversePreorder(array){ _traversePreorder(rootNode, array);} function _traversePreorder(node,array){ if (node == null) { return; } if (node.getIndices().length > 0) { for (let index=0;index< node.getIndices().length;index++) { document.write(array[node.getIndices()[index]] + " "); } } for (let index = 'a'.charCodeAt(0);index <= 'z'.charCodeAt(0);index++) { _traversePreorder(node.getChild(String.fromCharCode(index)), array); }} class Node{ constructor() { this.children = new Array(26); this.indices = []; } getChild(index) { if (index < 'a' || index > 'z') { return null; } return this.children[index.charCodeAt(0) - 'a'.charCodeAt(0)]; } addChild(index) { if (index < 'a' || index > 'z') { return; } let node = new Node(); this.children[index.charCodeAt(0) - 'a'.charCodeAt(0)] = node; } getIndices() { return this.indices; } addIndex(index) { this.indices.push(index); } } // function to sort an array // of strings using Triefunction printInSortedOrder(array){ for (let i = 0;i < array.length;i++) { insert(array[i], i); } traversePreorder(array);} // Driver programarray=["abc", "xyz","abcd", "bcd", "abc"]; printInSortedOrder(array); // This code is contributed by rag2127 </script> Output: abc abc abcd bcd xyz Time Complexity: Worst case occurs when every string is starting with a different character. In that case, it will visit all the nodes of each character of each string. So worst-case time complexity will be the sum of the length of every string i.e. O(|S1| + |S2| + |S3| + ... + |Sn|) where |S| is the length of the string. 29AjayKumar Aakash_Panchal sanjeev2552 rag2127 Trie Advanced Data Structure Sorting Sorting Trie Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ordered Set and GNU C++ PBDS 2-3 Trees | (Search, Insert and Deletion) Extendible Hashing (Dynamic approach to DBMS) Suffix Array | Set 1 (Introduction) Difference between Backtracking and Branch-N-Bound technique
[ { "code": null, "e": 25733, "s": 25705, "text": "\n09 Jul, 2021" }, { "code": null, "e": 25896, "s": 25733, "text": "Given an array of strings, print them in alphabetical (dictionary) order. If there are duplicates in input array, we need to print all the occurrences.Examples: " }, { "code": null, "e": 26118, "s": 25896, "text": "Input : arr[] = { \"abc\", \"xyz\", \"abcd\", \"bcd\", \"abc\" }\nOutput : abc abc abcd bcd xyz\n\nInput : arr[] = { \"geeks\", \"for\", \"geeks\", \"a\", \"portal\", \n \"to\", \"learn\" }\nOutput : a for geeks geeks learn portal to" }, { "code": null, "e": 26777, "s": 26120, "text": "Prerequisite: Trie | (Insert and Search). Approach: In the previous post array of strings is being sorted, printing only single occurrence of duplicate strings. In this post all occurrences of duplicate strings are printed in lexicographic order. To print the strings in alphabetical order we have to first insert them in the trie and then perform preorder traversal to print in alphabetical order. The nodes of trie contain an index[] array which stores the index position of all the strings of arr[] ending at that node. Except for trie’s leaf node all the other nodes have size 0 for the index[] array.Below is the implementation of the above approach. " }, { "code": null, "e": 26781, "s": 26777, "text": "C++" }, { "code": null, "e": 26786, "s": 26781, "text": "Java" }, { "code": null, "e": 26789, "s": 26786, "text": "C#" }, { "code": null, "e": 26797, "s": 26789, "text": "Python3" }, { "code": null, "e": 26808, "s": 26797, "text": "Javascript" }, { "code": "// C++ implementation to sort an array// of strings using Trie#include <bits/stdc++.h>using namespace std; const int MAX_CHAR = 26; struct Trie { // 'index' vectors size is greater than // 0 when node/ is a leaf node, otherwise // size is 0; vector<int> index; Trie* child[MAX_CHAR]; /*to make new trie*/ Trie() { // initializing fields for (int i = 0; i < MAX_CHAR; i++) child[i] = NULL; }}; // function to insert a string in trievoid insert(Trie* root, string str, int index){ Trie* node = root; for (int i = 0; i < str.size(); i++) { // taking ascii value to find index of // child node char ind = str[i] - 'a'; // making a new path if not already if (!node->child[ind]) node->child[ind] = new Trie(); // go to next node node = node->child[ind]; } // Mark leaf (end of string) and store // index of 'str' in index[] (node->index).push_back(index);} // function for preorder traversal of trievoid preorder(Trie* node, string arr[]){ // if node is empty if (node == NULL) return; for (int i = 0; i < MAX_CHAR; i++) { if (node->child[i] != NULL) { // if leaf node then print all the strings // for (node->child[i]->index).size() > 0) for (int j = 0; j < (node->child[i]->index).size(); j++) cout << arr[node->child[i]->index[j]] << \" \"; preorder(node->child[i], arr); } }} // function to sort an array// of strings using Trievoid printSorted(string arr[], int n){ Trie* root = new Trie(); // insert all strings of dictionary into trie for (int i = 0; i < n; i++) insert(root, arr[i], i); // print strings in lexicographic order preorder(root, arr);} // Driver program to test aboveint main(){ string arr[] = { \"abc\", \"xyz\", \"abcd\", \"bcd\", \"abc\" }; int n = sizeof(arr) / sizeof(arr[0]); printSorted(arr, n); return 0;}", "e": 28795, "s": 26808, "text": null }, { "code": "// Java implementation// to sort an array of// strings using Trieimport java.util.*; class Trie { private Node rootNode; /*to make new trie*/ Trie() { rootNode = null; } // function to insert // a string in trie void insert(String key, int index) { // making a new path // if not already if (rootNode == null) { rootNode = new Node(); } Node currentNode = rootNode; for (int i = 0;i < key.length();i++) { char keyChar = key.charAt(i); if (currentNode.getChild(keyChar) == null) { currentNode.addChild(keyChar); } // go to next node currentNode = currentNode.getChild(keyChar); } // Mark leaf (end of string) // and store index of 'str' // in index[] currentNode.addIndex(index); } void traversePreorder(String[] array) { traversePreorder(rootNode, array); } // function for preorder // traversal of trie private void traversePreorder(Node node, String[] array) { if (node == null) { return; } if (node.getIndices().size() > 0) { for (int index : node.getIndices()) { System.out.print(array[index] + \" \"); } } for (char index = 'a';index <= 'z';index++) { traversePreorder(node.getChild(index), array); } } private static class Node { private Node[] children; private List<Integer> indices; Node() { children = new Node[26]; indices = new ArrayList<>(0); } Node getChild(char index) { if (index < 'a' || index > 'z') { return null; } return children[index - 'a']; } void addChild(char index) { if (index < 'a' || index > 'z') { return; } Node node = new Node(); children[index - 'a'] = node; } List<Integer> getIndices() { return indices; } void addIndex(int index) { indices.add(index); } }} class SortStrings { // Driver program public static void main(String[] args) { String[] array = { \"abc\", \"xyz\", \"abcd\", \"bcd\", \"abc\" }; printInSortedOrder(array); } // function to sort an array // of strings using Trie private static void printInSortedOrder(String[] array) { Trie trie = new Trie(); for (int i = 0;i < array.length;i++) { trie.insert(array[i], i); } trie.traversePreorder(array); }} // Contributed by Harikrishnan Rajan", "e": 31721, "s": 28795, "text": null }, { "code": "// C# implementation// to sort an array of// strings using Trieusing System;using System.Collections.Generic; public class Trie{ public Node rootNode; /* to make new trie*/ public Trie() { rootNode = null; } // function to insert // a string in trie public void insert(String key, int index) { // making a new path // if not already if (rootNode == null) { rootNode = new Node(); } Node currentNode = rootNode; for (int i = 0;i < key.Length;i++) { char keyChar = key[i]; if (currentNode.getChild(keyChar) == null) { currentNode.addChild(keyChar); } // go to next node currentNode = currentNode.getChild(keyChar); } // Mark leaf (end of string) // and store index of 'str' // in index[] currentNode.addIndex(index); } public void traversePreorder(String[] array) { traversePreorder(rootNode, array); } // function for preorder // traversal of trie public void traversePreorder(Node node, String[] array) { if (node == null) { return; } if (node.getIndices().Count > 0) { foreach (int index in node.getIndices()) { Console.Write(array[index] + \" \"); } } for (char index = 'a';index <= 'z';index++) { traversePreorder(node.getChild(index), array); } } public class Node { public Node[] children; public List<int> indices; public Node() { children = new Node[26]; indices = new List<int>(0); } public Node getChild(char index) { if (index < 'a' || index > 'z') { return null; } return children[index - 'a']; } public void addChild(char index) { if (index < 'a' || index > 'z') { return; } Node node = new Node(); children[index - 'a'] = node; } public List<int> getIndices() { return indices; } public void addIndex(int index) { indices.Add(index); } }} public class SortStrings{ // Driver code public static void Main(String[] args) { String[] array = { \"abc\", \"xyz\", \"abcd\", \"bcd\", \"abc\" }; printInSortedOrder(array); } // function to sort an array // of strings using Trie static void printInSortedOrder(String[] array) { Trie trie = new Trie(); for (int i = 0;i < array.Length;i++) { trie.insert(array[i], i); } trie.traversePreorder(array); }} // This code has been contributed by 29AjayKumar", "e": 34714, "s": 31721, "text": null }, { "code": "# Python implementation to sort an array# of strings using Triefrom typing import ListMAX_CHAR = 26class Trie: def __init__(self) -> None: # 'index' vectors size is greater than # 0 when node/ is a leaf node, otherwise # size is 0; self.index = [] self.child = [None for _ in range(MAX_CHAR)] # function to insert a string in triedef insert(root: Trie, string: str, index: int) -> None: node = root for i in range(len(string)): # taking ascii value to find index of # child node ind = ord(string[i]) - ord('a') # making a new path if not already if (node.child[ind] == None): node.child[ind] = Trie() # go to next node node = node.child[ind] # Mark leaf (end of string) and store # index of 'str' in index[] (node.index).append(index) # function for preorder traversal of triedef preorder(node: Trie, arr: List[str]) -> None: # if node is empty if (node == None): return for i in range(MAX_CHAR): if (node.child[i] != None): # if leaf node then print all the strings # for (node.child[i].index).size() > 0) for j in range(len(node.child[i].index)): print(arr[node.child[i].index[j]], end = \" \") preorder(node.child[i], arr) # function to sort an array# of strings using Triedef printSorted(arr: List[str], n: int) -> None: root = Trie() # insert all strings of dictionary into trie for i in range(n): insert(root, arr[i], i) # print strings in lexicographic order preorder(root, arr) # Driver program to test aboveif __name__ == \"__main__\": arr = [\"abc\", \"xyz\", \"abcd\", \"bcd\", \"abc\"] n = len(arr) printSorted(arr, n) # This code is contributed by sanjeev2552", "e": 36509, "s": 34714, "text": null }, { "code": "<script> // JavaScript implementation// to sort an array of// strings using Trie let rootNode=null; // function to insert // a string in triefunction insert(key,index){ // making a new path // if not already if (rootNode == null) { rootNode = new Node(); } let currentNode = rootNode; for (let i = 0;i < key.length;i++) { let keyChar = key[i]; if (currentNode.getChild(keyChar) == null) { currentNode.addChild(keyChar); } // go to next node currentNode = currentNode.getChild(keyChar); } // Mark leaf (end of string) // and store index of 'str' // in index[] currentNode.addIndex(index);} // function for preorder // traversal of triefunction traversePreorder(array){ _traversePreorder(rootNode, array);} function _traversePreorder(node,array){ if (node == null) { return; } if (node.getIndices().length > 0) { for (let index=0;index< node.getIndices().length;index++) { document.write(array[node.getIndices()[index]] + \" \"); } } for (let index = 'a'.charCodeAt(0);index <= 'z'.charCodeAt(0);index++) { _traversePreorder(node.getChild(String.fromCharCode(index)), array); }} class Node{ constructor() { this.children = new Array(26); this.indices = []; } getChild(index) { if (index < 'a' || index > 'z') { return null; } return this.children[index.charCodeAt(0) - 'a'.charCodeAt(0)]; } addChild(index) { if (index < 'a' || index > 'z') { return; } let node = new Node(); this.children[index.charCodeAt(0) - 'a'.charCodeAt(0)] = node; } getIndices() { return this.indices; } addIndex(index) { this.indices.push(index); } } // function to sort an array // of strings using Triefunction printInSortedOrder(array){ for (let i = 0;i < array.length;i++) { insert(array[i], i); } traversePreorder(array);} // Driver programarray=[\"abc\", \"xyz\",\"abcd\", \"bcd\", \"abc\"]; printInSortedOrder(array); // This code is contributed by rag2127 </script>", "e": 39056, "s": 36509, "text": null }, { "code": null, "e": 39066, "s": 39056, "text": "Output: " }, { "code": null, "e": 39087, "s": 39066, "text": "abc abc abcd bcd xyz" }, { "code": null, "e": 39412, "s": 39087, "text": "Time Complexity: Worst case occurs when every string is starting with a different character. In that case, it will visit all the nodes of each character of each string. So worst-case time complexity will be the sum of the length of every string i.e. O(|S1| + |S2| + |S3| + ... + |Sn|) where |S| is the length of the string. " }, { "code": null, "e": 39424, "s": 39412, "text": "29AjayKumar" }, { "code": null, "e": 39439, "s": 39424, "text": "Aakash_Panchal" }, { "code": null, "e": 39451, "s": 39439, "text": "sanjeev2552" }, { "code": null, "e": 39459, "s": 39451, "text": "rag2127" }, { "code": null, "e": 39464, "s": 39459, "text": "Trie" }, { "code": null, "e": 39488, "s": 39464, "text": "Advanced Data Structure" }, { "code": null, "e": 39496, "s": 39488, "text": "Sorting" }, { "code": null, "e": 39504, "s": 39496, "text": "Sorting" }, { "code": null, "e": 39509, "s": 39504, "text": "Trie" }, { "code": null, "e": 39607, "s": 39509, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39636, "s": 39607, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 39678, "s": 39636, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 39724, "s": 39678, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 39760, "s": 39724, "text": "Suffix Array | Set 1 (Introduction)" } ]
Building a custom tf.data pipeline for object detection | by Florian Hermisch | Towards Data Science
Building an efficient input pipeline is an important performance optimization for training deep neural networks. Beside this, data provisioning needs even to be well structured and transparent do be ruled out as a source of errors for your training. While a lot of current developments are running on PyTorch — Tensorflow is still the way to go if you plan to go to Edge Devices or if want to run on giant training clusters with Terabytes of data. This is where the tf.data API with the tf.data.Dataset jumps in: having an efficient pipeline to provide you with training data which is versatile to scale up into data-center dimensions. Although, using it with your own data can still be frustrating, as you might hit some edges of the existing tutorials (I hit a lot of them). This is my advice for you and and my biggest learning out of it: do not try to use any shortcut — use the full-blown pipeline as it is meant to be used and things will be incredibly easy to use and to understand. That's why I wrote this tutorial for you — provide one end-to-end example which is simple in its core but utilizes most of the concepts of the tf.data API (without using any shortcut of writing files with special filenames in a directory structure named cats/dogs). We use the following: 3000 images each image contains an object (a dot) of one of three colors each dot is placed on a random position on that image Of course we want to predict where the dot is and which color it has based on the given images. Simple task, but can the labels be represented as a directory structure — I see no way. Do I want to save the labels in a CSV file to be matched again to images based on a UUID-filename — I tried that and it was no fun. I want my data together as Dataset records storing image data and label information and I want these streamed into my model for training. Read on if you like that idea too. In this article I mostly concentrate on the relevant code to make the pipeline based on tf.data work. You will get the full boiler-plate code in the connected notebook: https://gist.github.com/FHermisch/1a517121ecb11d0e0206226ac69915ee To ‘simulate’ large, complicated setups of generating test data (e.g. data augmentation, mechanical turks, etc.), I chose to generate images with some random data and use these. So there will be no ‘ready to use’ set loaded from some internet source. We create as simple images as possible for our test and validation data. Important for us, the data we use will have a structural complexity which is comparable to custom image classification and object detection tasks. As said before, our task is to detect the position of a rectangle within an image and the color of that rectangle. We can use just a plain black background. Or — to have just something more visual appealing, use some NASA image as these are often quite impressive and mostly public domain use. Datatype/shape of base image, web base image: uint8 / (112, 112, 3) , uint8 / (112, 112, 3) We continue with the NASA image. Note, both images are 112,112 size with RGB color channels as ‘channels last’ (Tensorflow style). Now, lets place some random things on that base. We build a function which places an object of given color on that image and returns the position where the object was placed. This is our simple solution to generate some ‘object detection like’ images. In the ‘placeobject’ function we initialize the object to be placed on the image: build a numpy array of ones in the size the object should have multiply by color value to convert every pixel into the desired color For placing the object on the image, we choose a random relative y and x position. Now, we can calculate the absolute pixel position and copy the object data into the base image. Lets have a look: there is now an object on our base image and the printed position matches with the objects position on the image. Position 0.9109465116914442 0.13220923689802044 We now have a way to place objects with a certain color on our base image and know exactly the position we have placed this object on. Position and color will be our label/ground-truth for the later detection. The image containing the object will be our training data. Lets automate this by choosing the color randomly and generate masses of these images and labels. Lets generate 5 images first and print out the labels. Generated data (112, 112, 3) 0.8395090863371965 0.9547828984929204 ObjColorTypes.SPECIALGenerated data (112, 112, 3) 0.5531254931489215 0.4768844126516376 ObjColorTypes.GREENGenerated data (112, 112, 3) 0.47239734539676304 0.23156864975331592 ObjColorTypes.REDGenerated data (112, 112, 3) 0.539600313491926 0.14757914149460205 ObjColorTypes.SPECIALGenerated data (112, 112, 3) 0.6978451492963156 0.5689848230831969 ObjColorTypes.RED We should also have a visual look on the data. Later, we want to train an AI to learn something from these image — so be nice to the AI and have a look yourself before you feed it to the AI: are you able to see what you want the AI to see?! First, we setup a class which contains all the needed things to write these records. Pardon me, as I was raised with OO paradigms and having classes and instantiated objects often just feels natural to me. You can use functions with partial parameters or anything else here too. import randomclass QTFRec(): def __init__(self, fname): self.fname = fname self.tfwriter = tf.io.TFRecordWriter(self.fname) def _bytes_feature(self, nparr): return tf.train.Feature( bytes_list=tf.train.BytesList(value=[nparr.tobytes()]))def _float_feature(self, nparr): return tf.train.Feature( float_list=tf.train.FloatList(value=nparr))def write_record(self, image, poslabel, collabel):feature = { 'image_raw': self._float_feature( image.ravel()), 'img_shape': self._bytes_feature( np.array(image.shape, dtype=np.uint8).ravel()), 'poslabel': self._float_feature( poslabel.ravel()), 'collabel': self._float_feature( collabel.ravel()) }tf_example = tf.train.Example( features=tf.train.Features(feature=feature)) self.tfwriter.write( tf_example.SerializeToString()) def close_record(self): self.tfwriter.flush() self.tfwriter.close() In our class, we construct a TFRecord writer which will be used to write data to disk in a tfrecord format. TFRecord is a way to store data examples in a sequential way. Whereby each example consists of a bunch of features. We define our features within the ‘write_record’ function as a dictionary. In this case, we do have image-data, position of the object on the image, color of the object and we also do want to store the shape of the image data.TFRecord allows certain datatypes to be selected for a feature. We go with byte_list and float_list for our feaures. Now, we put our actual data into the features: we start with having data in numpies which is just super convenient. We flat them out (‘.ravel()’) and put them to the respective feature-constructor. You may wonder why we store the image data as floats? This is a design choice (oops! — read later on the effects of this design choice) and therefore we already store the image data with color values in the 0<=val<=1 range, so we can later feed this directly to the training. You will see that there are a couple of places suitable for data conversions — if you have saved it here as uINT8 you can later convert it in the feeding pipeline.Last thing we need is a way to close the writer to assure everything is written to disk. We added a close_writer method to do this (little add-on: you might change this to work in conjunction with the python ‘with’ statement). That's it. One more thing we will come back to later: we currently do not write validation data separated from the training data. One might think that there will be a simple ‘split_dataset’ function which we can use later, but there is none with Datasets. This is understandable as tf.data is build to work with billions of records and one does not simply split billions of records in a certain way. We will later extend our class to actually write two sets of records. But lets continue with the training data first... We create an instance of QTFRec and build another small class to encapsulate this and provide a function which just suits our callback of the data generation. Ok, this works. Now we can generate a reasonable amount of records for our training set. qtfr = QTFRec(fname)tfrsaver = TFRsaver( qtfr)generatedata(baseimg, 3000, tfrsaver.savedata) qtfr.close_record() Lets use this dataset to setup an input pipeline to train a model.The next steps are quite comparable to tutorials using tfds, like e.g. MNist from tfds. We will focus on the part which takes some conversion logic as to adapt our data to the model training needs (we could have also written the data before in a better suited way, but lets do it this way to show you places where you can put in your custom conversion needs for you data and pipeline). Opening the written dataset again is easy. tfrds = tf.data.TFRecordDataset(TRAINSET_FNAME) We can go with the online documentation, but I like the convenient style of using the built-in ‘help(tfrds)’ to see what type I got and what functions it offers. As expected, a TFRecordDatasetV2. Notable functions: ‘apply’for mapping a transformation function on it and building a pipeline of transformations: looks good — we will later use this ‘as_numpy_iterator’this sounds handy for investigating the structure and the contents ‘other pipeline functions, batch/ shuffle/ etc.’ ‘take’takes an amount of elements out of the end of the pipeline Lets play around to see what happens: for npelem in tfrds.as_numpy_iterator(): print( type(npelem)) barr = np.frombuffer(npelem, dtype=np.byte ) print( barr.shape) break Lets see what it prints out. <class 'bytes'>(150629,) We got a numpy shape of 150629 — this should be around 112x112x3 = 37632 ? Wait, what happened? Ok, we stored the image data as floats (out of convenience) and therefore we have blown every color value from one byte (uint8) to 4 bytes (float32). We should really change this — so always have a look at your data. Thinking about it, it is crystal clear but I missed it. I leave it here for you as an example. There are much better ways to waste your disk and IO then storing 4 times the size just out of convenience. Lets continue. We got a tensor from the dataset and we have options to map different transformations to that set. We build a DataRead class which acts as the counterpart of our writer class from above. class DataRead(): def __init__(self): self.feature_description = { 'image_raw': tf.io.VarLenFeature( dtype=tf.float32), 'img_shape': tf.io.FixedLenFeature([], tf.string), 'poslabel': tf.io.VarLenFeature( dtype=tf.float32), 'collabel': tf.io.VarLenFeature( dtype=tf.float32) }def prepdata( self, fmap): pmap = tf.io.parse_single_example( fmap, self.feature_description)imgraw = tf.sparse.to_dense(pmap['image_raw']) imshape = tf.io.decode_raw(pmap['img_shape'], tf.uint8) poslabel = tf.sparse.to_dense(pmap['poslabel']) collabel = tf.one_hot( tf.cast( tf.sparse.to_dense(pmap['collabel']), tf.uint8), tf.constant(3))[0] return (tf.reshape( imgraw, tf.cast(imshape, tf.int32)), tf.concat( [poslabel,collabel], axis=-1)) We first have to parse the tensor as everything inside is just bytes. Therefore, setup a feature_description dictionary for the different elements. Our ‘prepdata’ function will later be mapped to the pipeline. We parse a single entry to be able to access every single feature within a record as specified. This is a good point to put additional transformation code for the data. We have to transformations to do: reshape the raw imagedata back into something structured: we decode the shape first and use this to reshape the imagedata back into its original 112x112x3 shape put label data together in one tensor: we concat the position label with the colortype which we convert to a one-hot representation before Now we got nice image data in 1x112x112x3 to feed for training an a label as 1x5 for the target/ ground-truth. The input pipeline just maps a bunch of transformations together. Map the parsing function we just built. Map a caching function. Shuffle data after each full iteration. Form batches out of the single piped items. Start some prefetching to always have batches for the training ready as soon as they are needed. datar = DataRead()traindat = tfrds.map( datar.prepdata, num_parallel_calls=tf.data.experimental.AUTOTUNE)traindat = traindat.cache()traindat = traindat.shuffle( 1000, seed=1234, reshuffle_each_iteration=True)traindat = traindat.batch( BATCHSIZE, drop_remainder=True)traindat = traindat.prefetch( tf.data.experimental.AUTOTUNE) As the result is still a Dataset, we use the as_numpy_iterator function again. Now, data pops out in our converted formats and we can easily visualize the image data and labels. [0.602948 0.2850269 0. 0. 1. ] This article is not focused on how to do object detection. So we do not get into detail for the next steps:Setup a model with a few convolutions and some fully connected layers at the end. Output is just a sigmoid which will be trained to match our labels (this is VERY basic but works for this extremely simplified example). Model: "functional_1"_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_1 (InputLayer) [(None, 112, 112, 3)] 0 _________________________________________________________________conv2d (Conv2D) (None, 112, 112, 16) 448 _________________________________________________________________re_lu (ReLU) (None, 112, 112, 16) 0 _________________________________________________________________max_pooling2d (MaxPooling2D) (None, 38, 38, 16) 0 _________________________________________________________________conv2d_1 (Conv2D) (None, 38, 38, 32) 4640 _________________________________________________________________re_lu_1 (ReLU) (None, 38, 38, 32) 0 _________________________________________________________________max_pooling2d_1 (MaxPooling2 (None, 13, 13, 32) 0 _________________________________________________________________flatten (Flatten) (None, 5408) 0 _________________________________________________________________dropout (Dropout) (None, 5408) 0 _________________________________________________________________dense (Dense) (None, 128) 692352 _________________________________________________________________re_lu_2 (ReLU) (None, 128) 0 _________________________________________________________________dense_1 (Dense) (None, 64) 8256 _________________________________________________________________re_lu_3 (ReLU) (None, 64) 0 _________________________________________________________________batch_normalization (BatchNo (None, 64) 256 _________________________________________________________________dense_2 (Dense) (None, 5) 325 =================================================================Total params: 706,277Trainable params: 706,149Non-trainable params: 128_________________________________________________________________ Compile it with SGD as optimizer and MeanSquaredError as loss. Run it and ... oh wait ... we have no validation data! Epoch 1/1046/46 [==============================] - 1s 15ms/step - loss: 0.1976Epoch 2/1046/46 [==============================] - 1s 15ms/step - loss: 0.1801Epoch 3/1046/46 [==============================] - 1s 14ms/step - loss: 0.1655... We do need a validation set to get any meaningful insights. Lets change our code for writing the data. We want to spare a certain percentage of our images for validation and save these to another Dataset.We need to add code to initialize (and later close) an additional writer. Within the ‘write_record’, we add a random step which generates a uniform random between 0 and 1 and routes the generated data to training or to validation according to the comparison with the provided validation split percentage. Here we split the data randomly, but this will also be the spot to put some more ‘intelligent’ logic — e.g. assure in a face detection scenario that the validation set will only contain people not present in the training set at all. This splitting logic should be close to the generation of the data and cannot be done later or during training. We run again and provide filenames for train and validation as well as a split percentage of 20%. qtfrec = QTFRecVal(FNAME, 0.2, FNAMEVAL)tfrsaver = TFRsaver( qtfrec)generatedata(baseimg, 3000, tfrsaver.savedata) qtfrec.close_record() Run to generate 3000 images (20% will be put to the validation set). Build a second pipeline for the validation (we don't have to shuffle the validation). tfvalrds = tf.data.TFRecordDataset(FNAMEVAL)valdat = tfvalrds.map( datar.prepdata, num_parallel_calls=tf.data.experimental.AUTOTUNE)valdat = valdat.cache()valdat = valdat.batch(BATCHSIZE, drop_remainder=True)valdat = valdat.prefetch( tf.data.experimental.AUTOTUNE) Generate, compile and run for 100 epochs. ...Epoch 98/10038/38 [==============================] - 1s 19ms/step - loss: 0.0020 - val_loss: 8.0567e-04Epoch 99/10038/38 [==============================] - 1s 20ms/step - loss: 0.0022 - val_loss: 8.2248e-04Epoch 100/10038/38 [==============================] - 1s 18ms/step - loss: 0.0021 - val_loss: 7.9342e-04 See how the losses have evolved. A word on accuracy here: we cannot use the out of the box accuracy functions as they will just not represent what we did. If you want some accuracy, you have to provide your own function: e.g. check if the correct color value was predicted and if the Euclidean distance between target position and predicted position is below a certain threshold. I would say yes — mostly. Color value is predicted very good but I expected the position detection to perform better...The good thing: you now have everything to build your own custom examples with tf.data pipelines for your detections. Groundtruth label: [0.5074 0.7342 0. 0. 1. ]Prediction from model: [0.5104 0.7335 0.0157 0.0145 0.9913] The full notebook is available as a GIST:
[ { "code": null, "e": 948, "s": 171, "text": "Building an efficient input pipeline is an important performance optimization for training deep neural networks. Beside this, data provisioning needs even to be well structured and transparent do be ruled out as a source of errors for your training. While a lot of current developments are running on PyTorch — Tensorflow is still the way to go if you plan to go to Edge Devices or if want to run on giant training clusters with Terabytes of data. This is where the tf.data API with the tf.data.Dataset jumps in: having an efficient pipeline to provide you with training data which is versatile to scale up into data-center dimensions. Although, using it with your own data can still be frustrating, as you might hit some edges of the existing tutorials (I hit a lot of them)." }, { "code": null, "e": 1427, "s": 948, "text": "This is my advice for you and and my biggest learning out of it: do not try to use any shortcut — use the full-blown pipeline as it is meant to be used and things will be incredibly easy to use and to understand. That's why I wrote this tutorial for you — provide one end-to-end example which is simple in its core but utilizes most of the concepts of the tf.data API (without using any shortcut of writing files with special filenames in a directory structure named cats/dogs)." }, { "code": null, "e": 1449, "s": 1427, "text": "We use the following:" }, { "code": null, "e": 1461, "s": 1449, "text": "3000 images" }, { "code": null, "e": 1522, "s": 1461, "text": "each image contains an object (a dot) of one of three colors" }, { "code": null, "e": 1576, "s": 1522, "text": "each dot is placed on a random position on that image" }, { "code": null, "e": 1892, "s": 1576, "text": "Of course we want to predict where the dot is and which color it has based on the given images. Simple task, but can the labels be represented as a directory structure — I see no way. Do I want to save the labels in a CSV file to be matched again to images based on a UUID-filename — I tried that and it was no fun." }, { "code": null, "e": 2030, "s": 1892, "text": "I want my data together as Dataset records storing image data and label information and I want these streamed into my model for training." }, { "code": null, "e": 2065, "s": 2030, "text": "Read on if you like that idea too." }, { "code": null, "e": 2301, "s": 2065, "text": "In this article I mostly concentrate on the relevant code to make the pipeline based on tf.data work. You will get the full boiler-plate code in the connected notebook: https://gist.github.com/FHermisch/1a517121ecb11d0e0206226ac69915ee" }, { "code": null, "e": 2887, "s": 2301, "text": "To ‘simulate’ large, complicated setups of generating test data (e.g. data augmentation, mechanical turks, etc.), I chose to generate images with some random data and use these. So there will be no ‘ready to use’ set loaded from some internet source. We create as simple images as possible for our test and validation data. Important for us, the data we use will have a structural complexity which is comparable to custom image classification and object detection tasks. As said before, our task is to detect the position of a rectangle within an image and the color of that rectangle." }, { "code": null, "e": 3066, "s": 2887, "text": "We can use just a plain black background. Or — to have just something more visual appealing, use some NASA image as these are often quite impressive and mostly public domain use." }, { "code": null, "e": 3159, "s": 3066, "text": "Datatype/shape of base image, web base image: uint8 / (112, 112, 3) , uint8 / (112, 112, 3)" }, { "code": null, "e": 3290, "s": 3159, "text": "We continue with the NASA image. Note, both images are 112,112 size with RGB color channels as ‘channels last’ (Tensorflow style)." }, { "code": null, "e": 3542, "s": 3290, "text": "Now, lets place some random things on that base. We build a function which places an object of given color on that image and returns the position where the object was placed. This is our simple solution to generate some ‘object detection like’ images." }, { "code": null, "e": 3624, "s": 3542, "text": "In the ‘placeobject’ function we initialize the object to be placed on the image:" }, { "code": null, "e": 3687, "s": 3624, "text": "build a numpy array of ones in the size the object should have" }, { "code": null, "e": 3757, "s": 3687, "text": "multiply by color value to convert every pixel into the desired color" }, { "code": null, "e": 3936, "s": 3757, "text": "For placing the object on the image, we choose a random relative y and x position. Now, we can calculate the absolute pixel position and copy the object data into the base image." }, { "code": null, "e": 4068, "s": 3936, "text": "Lets have a look: there is now an object on our base image and the printed position matches with the objects position on the image." }, { "code": null, "e": 4116, "s": 4068, "text": "Position 0.9109465116914442 0.13220923689802044" }, { "code": null, "e": 4483, "s": 4116, "text": "We now have a way to place objects with a certain color on our base image and know exactly the position we have placed this object on. Position and color will be our label/ground-truth for the later detection. The image containing the object will be our training data. Lets automate this by choosing the color randomly and generate masses of these images and labels." }, { "code": null, "e": 4538, "s": 4483, "text": "Lets generate 5 images first and print out the labels." }, { "code": null, "e": 4971, "s": 4538, "text": "Generated data (112, 112, 3) 0.8395090863371965 0.9547828984929204 ObjColorTypes.SPECIALGenerated data (112, 112, 3) 0.5531254931489215 0.4768844126516376 ObjColorTypes.GREENGenerated data (112, 112, 3) 0.47239734539676304 0.23156864975331592 ObjColorTypes.REDGenerated data (112, 112, 3) 0.539600313491926 0.14757914149460205 ObjColorTypes.SPECIALGenerated data (112, 112, 3) 0.6978451492963156 0.5689848230831969 ObjColorTypes.RED" }, { "code": null, "e": 5212, "s": 4971, "text": "We should also have a visual look on the data. Later, we want to train an AI to learn something from these image — so be nice to the AI and have a look yourself before you feed it to the AI: are you able to see what you want the AI to see?!" }, { "code": null, "e": 5491, "s": 5212, "text": "First, we setup a class which contains all the needed things to write these records. Pardon me, as I was raised with OO paradigms and having classes and instantiated objects often just feels natural to me. You can use functions with partial parameters or anything else here too." }, { "code": null, "e": 6567, "s": 5491, "text": "import randomclass QTFRec(): def __init__(self, fname): self.fname = fname self.tfwriter = tf.io.TFRecordWriter(self.fname) def _bytes_feature(self, nparr): return tf.train.Feature( bytes_list=tf.train.BytesList(value=[nparr.tobytes()]))def _float_feature(self, nparr): return tf.train.Feature( float_list=tf.train.FloatList(value=nparr))def write_record(self, image, poslabel, collabel):feature = { 'image_raw': self._float_feature( image.ravel()), 'img_shape': self._bytes_feature( np.array(image.shape, dtype=np.uint8).ravel()), 'poslabel': self._float_feature( poslabel.ravel()), 'collabel': self._float_feature( collabel.ravel()) }tf_example = tf.train.Example( features=tf.train.Features(feature=feature)) self.tfwriter.write( tf_example.SerializeToString()) def close_record(self): self.tfwriter.flush() self.tfwriter.close()" }, { "code": null, "e": 7134, "s": 6567, "text": "In our class, we construct a TFRecord writer which will be used to write data to disk in a tfrecord format. TFRecord is a way to store data examples in a sequential way. Whereby each example consists of a bunch of features. We define our features within the ‘write_record’ function as a dictionary. In this case, we do have image-data, position of the object on the image, color of the object and we also do want to store the shape of the image data.TFRecord allows certain datatypes to be selected for a feature. We go with byte_list and float_list for our feaures." }, { "code": null, "e": 7998, "s": 7134, "text": "Now, we put our actual data into the features: we start with having data in numpies which is just super convenient. We flat them out (‘.ravel()’) and put them to the respective feature-constructor. You may wonder why we store the image data as floats? This is a design choice (oops! — read later on the effects of this design choice) and therefore we already store the image data with color values in the 0<=val<=1 range, so we can later feed this directly to the training. You will see that there are a couple of places suitable for data conversions — if you have saved it here as uINT8 you can later convert it in the feeding pipeline.Last thing we need is a way to close the writer to assure everything is written to disk. We added a close_writer method to do this (little add-on: you might change this to work in conjunction with the python ‘with’ statement)." }, { "code": null, "e": 8518, "s": 7998, "text": "That's it. One more thing we will come back to later: we currently do not write validation data separated from the training data. One might think that there will be a simple ‘split_dataset’ function which we can use later, but there is none with Datasets. This is understandable as tf.data is build to work with billions of records and one does not simply split billions of records in a certain way. We will later extend our class to actually write two sets of records. But lets continue with the training data first..." }, { "code": null, "e": 8766, "s": 8518, "text": "We create an instance of QTFRec and build another small class to encapsulate this and provide a function which just suits our callback of the data generation. Ok, this works. Now we can generate a reasonable amount of records for our training set." }, { "code": null, "e": 8883, "s": 8766, "text": "qtfr = QTFRec(fname)tfrsaver = TFRsaver( qtfr)generatedata(baseimg, 3000, tfrsaver.savedata) qtfr.close_record()" }, { "code": null, "e": 9335, "s": 8883, "text": "Lets use this dataset to setup an input pipeline to train a model.The next steps are quite comparable to tutorials using tfds, like e.g. MNist from tfds. We will focus on the part which takes some conversion logic as to adapt our data to the model training needs (we could have also written the data before in a better suited way, but lets do it this way to show you places where you can put in your custom conversion needs for you data and pipeline)." }, { "code": null, "e": 9378, "s": 9335, "text": "Opening the written dataset again is easy." }, { "code": null, "e": 9426, "s": 9378, "text": "tfrds = tf.data.TFRecordDataset(TRAINSET_FNAME)" }, { "code": null, "e": 9588, "s": 9426, "text": "We can go with the online documentation, but I like the convenient style of using the built-in ‘help(tfrds)’ to see what type I got and what functions it offers." }, { "code": null, "e": 9641, "s": 9588, "text": "As expected, a TFRecordDatasetV2. Notable functions:" }, { "code": null, "e": 9772, "s": 9641, "text": "‘apply’for mapping a transformation function on it and building a pipeline of transformations: looks good — we will later use this" }, { "code": null, "e": 9858, "s": 9772, "text": "‘as_numpy_iterator’this sounds handy for investigating the structure and the contents" }, { "code": null, "e": 9907, "s": 9858, "text": "‘other pipeline functions, batch/ shuffle/ etc.’" }, { "code": null, "e": 9972, "s": 9907, "text": "‘take’takes an amount of elements out of the end of the pipeline" }, { "code": null, "e": 10010, "s": 9972, "text": "Lets play around to see what happens:" }, { "code": null, "e": 10154, "s": 10010, "text": "for npelem in tfrds.as_numpy_iterator(): print( type(npelem)) barr = np.frombuffer(npelem, dtype=np.byte ) print( barr.shape) break" }, { "code": null, "e": 10183, "s": 10154, "text": "Lets see what it prints out." }, { "code": null, "e": 10208, "s": 10183, "text": "<class 'bytes'>(150629,)" }, { "code": null, "e": 10724, "s": 10208, "text": "We got a numpy shape of 150629 — this should be around 112x112x3 = 37632 ? Wait, what happened? Ok, we stored the image data as floats (out of convenience) and therefore we have blown every color value from one byte (uint8) to 4 bytes (float32). We should really change this — so always have a look at your data. Thinking about it, it is crystal clear but I missed it. I leave it here for you as an example. There are much better ways to waste your disk and IO then storing 4 times the size just out of convenience." }, { "code": null, "e": 10926, "s": 10724, "text": "Lets continue. We got a tensor from the dataset and we have options to map different transformations to that set. We build a DataRead class which acts as the counterpart of our writer class from above." }, { "code": null, "e": 11905, "s": 10926, "text": "class DataRead(): def __init__(self): self.feature_description = { 'image_raw': tf.io.VarLenFeature( dtype=tf.float32), 'img_shape': tf.io.FixedLenFeature([], tf.string), 'poslabel': tf.io.VarLenFeature( dtype=tf.float32), 'collabel': tf.io.VarLenFeature( dtype=tf.float32) }def prepdata( self, fmap): pmap = tf.io.parse_single_example( fmap, self.feature_description)imgraw = tf.sparse.to_dense(pmap['image_raw']) imshape = tf.io.decode_raw(pmap['img_shape'], tf.uint8) poslabel = tf.sparse.to_dense(pmap['poslabel']) collabel = tf.one_hot( tf.cast( tf.sparse.to_dense(pmap['collabel']), tf.uint8), tf.constant(3))[0] return (tf.reshape( imgraw, tf.cast(imshape, tf.int32)), tf.concat( [poslabel,collabel], axis=-1))" }, { "code": null, "e": 12318, "s": 11905, "text": "We first have to parse the tensor as everything inside is just bytes. Therefore, setup a feature_description dictionary for the different elements. Our ‘prepdata’ function will later be mapped to the pipeline. We parse a single entry to be able to access every single feature within a record as specified. This is a good point to put additional transformation code for the data. We have to transformations to do:" }, { "code": null, "e": 12479, "s": 12318, "text": "reshape the raw imagedata back into something structured: we decode the shape first and use this to reshape the imagedata back into its original 112x112x3 shape" }, { "code": null, "e": 12618, "s": 12479, "text": "put label data together in one tensor: we concat the position label with the colortype which we convert to a one-hot representation before" }, { "code": null, "e": 12729, "s": 12618, "text": "Now we got nice image data in 1x112x112x3 to feed for training an a label as 1x5 for the target/ ground-truth." }, { "code": null, "e": 13040, "s": 12729, "text": "The input pipeline just maps a bunch of transformations together. Map the parsing function we just built. Map a caching function. Shuffle data after each full iteration. Form batches out of the single piped items. Start some prefetching to always have batches for the training ready as soon as they are needed." }, { "code": null, "e": 13385, "s": 13040, "text": "datar = DataRead()traindat = tfrds.map( datar.prepdata, num_parallel_calls=tf.data.experimental.AUTOTUNE)traindat = traindat.cache()traindat = traindat.shuffle( 1000, seed=1234, reshuffle_each_iteration=True)traindat = traindat.batch( BATCHSIZE, drop_remainder=True)traindat = traindat.prefetch( tf.data.experimental.AUTOTUNE)" }, { "code": null, "e": 13563, "s": 13385, "text": "As the result is still a Dataset, we use the as_numpy_iterator function again. Now, data pops out in our converted formats and we can easily visualize the image data and labels." }, { "code": null, "e": 13615, "s": 13563, "text": "[0.602948 0.2850269 0. 0. 1. ]" }, { "code": null, "e": 13941, "s": 13615, "text": "This article is not focused on how to do object detection. So we do not get into detail for the next steps:Setup a model with a few convolutions and some fully connected layers at the end. Output is just a sigmoid which will be trained to match our labels (this is VERY basic but works for this extremely simplified example)." }, { "code": null, "e": 16244, "s": 13941, "text": "Model: \"functional_1\"_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_1 (InputLayer) [(None, 112, 112, 3)] 0 _________________________________________________________________conv2d (Conv2D) (None, 112, 112, 16) 448 _________________________________________________________________re_lu (ReLU) (None, 112, 112, 16) 0 _________________________________________________________________max_pooling2d (MaxPooling2D) (None, 38, 38, 16) 0 _________________________________________________________________conv2d_1 (Conv2D) (None, 38, 38, 32) 4640 _________________________________________________________________re_lu_1 (ReLU) (None, 38, 38, 32) 0 _________________________________________________________________max_pooling2d_1 (MaxPooling2 (None, 13, 13, 32) 0 _________________________________________________________________flatten (Flatten) (None, 5408) 0 _________________________________________________________________dropout (Dropout) (None, 5408) 0 _________________________________________________________________dense (Dense) (None, 128) 692352 _________________________________________________________________re_lu_2 (ReLU) (None, 128) 0 _________________________________________________________________dense_1 (Dense) (None, 64) 8256 _________________________________________________________________re_lu_3 (ReLU) (None, 64) 0 _________________________________________________________________batch_normalization (BatchNo (None, 64) 256 _________________________________________________________________dense_2 (Dense) (None, 5) 325 =================================================================Total params: 706,277Trainable params: 706,149Non-trainable params: 128_________________________________________________________________" }, { "code": null, "e": 16307, "s": 16244, "text": "Compile it with SGD as optimizer and MeanSquaredError as loss." }, { "code": null, "e": 16362, "s": 16307, "text": "Run it and ... oh wait ... we have no validation data!" }, { "code": null, "e": 16600, "s": 16362, "text": "Epoch 1/1046/46 [==============================] - 1s 15ms/step - loss: 0.1976Epoch 2/1046/46 [==============================] - 1s 15ms/step - loss: 0.1801Epoch 3/1046/46 [==============================] - 1s 14ms/step - loss: 0.1655..." }, { "code": null, "e": 17109, "s": 16600, "text": "We do need a validation set to get any meaningful insights. Lets change our code for writing the data. We want to spare a certain percentage of our images for validation and save these to another Dataset.We need to add code to initialize (and later close) an additional writer. Within the ‘write_record’, we add a random step which generates a uniform random between 0 and 1 and routes the generated data to training or to validation according to the comparison with the provided validation split percentage." }, { "code": null, "e": 17454, "s": 17109, "text": "Here we split the data randomly, but this will also be the spot to put some more ‘intelligent’ logic — e.g. assure in a face detection scenario that the validation set will only contain people not present in the training set at all. This splitting logic should be close to the generation of the data and cannot be done later or during training." }, { "code": null, "e": 17552, "s": 17454, "text": "We run again and provide filenames for train and validation as well as a split percentage of 20%." }, { "code": null, "e": 17693, "s": 17552, "text": "qtfrec = QTFRecVal(FNAME, 0.2, FNAMEVAL)tfrsaver = TFRsaver( qtfrec)generatedata(baseimg, 3000, tfrsaver.savedata) qtfrec.close_record()" }, { "code": null, "e": 17762, "s": 17693, "text": "Run to generate 3000 images (20% will be put to the validation set)." }, { "code": null, "e": 17848, "s": 17762, "text": "Build a second pipeline for the validation (we don't have to shuffle the validation)." }, { "code": null, "e": 18117, "s": 17848, "text": "tfvalrds = tf.data.TFRecordDataset(FNAMEVAL)valdat = tfvalrds.map( datar.prepdata, num_parallel_calls=tf.data.experimental.AUTOTUNE)valdat = valdat.cache()valdat = valdat.batch(BATCHSIZE, drop_remainder=True)valdat = valdat.prefetch( tf.data.experimental.AUTOTUNE)" }, { "code": null, "e": 18159, "s": 18117, "text": "Generate, compile and run for 100 epochs." }, { "code": null, "e": 18473, "s": 18159, "text": "...Epoch 98/10038/38 [==============================] - 1s 19ms/step - loss: 0.0020 - val_loss: 8.0567e-04Epoch 99/10038/38 [==============================] - 1s 20ms/step - loss: 0.0022 - val_loss: 8.2248e-04Epoch 100/10038/38 [==============================] - 1s 18ms/step - loss: 0.0021 - val_loss: 7.9342e-04" }, { "code": null, "e": 18853, "s": 18473, "text": "See how the losses have evolved. A word on accuracy here: we cannot use the out of the box accuracy functions as they will just not represent what we did. If you want some accuracy, you have to provide your own function: e.g. check if the correct color value was predicted and if the Euclidean distance between target position and predicted position is below a certain threshold." }, { "code": null, "e": 19090, "s": 18853, "text": "I would say yes — mostly. Color value is predicted very good but I expected the position detection to perform better...The good thing: you now have everything to build your own custom examples with tf.data pipelines for your detections." }, { "code": null, "e": 19211, "s": 19090, "text": "Groundtruth label: [0.5074 0.7342 0. 0. 1. ]Prediction from model: [0.5104 0.7335 0.0157 0.0145 0.9913]" } ]
The Battle of Interactive Geographic Visualization Part 1 — Interactive Geoplot Using One Line of Code | by Francis Adrian Viernes | Towards Data Science
Geospatial data is probably one of the most complex forms of data that currently exists. For one reason, this form of data is not used in the usual conversations between analysts. For example, analysts do not usually talk about latitude and longitude, and/or, shapefiles. For another reason, the pattern exhibited by geospatial data is not easily apparent. As such, geovisualization plays an important role in the preliminary analysis and design of research. Geo-scatter plots are like normal scatterplots except that they use the geocode (location) of observation as the base of reference in mapping. This means that as opposed to a normal scatterplot that has the x and y variables (rational numeric type), the x and y for a geo-scatter plot are longitude and latitude and are nominal. Geo-scatter plots have been more popular recently due to the efforts of data scientists to track COVID-19 infections. In this article series, we’ll make use of the same dataset but with a different package. The dataset that we are going to use is the “Philippines Coffee Shops Footprint” dataset which I have generated last 2020 to map out the Google-maps-listed coffee shops in the Philippines. The process of generating this data is as follows: https://towardsdatascience.com/mapping-your-favorite-coffee-shop-in-the-philippines-using-google-places-api-and-folium-2f9d5ad697bf import pandas as pddf = pd.read_csv('data/Coffee Brands Footprint.csv', index_col=0)df.head() Note that for plotting geospatial graphs, it is important to have a column for longitude and latitude. In some cases, you may replace this with a GeoPandas geometric object (point, lines, polygon). Without further adieu, let’s begin. Holoviews is one of the high-level plotting packages out there currently. It’s very easy to use and for those who are strapped for time, I recommend this package. pip install holoviews Note Ensure to install the geoviews package as well. pip install geoviews A geoscatter plot can be generated using this one line of code: df.hvplot.points( x='lng', #longitude column y='lat', #latitude column hover_cols=['vicinity'], #tooltip when hovered over c='brand', #color argument title='Coffee Shops in The Philippines', geo=True, tiles='CartoLight') Notice that it is just like plotting a normal scatterplot! And just as our introduction stated, the x and y parameters pertain to longitude and latitude columns. The argument of geo=True is important for holoviews to interpret the x and y variables as forming the geocode. Let us remove the frame as well as it may not be visually appealing. This can be accomplished by setting xaxis and yaxis as None. df.hvplot.points( x='lng', y='lat', frame_height=1000, frame_width=500, xaxis=None, yaxis=None, hover_cols=['brand', 'vicinity'], c='brand', title='Coffee Shops in The Philippines', geo=True, tiles='CartoLight') Because of the overlapping points, it’s difficult to see just how many stores are in a particular area. What helps in this situation is setting the transparency of the points to less than 100%. For these cases, we can try to set it to 30% with the keyword alpha=0.3. df.hvplot.points( x='lng', y='lat', alpha=0.3, frame_height=1000, frame_width=500, xaxis=None, yaxis=None, hover_cols=['vicinity'], c='brand', title='Coffee Shops in The Philippines', geo=True, tiles='CartoLight') Aside from the fact that holoviews is easy to use and understand, the graph we have generated above can be deployed as a webpage which you can use for a presentation. A lot of our executives would prefer not to see the raw codes so deploying this as a separate webpage when reporting is a big plus. To deploy as a separate page: import panel as pnimport holoviews as hvimport holoviews.plotting.bokehpn.panel(geoscatter).servable(title='HoloViews App').show() #.show() makes it to be a separate html One disadvantage, as with most packages, is that the customization may not be as comprehensive when compared to other packages such as Folium. There are a lot of customizations that we can do to improve the visualization that we already have above. For readers interested in continuously improving the geo-scatter, the following are recommended: 1. Choose a Customized Color Palette — Particularly, what we have above are Coffee Brands and these can be associated with a particular color. For example, Starbucks has a particular color of green that can identify the brand well. The suggested approach here is to create a column for brands' colors where this column is supplied to the c or color parameter. 2. Try a different tile— For graphs with a lot of different colors (non-monotonic), it is ideal that the tiles are less-colorful to emphasize the points. For monotonic colors, applicable for continuous variables, colorful graphs can be used cautiously. The main idea is that the tile should not distract or take away from one glance the message of the geo-plot, which is the point of why we are doing this anyway. As you can see from what we have above, visualizing the points elevates our understanding of geospatial data. Patterns, such as those of the network effects, are readily available and we can probably infer that the more coffee shops in the area are, the more developed that place is. We’ll try a different package in the next series to compare the overall syntax and aesthetics. Full code on my Github page. Let me know what you think!
[ { "code": null, "e": 443, "s": 171, "text": "Geospatial data is probably one of the most complex forms of data that currently exists. For one reason, this form of data is not used in the usual conversations between analysts. For example, analysts do not usually talk about latitude and longitude, and/or, shapefiles." }, { "code": null, "e": 528, "s": 443, "text": "For another reason, the pattern exhibited by geospatial data is not easily apparent." }, { "code": null, "e": 630, "s": 528, "text": "As such, geovisualization plays an important role in the preliminary analysis and design of research." }, { "code": null, "e": 959, "s": 630, "text": "Geo-scatter plots are like normal scatterplots except that they use the geocode (location) of observation as the base of reference in mapping. This means that as opposed to a normal scatterplot that has the x and y variables (rational numeric type), the x and y for a geo-scatter plot are longitude and latitude and are nominal." }, { "code": null, "e": 1077, "s": 959, "text": "Geo-scatter plots have been more popular recently due to the efforts of data scientists to track COVID-19 infections." }, { "code": null, "e": 1166, "s": 1077, "text": "In this article series, we’ll make use of the same dataset but with a different package." }, { "code": null, "e": 1355, "s": 1166, "text": "The dataset that we are going to use is the “Philippines Coffee Shops Footprint” dataset which I have generated last 2020 to map out the Google-maps-listed coffee shops in the Philippines." }, { "code": null, "e": 1538, "s": 1355, "text": "The process of generating this data is as follows: https://towardsdatascience.com/mapping-your-favorite-coffee-shop-in-the-philippines-using-google-places-api-and-folium-2f9d5ad697bf" }, { "code": null, "e": 1647, "s": 1538, "text": "import pandas as pddf = pd.read_csv('data/Coffee Brands Footprint.csv', index_col=0)df.head()" }, { "code": null, "e": 1845, "s": 1647, "text": "Note that for plotting geospatial graphs, it is important to have a column for longitude and latitude. In some cases, you may replace this with a GeoPandas geometric object (point, lines, polygon)." }, { "code": null, "e": 1881, "s": 1845, "text": "Without further adieu, let’s begin." }, { "code": null, "e": 2044, "s": 1881, "text": "Holoviews is one of the high-level plotting packages out there currently. It’s very easy to use and for those who are strapped for time, I recommend this package." }, { "code": null, "e": 2066, "s": 2044, "text": "pip install holoviews" }, { "code": null, "e": 2119, "s": 2066, "text": "Note Ensure to install the geoviews package as well." }, { "code": null, "e": 2140, "s": 2119, "text": "pip install geoviews" }, { "code": null, "e": 2204, "s": 2140, "text": "A geoscatter plot can be generated using this one line of code:" }, { "code": null, "e": 2447, "s": 2204, "text": "df.hvplot.points( x='lng', #longitude column y='lat', #latitude column hover_cols=['vicinity'], #tooltip when hovered over c='brand', #color argument title='Coffee Shops in The Philippines', geo=True, tiles='CartoLight')" }, { "code": null, "e": 2609, "s": 2447, "text": "Notice that it is just like plotting a normal scatterplot! And just as our introduction stated, the x and y parameters pertain to longitude and latitude columns." }, { "code": null, "e": 2720, "s": 2609, "text": "The argument of geo=True is important for holoviews to interpret the x and y variables as forming the geocode." }, { "code": null, "e": 2850, "s": 2720, "text": "Let us remove the frame as well as it may not be visually appealing. This can be accomplished by setting xaxis and yaxis as None." }, { "code": null, "e": 3099, "s": 2850, "text": "df.hvplot.points( x='lng', y='lat', frame_height=1000, frame_width=500, xaxis=None, yaxis=None, hover_cols=['brand', 'vicinity'], c='brand', title='Coffee Shops in The Philippines', geo=True, tiles='CartoLight')" }, { "code": null, "e": 3293, "s": 3099, "text": "Because of the overlapping points, it’s difficult to see just how many stores are in a particular area. What helps in this situation is setting the transparency of the points to less than 100%." }, { "code": null, "e": 3366, "s": 3293, "text": "For these cases, we can try to set it to 30% with the keyword alpha=0.3." }, { "code": null, "e": 3620, "s": 3366, "text": "df.hvplot.points( x='lng', y='lat', alpha=0.3, frame_height=1000, frame_width=500, xaxis=None, yaxis=None, hover_cols=['vicinity'], c='brand', title='Coffee Shops in The Philippines', geo=True, tiles='CartoLight')" }, { "code": null, "e": 3787, "s": 3620, "text": "Aside from the fact that holoviews is easy to use and understand, the graph we have generated above can be deployed as a webpage which you can use for a presentation." }, { "code": null, "e": 3919, "s": 3787, "text": "A lot of our executives would prefer not to see the raw codes so deploying this as a separate webpage when reporting is a big plus." }, { "code": null, "e": 3949, "s": 3919, "text": "To deploy as a separate page:" }, { "code": null, "e": 4120, "s": 3949, "text": "import panel as pnimport holoviews as hvimport holoviews.plotting.bokehpn.panel(geoscatter).servable(title='HoloViews App').show() #.show() makes it to be a separate html" }, { "code": null, "e": 4263, "s": 4120, "text": "One disadvantage, as with most packages, is that the customization may not be as comprehensive when compared to other packages such as Folium." }, { "code": null, "e": 4827, "s": 4263, "text": "There are a lot of customizations that we can do to improve the visualization that we already have above. For readers interested in continuously improving the geo-scatter, the following are recommended: 1. Choose a Customized Color Palette — Particularly, what we have above are Coffee Brands and these can be associated with a particular color. For example, Starbucks has a particular color of green that can identify the brand well. The suggested approach here is to create a column for brands' colors where this column is supplied to the c or color parameter." }, { "code": null, "e": 5241, "s": 4827, "text": "2. Try a different tile— For graphs with a lot of different colors (non-monotonic), it is ideal that the tiles are less-colorful to emphasize the points. For monotonic colors, applicable for continuous variables, colorful graphs can be used cautiously. The main idea is that the tile should not distract or take away from one glance the message of the geo-plot, which is the point of why we are doing this anyway." }, { "code": null, "e": 5525, "s": 5241, "text": "As you can see from what we have above, visualizing the points elevates our understanding of geospatial data. Patterns, such as those of the network effects, are readily available and we can probably infer that the more coffee shops in the area are, the more developed that place is." }, { "code": null, "e": 5620, "s": 5525, "text": "We’ll try a different package in the next series to compare the overall syntax and aesthetics." }, { "code": null, "e": 5649, "s": 5620, "text": "Full code on my Github page." } ]
JavaScript program to merge two objects into a single object and adds the values for same keys
We have to write a function that takes in two objects, merges them into a single object, and adds the values for same keys. This has to be done in linear time and constant space, means using at most only one loop and merging the properties in the pre-existing objects and not creating any new variable. So, let’s write the code for this function − const obj1 = { value1: 45, value2: 33, value3: 41, value4: 4, value5: 65, value6: 5, value7: 15, }; const obj2 = { value1: 34, value3: 71, value5: 17, value7: 1, value9: 9, value11: 11, }; const mergeObjects = (obj1, obj2) => { for(key in obj1){ if(obj2[key]){ obj1[key] += obj2[key]; }; }; return; }; mergeObjects(obj1, obj2); console.log(obj1); The output in the console will be − { value1: 79, value2: 33, value3: 112, value4: 4, value5: 82, value6: 5, value7: 16 }
[ { "code": null, "e": 1365, "s": 1062, "text": "We have to write a function that takes in two objects, merges them into a single object, and adds the values for same keys. This has to be done in linear time and constant space, means using at most only one loop and merging the properties in the pre-existing objects and not creating any new variable." }, { "code": null, "e": 1410, "s": 1365, "text": "So, let’s write the code for this function −" }, { "code": null, "e": 1826, "s": 1410, "text": "const obj1 = {\n value1: 45,\n value2: 33,\n value3: 41,\n value4: 4,\n value5: 65,\n value6: 5,\n value7: 15,\n};\nconst obj2 = {\n value1: 34,\n value3: 71,\n value5: 17,\n value7: 1,\n value9: 9,\n value11: 11,\n};\nconst mergeObjects = (obj1, obj2) => {\n for(key in obj1){\n if(obj2[key]){\n obj1[key] += obj2[key];\n };\n };\n return;\n};\nmergeObjects(obj1, obj2);\nconsole.log(obj1);" }, { "code": null, "e": 1862, "s": 1826, "text": "The output in the console will be −" }, { "code": null, "e": 1969, "s": 1862, "text": "{\n value1: 79,\n value2: 33,\n value3: 112,\n value4: 4,\n value5: 82,\n value6: 5,\n value7: 16\n}" } ]
How to pass a value in where clause on PreparedStatement using JDBC?
To execute a statement with Where clause using PreparedStatement. Prepare the query by replacing the value in the clause with place holder “?” and, pass this query as a parameter to the prepareStatement() method. String query = "SELECT * FROM mobile_sales WHERE unit_sale >= ?"; //Creating the PreparedStatement object PreparedStatement pstmt = con.prepareStatement(query); Later, set the value to the place holder using the setXXX() method of the PreparedStatement interface. pstmt.setInt(1, 4000); ResultSet rs = pstmt.executeQuery(); Let us create a table with name mobile_sales in MySQL database using CREATE statement as shown below − CREATE TABLE mobile_sales ( mobile_brand VARCHAR(255), unit_sale INT ); Now, we will insert 11 records in mobile_sales table using INSERT statements − insert into mobile_sales values('Iphone', 3000); insert into mobile_sales values('Samsung', 4000); insert into mobile_sales values('Nokia', 5000); insert into mobile_sales values('Vivo', 1500); insert into mobile_sales values('Oppo', 900); insert into mobile_sales values('MI', 6400); insert into mobile_sales values('MotoG', 4360); insert into mobile_sales values('Lenovo', 4100); insert into mobile_sales values('RedMI', 4000); insert into mobile_sales values('MotoG', 4360); insert into mobile_sales values('OnePlus', 6334); Following JDBC program retrieves the records from mobile_sales table where unit sale value is greater than or equal to 4000. In this example we use the PreparedStatement to execute the SELECT query and set the value in the WHERE clause using the setter method. import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class PreparedStatement_WhereClause { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/testDB"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Query to retrieve the mobile brand with unit sale greater than (or, equal to) 4000 String query = "SELECT * FROM mobile_sales WHERE unit_sale >= ?"; //Creating the PreparedStatement object PreparedStatement pstmt = con.prepareStatement(query); pstmt.setInt(1, 4000); ResultSet rs = pstmt.executeQuery(); System.out.println("Mobile brands with unit sale greater or equal to 4000: "); while(rs.next()) { System.out.print("Name: "+rs.getString("mobile_brand")+", "); System.out.print("Customer Name: "+rs.getString("unit_sale")); System.out.println(); } } } Connection established...... Mobile brands with unit sale greater or equal to 4000: Name: Samsung, Customer Name: 4000 Name: Nokia, Customer Name: 5000 Name: MI, Customer Name: 6400 Name: MotoG, Customer Name: 4360 Name: Lenovo, Customer Name: 4100 Name: RedMi, Customer Name: 4000 Name: MotoG, Customer Name: 4360 Name: OnePlus, Customer Name: 6334
[ { "code": null, "e": 1275, "s": 1062, "text": "To execute a statement with Where clause using PreparedStatement. Prepare the query by replacing the value in the clause with place holder “?” and, pass this query as a parameter to the prepareStatement() method." }, { "code": null, "e": 1436, "s": 1275, "text": "String query = \"SELECT * FROM mobile_sales WHERE unit_sale >= ?\";\n//Creating the PreparedStatement object\nPreparedStatement pstmt = con.prepareStatement(query);" }, { "code": null, "e": 1539, "s": 1436, "text": "Later, set the value to the place holder using the setXXX() method of the PreparedStatement interface." }, { "code": null, "e": 1599, "s": 1539, "text": "pstmt.setInt(1, 4000);\nResultSet rs = pstmt.executeQuery();" }, { "code": null, "e": 1702, "s": 1599, "text": "Let us create a table with name mobile_sales in MySQL database using CREATE statement as shown below −" }, { "code": null, "e": 1780, "s": 1702, "text": "CREATE TABLE mobile_sales (\n mobile_brand VARCHAR(255),\n unit_sale INT\n);" }, { "code": null, "e": 1859, "s": 1780, "text": "Now, we will insert 11 records in mobile_sales table using INSERT statements −" }, { "code": null, "e": 2387, "s": 1859, "text": "insert into mobile_sales values('Iphone', 3000);\ninsert into mobile_sales values('Samsung', 4000);\ninsert into mobile_sales values('Nokia', 5000);\ninsert into mobile_sales values('Vivo', 1500);\ninsert into mobile_sales values('Oppo', 900);\ninsert into mobile_sales values('MI', 6400);\ninsert into mobile_sales values('MotoG', 4360);\ninsert into mobile_sales values('Lenovo', 4100);\ninsert into mobile_sales values('RedMI', 4000);\ninsert into mobile_sales values('MotoG', 4360);\ninsert into mobile_sales values('OnePlus', 6334);" }, { "code": null, "e": 2512, "s": 2387, "text": "Following JDBC program retrieves the records from mobile_sales table where unit sale value is greater than or equal to 4000." }, { "code": null, "e": 2648, "s": 2512, "text": "In this example we use the PreparedStatement to execute the SELECT query and set the value in the WHERE clause using the setter method." }, { "code": null, "e": 3873, "s": 2648, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\npublic class PreparedStatement_WhereClause {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/testDB\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Query to retrieve the mobile brand with unit sale greater than (or, equal to) 4000\n String query = \"SELECT * FROM mobile_sales WHERE unit_sale >= ?\";\n //Creating the PreparedStatement object\n PreparedStatement pstmt = con.prepareStatement(query);\n pstmt.setInt(1, 4000);\n ResultSet rs = pstmt.executeQuery();\n System.out.println(\"Mobile brands with unit sale greater or equal to 4000: \");\n while(rs.next()) {\n System.out.print(\"Name: \"+rs.getString(\"mobile_brand\")+\", \");\n System.out.print(\"Customer Name: \"+rs.getString(\"unit_sale\"));\n System.out.println();\n }\n }\n}" }, { "code": null, "e": 4223, "s": 3873, "text": "Connection established......\nMobile brands with unit sale greater or equal to 4000:\nName: Samsung, Customer Name: 4000\nName: Nokia, Customer Name: 5000\nName: MI, Customer Name: 6400\nName: MotoG, Customer Name: 4360\nName: Lenovo, Customer Name: 4100\nName: RedMi, Customer Name: 4000\nName: MotoG, Customer Name: 4360\nName: OnePlus, Customer Name: 6334" } ]
How to Convert Pandas Dataframe to Keras RNN and Back to Pandas for Multivariate Regression Problems | by Ran Pelta | Towards Data Science
The problem I encountered was rather common (I think): Taking data in a pandas dataframe format and making predictions using a time series regression model with keras RNN where I have more than one independent X (AKA features or predictors) and one dependent y. To be more precise, the problem was not to build the model, rather to convert the data from a pandas dataframe format to a format that an RNN model (in keras) requires and obtaining predictions from the keras model back as a pandas dataframe. It felt that wherever I looked for a solution I got explanations on how RNN works or solutions for uni-variate regression problem. Hence, I will try to keep this post as concise and focused as possible. The coding here assumes that you already did all the necessary preprocessing (e.g., data cleansing, feature engineering etc.) and have a ready-for-analysis time series in a pandas dataframe format. What you WILL NOT find here: · Theoretical explanations · Nice illustrations of an RNN model · Preprocessing techniques · A complicated or sophisticated model There are many sources online that well explain these issues, I highly recommend to check the StackOverflow questions and Jason Brownlee’s, Machine Learning Mastery blog post. What you WILL find here: · A straightforward Python code that takes a pandas dataframe and outputs predictions in the same format using a keras RNN LSTM model for multivariate regression problems. This post will describe snippets of code with explanations and a full seamless code will be provided at the end. Let’s begin: Step 1, let’s import all needed packages and check the keras version As you can see, my keras version is 2.3.1, so if you have some problems with the code I post here, please check that you have the same version or a higher one. Step 2, read the data As you can see, I have 32,128 rows and four columns, with one y and three X. The code here can work on any number of X including just one X. Note that you need to define your y column in order to make things easier and more generic. Optional step — plot the data I know, the resolution is not great here but you get the idea of how my data looks like. Step 3, split the data to train and test Please note here the comment in line #3. Let’s plot again to see if our split makes sense. Again, don’t mind the resolution, it’s not important. The plot looks good, the past (blue) is our training data and recent dates are our test data (orange). Step 4, separate X and y only for the training data. We will handle the test data later. Now, the X_train looks like this: and the y_train looks like this: Step 5, scale and prepare X and y data for keras This part requires some explanations. Here we convert the data from pandas dataframe to numpy arrays which is required by keras. In line 1–8 we first scale X and y using the sklearn MinMaxScaler model, so that their range will be from 0 to 1. The next lines are some shape manipulation to the y in order to make it applicable for keras. We need the shape of y to be (n, ), where n is the number of rows. Line 12 “pushes” the y data one step forward by adding zero in the first position and line 13 keeps the shape of y by deleting the last time step (last row). Here is a simplified example of what happens in line 12–13: #let's say y = [1,2,3,4]# y = np.insert(y,0,0) --> [0,1,2,3,4]# y = np.delete(y,-1) --> [0,1,2,3] If this is explanation is not clear enough, I refer you to Jason Brownlee’s blog post Multivariate Time Series Forecasting with LSTMs in Keras. Look for the section with the title: Multivariate Inputs and Dependent Series Example. To sum up the shape manipulation of y let’s have a quick look on what happened. We started with y data as a dataframe: And now it should look like this: array([0. , 0.12779697, 0.12401905, ..., 0.59237795, 0.6018512 , 0.61132446]) Step 6, combine X and y using the keras TimeseriesGenerator The TimeseriesGenerator transforms the separate X and y into a structure of samples ready to train deep learning models. I would recommend to print the shape of the generator object to make sure it worked. The shape should be (batch_size,n_input,n_features)exactly how it shows in step 6 in line 8. The hard part of converting our data from pandas dataframe to something ready to use for deep learning models is behind us. Now we can move on to step 7, instantiate the model: Note that I used here a very simple model, with only one hidden layer and without a dropout layer. This is because I wanted to keep this post concise and the actual model architecture is not the focus here. But feel free to experiment with more layers. Step 8, fit the model and plot the losses Also here, I used simple settings, only 5 epochs, just to illustrate the entire process. Now the model is ready to use and we can make predictions on the test set. The first line generates the X_test data by dropping the y from the test set, we do not want the y data to be included in the X. Then we scale the X_test according to the MinMaxScaler model which was fitted on the X_train earlier. Line 3 is important because we need to create a TimeseriesGenerator for the test data. I was struggling with this part because in the examples that I saw the y_test was included in here , but I do not want the model to have any knowledge whatsoever about the y_test data. I did not want the slightest chance of data leakage that will result in bias predictions. Thanks to a great help I received from Marco Cerliani on StackOverflow I understood that the second argument in the TimeseriesGenerator, which is the y_test is just a prediction method and that the actual values of the y_test don’t matter (in this specific place), so you can insert a dummy y_test → an array of zeros that has the same shape of the actual y_test data. The rest of the TimeseriesGenerator is similar to the training data, and also here I printed the shape to make sure it’s OK. Line 10 calls the predict method and line 11 rescales the predictions. Remember that we earlier scaled the y data between 0 and 1, so we need to scale it back. In line 12 we construct a dataframe from y_true and y_pred. Note that we only call for a subset of y_true (test[y_col].values[n_input:]), this is because the model needs n_input timesteps (rows or observations) to start predict, so it takes these n_input (in this case 25 timesteps) from X_test and only then start to predict. For example, if we had 50 timesteps in our test set (or 50 rows or observations), then we will have only 25 predictions because the first 25 were used by the model according to its architecture that we set. Now we have our results in a nice pandas dataframe structure: And we can plot them using results.plot();: That’s it, we began with data in a pandas dataframe format and finished with predictions in the same format. That’s the entire code in one block I hope this is useful and will help you in your machine learning missions. Please write me below if you have any comments.
[ { "code": null, "e": 677, "s": 172, "text": "The problem I encountered was rather common (I think): Taking data in a pandas dataframe format and making predictions using a time series regression model with keras RNN where I have more than one independent X (AKA features or predictors) and one dependent y. To be more precise, the problem was not to build the model, rather to convert the data from a pandas dataframe format to a format that an RNN model (in keras) requires and obtaining predictions from the keras model back as a pandas dataframe." }, { "code": null, "e": 1078, "s": 677, "text": "It felt that wherever I looked for a solution I got explanations on how RNN works or solutions for uni-variate regression problem. Hence, I will try to keep this post as concise and focused as possible. The coding here assumes that you already did all the necessary preprocessing (e.g., data cleansing, feature engineering etc.) and have a ready-for-analysis time series in a pandas dataframe format." }, { "code": null, "e": 1107, "s": 1078, "text": "What you WILL NOT find here:" }, { "code": null, "e": 1134, "s": 1107, "text": "· Theoretical explanations" }, { "code": null, "e": 1171, "s": 1134, "text": "· Nice illustrations of an RNN model" }, { "code": null, "e": 1198, "s": 1171, "text": "· Preprocessing techniques" }, { "code": null, "e": 1237, "s": 1198, "text": "· A complicated or sophisticated model" }, { "code": null, "e": 1413, "s": 1237, "text": "There are many sources online that well explain these issues, I highly recommend to check the StackOverflow questions and Jason Brownlee’s, Machine Learning Mastery blog post." }, { "code": null, "e": 1438, "s": 1413, "text": "What you WILL find here:" }, { "code": null, "e": 1610, "s": 1438, "text": "· A straightforward Python code that takes a pandas dataframe and outputs predictions in the same format using a keras RNN LSTM model for multivariate regression problems." }, { "code": null, "e": 1723, "s": 1610, "text": "This post will describe snippets of code with explanations and a full seamless code will be provided at the end." }, { "code": null, "e": 1736, "s": 1723, "text": "Let’s begin:" }, { "code": null, "e": 1805, "s": 1736, "text": "Step 1, let’s import all needed packages and check the keras version" }, { "code": null, "e": 1965, "s": 1805, "text": "As you can see, my keras version is 2.3.1, so if you have some problems with the code I post here, please check that you have the same version or a higher one." }, { "code": null, "e": 1987, "s": 1965, "text": "Step 2, read the data" }, { "code": null, "e": 2220, "s": 1987, "text": "As you can see, I have 32,128 rows and four columns, with one y and three X. The code here can work on any number of X including just one X. Note that you need to define your y column in order to make things easier and more generic." }, { "code": null, "e": 2250, "s": 2220, "text": "Optional step — plot the data" }, { "code": null, "e": 2339, "s": 2250, "text": "I know, the resolution is not great here but you get the idea of how my data looks like." }, { "code": null, "e": 2380, "s": 2339, "text": "Step 3, split the data to train and test" }, { "code": null, "e": 2471, "s": 2380, "text": "Please note here the comment in line #3. Let’s plot again to see if our split makes sense." }, { "code": null, "e": 2628, "s": 2471, "text": "Again, don’t mind the resolution, it’s not important. The plot looks good, the past (blue) is our training data and recent dates are our test data (orange)." }, { "code": null, "e": 2717, "s": 2628, "text": "Step 4, separate X and y only for the training data. We will handle the test data later." }, { "code": null, "e": 2751, "s": 2717, "text": "Now, the X_train looks like this:" }, { "code": null, "e": 2784, "s": 2751, "text": "and the y_train looks like this:" }, { "code": null, "e": 2833, "s": 2784, "text": "Step 5, scale and prepare X and y data for keras" }, { "code": null, "e": 3455, "s": 2833, "text": "This part requires some explanations. Here we convert the data from pandas dataframe to numpy arrays which is required by keras. In line 1–8 we first scale X and y using the sklearn MinMaxScaler model, so that their range will be from 0 to 1. The next lines are some shape manipulation to the y in order to make it applicable for keras. We need the shape of y to be (n, ), where n is the number of rows. Line 12 “pushes” the y data one step forward by adding zero in the first position and line 13 keeps the shape of y by deleting the last time step (last row). Here is a simplified example of what happens in line 12–13:" }, { "code": null, "e": 3553, "s": 3455, "text": "#let's say y = [1,2,3,4]# y = np.insert(y,0,0) --> [0,1,2,3,4]# y = np.delete(y,-1) --> [0,1,2,3]" }, { "code": null, "e": 3784, "s": 3553, "text": "If this is explanation is not clear enough, I refer you to Jason Brownlee’s blog post Multivariate Time Series Forecasting with LSTMs in Keras. Look for the section with the title: Multivariate Inputs and Dependent Series Example." }, { "code": null, "e": 3903, "s": 3784, "text": "To sum up the shape manipulation of y let’s have a quick look on what happened. We started with y data as a dataframe:" }, { "code": null, "e": 3937, "s": 3903, "text": "And now it should look like this:" }, { "code": null, "e": 4022, "s": 3937, "text": "array([0. , 0.12779697, 0.12401905, ..., 0.59237795, 0.6018512 , 0.61132446])" }, { "code": null, "e": 4082, "s": 4022, "text": "Step 6, combine X and y using the keras TimeseriesGenerator" }, { "code": null, "e": 4381, "s": 4082, "text": "The TimeseriesGenerator transforms the separate X and y into a structure of samples ready to train deep learning models. I would recommend to print the shape of the generator object to make sure it worked. The shape should be (batch_size,n_input,n_features)exactly how it shows in step 6 in line 8." }, { "code": null, "e": 4558, "s": 4381, "text": "The hard part of converting our data from pandas dataframe to something ready to use for deep learning models is behind us. Now we can move on to step 7, instantiate the model:" }, { "code": null, "e": 4811, "s": 4558, "text": "Note that I used here a very simple model, with only one hidden layer and without a dropout layer. This is because I wanted to keep this post concise and the actual model architecture is not the focus here. But feel free to experiment with more layers." }, { "code": null, "e": 4853, "s": 4811, "text": "Step 8, fit the model and plot the losses" }, { "code": null, "e": 4942, "s": 4853, "text": "Also here, I used simple settings, only 5 epochs, just to illustrate the entire process." }, { "code": null, "e": 5017, "s": 4942, "text": "Now the model is ready to use and we can make predictions on the test set." }, { "code": null, "e": 6104, "s": 5017, "text": "The first line generates the X_test data by dropping the y from the test set, we do not want the y data to be included in the X. Then we scale the X_test according to the MinMaxScaler model which was fitted on the X_train earlier. Line 3 is important because we need to create a TimeseriesGenerator for the test data. I was struggling with this part because in the examples that I saw the y_test was included in here , but I do not want the model to have any knowledge whatsoever about the y_test data. I did not want the slightest chance of data leakage that will result in bias predictions. Thanks to a great help I received from Marco Cerliani on StackOverflow I understood that the second argument in the TimeseriesGenerator, which is the y_test is just a prediction method and that the actual values of the y_test don’t matter (in this specific place), so you can insert a dummy y_test → an array of zeros that has the same shape of the actual y_test data. The rest of the TimeseriesGenerator is similar to the training data, and also here I printed the shape to make sure it’s OK." }, { "code": null, "e": 6798, "s": 6104, "text": "Line 10 calls the predict method and line 11 rescales the predictions. Remember that we earlier scaled the y data between 0 and 1, so we need to scale it back. In line 12 we construct a dataframe from y_true and y_pred. Note that we only call for a subset of y_true (test[y_col].values[n_input:]), this is because the model needs n_input timesteps (rows or observations) to start predict, so it takes these n_input (in this case 25 timesteps) from X_test and only then start to predict. For example, if we had 50 timesteps in our test set (or 50 rows or observations), then we will have only 25 predictions because the first 25 were used by the model according to its architecture that we set." }, { "code": null, "e": 6860, "s": 6798, "text": "Now we have our results in a nice pandas dataframe structure:" }, { "code": null, "e": 6904, "s": 6860, "text": "And we can plot them using results.plot();:" }, { "code": null, "e": 7013, "s": 6904, "text": "That’s it, we began with data in a pandas dataframe format and finished with predictions in the same format." }, { "code": null, "e": 7049, "s": 7013, "text": "That’s the entire code in one block" } ]
What are static member functions in C#?
Static functions can access only static variables. The static functions exist even before the object is created. Set static functions as − public static int getNum() {} The following is an example demonstrating the use of static functions − Live Demo using System; namespace Demo { class StaticVar { public static int num; public void count() { num++; } public static int getNum() { return num; } } class StaticTester { static void Main(string[] args) { StaticVar s = new StaticVar(); s.count(); s.count(); s.count(); Console.WriteLine("Variable num: {0}", StaticVar.getNum()); Console.ReadKey(); } } } Variable num: 3
[ { "code": null, "e": 1175, "s": 1062, "text": "Static functions can access only static variables. The static functions exist even before the object is created." }, { "code": null, "e": 1201, "s": 1175, "text": "Set static functions as −" }, { "code": null, "e": 1231, "s": 1201, "text": "public static int getNum() {}" }, { "code": null, "e": 1303, "s": 1231, "text": "The following is an example demonstrating the use of static functions −" }, { "code": null, "e": 1314, "s": 1303, "text": " Live Demo" }, { "code": null, "e": 1798, "s": 1314, "text": "using System;\n\nnamespace Demo {\n class StaticVar {\n public static int num;\n\n public void count() {\n num++;\n }\n\n public static int getNum() {\n return num;\n }\n }\n\n class StaticTester {\n static void Main(string[] args) {\n StaticVar s = new StaticVar();\n\n s.count();\n s.count();\n s.count();\n\n Console.WriteLine(\"Variable num: {0}\", StaticVar.getNum());\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 1814, "s": 1798, "text": "Variable num: 3" } ]
Stop Wasting Time with PyTorch Datasets! | by Eric Hofesmann | Towards Data Science
PyTorch is one of the most popular deep learning libraries out there. It provides one of the best balances between being easy to learn and a powerful framework for creating and training models quickly. Extensions of it like PyTorch Lightning make it even easier to write up and scale up networks. While it’s great that you can easily create and train complex models, constructing a model architecture will only get you part of the way to performing well on your task. Achieving high performance on your task depends just as much on improvements to your data as it does on improvements to your model architecture. Depending on your task, refining a dataset can get difficult. Especially as you increase the dimensionality of your data. Working with tabular data is often going to be more straightforward than working with an image or video dataset that you can’t even load into memory all at once. PyTorch datasets provide a great starting point for loading complex datasets, letting you define a class to load individual samples from disk and then creating data loaders to efficiently supply the data to your model. Problems arise when you want to start iterating over your dataset itself. PyTorch datasets are rigid. They have numerous limitations. First, they require a heavy code rewrite for any changes, which leads to dozens of hours wasted over the lifetime of a project. Second, they are merely a way to load data from disk, they do not support any data visualization or exploration that can help you construct better datasets. FiftyOne, the open-source pandas-like tool for visual datasets that I have been working on can work in conjunction with PyTorch (and many other tools) to help you get closer to and interact with your datasets. It provides a much more flexible representation for image and video datasets allowing you to search, slice, and visualize them with the help of the FiftyOne API and App without needing any rewrites for frequent changes. Although this article is primarily about PyTorch, other common frameworks, like TensorFlow, suffer from similar challenges. The magic that makes FiftyOne so flexible for overcoming these PyTorch dataset limitations is in FiftyOne Views. Basically, from a general FiftyOne dataset, you can create a specific view into your dataset with one line of code; the view is then directly used to create a PyTorch Dataset. For example, say that you trained an object detection model that is getting confused between cars, trucks, and buses. It could be beneficial to first train the model to predict them all as “vehicles”. Incorporating FiftyOne into your training workflow can make this as easy as: PyTorch datasets synergize well with FiftyOne datasets for hard computer vision problems like classification, object detection, segmentation, and more since you can use FiftyOne to visualize, understand, and select the data that you then use to train your PyTorch model. The flexibility of FiftyOne datasets lets you easily experiment with and finetune the datasets you use for training and testing to create better-performing models, faster. In this blog post, I am focusing on object detection since that is one of the most common vision tasks while also being fairly complex. However, these methods work for most ML tasks. Specifically, in this post I cover: Loading your labeled dataset into FiftyOne Writing a PyTorch object detection dataset that utilizes your loaded FiftyOne dataset Exploring views into your FiftyOne dataset for training and evaluation Training a Torchvision object detection model on your FiftyOne dataset views Evaluating your models in FiftyOne to refine your dataset Training models outside of PyTorch on FiftyOne datasets You can follow along with this blog post directly in your browser through this Google Colab notebook! Getting your data into FiftyOne is oftentimes actually easier than getting it into a PyTorch dataset. Additionally, once the data is in FiftyOne it is much more flexible allowing you to easily find and access even the most specific subsets of data that you can then use to train or evaluate your model. The goal of this blog is to train an object detection model so I am just using a standard object detection dataset as an example. Specifically, I am using the COCO 2017 dataset which I can load directly from the FiftyOne dataset zoo. In the spirit of making this post easy to follow along with, I am only using a subset of the COCO dataset (the 5000 validation images and labels) and later creating custom training and validation splits from that subset. We need the height and width of images later in this post so we need to compute metadata on the images in our dataset: If you have data that follows a certain format on disk (for example a directory tree for classification, the COCO detection format, or many more), then you can load it into FiftyOne in one line of code: If your dataset doesn’t follow a standard format, don’t fret, it’s still really easy to get it into FiftyOne. You just need to create a FiftyOne dataset and iteratively parse your data into FiftyOne samples that are then added to the dataset. A PyTorch dataset is a class that defines how to load a static dataset and its labels from disk via a simple iterator interface. They differ from FiftyOne datasets which are flexible representations of your data geared towards visualization, querying, and understanding. The symbiosis between the two dataset representations comes from the fact that FiftyOne datasets are optimized for helping you gather and curate datasets for training, while PyTorch datasets are designed to encapsulate a static dataset in a standard interface that can be efficiently loaded during training Using the flexible representation of FiftyOne datasets to understand and select the best training data for your task, then passing that data on to PyTorch datasets for efficient loading results in better models, faster. Every PyTorch model expects data and labels to pass into it in a certain format. Before being able to write up a PyTorch dataset class, you first need to understand the format that the model requires. Namely, we need to know exactly what format the data loader is expected to output when iterating through the dataset so that we can properly define the __getitem__ method in the PyTorch dataset. In this example, I am following the Torchvision object detection tutorial and construct a PyTorch dataset to work with their RCNN-based models. If you are following along, this code uses some of the utilities and methods for training and evaluation so you need to clone the tutorial code in the PyTorch git repository: # Download TorchVision repo to use some files from# references/detectiongit clone https://github.com/pytorch/vision.gitcd visiongit checkout v0.3.0cp references/detection/utils.py ../cp references/detection/transforms.py ../cp references/detection/coco_eval.py ../cp references/detection/engine.py ../cp references/detection/coco_utils.py ../ These object detection models expect our PyTorch dataset to output a (image, target) tuple for each sample where target is a dictionary containing the following fields: boxes (FloatTensor[N, 4]): the coordinates of the N bounding boxes in [x0, y0, x1, y1] format, ranging from 0 to W and 0 to H labels (Int64Tensor[N]): the label for each bounding box. 0 always represents the background class. image_id (Int64Tensor[1]): an image identifier. It should be unique between all the images in the dataset and is used during evaluation area (Tensor[N]): The area of the bounding box. This is used during evaluation with the COCO metric, to separate the metric scores between small, medium, and large boxes. iscrowd (UInt8Tensor[N]): instances with iscrowd=True will be ignored during evaluation. (If your dataset doesn’t support crowds, then this tensor will always just be 0's) The following code loads Faster-RCNN with a ResNet50 backbone from Torchvision and modify the classifier for the number of classes we are training on: (source of code and field descriptions presented above) In general, no matter what model you use, the corresponding PyTorch dataset needs to output the loaded image data along with relevant annotations and metadata for each sample. For example, for classifications tasks target would just be a single integer representing the class to which the sample belongs. Now that we have decided on the model and understand the format that the loaded data needs to follow, we can write a PyTorch dataset class that takes a FiftyOne dataset as input and parses the relevant information. Since the FiftyOne API is designed to be easy to use, parsing samples out of a FiftyOne dataset is generally easier than parsing them from disk. The constructor for the dataset class needs to take in our FiftyOne dataset create a list of image_paths that can be used by the __getitem__ method to index into individual samples and also access the corresponding FiftyOne sample by filepath. FiftyOne stores class labels as strings, so we also need a mapping of these strings back to integers to be used by the model. The __getitem__ method then needs to take in a unique integer idx and use that to access the corresponding FiftyOne sample. Then, since these models are trained on the COCO dataset, we can use the COCO utilities in FiftyOne to reformat each detection in the sample into the COCO format for detections, labels, areas, and crowds. We also add length and get_classes methods for usability. Once a PyTorch dataset is constructed for your data and model combination, you need to create a PyTorch data loader. These data loaders are the iterables that use the dataset code you wrote to import your data. They are fairly simple but provide some useful functionality like shuffling, batching, and loading data in parallel. Since we decided to back our datasets in FiftyOne, we can also perform actions like splitting and shuffling our data by creating views into our dataset. The take method on a FiftyOne dataset returns a subset containing random samples from the dataset. The exclude method prevents us from taking any samples that are in the training split for our validation split: Now say that you wanted to get more specific with the data that you use to train and test your model. For example, you might want to train on a specific subset of classes or remap some of the labels. If you are just using PyTorch code, then you need to go back and rewrite your Dataset class and possibly even go back to change your dataset files on disk. FiftyOne can do much more than just splitting and shuffling data and makes it easy to get exactly the data that you need for your model. One of the primary ways of interacting with your FiftyOne dataset is through different views into your dataset. These are constructed by applying operations like filtering, sorting, slicing, etc, that result in a specific view into certain labels/samples of your dataset. These operations make it easier to experiment with different subsets of data and continue to finetune your dataset to train better models. For example, cluttered images make it difficult for models to localize objects. We can use FiftyOne to create a view containing only samples with more than, say, 10 objects. You can perform the same operations on views as datasets, so we can create an instance of our PyTorch dataset from this view: Another example is if we want to train a model that is used primarily for road vehicle detection. We can easily create training and testing views (and corresponding PyTorch datasets) that only contain the classes car, truck, and bus: Now that we have decided on the data we want to use to train and test our model, the next step is to construct the training pipeline. This varies depending on what you want to accomplish with your model. The specifics of constructing and training models in PyTorch are out of the scope of this blog post, and for that, I refer you to other sources [1,2,3,4]. For this example, we are writing a simple training loop following the PyTorch object detection tutorial. This function takes a model and our PyTorch datasets as input and use the train_one_epoch() and evaluate() functions from the Torchvision object detection code: Let’s continue with the vehicle example from the previous section. We can use the torch_dataset and torch_dataset_test to define and train a model: Every epoch, this training loop prints evaluation metrics on the test split. After 4 epochs on the samples that we selected from the COCO dataset, we have reached 36.7% mAP. This is not surprising since this model was pretrained on COCO (but not this subset of classes). IoU metric: bbox Average Precision (AP) @[ IoU=0.50:0.95 ] = 0.367 Printing evaluation metrics is useful during training so that you can see how quickly your model is learning and when it begins to saturate. However, this Torchvision evaluation protocol only returns dataset-wide mAP metrics. To best understand where your model performs well and poorly, and thus having any hope of improving it, requires you to see how the model performs on individual samples. One of the main draws of FiftyOne is the ability to find failure modes of your model. The built-in evaluation protocols tell you exactly where your model got things right and where it got things wrong. Before we can evaluate the model, though, we need to run it on our test set and store the results in FiftyOne. Doing this is fairly simple and just requires us to run inference for the test images, get their corresponding FiftyOne samples, and add a new field called predictions to each sample to store the detections. The DetectionResults object that is returned stores information like the mAP and contains functions that let you plot confusion matrices, precision-recall curves, and more. Also, these evaluation runs are tracked in FiftyOne and can be managed through functions like list_evaluations(). What we are interested in, though, is the fact that evaluate_detections() updates the detections in thepredictions field with attributes indicating whether they are true positives, false positives, or false negatives. Using FiftyOne views and the App, we can quickly find the samples that the model performed worst on by sorting by false positives: Looking through some of these samples, a pattern emerges. A number of truck and car annotations are actually incorrect in the ground truth. There seems to be confusion for things like vans and SUVs that are interchangeably annotated as cars or trucks. It would be interesting to see a confusion matrix between these classes. By default, the evaluation only matches predictions with ground truth objects of the same class (classwise=True). We can rerun the evaluation with classwise=False and plot that confusion matrix. It would be best to get this data reannotated to fix these mistakes, but in the meantime, we can easily remedy this by simply creating a new view that remaps the labels car, truck, and bus all to vehicle and then retraining the model with that. Since our training data is backed by a FiftyOne dataset, this transformation is easy! Due to our ability to easily visualize and manage our dataset with FiftyOne, we were able to spot and take action on a dataset issue that would otherwise have gone unnoticed if we only concerned ourselves with dataset-wide evaluation metrics and fixed dataset representations. Through these efforts, we managed to increase the mAP of the model to 43%. Even though this example workflow may not work in all situations, this kind of class-merging strategy can be effective in cases where more fine-grained discrimination is not called for. If you are primarily focused on developing a novel model architecture, then you would likely want to start directly in PyTorch. However, if your goal is to train a model on a custom dataset and a common task, then there are a number of training frameworks that can make that even easier for you. Some notable training frameworks for object detection are Detectron2 and MMDetection. But no matter what framework you choose, they will likely not use PyTorch datasets and data loaders directly and instead require you to format your data on disk in a certain way. Detectron2 and MMDetection, for example, expect your data to be stored in the COCO format. Once you have reformatted your dataset, it can be loaded directly into these frameworks and trained on. Even though you are not loading the datasets yourself, FiftyOne can still help you with this process. With FiftyOne, any dataset or view that you have loaded into it can be exported in over a dozen different formats (COCO included). This means that you can parse your dataset into FiftyOne and export it in one line of code instead of needing to write numerous scripts to convert it yourself. PyTorch and related frameworks provide quick and easy methods to bootstrap your model development and training pipelines. However, they largely overlook the need to massage and finetune datasets to efficiently improve performance. FiftyOne is an ML developer tool designed to make it easy to load your datasets into a flexible format that works well with existing tools allowing you to provide better data for training and testing. As they say, “garbage in, garbage out”. High-quality, intentionally-curated data is critical to training great computer vision models. At Voxel51, we have over 25 years of CV/ML experience and care deeply about enabling the community to bring their AI solutions to life. That’s why we developed FiftyOne, an open-source tool that helps engineers and scientists to do better ML, faster. Want to learn more? Check us out at fiftyone.ai.
[ { "code": null, "e": 469, "s": 172, "text": "PyTorch is one of the most popular deep learning libraries out there. It provides one of the best balances between being easy to learn and a powerful framework for creating and training models quickly. Extensions of it like PyTorch Lightning make it even easier to write up and scale up networks." }, { "code": null, "e": 640, "s": 469, "text": "While it’s great that you can easily create and train complex models, constructing a model architecture will only get you part of the way to performing well on your task." }, { "code": null, "e": 785, "s": 640, "text": "Achieving high performance on your task depends just as much on improvements to your data as it does on improvements to your model architecture." }, { "code": null, "e": 1069, "s": 785, "text": "Depending on your task, refining a dataset can get difficult. Especially as you increase the dimensionality of your data. Working with tabular data is often going to be more straightforward than working with an image or video dataset that you can’t even load into memory all at once." }, { "code": null, "e": 1707, "s": 1069, "text": "PyTorch datasets provide a great starting point for loading complex datasets, letting you define a class to load individual samples from disk and then creating data loaders to efficiently supply the data to your model. Problems arise when you want to start iterating over your dataset itself. PyTorch datasets are rigid. They have numerous limitations. First, they require a heavy code rewrite for any changes, which leads to dozens of hours wasted over the lifetime of a project. Second, they are merely a way to load data from disk, they do not support any data visualization or exploration that can help you construct better datasets." }, { "code": null, "e": 2261, "s": 1707, "text": "FiftyOne, the open-source pandas-like tool for visual datasets that I have been working on can work in conjunction with PyTorch (and many other tools) to help you get closer to and interact with your datasets. It provides a much more flexible representation for image and video datasets allowing you to search, slice, and visualize them with the help of the FiftyOne API and App without needing any rewrites for frequent changes. Although this article is primarily about PyTorch, other common frameworks, like TensorFlow, suffer from similar challenges." }, { "code": null, "e": 2550, "s": 2261, "text": "The magic that makes FiftyOne so flexible for overcoming these PyTorch dataset limitations is in FiftyOne Views. Basically, from a general FiftyOne dataset, you can create a specific view into your dataset with one line of code; the view is then directly used to create a PyTorch Dataset." }, { "code": null, "e": 2828, "s": 2550, "text": "For example, say that you trained an object detection model that is getting confused between cars, trucks, and buses. It could be beneficial to first train the model to predict them all as “vehicles”. Incorporating FiftyOne into your training workflow can make this as easy as:" }, { "code": null, "e": 3490, "s": 2828, "text": "PyTorch datasets synergize well with FiftyOne datasets for hard computer vision problems like classification, object detection, segmentation, and more since you can use FiftyOne to visualize, understand, and select the data that you then use to train your PyTorch model. The flexibility of FiftyOne datasets lets you easily experiment with and finetune the datasets you use for training and testing to create better-performing models, faster. In this blog post, I am focusing on object detection since that is one of the most common vision tasks while also being fairly complex. However, these methods work for most ML tasks. Specifically, in this post I cover:" }, { "code": null, "e": 3533, "s": 3490, "text": "Loading your labeled dataset into FiftyOne" }, { "code": null, "e": 3619, "s": 3533, "text": "Writing a PyTorch object detection dataset that utilizes your loaded FiftyOne dataset" }, { "code": null, "e": 3690, "s": 3619, "text": "Exploring views into your FiftyOne dataset for training and evaluation" }, { "code": null, "e": 3767, "s": 3690, "text": "Training a Torchvision object detection model on your FiftyOne dataset views" }, { "code": null, "e": 3825, "s": 3767, "text": "Evaluating your models in FiftyOne to refine your dataset" }, { "code": null, "e": 3881, "s": 3825, "text": "Training models outside of PyTorch on FiftyOne datasets" }, { "code": null, "e": 3983, "s": 3881, "text": "You can follow along with this blog post directly in your browser through this Google Colab notebook!" }, { "code": null, "e": 4286, "s": 3983, "text": "Getting your data into FiftyOne is oftentimes actually easier than getting it into a PyTorch dataset. Additionally, once the data is in FiftyOne it is much more flexible allowing you to easily find and access even the most specific subsets of data that you can then use to train or evaluate your model." }, { "code": null, "e": 4741, "s": 4286, "text": "The goal of this blog is to train an object detection model so I am just using a standard object detection dataset as an example. Specifically, I am using the COCO 2017 dataset which I can load directly from the FiftyOne dataset zoo. In the spirit of making this post easy to follow along with, I am only using a subset of the COCO dataset (the 5000 validation images and labels) and later creating custom training and validation splits from that subset." }, { "code": null, "e": 4860, "s": 4741, "text": "We need the height and width of images later in this post so we need to compute metadata on the images in our dataset:" }, { "code": null, "e": 5063, "s": 4860, "text": "If you have data that follows a certain format on disk (for example a directory tree for classification, the COCO detection format, or many more), then you can load it into FiftyOne in one line of code:" }, { "code": null, "e": 5306, "s": 5063, "text": "If your dataset doesn’t follow a standard format, don’t fret, it’s still really easy to get it into FiftyOne. You just need to create a FiftyOne dataset and iteratively parse your data into FiftyOne samples that are then added to the dataset." }, { "code": null, "e": 5577, "s": 5306, "text": "A PyTorch dataset is a class that defines how to load a static dataset and its labels from disk via a simple iterator interface. They differ from FiftyOne datasets which are flexible representations of your data geared towards visualization, querying, and understanding." }, { "code": null, "e": 5884, "s": 5577, "text": "The symbiosis between the two dataset representations comes from the fact that FiftyOne datasets are optimized for helping you gather and curate datasets for training, while PyTorch datasets are designed to encapsulate a static dataset in a standard interface that can be efficiently loaded during training" }, { "code": null, "e": 6104, "s": 5884, "text": "Using the flexible representation of FiftyOne datasets to understand and select the best training data for your task, then passing that data on to PyTorch datasets for efficient loading results in better models, faster." }, { "code": null, "e": 6500, "s": 6104, "text": "Every PyTorch model expects data and labels to pass into it in a certain format. Before being able to write up a PyTorch dataset class, you first need to understand the format that the model requires. Namely, we need to know exactly what format the data loader is expected to output when iterating through the dataset so that we can properly define the __getitem__ method in the PyTorch dataset." }, { "code": null, "e": 6819, "s": 6500, "text": "In this example, I am following the Torchvision object detection tutorial and construct a PyTorch dataset to work with their RCNN-based models. If you are following along, this code uses some of the utilities and methods for training and evaluation so you need to clone the tutorial code in the PyTorch git repository:" }, { "code": null, "e": 7162, "s": 6819, "text": "# Download TorchVision repo to use some files from# references/detectiongit clone https://github.com/pytorch/vision.gitcd visiongit checkout v0.3.0cp references/detection/utils.py ../cp references/detection/transforms.py ../cp references/detection/coco_eval.py ../cp references/detection/engine.py ../cp references/detection/coco_utils.py ../" }, { "code": null, "e": 7331, "s": 7162, "text": "These object detection models expect our PyTorch dataset to output a (image, target) tuple for each sample where target is a dictionary containing the following fields:" }, { "code": null, "e": 7457, "s": 7331, "text": "boxes (FloatTensor[N, 4]): the coordinates of the N bounding boxes in [x0, y0, x1, y1] format, ranging from 0 to W and 0 to H" }, { "code": null, "e": 7557, "s": 7457, "text": "labels (Int64Tensor[N]): the label for each bounding box. 0 always represents the background class." }, { "code": null, "e": 7693, "s": 7557, "text": "image_id (Int64Tensor[1]): an image identifier. It should be unique between all the images in the dataset and is used during evaluation" }, { "code": null, "e": 7864, "s": 7693, "text": "area (Tensor[N]): The area of the bounding box. This is used during evaluation with the COCO metric, to separate the metric scores between small, medium, and large boxes." }, { "code": null, "e": 8036, "s": 7864, "text": "iscrowd (UInt8Tensor[N]): instances with iscrowd=True will be ignored during evaluation. (If your dataset doesn’t support crowds, then this tensor will always just be 0's)" }, { "code": null, "e": 8187, "s": 8036, "text": "The following code loads Faster-RCNN with a ResNet50 backbone from Torchvision and modify the classifier for the number of classes we are training on:" }, { "code": null, "e": 8243, "s": 8187, "text": "(source of code and field descriptions presented above)" }, { "code": null, "e": 8548, "s": 8243, "text": "In general, no matter what model you use, the corresponding PyTorch dataset needs to output the loaded image data along with relevant annotations and metadata for each sample. For example, for classifications tasks target would just be a single integer representing the class to which the sample belongs." }, { "code": null, "e": 8908, "s": 8548, "text": "Now that we have decided on the model and understand the format that the loaded data needs to follow, we can write a PyTorch dataset class that takes a FiftyOne dataset as input and parses the relevant information. Since the FiftyOne API is designed to be easy to use, parsing samples out of a FiftyOne dataset is generally easier than parsing them from disk." }, { "code": null, "e": 9278, "s": 8908, "text": "The constructor for the dataset class needs to take in our FiftyOne dataset create a list of image_paths that can be used by the __getitem__ method to index into individual samples and also access the corresponding FiftyOne sample by filepath. FiftyOne stores class labels as strings, so we also need a mapping of these strings back to integers to be used by the model." }, { "code": null, "e": 9665, "s": 9278, "text": "The __getitem__ method then needs to take in a unique integer idx and use that to access the corresponding FiftyOne sample. Then, since these models are trained on the COCO dataset, we can use the COCO utilities in FiftyOne to reformat each detection in the sample into the COCO format for detections, labels, areas, and crowds. We also add length and get_classes methods for usability." }, { "code": null, "e": 9993, "s": 9665, "text": "Once a PyTorch dataset is constructed for your data and model combination, you need to create a PyTorch data loader. These data loaders are the iterables that use the dataset code you wrote to import your data. They are fairly simple but provide some useful functionality like shuffling, batching, and loading data in parallel." }, { "code": null, "e": 10357, "s": 9993, "text": "Since we decided to back our datasets in FiftyOne, we can also perform actions like splitting and shuffling our data by creating views into our dataset. The take method on a FiftyOne dataset returns a subset containing random samples from the dataset. The exclude method prevents us from taking any samples that are in the training split for our validation split:" }, { "code": null, "e": 10713, "s": 10357, "text": "Now say that you wanted to get more specific with the data that you use to train and test your model. For example, you might want to train on a specific subset of classes or remap some of the labels. If you are just using PyTorch code, then you need to go back and rewrite your Dataset class and possibly even go back to change your dataset files on disk." }, { "code": null, "e": 11261, "s": 10713, "text": "FiftyOne can do much more than just splitting and shuffling data and makes it easy to get exactly the data that you need for your model. One of the primary ways of interacting with your FiftyOne dataset is through different views into your dataset. These are constructed by applying operations like filtering, sorting, slicing, etc, that result in a specific view into certain labels/samples of your dataset. These operations make it easier to experiment with different subsets of data and continue to finetune your dataset to train better models." }, { "code": null, "e": 11561, "s": 11261, "text": "For example, cluttered images make it difficult for models to localize objects. We can use FiftyOne to create a view containing only samples with more than, say, 10 objects. You can perform the same operations on views as datasets, so we can create an instance of our PyTorch dataset from this view:" }, { "code": null, "e": 11795, "s": 11561, "text": "Another example is if we want to train a model that is used primarily for road vehicle detection. We can easily create training and testing views (and corresponding PyTorch datasets) that only contain the classes car, truck, and bus:" }, { "code": null, "e": 12154, "s": 11795, "text": "Now that we have decided on the data we want to use to train and test our model, the next step is to construct the training pipeline. This varies depending on what you want to accomplish with your model. The specifics of constructing and training models in PyTorch are out of the scope of this blog post, and for that, I refer you to other sources [1,2,3,4]." }, { "code": null, "e": 12420, "s": 12154, "text": "For this example, we are writing a simple training loop following the PyTorch object detection tutorial. This function takes a model and our PyTorch datasets as input and use the train_one_epoch() and evaluate() functions from the Torchvision object detection code:" }, { "code": null, "e": 12568, "s": 12420, "text": "Let’s continue with the vehicle example from the previous section. We can use the torch_dataset and torch_dataset_test to define and train a model:" }, { "code": null, "e": 12839, "s": 12568, "text": "Every epoch, this training loop prints evaluation metrics on the test split. After 4 epochs on the samples that we selected from the COCO dataset, we have reached 36.7% mAP. This is not surprising since this model was pretrained on COCO (but not this subset of classes)." }, { "code": null, "e": 12907, "s": 12839, "text": "IoU metric: bbox Average Precision (AP) @[ IoU=0.50:0.95 ] = 0.367" }, { "code": null, "e": 13303, "s": 12907, "text": "Printing evaluation metrics is useful during training so that you can see how quickly your model is learning and when it begins to saturate. However, this Torchvision evaluation protocol only returns dataset-wide mAP metrics. To best understand where your model performs well and poorly, and thus having any hope of improving it, requires you to see how the model performs on individual samples." }, { "code": null, "e": 13824, "s": 13303, "text": "One of the main draws of FiftyOne is the ability to find failure modes of your model. The built-in evaluation protocols tell you exactly where your model got things right and where it got things wrong. Before we can evaluate the model, though, we need to run it on our test set and store the results in FiftyOne. Doing this is fairly simple and just requires us to run inference for the test images, get their corresponding FiftyOne samples, and add a new field called predictions to each sample to store the detections." }, { "code": null, "e": 14111, "s": 13824, "text": "The DetectionResults object that is returned stores information like the mAP and contains functions that let you plot confusion matrices, precision-recall curves, and more. Also, these evaluation runs are tracked in FiftyOne and can be managed through functions like list_evaluations()." }, { "code": null, "e": 14460, "s": 14111, "text": "What we are interested in, though, is the fact that evaluate_detections() updates the detections in thepredictions field with attributes indicating whether they are true positives, false positives, or false negatives. Using FiftyOne views and the App, we can quickly find the samples that the model performed worst on by sorting by false positives:" }, { "code": null, "e": 14712, "s": 14460, "text": "Looking through some of these samples, a pattern emerges. A number of truck and car annotations are actually incorrect in the ground truth. There seems to be confusion for things like vans and SUVs that are interchangeably annotated as cars or trucks." }, { "code": null, "e": 14980, "s": 14712, "text": "It would be interesting to see a confusion matrix between these classes. By default, the evaluation only matches predictions with ground truth objects of the same class (classwise=True). We can rerun the evaluation with classwise=False and plot that confusion matrix." }, { "code": null, "e": 15311, "s": 14980, "text": "It would be best to get this data reannotated to fix these mistakes, but in the meantime, we can easily remedy this by simply creating a new view that remaps the labels car, truck, and bus all to vehicle and then retraining the model with that. Since our training data is backed by a FiftyOne dataset, this transformation is easy!" }, { "code": null, "e": 15849, "s": 15311, "text": "Due to our ability to easily visualize and manage our dataset with FiftyOne, we were able to spot and take action on a dataset issue that would otherwise have gone unnoticed if we only concerned ourselves with dataset-wide evaluation metrics and fixed dataset representations. Through these efforts, we managed to increase the mAP of the model to 43%. Even though this example workflow may not work in all situations, this kind of class-merging strategy can be effective in cases where more fine-grained discrimination is not called for." }, { "code": null, "e": 16145, "s": 15849, "text": "If you are primarily focused on developing a novel model architecture, then you would likely want to start directly in PyTorch. However, if your goal is to train a model on a custom dataset and a common task, then there are a number of training frameworks that can make that even easier for you." }, { "code": null, "e": 16605, "s": 16145, "text": "Some notable training frameworks for object detection are Detectron2 and MMDetection. But no matter what framework you choose, they will likely not use PyTorch datasets and data loaders directly and instead require you to format your data on disk in a certain way. Detectron2 and MMDetection, for example, expect your data to be stored in the COCO format. Once you have reformatted your dataset, it can be loaded directly into these frameworks and trained on." }, { "code": null, "e": 16998, "s": 16605, "text": "Even though you are not loading the datasets yourself, FiftyOne can still help you with this process. With FiftyOne, any dataset or view that you have loaded into it can be exported in over a dozen different formats (COCO included). This means that you can parse your dataset into FiftyOne and export it in one line of code instead of needing to write numerous scripts to convert it yourself." }, { "code": null, "e": 17470, "s": 16998, "text": "PyTorch and related frameworks provide quick and easy methods to bootstrap your model development and training pipelines. However, they largely overlook the need to massage and finetune datasets to efficiently improve performance. FiftyOne is an ML developer tool designed to make it easy to load your datasets into a flexible format that works well with existing tools allowing you to provide better data for training and testing. As they say, “garbage in, garbage out”." }, { "code": null, "e": 17816, "s": 17470, "text": "High-quality, intentionally-curated data is critical to training great computer vision models. At Voxel51, we have over 25 years of CV/ML experience and care deeply about enabling the community to bring their AI solutions to life. That’s why we developed FiftyOne, an open-source tool that helps engineers and scientists to do better ML, faster." } ]
Get all methods of any object JavaScript
We are required to write a program (function) that takes in an object reference and returns an array of all the methods (member functions) that lives on that object.We are only required to return the methods in the array and not any other property that might have value of type other than a function. We will use the Object.getOwnPropertyNames function The Object.getOwnPropertyNames() method returns an array of all properties (enumerable or not) found directly upon a given object. And then we will filter the array to contain property of data type 'function' only. const returnMethods = (obj = {}) => { const members = Object.getOwnPropertyNames(obj); const methods = members.filter(el => { return typeof obj[el] === 'function'; }) return methods; }; console.log(returnMethods(Array.prototype)); And the output in the console will be − [ 'constructor', 'concat', 'copyWithin', 'fill', 'find', 'findIndex', 'lastIndexOf', 'pop', 'push', 'reverse', 'shift', 'unshift', 'slice', 'sort', 'splice', 'includes', 'indexOf', 'join', 'keys', 'entries', 'values', 'forEach', 'filter', 'flat', 'flatMap', 'map', 'every', 'some', 'reduce', 'reduceRight', 'toLocaleString', 'toString' ]
[ { "code": null, "e": 1363, "s": 1062, "text": "We are required to write a program (function) that takes in an object reference and returns an array of all the methods (member functions) that lives on that object.We are only required to return the methods in the array and not any other property that might have value of type other than a function." }, { "code": null, "e": 1415, "s": 1363, "text": "We will use the Object.getOwnPropertyNames function" }, { "code": null, "e": 1630, "s": 1415, "text": "The Object.getOwnPropertyNames() method returns an array of all properties (enumerable or not) found directly upon a given object. And then we will filter the array to contain property of data type 'function' only." }, { "code": null, "e": 1879, "s": 1630, "text": "const returnMethods = (obj = {}) => {\n const members = Object.getOwnPropertyNames(obj);\n const methods = members.filter(el => {\n return typeof obj[el] === 'function';\n })\n return methods;\n};\nconsole.log(returnMethods(Array.prototype));" }, { "code": null, "e": 1919, "s": 1879, "text": "And the output in the console will be −" }, { "code": null, "e": 2281, "s": 1919, "text": "[\n 'constructor', 'concat', 'copyWithin',\n'fill', 'find', 'findIndex', 'lastIndexOf', 'pop', 'push',\n 'reverse', 'shift', 'unshift', 'slice', 'sort', 'splice',\n 'includes', 'indexOf', 'join',\n 'keys', 'entries', 'values',\n 'forEach', 'filter', 'flat',\n 'flatMap', 'map', 'every',\n 'some', 'reduce', 'reduceRight',\n 'toLocaleString', 'toString'\n]" } ]
Automatically Generate Hotel Descriptions with LSTM | by Susan Li | Towards Data Science
In order to build a content based recommender system, I collected hotel descriptions for 152 hotels in Seattle. I was thinking of some other ways to torture this good quality clean data set. Hey! why not train my own text-generating neural network of hotel descriptions? That is, create a language model for generating natural language text (i.e. hotel descriptions) by implement and training a word-based Recurrent Neural Network. The objective of this project is to generate new hotel descriptions, given some input text. I do not expect results to be accurate, as long as the predicted text are coherent, I will be happy. And thanks for this tutorial from Shivam Bansal that helped me getting through the exercise. We have 152 descriptions (i.e. hotels) in total in our data set. Have a peek the 1st description: corpus = [x for x in all_descriptions]corpus[:1] After tokenization, we then can: Explore a dictionary of words and their counts. Explore a dictionary of words and how many documents each appeared in. Explore an integer count of the total number of documents that were used to fit the Tokenizer (i.e. total number of documents). Explore a dictionary of words and their uniquely assigned integers. t = Tokenizer(num_words=None, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n', lower=True, split=' ', char_level=False, oov_token=None, document_count=0)t.fit_on_texts(corpus)print(t.word_counts)print(t.word_docs)print(t.document_count)print(t.word_index)print('Found %s unique tokens.' % len(t.word_index)) We use Keras’ Tokenizer to vectorize text descriptions, We remove all punctuation. We turn the texts into space-separated sequences of words in lowercase. These sequences are then split into lists of tokens. We set char_level=False , so every word will be treated as a token other than character. The lists of tokens will then be indexed or / and vectorized. We convert the corpus into sequence of tokens. The above lists of integers represent the ngram phrases generated from the corpus. For example, lets say, a sentence of “located on the southern tip of lake Union” be represented by the index of words like this: Pads sequences to the same length Pad sequences transforms lists of integers into a 2D Numpy array of shape (num_samples, maxlen). The predictors and label look like this: As you can see, if we want accuracy, its going to be very very hard. We can now define our single LSTM model. A single hidden LSTM layer with 100 memory units. The network uses dropout with a probability of 10. The output layer is a Dense layer using the softmax activation function to output a probability prediction for each of the 3420 words between 0 and 1. Our problem is a single word classification problem with 3420 classes and as such is defined as optimizing the log loss (cross entropy), and use the ADAM optimization algorithm for speed. There is no test data set. We are modeling the entire training data to learn the probability of each word in a sequence. According to Keras documentation, At least 20 epochs are required before the generated text starts sounding coherent. so, we will train for 100 epochs. A this point, we can write a function that takes seed texts as input, and predict the next words. We tokenize the seed texts, pad sequences and pass them to the trained model. Try it out! I randomly choose “hilton seattle downtown” as seed texts, and I want model to return me the next 100 words. print(generate_text("hilton seattle downtown", 100, model, max_sequence_len)) I choose “best western seattle airport hotel” as seed texts, and I want the model to predict the next 200 words. print(generate_text("best western seattle airport hotel", 200, model, max_sequence_len)) I choose “located in the heart of downtown seattle” as seed texts, and I want the model to predict the next 300 words. print(generate_text('located in the heart of downtown seattle', 300, model, max_sequence_len)) There was no misspelling. The sentences look realistic. Some phrases get repeated again and again, in particular predicting a larger number of words as output for a given seed. A few thoughts on improvements: more training data, more training epochs, more layers, more memory units to the layers, predict fewer number of words as output for a given seed. Jupyter notebook can be found on Github. Enjoy the rest of the weekend!
[ { "code": null, "e": 363, "s": 172, "text": "In order to build a content based recommender system, I collected hotel descriptions for 152 hotels in Seattle. I was thinking of some other ways to torture this good quality clean data set." }, { "code": null, "e": 604, "s": 363, "text": "Hey! why not train my own text-generating neural network of hotel descriptions? That is, create a language model for generating natural language text (i.e. hotel descriptions) by implement and training a word-based Recurrent Neural Network." }, { "code": null, "e": 797, "s": 604, "text": "The objective of this project is to generate new hotel descriptions, given some input text. I do not expect results to be accurate, as long as the predicted text are coherent, I will be happy." }, { "code": null, "e": 890, "s": 797, "text": "And thanks for this tutorial from Shivam Bansal that helped me getting through the exercise." }, { "code": null, "e": 955, "s": 890, "text": "We have 152 descriptions (i.e. hotels) in total in our data set." }, { "code": null, "e": 988, "s": 955, "text": "Have a peek the 1st description:" }, { "code": null, "e": 1037, "s": 988, "text": "corpus = [x for x in all_descriptions]corpus[:1]" }, { "code": null, "e": 1070, "s": 1037, "text": "After tokenization, we then can:" }, { "code": null, "e": 1118, "s": 1070, "text": "Explore a dictionary of words and their counts." }, { "code": null, "e": 1189, "s": 1118, "text": "Explore a dictionary of words and how many documents each appeared in." }, { "code": null, "e": 1317, "s": 1189, "text": "Explore an integer count of the total number of documents that were used to fit the Tokenizer (i.e. total number of documents)." }, { "code": null, "e": 1385, "s": 1317, "text": "Explore a dictionary of words and their uniquely assigned integers." }, { "code": null, "e": 1692, "s": 1385, "text": "t = Tokenizer(num_words=None, filters='!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n', lower=True, split=' ', char_level=False, oov_token=None, document_count=0)t.fit_on_texts(corpus)print(t.word_counts)print(t.word_docs)print(t.document_count)print(t.word_index)print('Found %s unique tokens.' % len(t.word_index))" }, { "code": null, "e": 1748, "s": 1692, "text": "We use Keras’ Tokenizer to vectorize text descriptions," }, { "code": null, "e": 1775, "s": 1748, "text": "We remove all punctuation." }, { "code": null, "e": 1847, "s": 1775, "text": "We turn the texts into space-separated sequences of words in lowercase." }, { "code": null, "e": 1900, "s": 1847, "text": "These sequences are then split into lists of tokens." }, { "code": null, "e": 1989, "s": 1900, "text": "We set char_level=False , so every word will be treated as a token other than character." }, { "code": null, "e": 2051, "s": 1989, "text": "The lists of tokens will then be indexed or / and vectorized." }, { "code": null, "e": 2098, "s": 2051, "text": "We convert the corpus into sequence of tokens." }, { "code": null, "e": 2310, "s": 2098, "text": "The above lists of integers represent the ngram phrases generated from the corpus. For example, lets say, a sentence of “located on the southern tip of lake Union” be represented by the index of words like this:" }, { "code": null, "e": 2344, "s": 2310, "text": "Pads sequences to the same length" }, { "code": null, "e": 2441, "s": 2344, "text": "Pad sequences transforms lists of integers into a 2D Numpy array of shape (num_samples, maxlen)." }, { "code": null, "e": 2482, "s": 2441, "text": "The predictors and label look like this:" }, { "code": null, "e": 2551, "s": 2482, "text": "As you can see, if we want accuracy, its going to be very very hard." }, { "code": null, "e": 2592, "s": 2551, "text": "We can now define our single LSTM model." }, { "code": null, "e": 2642, "s": 2592, "text": "A single hidden LSTM layer with 100 memory units." }, { "code": null, "e": 2693, "s": 2642, "text": "The network uses dropout with a probability of 10." }, { "code": null, "e": 2844, "s": 2693, "text": "The output layer is a Dense layer using the softmax activation function to output a probability prediction for each of the 3420 words between 0 and 1." }, { "code": null, "e": 3032, "s": 2844, "text": "Our problem is a single word classification problem with 3420 classes and as such is defined as optimizing the log loss (cross entropy), and use the ADAM optimization algorithm for speed." }, { "code": null, "e": 3153, "s": 3032, "text": "There is no test data set. We are modeling the entire training data to learn the probability of each word in a sequence." }, { "code": null, "e": 3305, "s": 3153, "text": "According to Keras documentation, At least 20 epochs are required before the generated text starts sounding coherent. so, we will train for 100 epochs." }, { "code": null, "e": 3403, "s": 3305, "text": "A this point, we can write a function that takes seed texts as input, and predict the next words." }, { "code": null, "e": 3481, "s": 3403, "text": "We tokenize the seed texts, pad sequences and pass them to the trained model." }, { "code": null, "e": 3493, "s": 3481, "text": "Try it out!" }, { "code": null, "e": 3602, "s": 3493, "text": "I randomly choose “hilton seattle downtown” as seed texts, and I want model to return me the next 100 words." }, { "code": null, "e": 3680, "s": 3602, "text": "print(generate_text(\"hilton seattle downtown\", 100, model, max_sequence_len))" }, { "code": null, "e": 3793, "s": 3680, "text": "I choose “best western seattle airport hotel” as seed texts, and I want the model to predict the next 200 words." }, { "code": null, "e": 3882, "s": 3793, "text": "print(generate_text(\"best western seattle airport hotel\", 200, model, max_sequence_len))" }, { "code": null, "e": 4001, "s": 3882, "text": "I choose “located in the heart of downtown seattle” as seed texts, and I want the model to predict the next 300 words." }, { "code": null, "e": 4096, "s": 4001, "text": "print(generate_text('located in the heart of downtown seattle', 300, model, max_sequence_len))" }, { "code": null, "e": 4122, "s": 4096, "text": "There was no misspelling." }, { "code": null, "e": 4152, "s": 4122, "text": "The sentences look realistic." }, { "code": null, "e": 4273, "s": 4152, "text": "Some phrases get repeated again and again, in particular predicting a larger number of words as output for a given seed." }, { "code": null, "e": 4451, "s": 4273, "text": "A few thoughts on improvements: more training data, more training epochs, more layers, more memory units to the layers, predict fewer number of words as output for a given seed." } ]
OpenCV - Gaussian Blur
In Gaussian Blur operation, the image is convolved with a Gaussian filter instead of the box filter. The Gaussian filter is a low-pass filter that removes the high-frequency components are reduced. You can perform this operation on an image using the Gaussianblur() method of the imgproc class. Following is the syntax of this method − GaussianBlur(src, dst, ksize, sigmaX) This method accepts the following parameters − src − A Mat object representing the source (input image) for this operation. src − A Mat object representing the source (input image) for this operation. dst − A Mat object representing the destination (output image) for this operation. dst − A Mat object representing the destination (output image) for this operation. ksize − A Size object representing the size of the kernel. ksize − A Size object representing the size of the kernel. sigmaX − A variable of the type double representing the Gaussian kernel standard deviation in X direction. sigmaX − A variable of the type double representing the Gaussian kernel standard deviation in X direction. The following program demonstrates how to perform the Gaussian blur operation on an image. import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.Size; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class GaussianTest { public static void main(String args[]) { // Loading the OpenCV core library System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // Reading the Image from the file and storing it in to a Matrix object String file ="C:/EXAMPLES/OpenCV/sample.jpg"; Mat src = Imgcodecs.imread(file); // Creating an empty matrix to store the result Mat dst = new Mat(); // Applying GaussianBlur on the Image Imgproc.GaussianBlur(src, dst, new Size(45, 45), 0); // Writing the image Imgcodecs.imwrite("E:/OpenCV/chap9/Gaussian.jpg", dst); System.out.println("Image Processed"); } } Assume that following is the input image sample.jpg specified in the above program. On executing the program, you will get the following output − Image Processed If you open the specified path, you can observe the output image as follows − 70 Lectures 9 hours Abhilash Nelson 41 Lectures 4 hours Abhilash Nelson 20 Lectures 2 hours Spotle Learn 12 Lectures 46 mins Srikanth Guskra 19 Lectures 2 hours Haithem Gasmi 67 Lectures 6.5 hours Gianluca Mottola Print Add Notes Bookmark this page
[ { "code": null, "e": 3202, "s": 3004, "text": "In Gaussian Blur operation, the image is convolved with a Gaussian filter instead of the box filter. The Gaussian filter is a low-pass filter that removes the high-frequency components are reduced." }, { "code": null, "e": 3340, "s": 3202, "text": "You can perform this operation on an image using the Gaussianblur() method of the imgproc class. Following is the syntax of this method −" }, { "code": null, "e": 3379, "s": 3340, "text": "GaussianBlur(src, dst, ksize, sigmaX)\n" }, { "code": null, "e": 3426, "s": 3379, "text": "This method accepts the following parameters −" }, { "code": null, "e": 3503, "s": 3426, "text": "src − A Mat object representing the source (input image) for this operation." }, { "code": null, "e": 3580, "s": 3503, "text": "src − A Mat object representing the source (input image) for this operation." }, { "code": null, "e": 3663, "s": 3580, "text": "dst − A Mat object representing the destination (output image) for this operation." }, { "code": null, "e": 3746, "s": 3663, "text": "dst − A Mat object representing the destination (output image) for this operation." }, { "code": null, "e": 3805, "s": 3746, "text": "ksize − A Size object representing the size of the kernel." }, { "code": null, "e": 3864, "s": 3805, "text": "ksize − A Size object representing the size of the kernel." }, { "code": null, "e": 3971, "s": 3864, "text": "sigmaX − A variable of the type double representing the Gaussian kernel standard deviation in X direction." }, { "code": null, "e": 4078, "s": 3971, "text": "sigmaX − A variable of the type double representing the Gaussian kernel standard deviation in X direction." }, { "code": null, "e": 4169, "s": 4078, "text": "The following program demonstrates how to perform the Gaussian blur operation on an image." }, { "code": null, "e": 4998, "s": 4169, "text": "import org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.core.Size;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\n\npublic class GaussianTest {\n public static void main(String args[]) {\n // Loading the OpenCV core library\n System.loadLibrary(Core.NATIVE_LIBRARY_NAME);\n\n // Reading the Image from the file and storing it in to a Matrix object\n String file =\"C:/EXAMPLES/OpenCV/sample.jpg\";\n Mat src = Imgcodecs.imread(file);\n\n // Creating an empty matrix to store the result\n Mat dst = new Mat();\n \n // Applying GaussianBlur on the Image\n Imgproc.GaussianBlur(src, dst, new Size(45, 45), 0);\n\n // Writing the image\n Imgcodecs.imwrite(\"E:/OpenCV/chap9/Gaussian.jpg\", dst);\n System.out.println(\"Image Processed\");\n }\n}" }, { "code": null, "e": 5082, "s": 4998, "text": "Assume that following is the input image sample.jpg specified in the above program." }, { "code": null, "e": 5144, "s": 5082, "text": "On executing the program, you will get the following output −" }, { "code": null, "e": 5161, "s": 5144, "text": "Image Processed\n" }, { "code": null, "e": 5239, "s": 5161, "text": "If you open the specified path, you can observe the output image as follows −" }, { "code": null, "e": 5272, "s": 5239, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 5289, "s": 5272, "text": " Abhilash Nelson" }, { "code": null, "e": 5322, "s": 5289, "text": "\n 41 Lectures \n 4 hours \n" }, { "code": null, "e": 5339, "s": 5322, "text": " Abhilash Nelson" }, { "code": null, "e": 5372, "s": 5339, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 5386, "s": 5372, "text": " Spotle Learn" }, { "code": null, "e": 5418, "s": 5386, "text": "\n 12 Lectures \n 46 mins\n" }, { "code": null, "e": 5435, "s": 5418, "text": " Srikanth Guskra" }, { "code": null, "e": 5468, "s": 5435, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 5483, "s": 5468, "text": " Haithem Gasmi" }, { "code": null, "e": 5518, "s": 5483, "text": "\n 67 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5536, "s": 5518, "text": " Gianluca Mottola" }, { "code": null, "e": 5543, "s": 5536, "text": " Print" }, { "code": null, "e": 5554, "s": 5543, "text": " Add Notes" } ]
How to convert character to ASCII code using JavaScript ? - GeeksforGeeks
15 Sep, 2020 The purpose of this article is to get the ASCII code of any character by using JavaScript charCodeAt() method. This method is used to return the number indicating the Unicode value of the character at the specified index. Syntax: string.charCodeAt(index); Example: Below code illustrates that they can take character from the user and display the ASCII code of that character. HTML Code: HTML <!DOCTYPE html><html> <body style="text-align:center;"> <h2> GeeksForGeeks </h2> <h2> How to convert character to ASCII code in JavaScript </h2> <p> Enter any character: <input type="text" id="id1" name="text1" maxLength="1"> </p> <button onclick="myFunction()"> Get ASCII code </button> <p id="demo" style="color:red;"></body> </html> JavaScript Code: The following code snippet illustrates the JavaScript code used in the above HTML code. function myFunction() { var str = document.getElementById("id1"); if (str.value == "") { str.focus(); return; } var a = "ASCII Code is == > "; document.getElementById("demo").innerHTML = a + str.value.charCodeAt(0);} Final Code: The following example is the combination of the above two code snippets. <!DOCTYPE html><html> <body style="text-align:center;"> <h2> GeeksForGeeks </h2> <h2> How to convert character to ASCII code in JavaScript </h2> <script> function myFunction() { var str = document.getElementById("id1"); if (str.value == "") { str.focus(); return; } var a = "ASCII Code is == > "; document.getElementById("demo").innerHTML = a + str.value.charCodeAt(0); } </script> <p> Enter any character: <input type="text" id="id1" name="text1" maxLength="1"> </p> <button onclick="myFunction()"> Get ASCII code </button> <p id="demo" style="color:red;"></body> </html> Output: Before Clicking on Button: Before Clicking on Button: After Clicking On Button:Supported browsers:Google ChromeInternet ExplorerFirefoxOperaSafariMy Personal Notes arrow_drop_upSave After Clicking On Button: Supported browsers: Google Chrome Internet Explorer Firefox Opera Safari CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS How to set space between the flexbox ? Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to Create Time-Table schedule using HTML ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25376, "s": 25348, "text": "\n15 Sep, 2020" }, { "code": null, "e": 25598, "s": 25376, "text": "The purpose of this article is to get the ASCII code of any character by using JavaScript charCodeAt() method. This method is used to return the number indicating the Unicode value of the character at the specified index." }, { "code": null, "e": 25606, "s": 25598, "text": "Syntax:" }, { "code": null, "e": 25633, "s": 25606, "text": "string.charCodeAt(index); " }, { "code": null, "e": 25754, "s": 25633, "text": "Example: Below code illustrates that they can take character from the user and display the ASCII code of that character." }, { "code": null, "e": 25765, "s": 25754, "text": "HTML Code:" }, { "code": null, "e": 25770, "s": 25765, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body style=\"text-align:center;\"> <h2> GeeksForGeeks </h2> <h2> How to convert character to ASCII code in JavaScript </h2> <p> Enter any character: <input type=\"text\" id=\"id1\" name=\"text1\" maxLength=\"1\"> </p> <button onclick=\"myFunction()\"> Get ASCII code </button> <p id=\"demo\" style=\"color:red;\"></body> </html>", "e": 26195, "s": 25770, "text": null }, { "code": null, "e": 26300, "s": 26195, "text": "JavaScript Code: The following code snippet illustrates the JavaScript code used in the above HTML code." }, { "code": "function myFunction() { var str = document.getElementById(\"id1\"); if (str.value == \"\") { str.focus(); return; } var a = \"ASCII Code is == > \"; document.getElementById(\"demo\").innerHTML = a + str.value.charCodeAt(0);}", "e": 26554, "s": 26300, "text": null }, { "code": null, "e": 26639, "s": 26554, "text": "Final Code: The following example is the combination of the above two code snippets." }, { "code": "<!DOCTYPE html><html> <body style=\"text-align:center;\"> <h2> GeeksForGeeks </h2> <h2> How to convert character to ASCII code in JavaScript </h2> <script> function myFunction() { var str = document.getElementById(\"id1\"); if (str.value == \"\") { str.focus(); return; } var a = \"ASCII Code is == > \"; document.getElementById(\"demo\").innerHTML = a + str.value.charCodeAt(0); } </script> <p> Enter any character: <input type=\"text\" id=\"id1\" name=\"text1\" maxLength=\"1\"> </p> <button onclick=\"myFunction()\"> Get ASCII code </button> <p id=\"demo\" style=\"color:red;\"></body> </html>", "e": 27425, "s": 26639, "text": null }, { "code": null, "e": 27433, "s": 27425, "text": "Output:" }, { "code": null, "e": 27460, "s": 27433, "text": "Before Clicking on Button:" }, { "code": null, "e": 27487, "s": 27460, "text": "Before Clicking on Button:" }, { "code": null, "e": 27615, "s": 27487, "text": "After Clicking On Button:Supported browsers:Google ChromeInternet ExplorerFirefoxOperaSafariMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 27641, "s": 27615, "text": "After Clicking On Button:" }, { "code": null, "e": 27661, "s": 27641, "text": "Supported browsers:" }, { "code": null, "e": 27675, "s": 27661, "text": "Google Chrome" }, { "code": null, "e": 27693, "s": 27675, "text": "Internet Explorer" }, { "code": null, "e": 27701, "s": 27693, "text": "Firefox" }, { "code": null, "e": 27707, "s": 27701, "text": "Opera" }, { "code": null, "e": 27714, "s": 27707, "text": "Safari" }, { "code": null, "e": 27723, "s": 27714, "text": "CSS-Misc" }, { "code": null, "e": 27733, "s": 27723, "text": "HTML-Misc" }, { "code": null, "e": 27749, "s": 27733, "text": "JavaScript-Misc" }, { "code": null, "e": 27753, "s": 27749, "text": "CSS" }, { "code": null, "e": 27758, "s": 27753, "text": "HTML" }, { "code": null, "e": 27769, "s": 27758, "text": "JavaScript" }, { "code": null, "e": 27786, "s": 27769, "text": "Web Technologies" }, { "code": null, "e": 27791, "s": 27786, "text": "HTML" }, { "code": null, "e": 27889, "s": 27791, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27926, "s": 27889, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27965, "s": 27926, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 27994, "s": 27965, "text": "Form validation using jQuery" }, { "code": null, "e": 28036, "s": 27994, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 28083, "s": 28036, "text": "How to Create Time-Table schedule using HTML ?" }, { "code": null, "e": 28143, "s": 28083, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28204, "s": 28143, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28257, "s": 28204, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28307, "s": 28257, "text": "How to Insert Form Data into Database using PHP ?" } ]
Python String split() Method
Python string method split() returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num. Following is the syntax for split() method − str.split(str="", num=string.count(str)). str − This is any delimeter, by default it is space. str − This is any delimeter, by default it is space. num − this is number of lines minus one num − this is number of lines minus one This method returns a list of lines. The following example shows the usage of split() method. #!/usr/bin/python str = "Line1-abcdef \nLine2-abc \nLine4-abcd"; print str.split( ) print str.split(' ', 1 ) When we run above program, it produces following result − ['Line1-abcdef', 'Line2-abc', 'Line4-abcd'] ['Line1-abcdef', '\nLine2-abc \nLine4-abcd'] 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2445, "s": 2244, "text": "Python string method split() returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num." }, { "code": null, "e": 2490, "s": 2445, "text": "Following is the syntax for split() method −" }, { "code": null, "e": 2533, "s": 2490, "text": "str.split(str=\"\", num=string.count(str)).\n" }, { "code": null, "e": 2586, "s": 2533, "text": "str − This is any delimeter, by default it is space." }, { "code": null, "e": 2639, "s": 2586, "text": "str − This is any delimeter, by default it is space." }, { "code": null, "e": 2679, "s": 2639, "text": "num − this is number of lines minus one" }, { "code": null, "e": 2719, "s": 2679, "text": "num − this is number of lines minus one" }, { "code": null, "e": 2756, "s": 2719, "text": "This method returns a list of lines." }, { "code": null, "e": 2813, "s": 2756, "text": "The following example shows the usage of split() method." }, { "code": null, "e": 2923, "s": 2813, "text": "#!/usr/bin/python\n\nstr = \"Line1-abcdef \\nLine2-abc \\nLine4-abcd\";\nprint str.split( )\nprint str.split(' ', 1 )" }, { "code": null, "e": 2981, "s": 2923, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 3071, "s": 2981, "text": "['Line1-abcdef', 'Line2-abc', 'Line4-abcd']\n['Line1-abcdef', '\\nLine2-abc \\nLine4-abcd']\n" }, { "code": null, "e": 3108, "s": 3071, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3124, "s": 3108, "text": " Malhar Lathkar" }, { "code": null, "e": 3157, "s": 3124, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3176, "s": 3157, "text": " Arnab Chakraborty" }, { "code": null, "e": 3211, "s": 3176, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3233, "s": 3211, "text": " In28Minutes Official" }, { "code": null, "e": 3267, "s": 3233, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3295, "s": 3267, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3330, "s": 3295, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3344, "s": 3330, "text": " Lets Kode It" }, { "code": null, "e": 3377, "s": 3344, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3394, "s": 3377, "text": " Abhilash Nelson" }, { "code": null, "e": 3401, "s": 3394, "text": " Print" }, { "code": null, "e": 3412, "s": 3401, "text": " Add Notes" } ]
Data Structure - Circular Linked List
Circular Linked List is a variation of Linked list in which the first element points to the last element and the last element points to the first element. Both Singly Linked List and Doubly Linked List can be made into a circular linked list. In singly linked list, the next pointer of the last node points to the first node. In doubly linked list, the next pointer of the last node points to the first node and the previous pointer of the first node points to the last node making the circular in both directions. As per the above illustration, following are the important points to be considered. The last link's next points to the first link of the list in both cases of singly as well as doubly linked list. The last link's next points to the first link of the list in both cases of singly as well as doubly linked list. The first link's previous points to the last of the list in case of doubly linked list. The first link's previous points to the last of the list in case of doubly linked list. Following are the important operations supported by a circular list. insert − Inserts an element at the start of the list. insert − Inserts an element at the start of the list. delete − Deletes an element from the start of the list. delete − Deletes an element from the start of the list. display − Displays the list. display − Displays the list. Following code demonstrates the insertion operation in a circular linked list based on single linked list. insertFirst(data): Begin create a new node node -> data := data if the list is empty, then head := node next of node = head else temp := head while next of temp is not head, do temp := next of temp done next of node := head next of temp := node head := node end if End Following code demonstrates the deletion operation in a circular linked list based on single linked list. deleteFirst(): Begin if head is null, then it is Underflow and return else if next of head = head, then head := null deallocate head else ptr := head while next of ptr is not head, do ptr := next of ptr next of ptr = next of head deallocate head head := next of ptr end if End Following code demonstrates the display list operation in a circular linked list. display(): Begin if head is null, then Nothing to print and return else ptr := head while next of ptr is not head, do display data of ptr ptr := next of ptr display data of ptr end if End To know about its implementation in C programming language, please click here. 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2823, "s": 2580, "text": "Circular Linked List is a variation of Linked list in which the first element points to the last element and the last element points to the first element. Both Singly Linked List and Doubly Linked List can be made into a circular linked list." }, { "code": null, "e": 2906, "s": 2823, "text": "In singly linked list, the next pointer of the last node points to the first node." }, { "code": null, "e": 3095, "s": 2906, "text": "In doubly linked list, the next pointer of the last node points to the first node and the previous pointer of the first node points to the last node making the circular in both directions." }, { "code": null, "e": 3179, "s": 3095, "text": "As per the above illustration, following are the important points to be considered." }, { "code": null, "e": 3292, "s": 3179, "text": "The last link's next points to the first link of the list in both cases of singly as well as doubly linked list." }, { "code": null, "e": 3405, "s": 3292, "text": "The last link's next points to the first link of the list in both cases of singly as well as doubly linked list." }, { "code": null, "e": 3493, "s": 3405, "text": "The first link's previous points to the last of the list in case of doubly linked list." }, { "code": null, "e": 3581, "s": 3493, "text": "The first link's previous points to the last of the list in case of doubly linked list." }, { "code": null, "e": 3650, "s": 3581, "text": "Following are the important operations supported by a circular list." }, { "code": null, "e": 3704, "s": 3650, "text": "insert − Inserts an element at the start of the list." }, { "code": null, "e": 3758, "s": 3704, "text": "insert − Inserts an element at the start of the list." }, { "code": null, "e": 3814, "s": 3758, "text": "delete − Deletes an element from the start of the list." }, { "code": null, "e": 3870, "s": 3814, "text": "delete − Deletes an element from the start of the list." }, { "code": null, "e": 3899, "s": 3870, "text": "display − Displays the list." }, { "code": null, "e": 3928, "s": 3899, "text": "display − Displays the list." }, { "code": null, "e": 4035, "s": 3928, "text": "Following code demonstrates the insertion operation in a circular linked list based on single linked list." }, { "code": null, "e": 4373, "s": 4035, "text": "insertFirst(data):\nBegin\n create a new node\n node -> data := data\n if the list is empty, then\n head := node\n next of node = head\n else\n temp := head\n while next of temp is not head, do\n temp := next of temp\n done\n next of node := head\n next of temp := node\n head := node\n end if\nEnd" }, { "code": null, "e": 4479, "s": 4373, "text": "Following code demonstrates the deletion operation in a circular linked list based on single linked list." }, { "code": null, "e": 4825, "s": 4479, "text": "deleteFirst():\nBegin\n if head is null, then\n it is Underflow and return\n else if next of head = head, then\n head := null\n deallocate head\n else\n ptr := head\n while next of ptr is not head, do\n ptr := next of ptr\n next of ptr = next of head\n deallocate head\n head := next of ptr\n end if\nEnd" }, { "code": null, "e": 4907, "s": 4825, "text": "Following code demonstrates the display list operation in a circular linked list." }, { "code": null, "e": 5146, "s": 4907, "text": "display():\nBegin\n if head is null, then\n Nothing to print and return\n else\n ptr := head\n while next of ptr is not head, do\n display data of ptr\n ptr := next of ptr\n display data of ptr\n end if\nEnd" }, { "code": null, "e": 5225, "s": 5146, "text": "To know about its implementation in C programming language, please click here." }, { "code": null, "e": 5260, "s": 5225, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5272, "s": 5260, "text": " Ravi Kiran" }, { "code": null, "e": 5307, "s": 5272, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 5326, "s": 5307, "text": " Arnab Chakraborty" }, { "code": null, "e": 5361, "s": 5326, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 5376, "s": 5361, "text": " Parth Panjabi" }, { "code": null, "e": 5409, "s": 5376, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 5428, "s": 5409, "text": " Arnab Chakraborty" }, { "code": null, "e": 5462, "s": 5428, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 5490, "s": 5462, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5526, "s": 5490, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 5554, "s": 5526, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5561, "s": 5554, "text": " Print" }, { "code": null, "e": 5572, "s": 5561, "text": " Add Notes" } ]
F# - Functions
In F#, functions work like data types. You can declare and use a function in the same way like any other variable. Since functions can be used like any other variables, you can − Create a function, with a name and associate that name with a type. Assign it a value. Perform some calculation on that value. Pass it as a parameter to another function or sub-routine. Return a function as the result of another function. Functions are defined by using the let keyword. A function definition has the following syntax − let [inline] function-name parameter-list [ : return-type ] = function-body Where, function-name is an identifier that represents the function. function-name is an identifier that represents the function. parameter-list gives the list of parameters separated by spaces. You can also specify an explicit type for each parameter and if not specified compiler tends to deduce it from the function body (like variables). parameter-list gives the list of parameters separated by spaces. You can also specify an explicit type for each parameter and if not specified compiler tends to deduce it from the function body (like variables). function-body consists of an expression, or a compound expression consisting of a number of expressions. The final expression in the function body is the return value. function-body consists of an expression, or a compound expression consisting of a number of expressions. The final expression in the function body is the return value. return-type is a colon followed by a type and is optional. If the return type is not specified, then the compiler determines it from the final expression in the function body. return-type is a colon followed by a type and is optional. If the return type is not specified, then the compiler determines it from the final expression in the function body. You list the names of parameters right after the function name. You can specify the type of a parameter. The type of the parameter should follow the name of the parameter separated by a colon. If no parameter type is specified, it is inferred by the compiler. For example − let doubleIt (x : int) = 2 * x A function is called by specifying the function name followed by a space and then any arguments separated by spaces. For example − let vol = cylinderVolume 3.0 5.0 The following programs illustrate the concepts. The following program calculates the volume of a cylinder when the radius and length are given as parameters // the function calculates the volume of // a cylinder with radius and length as parameters let cylinderVolume radius length : float = // function body let pi = 3.14159 length * pi * radius * radius let vol = cylinderVolume 3.0 5.0 printfn " Volume: %g " vol When you compile and execute the program, it yields the following output − Volume: 141.372 The following program returns the larger value of two given parameters − // the function returns the larger value between two // arguments let max num1 num2 : int32 = // function body if(num1>num2)then num1 else num2 let res = max 39 52 printfn " Max Value: %d " res When you compile and execute the program, it yields the following output − Max Value: 52 let doubleIt (x : int) = 2 * x printfn "Double 19: %d" ( doubleIt(19)) When you compile and execute the program, it yields the following output − Double 19: 38 Recursive functions are functions that call themselves. You define a recursive using the let rec keyword combination. Syntax for defining a recursive function is − //Recursive function definition let rec function-name parameter-list = recursive-function-body For example − let rec fib n = if n < 2 then 1 else fib (n - 1) + fib (n - 2) The following program returns Fibonacci 1 to 10 − let rec fib n = if n < 2 then 1 else fib (n - 1) + fib (n - 2) for i = 1 to 10 do printfn "Fibonacci %d: %d" i (fib i) When you compile and execute the program, it yields the following output − Fibonacci 1: 1 Fibonacci 2: 2 Fibonacci 3: 3 Fibonacci 4: 5 Fibonacci 5: 8 Fibonacci 6: 13 Fibonacci 7: 21 Fibonacci 8: 34 Fibonacci 9: 55 Fibonacci 10: 89 The following program returns factorial 8 − open System let rec fact x = if x < 1 then 1 else x * fact (x - 1) Console.WriteLine(fact 8) When you compile and execute the program, it yields the following output − 40320 F# reports about data type in functions and values, using a chained arrow notation. Let us take an example of a function that takes one int input, and returns a string. In arrow notation, it is written as − int -> string Data types are read from left to right. Let us take another hypothetical function that takes two int data inputs and returns a string. let mydivfunction x y = (x / y).ToString();; F# reports the data type using chained arrow notation as − val mydivfunction : x:int -> y:int -> string The return type is represented by the rightmost data type in chained arrow notation. Some more examples − A lambda expression is an unnamed function. Let us take an example of two functions − let applyFunction ( f: int -> int -> int) x y = f x y let mul x y = x * y let res = applyFunction mul 5 7 printfn "%d" res When you compile and execute the program, it yields the following output − 35 Now in the above example, if instead of defining the function mul, we could have used lambda expressions as − let applyFunction ( f: int -> int -> int) x y = f x y let res = applyFunction (fun x y -> x * y ) 5 7 printfn "%d" res When you compile and execute the program, it yields the following output − 35 In F#, one function can be composed from other functions. The following example shows the composition of a function named f, from two functions function1 and function2 − let function1 x = x + 1 let function2 x = x * 5 let f = function1 >> function2 let res = f 10 printfn "%d" res When you compile and execute the program, it yields the following output − 55 F# also provides a feature called pipelining of functions. Pipelining allows function calls to be chained together as successive operations. The following example shows that − let function1 x = x + 1 let function2 x = x * 5 let res = 10 |> function1 |> function2 printfn "%d" res When you compile and execute the program, it yields the following output − 55 Print Add Notes Bookmark this page
[ { "code": null, "e": 2276, "s": 2161, "text": "In F#, functions work like data types. You can declare and use a function in the same way like any other variable." }, { "code": null, "e": 2340, "s": 2276, "text": "Since functions can be used like any other variables, you can −" }, { "code": null, "e": 2408, "s": 2340, "text": "Create a function, with a name and associate that name with a type." }, { "code": null, "e": 2427, "s": 2408, "text": "Assign it a value." }, { "code": null, "e": 2467, "s": 2427, "text": "Perform some calculation on that value." }, { "code": null, "e": 2526, "s": 2467, "text": "Pass it as a parameter to another function or sub-routine." }, { "code": null, "e": 2579, "s": 2526, "text": "Return a function as the result of another function." }, { "code": null, "e": 2676, "s": 2579, "text": "Functions are defined by using the let keyword. A function definition has the following syntax −" }, { "code": null, "e": 2756, "s": 2676, "text": "let [inline] function-name parameter-list [ : return-type ]\n = function-body\n" }, { "code": null, "e": 2763, "s": 2756, "text": "Where," }, { "code": null, "e": 2824, "s": 2763, "text": "function-name is an identifier that represents the function." }, { "code": null, "e": 2885, "s": 2824, "text": "function-name is an identifier that represents the function." }, { "code": null, "e": 3097, "s": 2885, "text": "parameter-list gives the list of parameters separated by spaces. You can also specify an explicit type for each parameter and if not specified compiler tends to deduce it from the function body (like variables)." }, { "code": null, "e": 3309, "s": 3097, "text": "parameter-list gives the list of parameters separated by spaces. You can also specify an explicit type for each parameter and if not specified compiler tends to deduce it from the function body (like variables)." }, { "code": null, "e": 3477, "s": 3309, "text": "function-body consists of an expression, or a compound expression consisting of a number of expressions. The final expression in the function body is the return value." }, { "code": null, "e": 3645, "s": 3477, "text": "function-body consists of an expression, or a compound expression consisting of a number of expressions. The final expression in the function body is the return value." }, { "code": null, "e": 3821, "s": 3645, "text": "return-type is a colon followed by a type and is optional. If the return type is not specified, then the compiler determines it from the final expression in the function body." }, { "code": null, "e": 3997, "s": 3821, "text": "return-type is a colon followed by a type and is optional. If the return type is not specified, then the compiler determines it from the final expression in the function body." }, { "code": null, "e": 4190, "s": 3997, "text": "You list the names of parameters right after the function name. You can specify the type of a parameter. The type of the parameter should follow the name of the parameter separated by a colon." }, { "code": null, "e": 4257, "s": 4190, "text": "If no parameter type is specified, it is inferred by the compiler." }, { "code": null, "e": 4271, "s": 4257, "text": "For example −" }, { "code": null, "e": 4303, "s": 4271, "text": "let doubleIt (x : int) = 2 * x\n" }, { "code": null, "e": 4420, "s": 4303, "text": "A function is called by specifying the function name followed by a space and then any arguments separated by spaces." }, { "code": null, "e": 4434, "s": 4420, "text": "For example −" }, { "code": null, "e": 4468, "s": 4434, "text": "let vol = cylinderVolume 3.0 5.0\n" }, { "code": null, "e": 4516, "s": 4468, "text": "The following programs illustrate the concepts." }, { "code": null, "e": 4625, "s": 4516, "text": "The following program calculates the volume of a cylinder when the radius and length are given as parameters" }, { "code": null, "e": 4896, "s": 4625, "text": "// the function calculates the volume of\n// a cylinder with radius and length as parameters\n\nlet cylinderVolume radius length : float =\n\n // function body\n let pi = 3.14159\n length * pi * radius * radius\n\nlet vol = cylinderVolume 3.0 5.0\nprintfn \" Volume: %g \" vol" }, { "code": null, "e": 4971, "s": 4896, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 4988, "s": 4971, "text": "Volume: 141.372\n" }, { "code": null, "e": 5061, "s": 4988, "text": "The following program returns the larger value of two given parameters −" }, { "code": null, "e": 5278, "s": 5061, "text": "// the function returns the larger value between two\n// arguments\n\nlet max num1 num2 : int32 =\n // function body\n if(num1>num2)then\n num1\n else\n num2\n\nlet res = max 39 52\nprintfn \" Max Value: %d \" res" }, { "code": null, "e": 5353, "s": 5278, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 5368, "s": 5353, "text": "Max Value: 52\n" }, { "code": null, "e": 5439, "s": 5368, "text": "let doubleIt (x : int) = 2 * x\nprintfn \"Double 19: %d\" ( doubleIt(19))" }, { "code": null, "e": 5514, "s": 5439, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 5529, "s": 5514, "text": "Double 19: 38\n" }, { "code": null, "e": 5585, "s": 5529, "text": "Recursive functions are functions that call themselves." }, { "code": null, "e": 5647, "s": 5585, "text": "You define a recursive using the let rec keyword combination." }, { "code": null, "e": 5693, "s": 5647, "text": "Syntax for defining a recursive function is −" }, { "code": null, "e": 5789, "s": 5693, "text": "//Recursive function definition\nlet rec function-name parameter-list = recursive-function-body\n" }, { "code": null, "e": 5803, "s": 5789, "text": "For example −" }, { "code": null, "e": 5867, "s": 5803, "text": "let rec fib n = if n < 2 then 1 else fib (n - 1) + fib (n - 2)\n" }, { "code": null, "e": 5917, "s": 5867, "text": "The following program returns Fibonacci 1 to 10 −" }, { "code": null, "e": 6039, "s": 5917, "text": "let rec fib n = if n < 2 then 1 else fib (n - 1) + fib (n - 2)\nfor i = 1 to 10 do\n printfn \"Fibonacci %d: %d\" i (fib i)" }, { "code": null, "e": 6114, "s": 6039, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 6271, "s": 6114, "text": "Fibonacci 1: 1\nFibonacci 2: 2\nFibonacci 3: 3\nFibonacci 4: 5\nFibonacci 5: 8\nFibonacci 6: 13\nFibonacci 7: 21\nFibonacci 8: 34\nFibonacci 9: 55\nFibonacci 10: 89\n" }, { "code": null, "e": 6315, "s": 6271, "text": "The following program returns factorial 8 −" }, { "code": null, "e": 6414, "s": 6315, "text": "open System\nlet rec fact x =\n if x < 1 then 1\n else x * fact (x - 1)\nConsole.WriteLine(fact 8)" }, { "code": null, "e": 6489, "s": 6414, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 6496, "s": 6489, "text": "40320\n" }, { "code": null, "e": 6703, "s": 6496, "text": "F# reports about data type in functions and values, using a chained arrow notation. Let us take an example of a function that takes one int input, and returns a string. In arrow notation, it is written as −" }, { "code": null, "e": 6718, "s": 6703, "text": "int -> string\n" }, { "code": null, "e": 6758, "s": 6718, "text": "Data types are read from left to right." }, { "code": null, "e": 6853, "s": 6758, "text": "Let us take another hypothetical function that takes two int data inputs and returns a string." }, { "code": null, "e": 6899, "s": 6853, "text": "let mydivfunction x y = (x / y).ToString();;\n" }, { "code": null, "e": 6958, "s": 6899, "text": "F# reports the data type using chained arrow notation as −" }, { "code": null, "e": 7004, "s": 6958, "text": "val mydivfunction : x:int -> y:int -> string\n" }, { "code": null, "e": 7089, "s": 7004, "text": "The return type is represented by the rightmost data type in chained arrow notation." }, { "code": null, "e": 7110, "s": 7089, "text": "Some more examples −" }, { "code": null, "e": 7154, "s": 7110, "text": "A lambda expression is an unnamed function." }, { "code": null, "e": 7196, "s": 7154, "text": "Let us take an example of two functions −" }, { "code": null, "e": 7319, "s": 7196, "text": "let applyFunction ( f: int -> int -> int) x y = f x y\nlet mul x y = x * y\nlet res = applyFunction mul 5 7\nprintfn \"%d\" res" }, { "code": null, "e": 7394, "s": 7319, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 7398, "s": 7394, "text": "35\n" }, { "code": null, "e": 7508, "s": 7398, "text": "Now in the above example, if instead of defining the function mul, we could have used lambda expressions as −" }, { "code": null, "e": 7627, "s": 7508, "text": "let applyFunction ( f: int -> int -> int) x y = f x y\nlet res = applyFunction (fun x y -> x * y ) 5 7\nprintfn \"%d\" res" }, { "code": null, "e": 7702, "s": 7627, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 7706, "s": 7702, "text": "35\n" }, { "code": null, "e": 7764, "s": 7706, "text": "In F#, one function can be composed from other functions." }, { "code": null, "e": 7876, "s": 7764, "text": "The following example shows the composition of a function named f, from two functions function1 and function2 −" }, { "code": null, "e": 7988, "s": 7876, "text": "let function1 x = x + 1\nlet function2 x = x * 5\n\nlet f = function1 >> function2\nlet res = f 10\nprintfn \"%d\" res" }, { "code": null, "e": 8063, "s": 7988, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 8067, "s": 8063, "text": "55\n" }, { "code": null, "e": 8208, "s": 8067, "text": "F# also provides a feature called pipelining of functions. Pipelining allows function calls to be chained together as successive operations." }, { "code": null, "e": 8243, "s": 8208, "text": "The following example shows that −" }, { "code": null, "e": 8348, "s": 8243, "text": "let function1 x = x + 1\nlet function2 x = x * 5\n\nlet res = 10 |> function1 |> function2\nprintfn \"%d\" res" }, { "code": null, "e": 8423, "s": 8348, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 8427, "s": 8423, "text": "55\n" }, { "code": null, "e": 8434, "s": 8427, "text": " Print" }, { "code": null, "e": 8445, "s": 8434, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: HTML table - hover rows
[]
Why should you be careful about String concatenation (+) operator in loops using Java?
Strings are used to store a sequence of characters in Java, they are treated as objects. The String class of the java.lang package represents a String. You can create a String either by using the new keyword (like any other object) or, by assigning value to the literal (like any other primitive datatype). Public class Sample{ Public static void main(String args[]){ String str1 = "Hello"; String str2 = "how are you"; } } Strings are immutable in Java i.e. once you create a String literal it cannot be modified. Since all the String values we define are objects of the String class they are stored on the heap area. But, unlike other objects in a separate memory location known as String Constant pool is allotted for the String objects. Whenever you define a String value JVM creates a String object with the given value in the String constant pool. Therefore, if you run the above program two String values are created in the String constant pool. If you try to concatenate these two String values as − str1 = str2 + str2; Since Strings are immutable in java, instead of modifying str1 a new (intermediate) String object is created with the concatenated value and it is assigned to the reference str1. If you concatenate Stings in loops for each iteration a new intermediate object is created in the String constant pool. This is not recommended as it causes memory issues. Therefore, concatenating strings in loops as shown in the following example is not recommended. public class StringExample { public static void main(String args[]) { String stringArray[] = {"Java", "JavaFX", "HBase", "Oracle"}; String singleString = new String(); for (int i=0; i<stringArray.length; i++) { singleString = singleString+stringArray[i]+" "; } System.out.println(singleString); } } Java JavaFX HBase Oracle If you have a scenario to add String values in loops it is recommended to use StringBuilder instead of Strings − public class StringExample { public static void main(String args[]) { String stringArray[] = {"Java", "JavaFX", "HBase", "Oracle"}; StringBuilder singleString = new StringBuilder(); for (int i=0; i<stringArray.length; i++) { singleString.append(stringArray[i]); singleString.append(" "); } System.out.println(singleString); } } Java JavaFX HBase Oracle
[ { "code": null, "e": 1214, "s": 1062, "text": "Strings are used to store a sequence of characters in Java, they are treated as objects. The String class of the java.lang package represents a String." }, { "code": null, "e": 1369, "s": 1214, "text": "You can create a String either by using the new keyword (like any other object) or, by assigning value to the literal (like any other primitive datatype)." }, { "code": null, "e": 1504, "s": 1369, "text": "Public class Sample{\n Public static void main(String args[]){\n String str1 = \"Hello\";\n String str2 = \"how are you\";\n }\n}" }, { "code": null, "e": 1595, "s": 1504, "text": "Strings are immutable in Java i.e. once you create a String literal it cannot be modified." }, { "code": null, "e": 1821, "s": 1595, "text": "Since all the String values we define are objects of the String class they are stored on the heap area. But, unlike other objects in a separate memory location known as String Constant pool is allotted for the String objects." }, { "code": null, "e": 2033, "s": 1821, "text": "Whenever you define a String value JVM creates a String object with the given value in the String constant pool. Therefore, if you run the above program two String values are created in the String constant pool." }, { "code": null, "e": 2088, "s": 2033, "text": "If you try to concatenate these two String values as −" }, { "code": null, "e": 2108, "s": 2088, "text": "str1 = str2 + str2;" }, { "code": null, "e": 2287, "s": 2108, "text": "Since Strings are immutable in java, instead of modifying str1 a new (intermediate) String object is created with the concatenated value and it is assigned to the reference str1." }, { "code": null, "e": 2555, "s": 2287, "text": "If you concatenate Stings in loops for each iteration a new intermediate object is created in the String constant pool. This is not recommended as it causes memory issues. Therefore, concatenating strings in loops as shown in the following example is not recommended." }, { "code": null, "e": 2899, "s": 2555, "text": "public class StringExample {\n public static void main(String args[]) {\n String stringArray[] = {\"Java\", \"JavaFX\", \"HBase\", \"Oracle\"};\n String singleString = new String();\n for (int i=0; i<stringArray.length; i++) {\n singleString = singleString+stringArray[i]+\" \";\n }\n System.out.println(singleString);\n }\n}" }, { "code": null, "e": 2924, "s": 2899, "text": "Java JavaFX HBase Oracle" }, { "code": null, "e": 3037, "s": 2924, "text": "If you have a scenario to add String values in loops it is recommended to use StringBuilder instead of Strings −" }, { "code": null, "e": 3419, "s": 3037, "text": "public class StringExample {\n public static void main(String args[]) {\n String stringArray[] = {\"Java\", \"JavaFX\", \"HBase\", \"Oracle\"};\n StringBuilder singleString = new StringBuilder();\n for (int i=0; i<stringArray.length; i++) {\n singleString.append(stringArray[i]);\n singleString.append(\" \");\n }\n System.out.println(singleString);\n }\n}" }, { "code": null, "e": 3444, "s": 3419, "text": "Java JavaFX HBase Oracle" } ]
Find the amplitude and number of waves for the given array
24 Feb, 2022 Given an array arr[] of N integers, the task is to find the amplitude and number of waves for the given array. If the array is not a wave array then print -1. Wave Array: An array is a wave array if it is continuously strictly increasing and decreasing or vice-versa. Amplitude is defined as the maximum difference of consecutive numbers. Examples: Input: arr[] = {1, 2, 1, 5, 0, 7, -6} Output: Amplitude = 13, Waves = 3 Explanation: For the array observe the pattern 1->2 (increase), 2->1 (decrease), 1->5 (increase), 5->0 (decrease), 0->7 (increase), 7->-6 (decrease). Amplitude = 13 (between 7 and -6) and total waves = 3Input: arr[] = {1, 2, 1, 5, 0, 7, 7} Output: -1 Explanation: The array is not waved array as the last two elements of the array are equal, hence the answer is -1. Approach: The idea is to check for both sides adjacent elements where both must be either less or greater than the current element. If this condition is satisfied then count the number of waves otherwise print -1, where the number of waves is (n – 1) / 2. While traversing the array keep updating the maximum difference between the consecutive element to get the amplitude of the given wave array. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the amplitude and// number of waves for the given arraybool check(int a[], int n){ int ma = a[1] - a[0]; // Check for both sides adjacent // elements that both must be less // or both must be greater // than current element for (int i = 1; i < n - 1; i++) { if ((a[i] > a[i - 1] && a[i + 1] < a[i]) || (a[i] < a[i - 1] && a[i + 1] > a[i])) // Update amplitude with max value ma = max(ma, abs(a[i] - a[i + 1])); else return false; } // Print the Amplitude cout << "Amplitude = " << ma; cout << endl; return true;} // Driver Codeint main(){ // Given array a[] int a[] = { 1, 2, 1, 5, 0, 7, -6 }; int n = sizeof a / sizeof a[0]; // Calculate number of waves int wave = (n - 1) / 2; // Function Call if (check(a, n)) cout << "Waves = " << wave; else cout << "-1"; return 0;} // Java program for the above approachimport java.util.*;class GFG{ // Function to find the amplitude and// number of waves for the given arraystatic boolean check(int a[], int n){ int ma = a[1] - a[0]; // Check for both sides adjacent // elements that both must be less // or both must be greater // than current element for (int i = 1; i < n - 1; i++) { if ((a[i] > a[i - 1] && a[i + 1] < a[i]) || (a[i] < a[i - 1] && a[i + 1] > a[i])) // Update amplitude with max value ma = Math.max(ma, Math.abs(a[i] - a[i + 1])); else return false; } // Print the Amplitude System.out.print("Amplitude = " + ma); System.out.println(); return true;} // Driver Codepublic static void main(String[] args){ // Given array a[] int a[] = { 1, 2, 1, 5, 0, 7, -6 }; int n = a.length; // Calculate number of waves int wave = (n - 1) / 2; // Function Call if (check(a, n)) System.out.print("Waves = " + wave); else System.out.print("-1");}} // This code is contributed by sapnasingh4991 # Python3 program for the above approach # Function to find the amplitude and# number of waves for the given arraydef check(a, n): ma = a[1] - a[0] # Check for both sides adjacent # elements that both must be less # or both must be greater # than current element for i in range(1, n - 1): if ((a[i] > a[i - 1] and a[i + 1] < a[i]) or (a[i] < a[i - 1] and a[i + 1] > a[i])): # Update amplitude with max value ma = max(ma, abs(a[i] - a[i + 1])) else: return False # Print the Amplitude print("Amplitude = ", ma) return True # Driver Codeif __name__ == '__main__': # Given array a[] a = [1, 2, 1, 5, 0, 7, -6] n = len(a) # Calculate number of waves wave = (n - 1) // 2 # Function Call if (check(a, n)): print("Waves = ",wave) else: print("-1") # This code is contributed by Mohit Kumar // C# program for the above approachusing System;class GFG{ // Function to find the amplitude and// number of waves for the given arraystatic bool check(int []a, int n){ int ma = a[1] - a[0]; // Check for both sides adjacent // elements that both must be less // or both must be greater // than current element for (int i = 1; i < n - 1; i++) { if ((a[i] > a[i - 1] && a[i + 1] < a[i]) || (a[i] < a[i - 1] && a[i + 1] > a[i])) // Update amplitude with max value ma = Math.Max(ma, Math.Abs(a[i] - a[i + 1])); else return false; } // Print the Amplitude Console.Write("Amplitude = " + ma); Console.WriteLine(); return true;} // Driver Codepublic static void Main(String[] args){ // Given array []a int []a = { 1, 2, 1, 5, 0, 7, -6 }; int n = a.Length; // Calculate number of waves int wave = (n - 1) / 2; // Function Call if (check(a, n)) Console.Write("Waves = " + wave); else Console.Write("-1");}} // This code is contributed by sapnasingh4991 <script>// JavaScript program for the above approach // Function to find the amplitude and// number of waves for the given arrayfunction check(a, n){ let ma = a[1] - a[0]; // Check for both sides adjacent // elements that both must be less // or both must be greater // than current element for (let i = 1; i < n - 1; i++) { if ((a[i] > a[i - 1] && a[i + 1] < a[i]) || (a[i] < a[i - 1] && a[i + 1] > a[i])) // Update amplitude with max value ma = Math.max(ma, Math.abs(a[i] - a[i + 1])); else return false; } // Print the Amplitude document.write("Amplitude = " + ma); document.write("<br/>"); return true;} // Driver Code // Given array a[] let a = [ 1, 2, 1, 5, 0, 7, -6 ]; let n = a.length; // Calculate number of waves let wave = (n - 1) / 2; // Function Call if (check(a, n)) document.write("Waves = " + wave); else document.write("-1"); </script> Amplitude = 13 Waves = 3 Time Complexity: O(N) Auxiliary Space: O(1) mohit kumar 29 sapnasingh4991 code_hunt adnanirshad158 simranarora5sos Arrays Greedy Mathematical Arrays Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Feb, 2022" }, { "code": null, "e": 187, "s": 28, "text": "Given an array arr[] of N integers, the task is to find the amplitude and number of waves for the given array. If the array is not a wave array then print -1." }, { "code": null, "e": 369, "s": 187, "text": "Wave Array: An array is a wave array if it is continuously strictly increasing and decreasing or vice-versa. Amplitude is defined as the maximum difference of consecutive numbers. " }, { "code": null, "e": 380, "s": 369, "text": "Examples: " }, { "code": null, "e": 820, "s": 380, "text": "Input: arr[] = {1, 2, 1, 5, 0, 7, -6} Output: Amplitude = 13, Waves = 3 Explanation: For the array observe the pattern 1->2 (increase), 2->1 (decrease), 1->5 (increase), 5->0 (decrease), 0->7 (increase), 7->-6 (decrease). Amplitude = 13 (between 7 and -6) and total waves = 3Input: arr[] = {1, 2, 1, 5, 0, 7, 7} Output: -1 Explanation: The array is not waved array as the last two elements of the array are equal, hence the answer is -1. " }, { "code": null, "e": 1220, "s": 820, "text": "Approach: The idea is to check for both sides adjacent elements where both must be either less or greater than the current element. If this condition is satisfied then count the number of waves otherwise print -1, where the number of waves is (n – 1) / 2. While traversing the array keep updating the maximum difference between the consecutive element to get the amplitude of the given wave array. " }, { "code": null, "e": 1272, "s": 1220, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1276, "s": 1272, "text": "C++" }, { "code": null, "e": 1281, "s": 1276, "text": "Java" }, { "code": null, "e": 1289, "s": 1281, "text": "Python3" }, { "code": null, "e": 1292, "s": 1289, "text": "C#" }, { "code": null, "e": 1303, "s": 1292, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the amplitude and// number of waves for the given arraybool check(int a[], int n){ int ma = a[1] - a[0]; // Check for both sides adjacent // elements that both must be less // or both must be greater // than current element for (int i = 1; i < n - 1; i++) { if ((a[i] > a[i - 1] && a[i + 1] < a[i]) || (a[i] < a[i - 1] && a[i + 1] > a[i])) // Update amplitude with max value ma = max(ma, abs(a[i] - a[i + 1])); else return false; } // Print the Amplitude cout << \"Amplitude = \" << ma; cout << endl; return true;} // Driver Codeint main(){ // Given array a[] int a[] = { 1, 2, 1, 5, 0, 7, -6 }; int n = sizeof a / sizeof a[0]; // Calculate number of waves int wave = (n - 1) / 2; // Function Call if (check(a, n)) cout << \"Waves = \" << wave; else cout << \"-1\"; return 0;}", "e": 2343, "s": 1303, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find the amplitude and// number of waves for the given arraystatic boolean check(int a[], int n){ int ma = a[1] - a[0]; // Check for both sides adjacent // elements that both must be less // or both must be greater // than current element for (int i = 1; i < n - 1; i++) { if ((a[i] > a[i - 1] && a[i + 1] < a[i]) || (a[i] < a[i - 1] && a[i + 1] > a[i])) // Update amplitude with max value ma = Math.max(ma, Math.abs(a[i] - a[i + 1])); else return false; } // Print the Amplitude System.out.print(\"Amplitude = \" + ma); System.out.println(); return true;} // Driver Codepublic static void main(String[] args){ // Given array a[] int a[] = { 1, 2, 1, 5, 0, 7, -6 }; int n = a.length; // Calculate number of waves int wave = (n - 1) / 2; // Function Call if (check(a, n)) System.out.print(\"Waves = \" + wave); else System.out.print(\"-1\");}} // This code is contributed by sapnasingh4991", "e": 3473, "s": 2343, "text": null }, { "code": "# Python3 program for the above approach # Function to find the amplitude and# number of waves for the given arraydef check(a, n): ma = a[1] - a[0] # Check for both sides adjacent # elements that both must be less # or both must be greater # than current element for i in range(1, n - 1): if ((a[i] > a[i - 1] and a[i + 1] < a[i]) or (a[i] < a[i - 1] and a[i + 1] > a[i])): # Update amplitude with max value ma = max(ma, abs(a[i] - a[i + 1])) else: return False # Print the Amplitude print(\"Amplitude = \", ma) return True # Driver Codeif __name__ == '__main__': # Given array a[] a = [1, 2, 1, 5, 0, 7, -6] n = len(a) # Calculate number of waves wave = (n - 1) // 2 # Function Call if (check(a, n)): print(\"Waves = \",wave) else: print(\"-1\") # This code is contributed by Mohit Kumar", "e": 4415, "s": 3473, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to find the amplitude and// number of waves for the given arraystatic bool check(int []a, int n){ int ma = a[1] - a[0]; // Check for both sides adjacent // elements that both must be less // or both must be greater // than current element for (int i = 1; i < n - 1; i++) { if ((a[i] > a[i - 1] && a[i + 1] < a[i]) || (a[i] < a[i - 1] && a[i + 1] > a[i])) // Update amplitude with max value ma = Math.Max(ma, Math.Abs(a[i] - a[i + 1])); else return false; } // Print the Amplitude Console.Write(\"Amplitude = \" + ma); Console.WriteLine(); return true;} // Driver Codepublic static void Main(String[] args){ // Given array []a int []a = { 1, 2, 1, 5, 0, 7, -6 }; int n = a.Length; // Calculate number of waves int wave = (n - 1) / 2; // Function Call if (check(a, n)) Console.Write(\"Waves = \" + wave); else Console.Write(\"-1\");}} // This code is contributed by sapnasingh4991", "e": 5521, "s": 4415, "text": null }, { "code": "<script>// JavaScript program for the above approach // Function to find the amplitude and// number of waves for the given arrayfunction check(a, n){ let ma = a[1] - a[0]; // Check for both sides adjacent // elements that both must be less // or both must be greater // than current element for (let i = 1; i < n - 1; i++) { if ((a[i] > a[i - 1] && a[i + 1] < a[i]) || (a[i] < a[i - 1] && a[i + 1] > a[i])) // Update amplitude with max value ma = Math.max(ma, Math.abs(a[i] - a[i + 1])); else return false; } // Print the Amplitude document.write(\"Amplitude = \" + ma); document.write(\"<br/>\"); return true;} // Driver Code // Given array a[] let a = [ 1, 2, 1, 5, 0, 7, -6 ]; let n = a.length; // Calculate number of waves let wave = (n - 1) / 2; // Function Call if (check(a, n)) document.write(\"Waves = \" + wave); else document.write(\"-1\"); </script>", "e": 6578, "s": 5521, "text": null }, { "code": null, "e": 6603, "s": 6578, "text": "Amplitude = 13\nWaves = 3" }, { "code": null, "e": 6650, "s": 6605, "text": "Time Complexity: O(N) Auxiliary Space: O(1) " }, { "code": null, "e": 6665, "s": 6650, "text": "mohit kumar 29" }, { "code": null, "e": 6680, "s": 6665, "text": "sapnasingh4991" }, { "code": null, "e": 6690, "s": 6680, "text": "code_hunt" }, { "code": null, "e": 6705, "s": 6690, "text": "adnanirshad158" }, { "code": null, "e": 6721, "s": 6705, "text": "simranarora5sos" }, { "code": null, "e": 6728, "s": 6721, "text": "Arrays" }, { "code": null, "e": 6735, "s": 6728, "text": "Greedy" }, { "code": null, "e": 6748, "s": 6735, "text": "Mathematical" }, { "code": null, "e": 6755, "s": 6748, "text": "Arrays" }, { "code": null, "e": 6762, "s": 6755, "text": "Greedy" }, { "code": null, "e": 6775, "s": 6762, "text": "Mathematical" } ]
Prototype Method – Python Design Patterns
12 Sep, 2021 Prototype Method is a Creational Design Pattern which aims to reduce the number of classes used for an application. It allows you to copy existing objects independent of the concrete implementation of their classes. Generally, here the object is created by copying a prototypical instance during run-time. It is highly recommended to use Prototype Method when the object creation is an expensive task in terms of time and usage of resources and already there exists a similar object. This method provides a way to copy the original object and then modify it according to our needs. Suppose we have a Shape class that produces different shapes such as circle, rectangle, square, etc and we already have an object of it. Now we want to create the exact copy of this object. How an ordinary developer will go? He/She will create a new object of the same class and will apply all the functionalities of the original objects and copy their values. But we can not copy each and every field of the original object as some may be private and protected and are not available from the outside of the object itself. Problems are not over here! you also become dependent on the code of other class which is certainly not a good practice in Software Development. For better understanding, let’s understand the example of Courses At GeeksforGeeks that provides courses like SDE, DSA, STL, etc. Creating objects for similar courses, again and again, is not a good task to utilize the resources in a better way. problem-builder-Method Note: Following code is written without using Prototype Method Python3 # concrete courseclass DSA(): """Class for Data Structures and Algorithms""" def Type(self): return "Data Structures and Algorithms" def __str__(self): return "DSA" # concrete courseclass SDE(): """Class for Software development Engineer""" def Type(self): return "Software Development Engineer" def __str__(self): return "SDE" # concrete courseclass STL(): """class for Standard Template Library of C++""" def Type(self): return "Standard Template Library" def __str__(self): return "STL" # main methodif __name__ == "__main__": sde = SDE() # object for SDE dsa = DSA() # object for DSA stl = STL() # object for STL print(f'Name of Course: {sde} and its type: {sde.Type()}') print(f'Name of Course: {stl} and its type: {stl.Type()}') print(f'Name of Course: {dsa} and its type: {dsa.Type()}') To deal with such problems, we use the Prototype method. We would create separate classes for Courses_At_GFG and Course_At_GFG_Cache which will help us in creating the exact copy of already existing object with the same field properties. This method delegates the cloning process to the actual objects that are being cloned. Here we declare a common interface or class which supports object cloning which allows us to clone the object without coupling our code to the class of that method. An object that supports cloning is called as Prototype. Python3 # import the required modules from abc import ABCMeta, abstractmethodimport copy # class - Courses at GeeksforGeeksclass Courses_At_GFG(metaclass = ABCMeta): # constructor def __init__(self): self.id = None self.type = None @abstractmethod def course(self): pass def get_type(self): return self.type def get_id(self): return self.id def set_id(self, sid): self.id = sid def clone(self): return copy.copy(self) # class - DSA courseclass DSA(Courses_At_GFG): def __init__(self): super().__init__() self.type = "Data Structures and Algorithms" def course(self): print("Inside DSA::course() method") # class - SDE Courseclass SDE(Courses_At_GFG): def __init__(self): super().__init__() self.type = "Software Development Engineer" def course(self): print("Inside SDE::course() method.") # class - STL Courseclass STL(Courses_At_GFG): def __init__(self): super().__init__() self.type = "Standard Template Library" def course(self): print("Inside STL::course() method.") # class - Courses At GeeksforGeeks Cacheclass Courses_At_GFG_Cache: # cache to store useful information cache = {} @staticmethod def get_course(sid): COURSE = Courses_At_GFG_Cache.cache.get(sid, None) return COURSE.clone() @staticmethod def load(): sde = SDE() sde.set_id("1") Courses_At_GFG_Cache.cache[sde.get_id()] = sde dsa = DSA() dsa.set_id("2") Courses_At_GFG_Cache.cache[dsa.get_id()] = dsa stl = STL() stl.set_id("3") Courses_At_GFG_Cache.cache[stl.get_id()] = stl # main functionif __name__ == '__main__': Courses_At_GFG_Cache.load() sde = Courses_At_GFG_Cache.get_course("1") print(sde.get_type()) dsa = Courses_At_GFG_Cache.get_course("2") print(dsa.get_type()) stl = Courses_At_GFG_Cache.get_course("3") print(stl.get_type()) Prototype-Method – UML-Diagram Less number of SubClasses : All the other Creational Design Patterns provides a lot of new subClasses which are definitely not easy to handle when we are working on a large project. But using Prototype Design Pattern, we get rid of this.Provides varying values to new objects: All the highly dynamic systems allows you to define new behavior through object composition by specifying values for an object’s variables and not by defining new classes.Provides varying structure to new objects: Generally all the applications build objects from parts and subparts. For convenience, such applications often allows you instantiate complex, user-defined structures to use a specific subcircuit again and again. Less number of SubClasses : All the other Creational Design Patterns provides a lot of new subClasses which are definitely not easy to handle when we are working on a large project. But using Prototype Design Pattern, we get rid of this. Provides varying values to new objects: All the highly dynamic systems allows you to define new behavior through object composition by specifying values for an object’s variables and not by defining new classes. Provides varying structure to new objects: Generally all the applications build objects from parts and subparts. For convenience, such applications often allows you instantiate complex, user-defined structures to use a specific subcircuit again and again. Abstraction: It helps in achieving the abstraction by hiding the concrete implementation details of the class.Waste of resources at lower level: It might be proved as the overkill of resources for a project that uses very few objects Abstraction: It helps in achieving the abstraction by hiding the concrete implementation details of the class. Waste of resources at lower level: It might be proved as the overkill of resources for a project that uses very few objects Independency from Concrete Class: Prototype method provides the way to implement the new objects without depending upon the concrete implementation of the class.Recurring problems : Prototype method is also used to solve the recurring and complex problems of the software development. Independency from Concrete Class: Prototype method provides the way to implement the new objects without depending upon the concrete implementation of the class. Recurring problems : Prototype method is also used to solve the recurring and complex problems of the software development. Further Read – Prototype Design Pattern in Java simmytarika5 surindertarika1234 python-design-pattern Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Enumerate() in Python Rotate axis tick labels in Seaborn and Matplotlib Python Dictionary Deque in Python Stack in Python Queue in Python Different ways to create Pandas Dataframe sum() function in Python Check if element exists in list in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Sep, 2021" }, { "code": null, "e": 636, "s": 54, "text": "Prototype Method is a Creational Design Pattern which aims to reduce the number of classes used for an application. It allows you to copy existing objects independent of the concrete implementation of their classes. Generally, here the object is created by copying a prototypical instance during run-time. It is highly recommended to use Prototype Method when the object creation is an expensive task in terms of time and usage of resources and already there exists a similar object. This method provides a way to copy the original object and then modify it according to our needs." }, { "code": null, "e": 1304, "s": 636, "text": "Suppose we have a Shape class that produces different shapes such as circle, rectangle, square, etc and we already have an object of it. Now we want to create the exact copy of this object. How an ordinary developer will go? He/She will create a new object of the same class and will apply all the functionalities of the original objects and copy their values. But we can not copy each and every field of the original object as some may be private and protected and are not available from the outside of the object itself. Problems are not over here! you also become dependent on the code of other class which is certainly not a good practice in Software Development." }, { "code": null, "e": 1551, "s": 1304, "text": "For better understanding, let’s understand the example of Courses At GeeksforGeeks that provides courses like SDE, DSA, STL, etc. Creating objects for similar courses, again and again, is not a good task to utilize the resources in a better way. " }, { "code": null, "e": 1574, "s": 1551, "text": "problem-builder-Method" }, { "code": null, "e": 1637, "s": 1574, "text": "Note: Following code is written without using Prototype Method" }, { "code": null, "e": 1645, "s": 1637, "text": "Python3" }, { "code": "# concrete courseclass DSA(): \"\"\"Class for Data Structures and Algorithms\"\"\" def Type(self): return \"Data Structures and Algorithms\" def __str__(self): return \"DSA\" # concrete courseclass SDE(): \"\"\"Class for Software development Engineer\"\"\" def Type(self): return \"Software Development Engineer\" def __str__(self): return \"SDE\" # concrete courseclass STL(): \"\"\"class for Standard Template Library of C++\"\"\" def Type(self): return \"Standard Template Library\" def __str__(self): return \"STL\" # main methodif __name__ == \"__main__\": sde = SDE() # object for SDE dsa = DSA() # object for DSA stl = STL() # object for STL print(f'Name of Course: {sde} and its type: {sde.Type()}') print(f'Name of Course: {stl} and its type: {stl.Type()}') print(f'Name of Course: {dsa} and its type: {dsa.Type()}')", "e": 2539, "s": 1645, "text": null }, { "code": null, "e": 3086, "s": 2539, "text": "To deal with such problems, we use the Prototype method. We would create separate classes for Courses_At_GFG and Course_At_GFG_Cache which will help us in creating the exact copy of already existing object with the same field properties. This method delegates the cloning process to the actual objects that are being cloned. Here we declare a common interface or class which supports object cloning which allows us to clone the object without coupling our code to the class of that method. An object that supports cloning is called as Prototype. " }, { "code": null, "e": 3094, "s": 3086, "text": "Python3" }, { "code": "# import the required modules from abc import ABCMeta, abstractmethodimport copy # class - Courses at GeeksforGeeksclass Courses_At_GFG(metaclass = ABCMeta): # constructor def __init__(self): self.id = None self.type = None @abstractmethod def course(self): pass def get_type(self): return self.type def get_id(self): return self.id def set_id(self, sid): self.id = sid def clone(self): return copy.copy(self) # class - DSA courseclass DSA(Courses_At_GFG): def __init__(self): super().__init__() self.type = \"Data Structures and Algorithms\" def course(self): print(\"Inside DSA::course() method\") # class - SDE Courseclass SDE(Courses_At_GFG): def __init__(self): super().__init__() self.type = \"Software Development Engineer\" def course(self): print(\"Inside SDE::course() method.\") # class - STL Courseclass STL(Courses_At_GFG): def __init__(self): super().__init__() self.type = \"Standard Template Library\" def course(self): print(\"Inside STL::course() method.\") # class - Courses At GeeksforGeeks Cacheclass Courses_At_GFG_Cache: # cache to store useful information cache = {} @staticmethod def get_course(sid): COURSE = Courses_At_GFG_Cache.cache.get(sid, None) return COURSE.clone() @staticmethod def load(): sde = SDE() sde.set_id(\"1\") Courses_At_GFG_Cache.cache[sde.get_id()] = sde dsa = DSA() dsa.set_id(\"2\") Courses_At_GFG_Cache.cache[dsa.get_id()] = dsa stl = STL() stl.set_id(\"3\") Courses_At_GFG_Cache.cache[stl.get_id()] = stl # main functionif __name__ == '__main__': Courses_At_GFG_Cache.load() sde = Courses_At_GFG_Cache.get_course(\"1\") print(sde.get_type()) dsa = Courses_At_GFG_Cache.get_course(\"2\") print(dsa.get_type()) stl = Courses_At_GFG_Cache.get_course(\"3\") print(stl.get_type())", "e": 5093, "s": 3094, "text": null }, { "code": null, "e": 5124, "s": 5093, "text": "Prototype-Method – UML-Diagram" }, { "code": null, "e": 5828, "s": 5124, "text": "Less number of SubClasses : All the other Creational Design Patterns provides a lot of new subClasses which are definitely not easy to handle when we are working on a large project. But using Prototype Design Pattern, we get rid of this.Provides varying values to new objects: All the highly dynamic systems allows you to define new behavior through object composition by specifying values for an object’s variables and not by defining new classes.Provides varying structure to new objects: Generally all the applications build objects from parts and subparts. For convenience, such applications often allows you instantiate complex, user-defined structures to use a specific subcircuit again and again." }, { "code": null, "e": 6066, "s": 5828, "text": "Less number of SubClasses : All the other Creational Design Patterns provides a lot of new subClasses which are definitely not easy to handle when we are working on a large project. But using Prototype Design Pattern, we get rid of this." }, { "code": null, "e": 6278, "s": 6066, "text": "Provides varying values to new objects: All the highly dynamic systems allows you to define new behavior through object composition by specifying values for an object’s variables and not by defining new classes." }, { "code": null, "e": 6534, "s": 6278, "text": "Provides varying structure to new objects: Generally all the applications build objects from parts and subparts. For convenience, such applications often allows you instantiate complex, user-defined structures to use a specific subcircuit again and again." }, { "code": null, "e": 6768, "s": 6534, "text": "Abstraction: It helps in achieving the abstraction by hiding the concrete implementation details of the class.Waste of resources at lower level: It might be proved as the overkill of resources for a project that uses very few objects" }, { "code": null, "e": 6879, "s": 6768, "text": "Abstraction: It helps in achieving the abstraction by hiding the concrete implementation details of the class." }, { "code": null, "e": 7003, "s": 6879, "text": "Waste of resources at lower level: It might be proved as the overkill of resources for a project that uses very few objects" }, { "code": null, "e": 7288, "s": 7003, "text": "Independency from Concrete Class: Prototype method provides the way to implement the new objects without depending upon the concrete implementation of the class.Recurring problems : Prototype method is also used to solve the recurring and complex problems of the software development." }, { "code": null, "e": 7450, "s": 7288, "text": "Independency from Concrete Class: Prototype method provides the way to implement the new objects without depending upon the concrete implementation of the class." }, { "code": null, "e": 7574, "s": 7450, "text": "Recurring problems : Prototype method is also used to solve the recurring and complex problems of the software development." }, { "code": null, "e": 7623, "s": 7574, "text": "Further Read – Prototype Design Pattern in Java " }, { "code": null, "e": 7636, "s": 7623, "text": "simmytarika5" }, { "code": null, "e": 7655, "s": 7636, "text": "surindertarika1234" }, { "code": null, "e": 7677, "s": 7655, "text": "python-design-pattern" }, { "code": null, "e": 7684, "s": 7677, "text": "Python" }, { "code": null, "e": 7782, "s": 7684, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7827, "s": 7782, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 7849, "s": 7827, "text": "Enumerate() in Python" }, { "code": null, "e": 7899, "s": 7849, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 7917, "s": 7899, "text": "Python Dictionary" }, { "code": null, "e": 7933, "s": 7917, "text": "Deque in Python" }, { "code": null, "e": 7949, "s": 7933, "text": "Stack in Python" }, { "code": null, "e": 7965, "s": 7949, "text": "Queue in Python" }, { "code": null, "e": 8007, "s": 7965, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 8032, "s": 8007, "text": "sum() function in Python" } ]
Shell Script to Check Hard Disk Revolutions Per Minute (RPM) Speed
30 Jun, 2021 RPM is an acronym for Revolution Per Minute. RPM is the number of revolutions a hard disk makes in a single minute. Normally, the higher the RPM of a disk the better it is, however with higher RPM comes higher cost. Below is a shell script to check the RPM of a hard disk. hdparm is an acronym for hard disk parameter. hdparm is a command-line utility widely used for performing analysis on the disks that a user system has. It can help us to get statistics about the hard disk, modify writing intervals, and DMA settings. It is used to display and alter the SATA/IDE device parameters. Syntax: hdparm [option] [device] Here, in our case, our hard disk is at “/dev/sda”. It is just the Linux/Unix way of naming disks just like Windows has C: D: drives. Similarly, in Linux, we have sda, sdc,sdb, etc and /dev is the directory for where these drives are. To list all the disks that you have in your system, run the following command: sudo lsblk Output: Marked HDD Here, marked one is my hard disk drive, and you can see the name of the drive is assigned as sda. Script: #!/bin/sh # shell script to find the RPM speed of a Hard disk # storing hard disk name into variable disk disk="/dev/sda" # finding the Rotation speed of the hard disk # fetching the integer value # i.e. the speed of the hard disk # and saving it into another variable output=$(sudo hdparm -I $disk | grep Rotation | grep --only-matching --extended-regexp '[0-9]+' ) # Displaying the RPM speed of the hard disk echo "The RPM speed of the Hard disk is: $output rpm" Note: You have to enter your password after running this script. And ‘-I’ flag in the hdparm means that we are fetching information from the disk live and in this statement “grep –only-matching –extended-regexp ‘[0-9]+'”, “–only-matching” will fetch the rotation speed with the extra string output with it by using “–only-matching” with “–extended-regexp” with the pattern “[0-9]+” we are ensuring only the numerical value to display i.e. the rpm speed, “[0-9]+” will fetch any numerical value in the pattern it will match for any integer value from 0-9 and the “+” symbol shows that it can match any number of occurrences more than 1. Speed of the Hard disk Linux-Shell-Commands Picked Shell Script Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 nohup Command in Linux with Examples Introduction to Linux Operating System Array Basics in Shell Scripting | Set 1 chmod command in Linux with examples mv command in Linux with examples Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2021" }, { "code": null, "e": 301, "s": 28, "text": "RPM is an acronym for Revolution Per Minute. RPM is the number of revolutions a hard disk makes in a single minute. Normally, the higher the RPM of a disk the better it is, however with higher RPM comes higher cost. Below is a shell script to check the RPM of a hard disk." }, { "code": null, "e": 615, "s": 301, "text": "hdparm is an acronym for hard disk parameter. hdparm is a command-line utility widely used for performing analysis on the disks that a user system has. It can help us to get statistics about the hard disk, modify writing intervals, and DMA settings. It is used to display and alter the SATA/IDE device parameters." }, { "code": null, "e": 624, "s": 615, "text": "Syntax: " }, { "code": null, "e": 649, "s": 624, "text": "hdparm [option] [device]" }, { "code": null, "e": 884, "s": 649, "text": "Here, in our case, our hard disk is at “/dev/sda”. It is just the Linux/Unix way of naming disks just like Windows has C: D: drives. Similarly, in Linux, we have sda, sdc,sdb, etc and /dev is the directory for where these drives are." }, { "code": null, "e": 963, "s": 884, "text": "To list all the disks that you have in your system, run the following command:" }, { "code": null, "e": 974, "s": 963, "text": "sudo lsblk" }, { "code": null, "e": 982, "s": 974, "text": "Output:" }, { "code": null, "e": 993, "s": 982, "text": "Marked HDD" }, { "code": null, "e": 1091, "s": 993, "text": "Here, marked one is my hard disk drive, and you can see the name of the drive is assigned as sda." }, { "code": null, "e": 1099, "s": 1091, "text": "Script:" }, { "code": null, "e": 1571, "s": 1099, "text": "#!/bin/sh\n\n# shell script to find the RPM speed of a Hard disk\n\n# storing hard disk name into variable disk\ndisk=\"/dev/sda\"\n\n# finding the Rotation speed of the hard disk \n# fetching the integer value \n# i.e. the speed of the hard disk \n# and saving it into another variable\noutput=$(sudo hdparm -I $disk | grep Rotation | grep --only-matching --extended-regexp '[0-9]+' )\n\n# Displaying the RPM speed of the hard disk\necho \"The RPM speed of the Hard disk is: $output rpm\"" }, { "code": null, "e": 2208, "s": 1571, "text": "Note: You have to enter your password after running this script. And ‘-I’ flag in the hdparm means that we are fetching information from the disk live and in this statement “grep –only-matching –extended-regexp ‘[0-9]+'”, “–only-matching” will fetch the rotation speed with the extra string output with it by using “–only-matching” with “–extended-regexp” with the pattern “[0-9]+” we are ensuring only the numerical value to display i.e. the rpm speed, “[0-9]+” will fetch any numerical value in the pattern it will match for any integer value from 0-9 and the “+” symbol shows that it can match any number of occurrences more than 1." }, { "code": null, "e": 2231, "s": 2208, "text": "Speed of the Hard disk" }, { "code": null, "e": 2252, "s": 2231, "text": "Linux-Shell-Commands" }, { "code": null, "e": 2259, "s": 2252, "text": "Picked" }, { "code": null, "e": 2272, "s": 2259, "text": "Shell Script" }, { "code": null, "e": 2283, "s": 2272, "text": "Linux-Unix" }, { "code": null, "e": 2381, "s": 2283, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2407, "s": 2381, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2442, "s": 2407, "text": "scp command in Linux with Examples" }, { "code": null, "e": 2479, "s": 2442, "text": "chown command in Linux with Examples" }, { "code": null, "e": 2508, "s": 2479, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 2545, "s": 2508, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 2584, "s": 2545, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 2624, "s": 2584, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 2661, "s": 2624, "text": "chmod command in Linux with examples" }, { "code": null, "e": 2695, "s": 2661, "text": "mv command in Linux with examples" } ]
Self Dual functions in Digital Logic
07 Apr, 2022 A function is said to be Self dual if and only if its dual is equivalent to the given function, i.e., if a given function is f(X, Y, Z) = (XY + YZ + ZX) then its dual is, fd(X, Y, Z) = (X + Y).(Y + Z).(Z + X) (fd = dual of the given function) = (XY + YZ + ZX), it is equivalent to the given function. So function is self dual. In a dual function: AND operator of a given function is changed to OR operator and vice-versa.A constant 1 (or true) of a given function is changed to a constant 0 (or false) and vice-versa. AND operator of a given function is changed to OR operator and vice-versa. A constant 1 (or true) of a given function is changed to a constant 0 (or false) and vice-versa. A Switching function or Boolean function is said to be Self-dual if: The given function is neutral i.e., (the number of minterms is equal to the number of max terms). For more about minterm and max term (see Canonical and Standard Form).The function does not contain two mutually exclusive terms. The given function is neutral i.e., (the number of minterms is equal to the number of max terms). For more about minterm and max term (see Canonical and Standard Form). The function does not contain two mutually exclusive terms. Note: Mutually exclusive term of XYZ is (X’Y’Z’) i.e, the complement of XYZ. So, two mutually exclusive terms are the complement each other. Example: In the above table, Mutually exclusive terms are: (0,7), (1,6), (2,5), (3,4) Explanation: Complement of (000) i.e, 0 is (111) i.e, 7 so, (0, 7 are mutually exclusive to each other.) Complement of (001) i.e, 1 is (110) i.e, 6 so, (1, 6 are mutually exclusive to each other.) Complement of (010) i.e, 2 is (101) i.e, 5 so, (2, 5 are mutually exclusive to each other.) Complement of (011) i.e, 3 is (100) i.e, 4 so, (3, 4 are mutually exclusive to each other.) Now, let us check the number of Self-dual functions possible for a given function. Let, a function has n variables then, Number of pairs possible = 2n/2 = 2(n-1) Therefore, the number of Self-dual functions is possible with n variables = 22^(n-1) There are 2 possibilities for each pair. Example: What is the total number of self-duals of a function which has 3 variables X, Y, and Z? = 22^(3-1) = 22^2 = 24 = 16 Note: Every Self-dual function is neutral but every neutral function is not Self-dual.Self-duality is closed under complement i.e, the complement of a Self-dual function is also Self-dual. Every Self-dual function is neutral but every neutral function is not Self-dual. Self-duality is closed under complement i.e, the complement of a Self-dual function is also Self-dual. sooda367 vikaskonaparthi Digital Electronics & Logic Design Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to memory and memory units Analog to Digital Conversion Latches in Digital Logic Digital to Analog Conversion Introduction of Sequential Circuits Relationship between number of nodes and height of binary tree Inequalities in LaTeX Difference between Propositional Logic and Predicate Logic Mathematics | Introduction to Propositional Logic | Set 1 Arrow Symbols in LaTeX
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Apr, 2022" }, { "code": null, "e": 381, "s": 53, "text": "A function is said to be Self dual if and only if its dual is equivalent to the given function, i.e., if a given function is f(X, Y, Z) = (XY + YZ + ZX) then its dual is, fd(X, Y, Z) = (X + Y).(Y + Z).(Z + X) (fd = dual of the given function) = (XY + YZ + ZX), it is equivalent to the given function. So function is self dual. " }, { "code": null, "e": 402, "s": 381, "text": "In a dual function: " }, { "code": null, "e": 573, "s": 402, "text": "AND operator of a given function is changed to OR operator and vice-versa.A constant 1 (or true) of a given function is changed to a constant 0 (or false) and vice-versa." }, { "code": null, "e": 648, "s": 573, "text": "AND operator of a given function is changed to OR operator and vice-versa." }, { "code": null, "e": 745, "s": 648, "text": "A constant 1 (or true) of a given function is changed to a constant 0 (or false) and vice-versa." }, { "code": null, "e": 816, "s": 745, "text": "A Switching function or Boolean function is said to be Self-dual if: " }, { "code": null, "e": 1044, "s": 816, "text": "The given function is neutral i.e., (the number of minterms is equal to the number of max terms). For more about minterm and max term (see Canonical and Standard Form).The function does not contain two mutually exclusive terms." }, { "code": null, "e": 1213, "s": 1044, "text": "The given function is neutral i.e., (the number of minterms is equal to the number of max terms). For more about minterm and max term (see Canonical and Standard Form)." }, { "code": null, "e": 1273, "s": 1213, "text": "The function does not contain two mutually exclusive terms." }, { "code": null, "e": 1415, "s": 1273, "text": "Note: Mutually exclusive term of XYZ is (X’Y’Z’) i.e, the complement of XYZ. So, two mutually exclusive terms are the complement each other. " }, { "code": null, "e": 1425, "s": 1415, "text": "Example: " }, { "code": null, "e": 1477, "s": 1425, "text": "In the above table, Mutually exclusive terms are: " }, { "code": null, "e": 1505, "s": 1477, "text": "(0,7), (1,6), (2,5), (3,4) " }, { "code": null, "e": 1520, "s": 1505, "text": "Explanation: " }, { "code": null, "e": 1612, "s": 1520, "text": "Complement of (000) i.e, 0 is (111) i.e, 7 so, (0, 7 are mutually exclusive to each other.)" }, { "code": null, "e": 1704, "s": 1612, "text": "Complement of (001) i.e, 1 is (110) i.e, 6 so, (1, 6 are mutually exclusive to each other.)" }, { "code": null, "e": 1796, "s": 1704, "text": "Complement of (010) i.e, 2 is (101) i.e, 5 so, (2, 5 are mutually exclusive to each other.)" }, { "code": null, "e": 1888, "s": 1796, "text": "Complement of (011) i.e, 3 is (100) i.e, 4 so, (3, 4 are mutually exclusive to each other.)" }, { "code": null, "e": 2009, "s": 1888, "text": "Now, let us check the number of Self-dual functions possible for a given function. Let, a function has n variables then," }, { "code": null, "e": 2051, "s": 2009, "text": " Number of pairs possible = 2n/2 = 2(n-1)" }, { "code": null, "e": 2127, "s": 2051, "text": "Therefore, the number of Self-dual functions is possible with n variables " }, { "code": null, "e": 2139, "s": 2127, "text": "= 22^(n-1) " }, { "code": null, "e": 2181, "s": 2139, "text": "There are 2 possibilities for each pair. " }, { "code": null, "e": 2280, "s": 2181, "text": "Example: What is the total number of self-duals of a function which has 3 variables X, Y, and Z? " }, { "code": null, "e": 2310, "s": 2280, "text": "= 22^(3-1) \n= 22^2\n= 24\n= 16 " }, { "code": null, "e": 2318, "s": 2310, "text": "Note: " }, { "code": null, "e": 2501, "s": 2318, "text": "Every Self-dual function is neutral but every neutral function is not Self-dual.Self-duality is closed under complement i.e, the complement of a Self-dual function is also Self-dual." }, { "code": null, "e": 2582, "s": 2501, "text": "Every Self-dual function is neutral but every neutral function is not Self-dual." }, { "code": null, "e": 2685, "s": 2582, "text": "Self-duality is closed under complement i.e, the complement of a Self-dual function is also Self-dual." }, { "code": null, "e": 2694, "s": 2685, "text": "sooda367" }, { "code": null, "e": 2710, "s": 2694, "text": "vikaskonaparthi" }, { "code": null, "e": 2745, "s": 2710, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 2769, "s": 2745, "text": "Engineering Mathematics" }, { "code": null, "e": 2777, "s": 2769, "text": "GATE CS" }, { "code": null, "e": 2875, "s": 2777, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2915, "s": 2875, "text": "Introduction to memory and memory units" }, { "code": null, "e": 2944, "s": 2915, "text": "Analog to Digital Conversion" }, { "code": null, "e": 2969, "s": 2944, "text": "Latches in Digital Logic" }, { "code": null, "e": 2998, "s": 2969, "text": "Digital to Analog Conversion" }, { "code": null, "e": 3034, "s": 2998, "text": "Introduction of Sequential Circuits" }, { "code": null, "e": 3097, "s": 3034, "text": "Relationship between number of nodes and height of binary tree" }, { "code": null, "e": 3119, "s": 3097, "text": "Inequalities in LaTeX" }, { "code": null, "e": 3178, "s": 3119, "text": "Difference between Propositional Logic and Predicate Logic" }, { "code": null, "e": 3236, "s": 3178, "text": "Mathematics | Introduction to Propositional Logic | Set 1" } ]
List all values of a certain field in MongoDB?
To get the list of all values of certain fields in MongoDB, you can use distinct(). The syntax is as follows − db.yourCollectionName.distinct( "yourFieldName"); To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows − > db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[10,20,30]}); { "acknowledged" : true, "insertedId" : ObjectId("5c8fc89ed3c9d04998abf011") } > db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[40,50,60]}); { "acknowledged" : true, "insertedId" : ObjectId("5c8fc8abd3c9d04998abf012") } > db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[10,20,30]}); { "acknowledged" : true, "insertedId" : ObjectId("5c8fc8d7d3c9d04998abf013") } > db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[40,50,70]}); { "acknowledged" : true, "insertedId" : ObjectId("5c8fc8e2d3c9d04998abf014") } Display all documents from a collection with the help of find() method. The query is as follows − > db.listAllValuesOfCeratinFieldsDemo.find().pretty(); The following is the output − { "_id" : ObjectId("5c8fc89ed3c9d04998abf011"), "ListOfValues" : [ 10, 20, 30 ] } { "_id" : ObjectId("5c8fc8abd3c9d04998abf012"), "ListOfValues" : [ 40, 50, 60 ] } { "_id" : ObjectId("5c8fc8d7d3c9d04998abf013"), "ListOfValues" : [ 10, 20, 30 ] } { "_id" : ObjectId("5c8fc8e2d3c9d04998abf014"), "ListOfValues" : [ 40, 50, 70 ] } Here is the query to get the list all values of a certain field in MongoDB. We are displaying the record of the field ‘ListOfValues’ − > db.listAllValuesOfCeratinFieldsDemo.distinct( "ListOfValues"); The following is the output − [ 10, 20, 30, 40, 50, 60, 70 ]
[ { "code": null, "e": 1298, "s": 1187, "text": "To get the list of all values of certain fields in MongoDB, you can use distinct(). The syntax is as follows −" }, { "code": null, "e": 1348, "s": 1298, "text": "db.yourCollectionName.distinct( \"yourFieldName\");" }, { "code": null, "e": 1491, "s": 1348, "text": "To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −" }, { "code": null, "e": 2143, "s": 1491, "text": "> db.listAllValuesOfCeratinFieldsDemo.insertOne({\"ListOfValues\":[10,20,30]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8fc89ed3c9d04998abf011\")\n}\n> db.listAllValuesOfCeratinFieldsDemo.insertOne({\"ListOfValues\":[40,50,60]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8fc8abd3c9d04998abf012\")\n}\n> db.listAllValuesOfCeratinFieldsDemo.insertOne({\"ListOfValues\":[10,20,30]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8fc8d7d3c9d04998abf013\")\n}\n> db.listAllValuesOfCeratinFieldsDemo.insertOne({\"ListOfValues\":[40,50,70]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8fc8e2d3c9d04998abf014\")\n}" }, { "code": null, "e": 2241, "s": 2143, "text": "Display all documents from a collection with the help of find() method. The query is as follows −" }, { "code": null, "e": 2297, "s": 2241, "text": "> db.listAllValuesOfCeratinFieldsDemo.find().pretty();\n" }, { "code": null, "e": 2327, "s": 2297, "text": "The following is the output −" }, { "code": null, "e": 2763, "s": 2327, "text": "{\n \"_id\" : ObjectId(\"5c8fc89ed3c9d04998abf011\"),\n \"ListOfValues\" : [\n 10,\n 20,\n 30\n ]\n}\n{\n \"_id\" : ObjectId(\"5c8fc8abd3c9d04998abf012\"),\n \"ListOfValues\" : [\n 40,\n 50,\n 60\n ]\n}\n{\n \"_id\" : ObjectId(\"5c8fc8d7d3c9d04998abf013\"),\n \"ListOfValues\" : [\n 10,\n 20,\n 30\n ]\n}\n{\n \"_id\" : ObjectId(\"5c8fc8e2d3c9d04998abf014\"),\n \"ListOfValues\" : [\n 40,\n 50,\n 70\n ]\n}" }, { "code": null, "e": 2898, "s": 2763, "text": "Here is the query to get the list all values of a certain field in MongoDB. We are displaying the record of the field ‘ListOfValues’ −" }, { "code": null, "e": 2963, "s": 2898, "text": "> db.listAllValuesOfCeratinFieldsDemo.distinct( \"ListOfValues\");" }, { "code": null, "e": 2993, "s": 2963, "text": "The following is the output −" }, { "code": null, "e": 3024, "s": 2993, "text": "[ 10, 20, 30, 40, 50, 60, 70 ]" } ]
Windows 10 Toast Notifications with Python
We can create a notifier for the events that occurred in Windows using Python. This is very simple with the win10toast module. If you are familiar with the Toast in Android then understanding the Toast notifications with Python is a piece of cake. We can generate notifications whenever an event occurs as a remainder. Let's see. Run the following command in command-line to install win10toast module pip install win10toast If the module successfully installed then, you will get the following result when you run the command. Collecting win10toast Downloading https://files.pythonhosted.org/packages/d4/ba/95c0ea87d9bcad68b90d8cb130a313b939c88d8338a2fed7c11eaee972fe/win10toast-0.9-py2.py3-none-any.whl Collecting pypiwin32 (from win10toast) Downloading https://files.pythonhosted.org/packages/d0/1b/2f292bbd742e369a100c91faa0483172cd91a1a422a6692055ac920946c5/pypiwin32-223-py3-none-any.whl Requirement already satisfied: setuptools in c:\users\hafeezulkareem\anaconda3\lib\site-packages (from win10toast) (40.8.0) Requirement already satisfied: pywin32>=223 in c:\users\hafeezulkareem\anaconda3\lib\site-packages (from pypiwin32->win10toast) (223) Installing collected packages: pypiwin32, win10toast Successfully installed pypiwin32-223 win10toast-0.9 Import ToastNotifier class from the win10toast. Import ToastNotifier class from the win10toast. Instantiate the class. Instantiate the class. Invoke the show_toast('title', 'message', duration = time_in_sec, icon_path = 'path to .ico file') method with the desired arguments. Invoke the show_toast('title', 'message', duration = time_in_sec, icon_path = 'path to .ico file') method with the desired arguments. You will get True as output after notification duration complete, if successful. You will get True as output after notification duration complete, if successful. Let's see it with a simple example. ## program to generate a simple toast notifier from win10toast import ToastNotifier ## instantiating the class notifier = ToastNotifier() ## invoking the show_toast() method with required arguments notifier.show_toast("Sample Notification", "You are learning at Tutorialspoint", duration = 25, icon_path = "globe.ico") If you run the above program, you will get the following results. You can add this notification program when an event occurs on your system. If you have any doubts regarding the tutorial, please mention them in the comment section.
[ { "code": null, "e": 1517, "s": 1187, "text": "We can create a notifier for the events that occurred in Windows using Python. This is very simple with the win10toast module. If you are familiar with the Toast in Android then understanding the Toast notifications with Python is a piece of cake. We can generate notifications whenever an event occurs as a remainder. Let's see." }, { "code": null, "e": 1588, "s": 1517, "text": "Run the following command in command-line to install win10toast module" }, { "code": null, "e": 1611, "s": 1588, "text": "pip install win10toast" }, { "code": null, "e": 1714, "s": 1611, "text": "If the module successfully installed then, you will get the following result when you run the command." }, { "code": null, "e": 2443, "s": 1714, "text": "Collecting win10toast\nDownloading https://files.pythonhosted.org/packages/d4/ba/95c0ea87d9bcad68b90d8cb130a313b939c88d8338a2fed7c11eaee972fe/win10toast-0.9-py2.py3-none-any.whl\nCollecting pypiwin32 (from win10toast)\nDownloading https://files.pythonhosted.org/packages/d0/1b/2f292bbd742e369a100c91faa0483172cd91a1a422a6692055ac920946c5/pypiwin32-223-py3-none-any.whl\nRequirement already satisfied: setuptools in c:\\users\\hafeezulkareem\\anaconda3\\lib\\site-packages (from win10toast) (40.8.0)\nRequirement already satisfied: pywin32>=223 in c:\\users\\hafeezulkareem\\anaconda3\\lib\\site-packages (from pypiwin32->win10toast) (223)\nInstalling collected packages: pypiwin32, win10toast\nSuccessfully installed pypiwin32-223 win10toast-0.9" }, { "code": null, "e": 2491, "s": 2443, "text": "Import ToastNotifier class from the win10toast." }, { "code": null, "e": 2539, "s": 2491, "text": "Import ToastNotifier class from the win10toast." }, { "code": null, "e": 2562, "s": 2539, "text": "Instantiate the class." }, { "code": null, "e": 2585, "s": 2562, "text": "Instantiate the class." }, { "code": null, "e": 2719, "s": 2585, "text": "Invoke the show_toast('title', 'message', duration = time_in_sec, icon_path = 'path to .ico file') method with the desired arguments." }, { "code": null, "e": 2853, "s": 2719, "text": "Invoke the show_toast('title', 'message', duration = time_in_sec, icon_path = 'path to .ico file') method with the desired arguments." }, { "code": null, "e": 2934, "s": 2853, "text": "You will get True as output after notification duration complete, if successful." }, { "code": null, "e": 3015, "s": 2934, "text": "You will get True as output after notification duration complete, if successful." }, { "code": null, "e": 3051, "s": 3015, "text": "Let's see it with a simple example." }, { "code": null, "e": 3370, "s": 3051, "text": "## program to generate a simple toast notifier\nfrom win10toast import ToastNotifier\n## instantiating the class\nnotifier = ToastNotifier()\n## invoking the show_toast() method with required arguments notifier.show_toast(\"Sample Notification\", \"You are learning at Tutorialspoint\", duration = 25, icon_path = \"globe.ico\")" }, { "code": null, "e": 3436, "s": 3370, "text": "If you run the above program, you will get the following results." }, { "code": null, "e": 3602, "s": 3436, "text": "You can add this notification program when an event occurs on your system. If you have any doubts regarding the tutorial, please mention them in the comment section." } ]
DateTime.FromOADate() Method in C#
28 Jan, 2019 DateTime.FromOADate(Double) Method is used to return a DateTime equivalent to the specified OLE Automation Date. Syntax: public static DateTime FromOADate (double d);Here, it takes an OLE Automation Date value. Return Value: This method returns an object that represents the same date and time as d. Exception: This method will give ArgumentException if the date is not a valid OLE Automation Date value. Below programs illustrate the use of DateTime.FromOADate(Double) Method: Example 1: // C# program to demonstrate the// DateTime.FromOADate(Int64) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // converting 657435.0 OLE // Automation Date value. // into DateTime format // using FromOADate() method DateTime date2 = DateTime.FromOADate(657435.0); // Display the date2 System.Console.WriteLine("DateTime " + ": {0:y} {0:dd}",date2); } catch (ArgumentException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} DateTime : 3699 December 28 Example 2: For ArgumentException // C# program to demonstrate the// DateTime.FromOADate(Int64) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // converting 657435.0 OLE // Automation Date value. // into DateTime format // using FromOADate() method DateTime date2 = DateTime.FromOADate(-657435.0); // Display the date2 System.Console.WriteLine("DateTime " + ": {0:y} {0:dd}",date2); } catch (ArgumentException e) { Console.WriteLine("The date is not a valid "+ "OLE Automation Date value."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} The date is not a valid OLE Automation Date value. Exception Thrown: System.ArgumentException Reference: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.fromoadate?view=netframework-4.7.2 CSharp DateTime Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jan, 2019" }, { "code": null, "e": 141, "s": 28, "text": "DateTime.FromOADate(Double) Method is used to return a DateTime equivalent to the specified OLE Automation Date." }, { "code": null, "e": 239, "s": 141, "text": "Syntax: public static DateTime FromOADate (double d);Here, it takes an OLE Automation Date value." }, { "code": null, "e": 328, "s": 239, "text": "Return Value: This method returns an object that represents the same date and time as d." }, { "code": null, "e": 433, "s": 328, "text": "Exception: This method will give ArgumentException if the date is not a valid OLE Automation Date value." }, { "code": null, "e": 506, "s": 433, "text": "Below programs illustrate the use of DateTime.FromOADate(Double) Method:" }, { "code": null, "e": 517, "s": 506, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// DateTime.FromOADate(Int64) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // converting 657435.0 OLE // Automation Date value. // into DateTime format // using FromOADate() method DateTime date2 = DateTime.FromOADate(657435.0); // Display the date2 System.Console.WriteLine(\"DateTime \" + \": {0:y} {0:dd}\",date2); } catch (ArgumentException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 1256, "s": 517, "text": null }, { "code": null, "e": 1285, "s": 1256, "text": "DateTime : 3699 December 28\n" }, { "code": null, "e": 1318, "s": 1285, "text": "Example 2: For ArgumentException" }, { "code": "// C# program to demonstrate the// DateTime.FromOADate(Int64) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // converting 657435.0 OLE // Automation Date value. // into DateTime format // using FromOADate() method DateTime date2 = DateTime.FromOADate(-657435.0); // Display the date2 System.Console.WriteLine(\"DateTime \" + \": {0:y} {0:dd}\",date2); } catch (ArgumentException e) { Console.WriteLine(\"The date is not a valid \"+ \"OLE Automation Date value.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 2178, "s": 1318, "text": null }, { "code": null, "e": 2273, "s": 2178, "text": "The date is not a valid OLE Automation Date value.\nException Thrown: System.ArgumentException\n" }, { "code": null, "e": 2284, "s": 2273, "text": "Reference:" }, { "code": null, "e": 2379, "s": 2284, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.fromoadate?view=netframework-4.7.2" }, { "code": null, "e": 2402, "s": 2379, "text": "CSharp DateTime Struct" }, { "code": null, "e": 2416, "s": 2402, "text": "CSharp-method" }, { "code": null, "e": 2419, "s": 2416, "text": "C#" } ]
Python Turtle Tutorial
08 Feb, 2021 Turtle is a Python module that provides a drawing board like feature, which enables users to create pictures and shapes. Turtle is one of the most popular ways of introducing programming to kids and is part of the original LOGO programming language. The on-screen pen that is used for drawing is called the turtle and can be moved using the functions like turtle.forward(), turtle.left(), etc. For example turtle.forward(10) will move the pen in the forward direction by 10 pixels. Consider the below example for better understanding. Example: Python3 import turtle # moves the pen in the # forward direction by # 110 pixelsturtle.forward(110) # changes the direction of # the pen by 10 degrees in the# left directionturtle.left(110) # moves the pen in the # forward direction in # the new direction by# 110 pixelsturtle.forward(110) Let’s get started learning Turtle from basics to advance with the help huge dataset containing well-explained functions and exercises which are categorized properly to help you learn it in a more systematic way. Turtle Programming in Python turtle.backward() method in Python turtle.left() method in Python turtle.right() method in Python turtle.setx() function in Python turtle.sety() function in Python turtle.seth() function in Python turtle.dot() function in Python turtle.home() function in Python turtle.speed() function in Python turtle.undo() function in Python turtle.stamp() function in Python turtle.clearstamp() method in Python turtle.clearstamps() method in Python turtle.towards() function in Python turtle.heading() function in Python turtle.xcor() function in Python turtle.ycor() function in Python turtle.degrees() function in Python Python – turtle.radians() turtle.up() method in Python turtle.down() method in Python turtle.isdown() function in Python turtle.width() function in Python turtle.pen() function in Python turtle.write() function in Python turtle.color() method in Python turtle.fillcolor() function in Python Python – turtle.pencolor() method turtle.filling() function in Python turtle.begin_fill() function in Python turtle.end_fill() function in Python Python – turtle.clear() turtle.onclick() function in Python turtle.onkey() function in Python turtle.onscreenclick() function in Python turtle.onrelease() function in Python turtle.ontimer() function in Python turtle.ondrag() function in Python Python – turtle.exitonclick() Python – turtle.done() turtle.showturtle() function in Python turtle.isvisible() function in Python turtle.shape() function in Python turtle.turtlesize() function in Python turtle.tilt() function in Python turtle.shapetransform() function in Python turtle.settiltangle() function in Python turtle.shearfactor() function in Python turtle.get_poly() function in Python turtle.resizemode() function in Python turtle.pos() method in Python turtle.reset() function in Python turtle.resetscreen() function in Python Python – turtle.Screen().setup() method Python – turtle.clear() turtle.bgpic() function in Python turtle.Screen().turtles() function in Python turtle.setworldcoordinates() function in Python turtle.numinput() function in Python turtle.textinput() function in Python turtle.window_height() function in Python turtle.window_width() function in Python turtle.screensize() function in Python turtle.title() function in Python Python – turtle.done() turtle.addshape() function in Python turtle.colormode() function in Python Python – turtle.delay() method turtle.tracer() function in Python turtle.mode() function in Python turtle.register_shape() function in Python Python – turtle.bye() turtle.clone() function in Python turtle.undobufferentries() function in Python turtle.setundobuffer() function in Python turtle.getpen() function in Python turtle.getshapes() function in Python turtle.get_shapepoly() function in Python turtle.getscreen() function in Python How to Get Coordinate Of Screen in Python Turtle ? Draw Square and Rectangle in Turtle – Python Draw Color Filled Shapes in Turtle – Python Python – Draw Hexagon Using Turtle Graphics Python – Draw Octagonal shape Using Turtle Graphics Draw any polygon in Turtle – Python Draw Ellipse Using Turtle in Python Draw Cube and Cuboid in Python using Turtle Draw Colored Solid Cube using Turtle in Python Python – Draw Star Using Turtle Graphics How to draw color filled star in Python-Turtle? Draw Rainbow using Turtle Graphics in Python Python – Write “GFG” using Turtle Graphics Python – Draw “GFG” logo using Turtle Graphics Draw smiling face emoji using Turtle in Python Draw Shape inside Shape in Python Using Turtle Draw an Olympic Symbol in Python using Turtle Draw Concentric Circles with VIBGYOR Using Turtle in Python Draw Dot Patterns Using Turtle in Python Draw a car using Turtle in Python Draw sun using Turtle module in Python Draw Heart Using Turtle Graphics in Python Draw Diamond shape using Turtle graphics in Python Draw Graph Grid Using Turtle in Python Draw Panda Using Turtle Graphics in Python Draw house using Turtle programming in Python Draw a snowman using turtle module in Python Draw Clock Design using Turtle in Python Create digital clock using Python-Turtle Draw Colourful Star Pattern in Turtle – Python Print a Spirograph using turtle in Python Draw Spiraling Star using Turtle in Python Draw Spiraling Square using Turtle in Python Draw Spiraling Triangle using Turtle in Python Draw Spiraling Polygon using Turtle in Python Draw Colorful Spiral Web Using Turtle Graphics in Python Draw a Tic Tac Toe Board using Python-Turtle Draw Chess Board Using Turtle in Python Python – Hilbert Curve using turtle Turtle – Draw Lines using arrow keys Draw lines at the respective positions clicked by the mouse using Turtle Python Turtle – Graphics Keyboard Commands How to make Triangle in Python Turtle using onscreenclick? How to Create custom Turtle shapes in Python? Circle of Squares using Python How to draw 2-layered and colored spider web in Python using Turtle Module? Y Fractal tree in Python using Turtle How to make Indian Flag using Turtle – Python Draw Starry Sky with Moon using Turtle in Python Draw moving object using Turtle in Python Create a simple Animation using Turtle in Python Create a Simple Two Player Game using Turtle in Python Create a Snake-Game using Turtle in Python Create pong game using Python – Turtle Flipping Tiles (memory game) using Python3 Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Feb, 2021" }, { "code": null, "e": 304, "s": 54, "text": "Turtle is a Python module that provides a drawing board like feature, which enables users to create pictures and shapes. Turtle is one of the most popular ways of introducing programming to kids and is part of the original LOGO programming language." }, { "code": null, "e": 589, "s": 304, "text": "The on-screen pen that is used for drawing is called the turtle and can be moved using the functions like turtle.forward(), turtle.left(), etc. For example turtle.forward(10) will move the pen in the forward direction by 10 pixels. Consider the below example for better understanding." }, { "code": null, "e": 598, "s": 589, "text": "Example:" }, { "code": null, "e": 606, "s": 598, "text": "Python3" }, { "code": "import turtle # moves the pen in the # forward direction by # 110 pixelsturtle.forward(110) # changes the direction of # the pen by 10 degrees in the# left directionturtle.left(110) # moves the pen in the # forward direction in # the new direction by# 110 pixelsturtle.forward(110)", "e": 891, "s": 606, "text": null }, { "code": null, "e": 1103, "s": 891, "text": "Let’s get started learning Turtle from basics to advance with the help huge dataset containing well-explained functions and exercises which are categorized properly to help you learn it in a more systematic way." }, { "code": null, "e": 1132, "s": 1103, "text": "Turtle Programming in Python" }, { "code": null, "e": 1167, "s": 1132, "text": "turtle.backward() method in Python" }, { "code": null, "e": 1198, "s": 1167, "text": "turtle.left() method in Python" }, { "code": null, "e": 1230, "s": 1198, "text": "turtle.right() method in Python" }, { "code": null, "e": 1263, "s": 1230, "text": "turtle.setx() function in Python" }, { "code": null, "e": 1296, "s": 1263, "text": "turtle.sety() function in Python" }, { "code": null, "e": 1329, "s": 1296, "text": "turtle.seth() function in Python" }, { "code": null, "e": 1361, "s": 1329, "text": "turtle.dot() function in Python" }, { "code": null, "e": 1394, "s": 1361, "text": "turtle.home() function in Python" }, { "code": null, "e": 1428, "s": 1394, "text": "turtle.speed() function in Python" }, { "code": null, "e": 1461, "s": 1428, "text": "turtle.undo() function in Python" }, { "code": null, "e": 1495, "s": 1461, "text": "turtle.stamp() function in Python" }, { "code": null, "e": 1532, "s": 1495, "text": "turtle.clearstamp() method in Python" }, { "code": null, "e": 1570, "s": 1532, "text": "turtle.clearstamps() method in Python" }, { "code": null, "e": 1606, "s": 1570, "text": "turtle.towards() function in Python" }, { "code": null, "e": 1642, "s": 1606, "text": "turtle.heading() function in Python" }, { "code": null, "e": 1675, "s": 1642, "text": "turtle.xcor() function in Python" }, { "code": null, "e": 1708, "s": 1675, "text": "turtle.ycor() function in Python" }, { "code": null, "e": 1744, "s": 1708, "text": "turtle.degrees() function in Python" }, { "code": null, "e": 1770, "s": 1744, "text": "Python – turtle.radians()" }, { "code": null, "e": 1799, "s": 1770, "text": "turtle.up() method in Python" }, { "code": null, "e": 1830, "s": 1799, "text": "turtle.down() method in Python" }, { "code": null, "e": 1865, "s": 1830, "text": "turtle.isdown() function in Python" }, { "code": null, "e": 1899, "s": 1865, "text": "turtle.width() function in Python" }, { "code": null, "e": 1931, "s": 1899, "text": "turtle.pen() function in Python" }, { "code": null, "e": 1965, "s": 1931, "text": "turtle.write() function in Python" }, { "code": null, "e": 1997, "s": 1965, "text": "turtle.color() method in Python" }, { "code": null, "e": 2035, "s": 1997, "text": "turtle.fillcolor() function in Python" }, { "code": null, "e": 2069, "s": 2035, "text": "Python – turtle.pencolor() method" }, { "code": null, "e": 2105, "s": 2069, "text": "turtle.filling() function in Python" }, { "code": null, "e": 2144, "s": 2105, "text": "turtle.begin_fill() function in Python" }, { "code": null, "e": 2181, "s": 2144, "text": "turtle.end_fill() function in Python" }, { "code": null, "e": 2205, "s": 2181, "text": "Python – turtle.clear()" }, { "code": null, "e": 2241, "s": 2205, "text": "turtle.onclick() function in Python" }, { "code": null, "e": 2275, "s": 2241, "text": "turtle.onkey() function in Python" }, { "code": null, "e": 2317, "s": 2275, "text": "turtle.onscreenclick() function in Python" }, { "code": null, "e": 2355, "s": 2317, "text": "turtle.onrelease() function in Python" }, { "code": null, "e": 2391, "s": 2355, "text": "turtle.ontimer() function in Python" }, { "code": null, "e": 2426, "s": 2391, "text": "turtle.ondrag() function in Python" }, { "code": null, "e": 2456, "s": 2426, "text": "Python – turtle.exitonclick()" }, { "code": null, "e": 2479, "s": 2456, "text": "Python – turtle.done()" }, { "code": null, "e": 2518, "s": 2479, "text": "turtle.showturtle() function in Python" }, { "code": null, "e": 2556, "s": 2518, "text": "turtle.isvisible() function in Python" }, { "code": null, "e": 2590, "s": 2556, "text": "turtle.shape() function in Python" }, { "code": null, "e": 2629, "s": 2590, "text": "turtle.turtlesize() function in Python" }, { "code": null, "e": 2662, "s": 2629, "text": "turtle.tilt() function in Python" }, { "code": null, "e": 2705, "s": 2662, "text": "turtle.shapetransform() function in Python" }, { "code": null, "e": 2746, "s": 2705, "text": "turtle.settiltangle() function in Python" }, { "code": null, "e": 2786, "s": 2746, "text": "turtle.shearfactor() function in Python" }, { "code": null, "e": 2823, "s": 2786, "text": "turtle.get_poly() function in Python" }, { "code": null, "e": 2862, "s": 2823, "text": "turtle.resizemode() function in Python" }, { "code": null, "e": 2892, "s": 2862, "text": "turtle.pos() method in Python" }, { "code": null, "e": 2926, "s": 2892, "text": "turtle.reset() function in Python" }, { "code": null, "e": 2966, "s": 2926, "text": "turtle.resetscreen() function in Python" }, { "code": null, "e": 3006, "s": 2966, "text": "Python – turtle.Screen().setup() method" }, { "code": null, "e": 3030, "s": 3006, "text": "Python – turtle.clear()" }, { "code": null, "e": 3064, "s": 3030, "text": "turtle.bgpic() function in Python" }, { "code": null, "e": 3109, "s": 3064, "text": "turtle.Screen().turtles() function in Python" }, { "code": null, "e": 3157, "s": 3109, "text": "turtle.setworldcoordinates() function in Python" }, { "code": null, "e": 3194, "s": 3157, "text": "turtle.numinput() function in Python" }, { "code": null, "e": 3232, "s": 3194, "text": "turtle.textinput() function in Python" }, { "code": null, "e": 3274, "s": 3232, "text": "turtle.window_height() function in Python" }, { "code": null, "e": 3315, "s": 3274, "text": "turtle.window_width() function in Python" }, { "code": null, "e": 3354, "s": 3315, "text": "turtle.screensize() function in Python" }, { "code": null, "e": 3388, "s": 3354, "text": "turtle.title() function in Python" }, { "code": null, "e": 3411, "s": 3388, "text": "Python – turtle.done()" }, { "code": null, "e": 3448, "s": 3411, "text": "turtle.addshape() function in Python" }, { "code": null, "e": 3486, "s": 3448, "text": "turtle.colormode() function in Python" }, { "code": null, "e": 3517, "s": 3486, "text": "Python – turtle.delay() method" }, { "code": null, "e": 3552, "s": 3517, "text": "turtle.tracer() function in Python" }, { "code": null, "e": 3585, "s": 3552, "text": "turtle.mode() function in Python" }, { "code": null, "e": 3628, "s": 3585, "text": "turtle.register_shape() function in Python" }, { "code": null, "e": 3650, "s": 3628, "text": "Python – turtle.bye()" }, { "code": null, "e": 3684, "s": 3650, "text": "turtle.clone() function in Python" }, { "code": null, "e": 3730, "s": 3684, "text": "turtle.undobufferentries() function in Python" }, { "code": null, "e": 3772, "s": 3730, "text": "turtle.setundobuffer() function in Python" }, { "code": null, "e": 3807, "s": 3772, "text": "turtle.getpen() function in Python" }, { "code": null, "e": 3845, "s": 3807, "text": "turtle.getshapes() function in Python" }, { "code": null, "e": 3887, "s": 3845, "text": "turtle.get_shapepoly() function in Python" }, { "code": null, "e": 3925, "s": 3887, "text": "turtle.getscreen() function in Python" }, { "code": null, "e": 3976, "s": 3925, "text": "How to Get Coordinate Of Screen in Python Turtle ?" }, { "code": null, "e": 4021, "s": 3976, "text": "Draw Square and Rectangle in Turtle – Python" }, { "code": null, "e": 4065, "s": 4021, "text": "Draw Color Filled Shapes in Turtle – Python" }, { "code": null, "e": 4109, "s": 4065, "text": "Python – Draw Hexagon Using Turtle Graphics" }, { "code": null, "e": 4161, "s": 4109, "text": "Python – Draw Octagonal shape Using Turtle Graphics" }, { "code": null, "e": 4197, "s": 4161, "text": "Draw any polygon in Turtle – Python" }, { "code": null, "e": 4233, "s": 4197, "text": "Draw Ellipse Using Turtle in Python" }, { "code": null, "e": 4277, "s": 4233, "text": "Draw Cube and Cuboid in Python using Turtle" }, { "code": null, "e": 4324, "s": 4277, "text": "Draw Colored Solid Cube using Turtle in Python" }, { "code": null, "e": 4365, "s": 4324, "text": "Python – Draw Star Using Turtle Graphics" }, { "code": null, "e": 4413, "s": 4365, "text": "How to draw color filled star in Python-Turtle?" }, { "code": null, "e": 4458, "s": 4413, "text": "Draw Rainbow using Turtle Graphics in Python" }, { "code": null, "e": 4501, "s": 4458, "text": "Python – Write “GFG” using Turtle Graphics" }, { "code": null, "e": 4548, "s": 4501, "text": "Python – Draw “GFG” logo using Turtle Graphics" }, { "code": null, "e": 4595, "s": 4548, "text": "Draw smiling face emoji using Turtle in Python" }, { "code": null, "e": 4642, "s": 4595, "text": "Draw Shape inside Shape in Python Using Turtle" }, { "code": null, "e": 4688, "s": 4642, "text": "Draw an Olympic Symbol in Python using Turtle" }, { "code": null, "e": 4748, "s": 4688, "text": "Draw Concentric Circles with VIBGYOR Using Turtle in Python" }, { "code": null, "e": 4789, "s": 4748, "text": "Draw Dot Patterns Using Turtle in Python" }, { "code": null, "e": 4823, "s": 4789, "text": "Draw a car using Turtle in Python" }, { "code": null, "e": 4862, "s": 4823, "text": "Draw sun using Turtle module in Python" }, { "code": null, "e": 4905, "s": 4862, "text": "Draw Heart Using Turtle Graphics in Python" }, { "code": null, "e": 4956, "s": 4905, "text": "Draw Diamond shape using Turtle graphics in Python" }, { "code": null, "e": 4995, "s": 4956, "text": "Draw Graph Grid Using Turtle in Python" }, { "code": null, "e": 5038, "s": 4995, "text": "Draw Panda Using Turtle Graphics in Python" }, { "code": null, "e": 5084, "s": 5038, "text": "Draw house using Turtle programming in Python" }, { "code": null, "e": 5129, "s": 5084, "text": "Draw a snowman using turtle module in Python" }, { "code": null, "e": 5170, "s": 5129, "text": "Draw Clock Design using Turtle in Python" }, { "code": null, "e": 5211, "s": 5170, "text": "Create digital clock using Python-Turtle" }, { "code": null, "e": 5258, "s": 5211, "text": "Draw Colourful Star Pattern in Turtle – Python" }, { "code": null, "e": 5300, "s": 5258, "text": "Print a Spirograph using turtle in Python" }, { "code": null, "e": 5343, "s": 5300, "text": "Draw Spiraling Star using Turtle in Python" }, { "code": null, "e": 5388, "s": 5343, "text": "Draw Spiraling Square using Turtle in Python" }, { "code": null, "e": 5435, "s": 5388, "text": "Draw Spiraling Triangle using Turtle in Python" }, { "code": null, "e": 5481, "s": 5435, "text": "Draw Spiraling Polygon using Turtle in Python" }, { "code": null, "e": 5538, "s": 5481, "text": "Draw Colorful Spiral Web Using Turtle Graphics in Python" }, { "code": null, "e": 5583, "s": 5538, "text": "Draw a Tic Tac Toe Board using Python-Turtle" }, { "code": null, "e": 5623, "s": 5583, "text": "Draw Chess Board Using Turtle in Python" }, { "code": null, "e": 5659, "s": 5623, "text": "Python – Hilbert Curve using turtle" }, { "code": null, "e": 5696, "s": 5659, "text": "Turtle – Draw Lines using arrow keys" }, { "code": null, "e": 5769, "s": 5696, "text": "Draw lines at the respective positions clicked by the mouse using Turtle" }, { "code": null, "e": 5812, "s": 5769, "text": "Python Turtle – Graphics Keyboard Commands" }, { "code": null, "e": 5871, "s": 5812, "text": "How to make Triangle in Python Turtle using onscreenclick?" }, { "code": null, "e": 5917, "s": 5871, "text": "How to Create custom Turtle shapes in Python?" }, { "code": null, "e": 5948, "s": 5917, "text": "Circle of Squares using Python" }, { "code": null, "e": 6024, "s": 5948, "text": "How to draw 2-layered and colored spider web in Python using Turtle Module?" }, { "code": null, "e": 6062, "s": 6024, "text": "Y Fractal tree in Python using Turtle" }, { "code": null, "e": 6108, "s": 6062, "text": "How to make Indian Flag using Turtle – Python" }, { "code": null, "e": 6157, "s": 6108, "text": "Draw Starry Sky with Moon using Turtle in Python" }, { "code": null, "e": 6199, "s": 6157, "text": "Draw moving object using Turtle in Python" }, { "code": null, "e": 6248, "s": 6199, "text": "Create a simple Animation using Turtle in Python" }, { "code": null, "e": 6303, "s": 6248, "text": "Create a Simple Two Player Game using Turtle in Python" }, { "code": null, "e": 6346, "s": 6303, "text": "Create a Snake-Game using Turtle in Python" }, { "code": null, "e": 6385, "s": 6346, "text": "Create pong game using Python – Turtle" }, { "code": null, "e": 6428, "s": 6385, "text": "Flipping Tiles (memory game) using Python3" }, { "code": null, "e": 6442, "s": 6428, "text": "Python-turtle" }, { "code": null, "e": 6449, "s": 6442, "text": "Python" }, { "code": null, "e": 6547, "s": 6449, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6579, "s": 6547, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 6606, "s": 6579, "text": "Python Classes and Objects" }, { "code": null, "e": 6627, "s": 6606, "text": "Python OOPs Concepts" }, { "code": null, "e": 6658, "s": 6627, "text": "Python | os.path.join() method" }, { "code": null, "e": 6714, "s": 6658, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 6737, "s": 6714, "text": "Introduction To PYTHON" }, { "code": null, "e": 6779, "s": 6737, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 6821, "s": 6779, "text": "Check if element exists in list in Python" }, { "code": null, "e": 6860, "s": 6821, "text": "Python | datetime.timedelta() function" } ]
Python | Generate QR Code using pyqrcode module
17 May, 2020 Let’s see how to generate QR code in Python using pyqrcode module. pyqrcode module is a QR code generator. The module automates most of the building process for creating QR codes. This module attempts to follow the QR code standard as closely as possible. The terminology and the encodings used in pyqrcode come directly from the standard. Installation $ pip install pyqrcode install an additional module pypng to save image in png format: $ pip install pypng pyqrcode.create(content, error='H', version=None, mode=None, encoding=None) : When creating a QR code only the content to be encoded is required, all the other properties of the code will be guessed based on the contents given. This function will return a QRCode object. One can specify all the properties of required QR code through the optional parameters of the pyqrcode.create() function. Below are some properties: error: This parameter sets the error correction level of the code.version: This parameter specifies the size and data capacity of the code.mode: This parameter sets how the contents will be encoded. Below is the code: # Import QRCode from pyqrcodeimport pyqrcodeimport pngfrom pyqrcode import QRCode # String which represents the QR codes = "www.geeksforgeeks.org" # Generate QR codeurl = pyqrcode.create(s) # Create and save the svg file naming "myqr.svg"url.svg("myqr.svg", scale = 8) # Create and save the png file naming "myqr.png"url.png('myqr.png', scale = 6) Output: VarshaGS shauryasheth95 python-modules python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 54, "s": 26, "text": "\n17 May, 2020" }, { "code": null, "e": 121, "s": 54, "text": "Let’s see how to generate QR code in Python using pyqrcode module." }, { "code": null, "e": 394, "s": 121, "text": "pyqrcode module is a QR code generator. The module automates most of the building process for creating QR codes. This module attempts to follow the QR code standard as closely as possible. The terminology and the encodings used in pyqrcode come directly from the standard." }, { "code": null, "e": 407, "s": 394, "text": "Installation" }, { "code": null, "e": 431, "s": 407, "text": "$ pip install pyqrcode\n" }, { "code": null, "e": 496, "s": 431, "text": " install an additional module pypng to save image in png format:" }, { "code": null, "e": 517, "s": 496, "text": "$ pip install pypng\n" }, { "code": null, "e": 789, "s": 517, "text": " pyqrcode.create(content, error='H', version=None, mode=None, encoding=None) : When creating a QR code only the content to be encoded is required, all the other properties of the code will be guessed based on the contents given. This function will return a QRCode object." }, { "code": null, "e": 938, "s": 789, "text": "One can specify all the properties of required QR code through the optional parameters of the pyqrcode.create() function. Below are some properties:" }, { "code": null, "e": 1137, "s": 938, "text": "error: This parameter sets the error correction level of the code.version: This parameter specifies the size and data capacity of the code.mode: This parameter sets how the contents will be encoded." }, { "code": null, "e": 1156, "s": 1137, "text": "Below is the code:" }, { "code": "# Import QRCode from pyqrcodeimport pyqrcodeimport pngfrom pyqrcode import QRCode # String which represents the QR codes = \"www.geeksforgeeks.org\" # Generate QR codeurl = pyqrcode.create(s) # Create and save the svg file naming \"myqr.svg\"url.svg(\"myqr.svg\", scale = 8) # Create and save the png file naming \"myqr.png\"url.png('myqr.png', scale = 6)", "e": 1510, "s": 1156, "text": null }, { "code": null, "e": 1518, "s": 1510, "text": "Output:" }, { "code": null, "e": 1527, "s": 1518, "text": "VarshaGS" }, { "code": null, "e": 1542, "s": 1527, "text": "shauryasheth95" }, { "code": null, "e": 1557, "s": 1542, "text": "python-modules" }, { "code": null, "e": 1572, "s": 1557, "text": "python-utility" }, { "code": null, "e": 1579, "s": 1572, "text": "Python" }, { "code": null, "e": 1677, "s": 1579, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1695, "s": 1677, "text": "Python Dictionary" }, { "code": null, "e": 1737, "s": 1695, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1759, "s": 1737, "text": "Enumerate() in Python" }, { "code": null, "e": 1794, "s": 1759, "text": "Read a file line by line in Python" }, { "code": null, "e": 1820, "s": 1794, "text": "Python String | replace()" }, { "code": null, "e": 1852, "s": 1820, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1881, "s": 1852, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1908, "s": 1881, "text": "Python Classes and Objects" }, { "code": null, "e": 1938, "s": 1908, "text": "Iterate over a list in Python" } ]
Microsoft Azure – Create Alert For Conditional Access Policy Changes
16 Dec, 2021 In this article, we will look into the process of creating an alert for Conditional Access Policy Changes. Conditional Access brings signals together, to make decisions, and enforce organizational policies. Creation of a New Conditional Access Policy,Deletion of a Conditional Access Policy,Changes to any current Conditional Access Policy. Creation of a New Conditional Access Policy, Deletion of a Conditional Access Policy, Changes to any current Conditional Access Policy. Log Analytics Workspace Contributor Access on Subscription or Resource Group to create alerts. Follow the below steps to enable alter on conditional policy changes: Step 1: Login to Azure Portal Step 2: Navigate to select Log Analytics Workspace >> from left menu select Logs >> Copy the below Search Query and Add Query (Copy the below Search Query) >> Click on Run (Refer Output Screenshot) Search Query: AuditLogs | where Category == "Policy" and LoggedByService == "Conditional Access" | project ActivityDateTime, InitiatedBy.user.userPrincipalName, TargetResources[0].displayName, ActivityDisplayName Output: Step 3: After running the Query, from top-right Click on + New alert rule. Then, click on Condition name and set up the required. Alert Logic: Number of results Operator: Greater than Threshold value : 0 Period (in minutes) : 15 Frequency (in minutes) : 15 Now Click on “OK” Step 4: Add Action Group and Configure Notification >> click on Add action group and fill in the following details. Action Group: Subscription: Provide the Select Subscription Resource group: Provide Select Resource group Action group name : Select Requested Action Group (for example: security-notification) Display name : conditAccess Notification: Notification type : Email/SMS message/Push/Voice Name: Email-Action Select : Email >> security@domain.com After filling up the required changes click on save changes. Customize actions : Email Subject >> Add Subject line >> “Conditional Access Changes Detected – Alert” Alert rule name: Conditional Access Changes Detected Description: This alert detects: Creation of a New Conditional Access PolicyDeletion of a Conditional Access PolicyChanges to any current Conditional Access Policy Creation of a New Conditional Access Policy Deletion of a Conditional Access Policy Changes to any current Conditional Access Policy Resource group: Select same as Scope Resource Group Severity: 2 Warning Automatically resolve alerts: false Suppress alerts: false Step 5: Click on Review and Create. Once the alert is triggered, configured email user will be notified about the alert details. That’s it, you are done. At this point, we have successfully enabled email alert whenever there are any conditional policy changes. azure-virtual-machine Cloud-Computing Microsoft Azure Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Dec, 2021" }, { "code": null, "e": 236, "s": 28, "text": "In this article, we will look into the process of creating an alert for Conditional Access Policy Changes. Conditional Access brings signals together, to make decisions, and enforce organizational policies. " }, { "code": null, "e": 370, "s": 236, "text": "Creation of a New Conditional Access Policy,Deletion of a Conditional Access Policy,Changes to any current Conditional Access Policy." }, { "code": null, "e": 415, "s": 370, "text": "Creation of a New Conditional Access Policy," }, { "code": null, "e": 456, "s": 415, "text": "Deletion of a Conditional Access Policy," }, { "code": null, "e": 506, "s": 456, "text": "Changes to any current Conditional Access Policy." }, { "code": null, "e": 530, "s": 506, "text": "Log Analytics Workspace" }, { "code": null, "e": 601, "s": 530, "text": "Contributor Access on Subscription or Resource Group to create alerts." }, { "code": null, "e": 671, "s": 601, "text": "Follow the below steps to enable alter on conditional policy changes:" }, { "code": null, "e": 701, "s": 671, "text": "Step 1: Login to Azure Portal" }, { "code": null, "e": 899, "s": 701, "text": "Step 2: Navigate to select Log Analytics Workspace >> from left menu select Logs >> Copy the below Search Query and Add Query (Copy the below Search Query) >> Click on Run (Refer Output Screenshot)" }, { "code": null, "e": 913, "s": 899, "text": "Search Query:" }, { "code": null, "e": 1112, "s": 913, "text": "AuditLogs\n| where Category == \"Policy\" and LoggedByService == \"Conditional Access\"\n| project ActivityDateTime, InitiatedBy.user.userPrincipalName, TargetResources[0].displayName, ActivityDisplayName" }, { "code": null, "e": 1120, "s": 1112, "text": "Output:" }, { "code": null, "e": 1250, "s": 1120, "text": "Step 3: After running the Query, from top-right Click on + New alert rule. Then, click on Condition name and set up the required." }, { "code": null, "e": 1281, "s": 1250, "text": "Alert Logic: Number of results" }, { "code": null, "e": 1304, "s": 1281, "text": "Operator: Greater than" }, { "code": null, "e": 1324, "s": 1304, "text": "Threshold value : 0" }, { "code": null, "e": 1349, "s": 1324, "text": "Period (in minutes) : 15" }, { "code": null, "e": 1377, "s": 1349, "text": "Frequency (in minutes) : 15" }, { "code": null, "e": 1395, "s": 1377, "text": "Now Click on “OK”" }, { "code": null, "e": 1511, "s": 1395, "text": "Step 4: Add Action Group and Configure Notification >> click on Add action group and fill in the following details." }, { "code": null, "e": 1525, "s": 1511, "text": "Action Group:" }, { "code": null, "e": 1571, "s": 1525, "text": "Subscription: Provide the Select Subscription" }, { "code": null, "e": 1617, "s": 1571, "text": "Resource group: Provide Select Resource group" }, { "code": null, "e": 1704, "s": 1617, "text": "Action group name : Select Requested Action Group (for example: security-notification)" }, { "code": null, "e": 1732, "s": 1704, "text": "Display name : conditAccess" }, { "code": null, "e": 1746, "s": 1732, "text": "Notification:" }, { "code": null, "e": 1795, "s": 1746, "text": "Notification type : Email/SMS message/Push/Voice" }, { "code": null, "e": 1814, "s": 1795, "text": "Name: Email-Action" }, { "code": null, "e": 1852, "s": 1814, "text": "Select : Email >> security@domain.com" }, { "code": null, "e": 1913, "s": 1852, "text": "After filling up the required changes click on save changes." }, { "code": null, "e": 2016, "s": 1913, "text": "Customize actions : Email Subject >> Add Subject line >> “Conditional Access Changes Detected – Alert”" }, { "code": null, "e": 2069, "s": 2016, "text": "Alert rule name: Conditional Access Changes Detected" }, { "code": null, "e": 2082, "s": 2069, "text": "Description:" }, { "code": null, "e": 2102, "s": 2082, "text": "This alert detects:" }, { "code": null, "e": 2233, "s": 2102, "text": "Creation of a New Conditional Access PolicyDeletion of a Conditional Access PolicyChanges to any current Conditional Access Policy" }, { "code": null, "e": 2277, "s": 2233, "text": "Creation of a New Conditional Access Policy" }, { "code": null, "e": 2317, "s": 2277, "text": "Deletion of a Conditional Access Policy" }, { "code": null, "e": 2366, "s": 2317, "text": "Changes to any current Conditional Access Policy" }, { "code": null, "e": 2418, "s": 2366, "text": "Resource group: Select same as Scope Resource Group" }, { "code": null, "e": 2438, "s": 2418, "text": "Severity: 2 Warning" }, { "code": null, "e": 2474, "s": 2438, "text": "Automatically resolve alerts: false" }, { "code": null, "e": 2497, "s": 2474, "text": "Suppress alerts: false" }, { "code": null, "e": 2626, "s": 2497, "text": "Step 5: Click on Review and Create. Once the alert is triggered, configured email user will be notified about the alert details." }, { "code": null, "e": 2758, "s": 2626, "text": "That’s it, you are done. At this point, we have successfully enabled email alert whenever there are any conditional policy changes." }, { "code": null, "e": 2780, "s": 2758, "text": "azure-virtual-machine" }, { "code": null, "e": 2796, "s": 2780, "text": "Cloud-Computing" }, { "code": null, "e": 2812, "s": 2796, "text": "Microsoft Azure" } ]
JavaScript | Importing and Exporting Modules
14 Feb, 2019 JavaScript Modules are basically libraries which are included in the given program. They are used for connecting two JavaScript programs together to call the functions written in one program without writing the body of the functions itself in another program. Importing a library: It means include a library in a program so that use the function is defined in that library. For this, use ‘require’ function in which pass the library name with its relative path.Example: Suppose a library is made in the same folder with file name library.js, then include the file by using require function: const lib = require('./library') which will return reference to that library. Now if there is area function defined in the library, then use it as lib.area(). Exporting a library: There is a special object in JavaScript called module.exports. When some program include or import this module (program), this object will be exposed. Therefore, all those functions that need to be exposed or need to be available so that it can used in some other file, defined in module.exports. Expample : Write two different programs and then see how to use functions defined in the library (Module) in given program. Define two simple functions in the library for calculating and printing area and perimeter of a rectangle when provided with length and breadth. Then export the functions so that other programs can import them if needed and can use them. Exporting Module Example : library.js <script>// Area functionlet area = function (length, breadth) { let a = length * breadth; console.log('Area of the rectangle is ' + a + ' square unit');} // Perimeter functionlet perimeter = function (length, breadth) { let p = 2 * (length + breadth); console.log('Perimeter of the rectangle is ' + p + ' unit');} // Making all functions available in this// module to exports that we have made// so that we can import this module and// use these functions whenever we want.module.exports = { area, perimeter}</script> Importing Module Example For importing any module, use a function called ‘Require’ which takes in the module name and if its user defined module then its relative path as argument and returns its reference. The script.js contains the above JavaScript module (library.js). Script.js <script>// Importing the module library containing// area and perimeter functions.// " ./ " is used if both the files are in the same folder.const lib = require('./library'); let length = 10;let breadth = 5; // Calling the functions // defined in the lib modulelib.area(length, breadth);lib.perimeter(length, breadth);</script> Output: Area of the rectangle is 50 square unit Perimeter of the rectangle is 30 unit Note: To run the script first make both files in the same folder and then run script.js using NodeJs interpreter in terminal. javascript-basics Technical Scripter 2018 JavaScript Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Feb, 2019" }, { "code": null, "e": 314, "s": 54, "text": "JavaScript Modules are basically libraries which are included in the given program. They are used for connecting two JavaScript programs together to call the functions written in one program without writing the body of the functions itself in another program." }, { "code": null, "e": 645, "s": 314, "text": "Importing a library: It means include a library in a program so that use the function is defined in that library. For this, use ‘require’ function in which pass the library name with its relative path.Example: Suppose a library is made in the same folder with file name library.js, then include the file by using require function:" }, { "code": null, "e": 679, "s": 645, "text": "const lib = require('./library') " }, { "code": null, "e": 805, "s": 679, "text": "which will return reference to that library. Now if there is area function defined in the library, then use it as lib.area()." }, { "code": null, "e": 1123, "s": 805, "text": "Exporting a library: There is a special object in JavaScript called module.exports. When some program include or import this module (program), this object will be exposed. Therefore, all those functions that need to be exposed or need to be available so that it can used in some other file, defined in module.exports." }, { "code": null, "e": 1485, "s": 1123, "text": "Expample : Write two different programs and then see how to use functions defined in the library (Module) in given program. Define two simple functions in the library for calculating and printing area and perimeter of a rectangle when provided with length and breadth. Then export the functions so that other programs can import them if needed and can use them." }, { "code": null, "e": 1523, "s": 1485, "text": "Exporting Module Example : library.js" }, { "code": "<script>// Area functionlet area = function (length, breadth) { let a = length * breadth; console.log('Area of the rectangle is ' + a + ' square unit');} // Perimeter functionlet perimeter = function (length, breadth) { let p = 2 * (length + breadth); console.log('Perimeter of the rectangle is ' + p + ' unit');} // Making all functions available in this// module to exports that we have made// so that we can import this module and// use these functions whenever we want.module.exports = { area, perimeter}</script>", "e": 2061, "s": 1523, "text": null }, { "code": null, "e": 2086, "s": 2061, "text": "Importing Module Example" }, { "code": null, "e": 2268, "s": 2086, "text": "For importing any module, use a function called ‘Require’ which takes in the module name and if its user defined module then its relative path as argument and returns its reference." }, { "code": null, "e": 2333, "s": 2268, "text": "The script.js contains the above JavaScript module (library.js)." }, { "code": null, "e": 2343, "s": 2333, "text": "Script.js" }, { "code": "<script>// Importing the module library containing// area and perimeter functions.// \" ./ \" is used if both the files are in the same folder.const lib = require('./library'); let length = 10;let breadth = 5; // Calling the functions // defined in the lib modulelib.area(length, breadth);lib.perimeter(length, breadth);</script>", "e": 2674, "s": 2343, "text": null }, { "code": null, "e": 2682, "s": 2674, "text": "Output:" }, { "code": null, "e": 2760, "s": 2682, "text": "Area of the rectangle is 50 square unit\nPerimeter of the rectangle is 30 unit" }, { "code": null, "e": 2886, "s": 2760, "text": "Note: To run the script first make both files in the same folder and then run script.js using NodeJs interpreter in terminal." }, { "code": null, "e": 2904, "s": 2886, "text": "javascript-basics" }, { "code": null, "e": 2928, "s": 2904, "text": "Technical Scripter 2018" }, { "code": null, "e": 2939, "s": 2928, "text": "JavaScript" }, { "code": null, "e": 2958, "s": 2939, "text": "Technical Scripter" }, { "code": null, "e": 2975, "s": 2958, "text": "Web Technologies" } ]
Array Size in Perl
The size of an array in Perl can be determined using the scalar context on the array - the returned value will be the number of elements in the array − @array = (1,2,3); print "Size: ",scalar @array,"\n"; The value returned will always be the physical size of the array, not the number of valid elements. You can demonstrate this, and the difference between scalar @array and $#array, using this fragment is as follows − Live Demo #!/usr/bin/perl @array = (1,2,3); $array[50] = 4; $size = @array; $max_index = $#array; print "Size: $size\n"; print "Max Index: $max_index\n"; This will produce the following result − Size: 51 Max Index: 50 There are only four elements in the array that contains information, but the array is 51 elements long, with the highest index of 50.
[ { "code": null, "e": 1214, "s": 1062, "text": "The size of an array in Perl can be determined using the scalar context on the array - the returned value will be the number of elements in the array −" }, { "code": null, "e": 1267, "s": 1214, "text": "@array = (1,2,3);\nprint \"Size: \",scalar @array,\"\\n\";" }, { "code": null, "e": 1483, "s": 1267, "text": "The value returned will always be the physical size of the array, not the number of valid elements. You can demonstrate this, and the difference between scalar @array and $#array, using this fragment is as follows −" }, { "code": null, "e": 1494, "s": 1483, "text": " Live Demo" }, { "code": null, "e": 1639, "s": 1494, "text": "#!/usr/bin/perl\n@array = (1,2,3);\n$array[50] = 4;\n$size = @array;\n$max_index = $#array;\n\nprint \"Size: $size\\n\";\nprint \"Max Index: $max_index\\n\";" }, { "code": null, "e": 1680, "s": 1639, "text": "This will produce the following result −" }, { "code": null, "e": 1703, "s": 1680, "text": "Size: 51\nMax Index: 50" }, { "code": null, "e": 1837, "s": 1703, "text": "There are only four elements in the array that contains information, but the array is 51 elements long, with the highest index of 50." } ]
Yii - Installation
The most straightforward way to get started with Yii2 is to use the basic application template provided by the Yii2 team. This template is also available through the Composer tool. Step 1 − Find a suitable directory in your hard drive and download the Composer PHAR (PHP archive) via the following command. curl -sS https://getcomposer.org/installer | php Step 2 − Then move this archive to the bin directory. mv composer.phar /usr/local/bin/composer Step 3 − With the Composer installed, you can install Yii2 basic application template. Run these commands. composer global require "fxp/composer-asset-plugin:~1.1.1" composer create-project --prefer-dist yiisoft/yii2-app-basic helloworld The first command installs the composer asset plugin, which manages npm and bower dependencies. The second command installs Yii2 basic application template in a directory called helloworld. Step 4 − Now open the helloworld directory and launch the web server built into PHP. php -S localhost:8080 -t web Step 5 − Then open http://localhost:8080 in your browser. You can see the welcome page. Print Add Notes Bookmark this page
[ { "code": null, "e": 3014, "s": 2833, "text": "The most straightforward way to get started with Yii2 is to use the basic application template provided by the Yii2 team. This template is also available through the Composer tool." }, { "code": null, "e": 3140, "s": 3014, "text": "Step 1 − Find a suitable directory in your hard drive and download the Composer PHAR (PHP archive) via the following command." }, { "code": null, "e": 3190, "s": 3140, "text": "curl -sS https://getcomposer.org/installer | php\n" }, { "code": null, "e": 3244, "s": 3190, "text": "Step 2 − Then move this archive to the bin directory." }, { "code": null, "e": 3286, "s": 3244, "text": "mv composer.phar /usr/local/bin/composer\n" }, { "code": null, "e": 3393, "s": 3286, "text": "Step 3 − With the Composer installed, you can install Yii2 basic application template. Run these commands." }, { "code": null, "e": 3527, "s": 3393, "text": "composer global require \"fxp/composer-asset-plugin:~1.1.1\" \ncomposer create-project --prefer-dist yiisoft/yii2-app-basic helloworld \n" }, { "code": null, "e": 3717, "s": 3527, "text": "The first command installs the composer asset plugin, which manages npm and bower dependencies. The second command installs Yii2 basic application template in a directory called helloworld." }, { "code": null, "e": 3802, "s": 3717, "text": "Step 4 − Now open the helloworld directory and launch the web server built into PHP." }, { "code": null, "e": 3832, "s": 3802, "text": "php -S localhost:8080 -t web\n" }, { "code": null, "e": 3920, "s": 3832, "text": "Step 5 − Then open http://localhost:8080 in your browser. You can see the welcome page." }, { "code": null, "e": 3927, "s": 3920, "text": " Print" }, { "code": null, "e": 3938, "s": 3927, "text": " Add Notes" } ]
Make all column names lower case in MySQL with a single query
Let us first create a − mysql> create table DemoTable1 -> ( -> StudentFirstName varchar(20), -> StudentLastName varchar(20), -> StudentAge int, -> StudentCountryName varchar(20) -> ); Query OK, 0 rows affected (4.20 sec) Let us now make all column names lower case in MySQL − mysql> select concat('alter table ', table_name, ' change `', column_name, '` `', -> lower(column_name), '` ', column_type, ';') -> from information_schema.columns where table_schema = 'demo'; This will produce the following output − +-----------------------------------------------------------------------------------------------------------------+ | concat('alter table ', table_name, ' change `', column_name, '` `', lower(column_name), '` ', column_type, ';') | +-----------------------------------------------------------------------------------------------------------------+ | alter table demotable1 change `StudentFirstName` `studentfirstname` varchar(20); | | alter table demotable1 change `StudentLastName` `studentlastname` varchar(20); | | alter table demotable1 change `StudentAge` `studentage` int(11); | | alter table demotable1 change `StudentCountryName` `studentcountryname` varchar(20); | | alter table mytable change `MyEuroColumn` `myeurocolumn` varchar(5); | +-----------------------------------------------------------------------------------------------------------------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1086, "s": 1062, "text": "Let us first create a −" }, { "code": null, "e": 1301, "s": 1086, "text": "mysql> create table DemoTable1\n -> (\n -> StudentFirstName varchar(20),\n -> StudentLastName varchar(20),\n -> StudentAge int,\n -> StudentCountryName varchar(20)\n -> );\nQuery OK, 0 rows affected (4.20 sec)" }, { "code": null, "e": 1356, "s": 1301, "text": "Let us now make all column names lower case in MySQL −" }, { "code": null, "e": 1556, "s": 1356, "text": "mysql> select concat('alter table ', table_name, ' change `', column_name, '` `',\n -> lower(column_name), '` ', column_type, ';')\n -> from information_schema.columns where table_schema = 'demo';" }, { "code": null, "e": 1597, "s": 1556, "text": "This will produce the following output −" }, { "code": null, "e": 2666, "s": 1597, "text": "+-----------------------------------------------------------------------------------------------------------------+\n| concat('alter table ', table_name, ' change `', column_name, '` `', lower(column_name), '` ', column_type, ';') |\n+-----------------------------------------------------------------------------------------------------------------+\n| alter table demotable1 change `StudentFirstName` `studentfirstname` varchar(20); |\n| alter table demotable1 change `StudentLastName` `studentlastname` varchar(20); |\n| alter table demotable1 change `StudentAge` `studentage` int(11); |\n| alter table demotable1 change `StudentCountryName` `studentcountryname` varchar(20); |\n| alter table mytable change `MyEuroColumn` `myeurocolumn` varchar(5); |\n+-----------------------------------------------------------------------------------------------------------------+\n5 rows in set (0.00 sec)" } ]
How to add the entry in the windows host file using PowerShell?
To add the content to the host file, we need to first retrieve the content using the Get-Content command and the need to set the content to the host file after adding the entry. The Code is shown below. We need to add the global entry to it. $file = "C:\Windows\System32\drivers\etc\hosts" $hostfile = Get-Content $file $hostfile += "8.8.8.8 Google.com" Set-Content -Path $file -Value $hostfile -Force Once you check the host file entry "8.8.8.8 Google.com" will be added to the host file. To add the entry on the remote computer, you just need to point that file location to the host file of the remote server and the rest of the content will be the same. $file = \\Comptuter1\C$\Windows\System32\drivers\etc\hosts $hostfile = Get-Content $file $hostfile += "8.8.8.8 Google.com" Set-Content -Path $file -Value $hostfile -Force
[ { "code": null, "e": 1429, "s": 1187, "text": "To add the content to the host file, we need to first retrieve the content using the Get-Content command and the need to set the content to the host file after adding the entry. The Code is shown below. We need to add the global entry to it." }, { "code": null, "e": 1591, "s": 1429, "text": "$file = \"C:\\Windows\\System32\\drivers\\etc\\hosts\"\n$hostfile = Get-Content $file\n$hostfile += \"8.8.8.8 Google.com\"\nSet-Content -Path $file -Value $hostfile -Force" }, { "code": null, "e": 1689, "s": 1591, "text": "Once you check the host file entry \"8.8.8.8 Google.com\" will be added to the host file." }, { "code": null, "e": 1856, "s": 1689, "text": "To add the entry on the remote computer, you just need to point that file location to the host file of the remote server and the rest of the content will be the same." }, { "code": null, "e": 2029, "s": 1856, "text": "$file = \\\\Comptuter1\\C$\\Windows\\System32\\drivers\\etc\\hosts\n$hostfile = Get-Content $file\n$hostfile += \"8.8.8.8 Google.com\"\nSet-Content -Path $file -Value $hostfile -Force" } ]
Program to calculate area of a parallelogram
05 Apr, 2021 Given integers A and B denoting the length of sides of a parallelogram and Y that is the angle between the sides and length of diagonals D1 and D2 of the parallelogram and an angle 0 at the intersection of the diagonal, the task is to find the area of the parallelogram from the information provided. A parallelogram is a type of quadrilateral that has equal and parallel opposite sides and angle between them is not right angle. Examples: Input: A = 6, B = 10, 0 = 30Output: 18.48Explanation:For the given sides 6 and 10 and for the angle 30 degree the area of parallelogram will be 18.48. Input: A = 3, B = 5, Y = 45Output: 10.61Explanation:For the given sides 3 and 5 and for the angle 45 degree the length of diagonal will be 10.61. Input: D1 = 3, D2 = 5, 0 = 90Output: 7.5Explanation:For the given diagonals 3 and 5 and for the angle 90 degree the area of parallelogram will be 7.5. Approach: The area of the parallelogram can be calculated by the following three formulas: From given sides A and B and the angle between the diagonals, the area of the parallelogram can be calculated by the following formula: Area of Parallelogram for sides and angle between diagonals = ((A2 – B2) * tan 0) / 2 From given sides A and B and the angle between the sides, the area of the parallelogram is can be calculated by the following formula: Area of Parallelogram for sides and angle between sides = A * B * sin Y From the given length of diagonals D1 and D2 and the angle between them, the area of the parallelogram can be calculated by the following formula: Area of Parallelogram for diagonals and angle between diagonals = (D1 * D2 * sin 0)/2 Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the// above approach#include <bits/stdc++.h>using namespace std; double toRadians(int degree){ double pi = 3.14159265359; return ((double)degree * (pi / 180));} // Function to return the area of// parallelogram using sides and// angle at the intersection of diagonaldouble Area_Parallelogram1(int a, int b, int theta){ // Calculate area of parallelogram double area = (abs(tan(toRadians(theta))) / 2) * abs(a * a - b * b); // Return the answer return area;} // Function to return the area of// parallelogram using sides and// angle at the intersection of sidesdouble Area_Parallelogram2(int a, int b, int gamma){ // Calculate area of parallelogram double area = (abs(sin(toRadians(gamma)))) * abs(a * b); // Return the answer return area;} // Function to return the area of// parallelogram using diagonals and// angle at the intersection of diagonalsstatic double Area_Parallelogram3(int d1, int d2, int theta){ // Calculate area of parallelogram double area = (abs(sin(toRadians(theta))) / 2) * abs(d1 * d2); // Return the answer return area;} // Driver Codeint main(){ // Given diagonal and angle int d1 = 3; int d2 = 5; int theta = 90; // Function call double area = Area_Parallelogram3(d1, d2, theta); // Print the area printf("%.2f", area);} // This code is contributed by rutvik_56 // Java program for above approachimport java.io.*; class GFG{ // Function to return the area of// parallelogram using sides and// angle at the intersection of diagonalstatic double Area_Parallelogram1(int a, int b, int theta){ // Calculate area of parallelogram double area = (Math.abs(Math.tan( Math.toRadians(theta))) / 2) * Math.abs(a * a - b * b); // Return the answer return area;} // Function to return the area of// parallelogram using sides and// angle at the intersection of sidesstatic double Area_Parallelogram2(int a, int b, int gamma){ // Calculate area of parallelogram double area = (Math.abs(Math.sin( Math.toRadians(gamma)))) * Math.abs(a * b); // Return the answer return area;} // Function to return the area of// parallelogram using diagonals and// angle at the intersection of diagonalsstatic double Area_Parallelogram3(int d1, int d2, int theta){ // Calculate area of parallelogram double area = (Math.abs(Math.sin( Math.toRadians(theta))) / 2) * Math.abs(d1 * d2); // Return the answer return area;} // Driver codepublic static void main (String[] args){ // Given diagonal and angle int d1 = 3; int d2 = 5; int theta = 90; // Function call double area = Area_Parallelogram3( d1, d2, theta); // Print the area System.out.format("%.2f", area);}} // This code is contributed by offbeat # Python3 program for the above approach import math # Function to return the area of# parallelogram using sides and# angle at the intersection of diagonaldef Area_Parallelogram1(a, b, theta): # Calculate area of parallelogram area = (abs(math.tan(math.radians(theta)))/2) \ * abs(a**2 - b**2) # Return the answer return area # Function to return the area of# parallelogram using sides and# angle at the intersection of sidesdef Area_Parallelogram2(a, b, gamma): # Calculate area of parallelogram area = (abs(math.sin(math.radians(gamma)))) \ * abs(a * b) # Return the answer return area # Function to return the area of# parallelogram using diagonals and# angle at the intersection of diagonalsdef Area_Parallelogram3(d1, d2, theta): # Calculate area of parallelogram area = (abs(math.sin(math.radians(theta)))/2) \ * abs(d1 * d2) # Return the answer return area # Driver Code # Given diagonal and angled1 = 3d2 = 5theta = 90 # Function Callarea = Area_Parallelogram3(d1, d2, theta)# Print the areaprint(round(area, 2)) // C# program for// the above approachusing System;class GFG{ // Function to return the area of// parallelogram using sides and// angle at the intersection of diagonalstatic double Area_Parallelogram1(int a, int b, int theta){ // Calculate area of parallelogram double area = (Math.Abs(Math.Tan((theta * Math.PI) / 180)) / 2) * Math.Abs(a * a - b * b); // Return the answer return area;} // Function to return the area of// parallelogram using sides and// angle at the intersection of sidesstatic double Area_Parallelogram2(int a, int b, int gamma){ // Calculate area of parallelogram double area = (Math.Abs(Math.Sin((gamma * Math.PI) / 180))) * Math.Abs(a * b); // Return the answer return area;} // Function to return the area of// parallelogram using diagonals and// angle at the intersection of diagonalsstatic double Area_Parallelogram3(int d1, int d2, int theta){ // Calculate area of parallelogram double area = (Math.Abs(Math.Sin((theta * Math.PI) / 180)) / 2) * Math.Abs(d1 * d2); // Return the answer return area;} // Driver codepublic static void Main(String[] args){ // Given diagonal and angle int d1 = 3; int d2 = 5; int theta = 90; // Function call double area = Area_Parallelogram3(d1, d2, theta); // Print the area Console.Write("{0:F2}", area);}} // This code is contributed by Rajput-Ji <script> // Javascript program for the// above approachfunction toRadians(degree){ let pi = 3.14159265359; return (degree * (pi / 180));} // Function to return the area of// parallelogram using sides and// angle at the intersection of diagonalfunction Area_Parallelogram1(a, b, theta){ // Calculate area of parallelogram let area = (Math.abs(Math.tan(toRadians(theta))) / 2) * Math.abs(a * a - b * b); // Return the answer return area;} // Function to return the area of// parallelogram using sides and// angle at the intersection of sidesfunction Area_Parallelogram2(a, b, gamma){ // Calculate area of parallelogram let area = (Math.abs(Math.sin(toRadians(gamma)))) * Math.abs(a * b); // Return the answer return area;} // Function to return the area of// parallelogram using diagonals and// angle at the intersection of diagonalsfunction Area_Parallelogram3(d1, d2, theta){ // Calculate area of parallelogram let area = (Math.abs(Math.sin(toRadians(theta))) / 2) * Math.abs(d1 * d2); // Return the answer return area;} // Driver Code // Given diagonal and anglelet d1 = 3;let d2 = 5;let theta = 90; // Function calllet area = Area_Parallelogram3(d1, d2, theta); // Print the areadocument.write(area); // This code is contributed by Mayank Tyagi </script> 7.5 Time Complexity: O(1)Auxiliary Space: O(1) offbeat Rajput-Ji rutvik_56 mayanktyagi1709 Geometric-Lines Maths Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum Manhattan distance between a distinct pair from N coordinates Total area of two overlapping rectangles Largest area possible after removal of a series of horizontal & vertical bars Program to find line passing through 2 Points Orientation of 3 ordered points Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Apr, 2021" }, { "code": null, "e": 329, "s": 28, "text": "Given integers A and B denoting the length of sides of a parallelogram and Y that is the angle between the sides and length of diagonals D1 and D2 of the parallelogram and an angle 0 at the intersection of the diagonal, the task is to find the area of the parallelogram from the information provided." }, { "code": null, "e": 458, "s": 329, "text": "A parallelogram is a type of quadrilateral that has equal and parallel opposite sides and angle between them is not right angle." }, { "code": null, "e": 468, "s": 458, "text": "Examples:" }, { "code": null, "e": 619, "s": 468, "text": "Input: A = 6, B = 10, 0 = 30Output: 18.48Explanation:For the given sides 6 and 10 and for the angle 30 degree the area of parallelogram will be 18.48." }, { "code": null, "e": 765, "s": 619, "text": "Input: A = 3, B = 5, Y = 45Output: 10.61Explanation:For the given sides 3 and 5 and for the angle 45 degree the length of diagonal will be 10.61." }, { "code": null, "e": 916, "s": 765, "text": "Input: D1 = 3, D2 = 5, 0 = 90Output: 7.5Explanation:For the given diagonals 3 and 5 and for the angle 90 degree the area of parallelogram will be 7.5." }, { "code": null, "e": 1007, "s": 916, "text": "Approach: The area of the parallelogram can be calculated by the following three formulas:" }, { "code": null, "e": 1143, "s": 1007, "text": "From given sides A and B and the angle between the diagonals, the area of the parallelogram can be calculated by the following formula:" }, { "code": null, "e": 1230, "s": 1143, "text": " Area of Parallelogram for sides and angle between diagonals = ((A2 – B2) * tan 0) / 2" }, { "code": null, "e": 1367, "s": 1230, "text": "From given sides A and B and the angle between the sides, the area of the parallelogram is can be calculated by the following formula: " }, { "code": null, "e": 1440, "s": 1367, "text": "Area of Parallelogram for sides and angle between sides = A * B * sin Y " }, { "code": null, "e": 1589, "s": 1440, "text": "From the given length of diagonals D1 and D2 and the angle between them, the area of the parallelogram can be calculated by the following formula: " }, { "code": null, "e": 1675, "s": 1589, "text": "Area of Parallelogram for diagonals and angle between diagonals = (D1 * D2 * sin 0)/2" }, { "code": null, "e": 1726, "s": 1675, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1730, "s": 1726, "text": "C++" }, { "code": null, "e": 1735, "s": 1730, "text": "Java" }, { "code": null, "e": 1743, "s": 1735, "text": "Python3" }, { "code": null, "e": 1746, "s": 1743, "text": "C#" }, { "code": null, "e": 1757, "s": 1746, "text": "Javascript" }, { "code": "// C++ program for the// above approach#include <bits/stdc++.h>using namespace std; double toRadians(int degree){ double pi = 3.14159265359; return ((double)degree * (pi / 180));} // Function to return the area of// parallelogram using sides and// angle at the intersection of diagonaldouble Area_Parallelogram1(int a, int b, int theta){ // Calculate area of parallelogram double area = (abs(tan(toRadians(theta))) / 2) * abs(a * a - b * b); // Return the answer return area;} // Function to return the area of// parallelogram using sides and// angle at the intersection of sidesdouble Area_Parallelogram2(int a, int b, int gamma){ // Calculate area of parallelogram double area = (abs(sin(toRadians(gamma)))) * abs(a * b); // Return the answer return area;} // Function to return the area of// parallelogram using diagonals and// angle at the intersection of diagonalsstatic double Area_Parallelogram3(int d1, int d2, int theta){ // Calculate area of parallelogram double area = (abs(sin(toRadians(theta))) / 2) * abs(d1 * d2); // Return the answer return area;} // Driver Codeint main(){ // Given diagonal and angle int d1 = 3; int d2 = 5; int theta = 90; // Function call double area = Area_Parallelogram3(d1, d2, theta); // Print the area printf(\"%.2f\", area);} // This code is contributed by rutvik_56", "e": 3321, "s": 1757, "text": null }, { "code": "// Java program for above approachimport java.io.*; class GFG{ // Function to return the area of// parallelogram using sides and// angle at the intersection of diagonalstatic double Area_Parallelogram1(int a, int b, int theta){ // Calculate area of parallelogram double area = (Math.abs(Math.tan( Math.toRadians(theta))) / 2) * Math.abs(a * a - b * b); // Return the answer return area;} // Function to return the area of// parallelogram using sides and// angle at the intersection of sidesstatic double Area_Parallelogram2(int a, int b, int gamma){ // Calculate area of parallelogram double area = (Math.abs(Math.sin( Math.toRadians(gamma)))) * Math.abs(a * b); // Return the answer return area;} // Function to return the area of// parallelogram using diagonals and// angle at the intersection of diagonalsstatic double Area_Parallelogram3(int d1, int d2, int theta){ // Calculate area of parallelogram double area = (Math.abs(Math.sin( Math.toRadians(theta))) / 2) * Math.abs(d1 * d2); // Return the answer return area;} // Driver codepublic static void main (String[] args){ // Given diagonal and angle int d1 = 3; int d2 = 5; int theta = 90; // Function call double area = Area_Parallelogram3( d1, d2, theta); // Print the area System.out.format(\"%.2f\", area);}} // This code is contributed by offbeat", "e": 4941, "s": 3321, "text": null }, { "code": "# Python3 program for the above approach import math # Function to return the area of# parallelogram using sides and# angle at the intersection of diagonaldef Area_Parallelogram1(a, b, theta): # Calculate area of parallelogram area = (abs(math.tan(math.radians(theta)))/2) \\ * abs(a**2 - b**2) # Return the answer return area # Function to return the area of# parallelogram using sides and# angle at the intersection of sidesdef Area_Parallelogram2(a, b, gamma): # Calculate area of parallelogram area = (abs(math.sin(math.radians(gamma)))) \\ * abs(a * b) # Return the answer return area # Function to return the area of# parallelogram using diagonals and# angle at the intersection of diagonalsdef Area_Parallelogram3(d1, d2, theta): # Calculate area of parallelogram area = (abs(math.sin(math.radians(theta)))/2) \\ * abs(d1 * d2) # Return the answer return area # Driver Code # Given diagonal and angled1 = 3d2 = 5theta = 90 # Function Callarea = Area_Parallelogram3(d1, d2, theta)# Print the areaprint(round(area, 2))", "e": 6037, "s": 4941, "text": null }, { "code": "// C# program for// the above approachusing System;class GFG{ // Function to return the area of// parallelogram using sides and// angle at the intersection of diagonalstatic double Area_Parallelogram1(int a, int b, int theta){ // Calculate area of parallelogram double area = (Math.Abs(Math.Tan((theta * Math.PI) / 180)) / 2) * Math.Abs(a * a - b * b); // Return the answer return area;} // Function to return the area of// parallelogram using sides and// angle at the intersection of sidesstatic double Area_Parallelogram2(int a, int b, int gamma){ // Calculate area of parallelogram double area = (Math.Abs(Math.Sin((gamma * Math.PI) / 180))) * Math.Abs(a * b); // Return the answer return area;} // Function to return the area of// parallelogram using diagonals and// angle at the intersection of diagonalsstatic double Area_Parallelogram3(int d1, int d2, int theta){ // Calculate area of parallelogram double area = (Math.Abs(Math.Sin((theta * Math.PI) / 180)) / 2) * Math.Abs(d1 * d2); // Return the answer return area;} // Driver codepublic static void Main(String[] args){ // Given diagonal and angle int d1 = 3; int d2 = 5; int theta = 90; // Function call double area = Area_Parallelogram3(d1, d2, theta); // Print the area Console.Write(\"{0:F2}\", area);}} // This code is contributed by Rajput-Ji", "e": 7597, "s": 6037, "text": null }, { "code": "<script> // Javascript program for the// above approachfunction toRadians(degree){ let pi = 3.14159265359; return (degree * (pi / 180));} // Function to return the area of// parallelogram using sides and// angle at the intersection of diagonalfunction Area_Parallelogram1(a, b, theta){ // Calculate area of parallelogram let area = (Math.abs(Math.tan(toRadians(theta))) / 2) * Math.abs(a * a - b * b); // Return the answer return area;} // Function to return the area of// parallelogram using sides and// angle at the intersection of sidesfunction Area_Parallelogram2(a, b, gamma){ // Calculate area of parallelogram let area = (Math.abs(Math.sin(toRadians(gamma)))) * Math.abs(a * b); // Return the answer return area;} // Function to return the area of// parallelogram using diagonals and// angle at the intersection of diagonalsfunction Area_Parallelogram3(d1, d2, theta){ // Calculate area of parallelogram let area = (Math.abs(Math.sin(toRadians(theta))) / 2) * Math.abs(d1 * d2); // Return the answer return area;} // Driver Code // Given diagonal and anglelet d1 = 3;let d2 = 5;let theta = 90; // Function calllet area = Area_Parallelogram3(d1, d2, theta); // Print the areadocument.write(area); // This code is contributed by Mayank Tyagi </script>", "e": 9109, "s": 7597, "text": null }, { "code": null, "e": 9113, "s": 9109, "text": "7.5" }, { "code": null, "e": 9158, "s": 9115, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 9166, "s": 9158, "text": "offbeat" }, { "code": null, "e": 9176, "s": 9166, "text": "Rajput-Ji" }, { "code": null, "e": 9186, "s": 9176, "text": "rutvik_56" }, { "code": null, "e": 9202, "s": 9186, "text": "mayanktyagi1709" }, { "code": null, "e": 9218, "s": 9202, "text": "Geometric-Lines" }, { "code": null, "e": 9224, "s": 9218, "text": "Maths" }, { "code": null, "e": 9234, "s": 9224, "text": "Geometric" }, { "code": null, "e": 9247, "s": 9234, "text": "Mathematical" }, { "code": null, "e": 9260, "s": 9247, "text": "Mathematical" }, { "code": null, "e": 9270, "s": 9260, "text": "Geometric" }, { "code": null, "e": 9368, "s": 9270, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9438, "s": 9368, "text": "Maximum Manhattan distance between a distinct pair from N coordinates" }, { "code": null, "e": 9479, "s": 9438, "text": "Total area of two overlapping rectangles" }, { "code": null, "e": 9557, "s": 9479, "text": "Largest area possible after removal of a series of horizontal & vertical bars" }, { "code": null, "e": 9603, "s": 9557, "text": "Program to find line passing through 2 Points" }, { "code": null, "e": 9635, "s": 9603, "text": "Orientation of 3 ordered points" }, { "code": null, "e": 9665, "s": 9635, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 9708, "s": 9665, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 9768, "s": 9708, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 9783, "s": 9768, "text": "C++ Data Types" } ]
Python | numpy.datetime64() method
05 Sep, 2019 With the help of numpy.datetime64() method, we can get the date in a numpy array in a particular format i.e year-month-day by using numpy.datetime64() method. Syntax : numpy.datetime64(date)Return : Return the date in a format ‘yyyy-mm-dd’. Example #1 :In this example we can see that by using numpy.datetime64() method, we are able to get the date in the particular format i.e yyyy-mm-dd. # import numpyimport numpy as np # using numpy.datetime64() methodgfg = np.array(np.datetime64('2019-08-26')) print(gfg) Output : array(‘2019-08-26′, dtype=’datetime64[D]’) Example #2 : # import numpyimport numpy as np # using numpy.datetime64() methodgfg = np.array(np.datetime64('2019-08', 'D')) print(gfg) Output : array(‘2019-08-01′, dtype=’datetime64[D]’) Python numpy-DataType Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Sep, 2019" }, { "code": null, "e": 187, "s": 28, "text": "With the help of numpy.datetime64() method, we can get the date in a numpy array in a particular format i.e year-month-day by using numpy.datetime64() method." }, { "code": null, "e": 269, "s": 187, "text": "Syntax : numpy.datetime64(date)Return : Return the date in a format ‘yyyy-mm-dd’." }, { "code": null, "e": 418, "s": 269, "text": "Example #1 :In this example we can see that by using numpy.datetime64() method, we are able to get the date in the particular format i.e yyyy-mm-dd." }, { "code": "# import numpyimport numpy as np # using numpy.datetime64() methodgfg = np.array(np.datetime64('2019-08-26')) print(gfg)", "e": 541, "s": 418, "text": null }, { "code": null, "e": 550, "s": 541, "text": "Output :" }, { "code": null, "e": 593, "s": 550, "text": "array(‘2019-08-26′, dtype=’datetime64[D]’)" }, { "code": null, "e": 606, "s": 593, "text": "Example #2 :" }, { "code": "# import numpyimport numpy as np # using numpy.datetime64() methodgfg = np.array(np.datetime64('2019-08', 'D')) print(gfg)", "e": 731, "s": 606, "text": null }, { "code": null, "e": 740, "s": 731, "text": "Output :" }, { "code": null, "e": 783, "s": 740, "text": "array(‘2019-08-01′, dtype=’datetime64[D]’)" }, { "code": null, "e": 805, "s": 783, "text": "Python numpy-DataType" }, { "code": null, "e": 812, "s": 805, "text": "Python" }, { "code": null, "e": 910, "s": 812, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 928, "s": 910, "text": "Python Dictionary" }, { "code": null, "e": 970, "s": 928, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 992, "s": 970, "text": "Enumerate() in Python" }, { "code": null, "e": 1027, "s": 992, "text": "Read a file line by line in Python" }, { "code": null, "e": 1053, "s": 1027, "text": "Python String | replace()" }, { "code": null, "e": 1085, "s": 1053, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1114, "s": 1085, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1141, "s": 1114, "text": "Python Classes and Objects" }, { "code": null, "e": 1162, "s": 1141, "text": "Python OOPs Concepts" } ]
Inserting m into n such that m starts at bit j and ends at bit i.
31 May, 2021 We are given two numbers n and m, and two-bit positions, i and j. Insert bits of m into n starting from j to i. We can assume that the bits j through i have enough space to fit all of m. That is, if m = 10011, you can assume that there are at least 5 bits between j and i. You would not, for example, have j = 3 and i = 2, because m could not fully fit between bit 3 and bit 2. Examples : Input : n = 1024 m = 19 i = 2 j = 6; Output : n = 1100 Binary representations of input numbers m in binary is (10011)2 n in binary is (10000000000)2 Binary representations of output number (10000000000)2 Input : n = 5 m = 3 i = 1 j = 2 Output : 7 Algorithm : 1. Clear the bits j through i in n 2. Shift m so that it lines up with bits j through i 3. Return Bitwise AND of m and n. The trickiest part is Step 1. How do we clear the bits in n? We can do this with a mask. This mask will have all 1s, except for 0s in the bits j through i. We create this mask by creating the left half of the mask first, and then the right half. Following is the implementation of the above approach. C++ Java Python3 C# PHP Javascript // C++ program for implementation of updateBits()#include <bits/stdc++.h>using namespace std; // Function to updateBits M insert to N.int updateBits(int n, int m, int i, int j){ /* Create a mask to clear bits i through j in n. EXAMPLE: i = 2, j = 4. Result should be 11100011. For simplicity, we'll use just 8 bits for the example. */ int allOnes = ~0; // will equal sequence of all ls // ls before position j, then 0s. left = 11100000 int left= allOnes << (j + 1); // l's after position i. right = 00000011 int right = ((1 << i) - 1); // All ls, except for 0s between i and j. mask 11100011 int mask = left | right; /* Clear bits j through i then put min there */ int n_cleared = n & mask; // Clear bits j through i. int m_shifted = m << i; // Move m into correct position. return (n_cleared | m_shifted); // OR them, and we're done!} // Driver Codeint main(){ int n = 1024; // in Binary N= 10000000000 int m = 19; // in Binary M= 10011 int i = 2, j = 6; cout << updateBits(n,m,i,j); return 0;} // Java program for implementation of updateBits() class UpdateBits{ // Function to updateBits M insert to N. static int updateBits(int n, int m, int i, int j) { /* Create a mask to clear bits i through j in n. EXAMPLE: i = 2, j = 4. Result should be 11100011. For simplicity, we'll use just 8 bits for the example. */ int allOnes = ~0; // will equal sequence of all ls // ls before position j, then 0s. left = 11100000 int left= allOnes << (j + 1); // l's after position i. right = 00000011 int right = ((1 << i) - 1); // All ls, except for 0s between i and j. mask 11100011 int mask = left | right; /* Clear bits j through i then put min there */ // Clear bits j through i. int n_cleared = n & mask; // Move m into correct position. int m_shifted = m << i; // OR them, and we're done! return (n_cleared | m_shifted); } public static void main (String[] args) { // in Binary N= 10000000000 int n = 1024; // in Binary M= 10011 int m = 19; int i = 2, j = 6; System.out.println(updateBits(n,m,i,j)); }} # Python3 program for implementation# of updateBits() # Function to updateBits M insert to N.def updateBits(n, m, i, j): # Create a mask to clear bits i through # j in n. EXAMPLE: i = 2, j = 4. Result # should be 11100011. For simplicity, # we'll use just 8 bits for the example. # will equal sequence of all ls allOnes = ~0 # ls before position j, # then 0s. left = 11100000 left = allOnes << (j + 1) # l's after position i. right = 00000011 right = ((1 << i) - 1) # All ls, except for 0s between # i and j. mask 11100011 mask = left | right # Clear bits j through i then put min there n_cleared = n & mask # Move m into correct position. m_shifted = m << i return (n_cleared | m_shifted) # Driver Coden = 1024 # in Binary N = 10000000000m = 19 # in Binary M = 10011i = 2; j = 6print(updateBits(n, m, i, j)) # This code is contributed by Anant Agarwal. // C# program for implementation of// updateBits()using System; class GFG { // Function to updateBits M // insert to N. static int updateBits(int n, int m, int i, int j) { /* Create a mask to clear bits i through j in n. EXAMPLE: i = 2, j = 4. Result should be 11100011. For simplicity, we'll use just 8 bits for the example. */ // will equal sequence of all ls int allOnes = ~0; // ls before position j, then 0s. // left = 11100000 int left= allOnes << (j + 1); // l's after position i. // right = 00000011 int right = ((1 << i) - 1); // All ls, except for 0s between i // and j. mask 11100011 int mask = left | right; /* Clear bits j through i then put min there */ // Clear bits j through i. int n_cleared = n & mask; // Move m into correct position. int m_shifted = m << i; // OR them, and we're done! return (n_cleared | m_shifted); } public static void Main() { // in Binary N= 10000000000 int n = 1024; // in Binary M= 10011 int m = 19; int i = 2, j = 6; Console.WriteLine(updateBits(n, m, i, j)); }} //This code is contributed by Anant Agarwal. <?php// PHP program for implementation// of updateBits() // Function to updateBits// M insert to N. function updateBits($n, $m, $i, $j){ // Create a mask to clear // bits i through j in n. // EXAMPLE: i = 2, j = 4. // Result should be 11100011. // For simplicity, we'll use // just 8 bits for the example. // will equal sequence of all ls $allOnes = ~0; // ls before position j, then // 0s. left = 11100000 $left= $allOnes << ($j + 1); // l's after position i. // right = 00000011 $right = ((1 << $i) - 1); // All ls, except for 0s between // i and j. mask 11100011 $mask = $left | $right; // Clear bits j through i // then put min there // Clear bits j through i. $n_cleared = $n & $mask; // Move m into correct position. $m_shifted = $m << $i; // OR them, and we're done! return ($n_cleared | $m_shifted);} // Driver Code // in Binary N= 10000000000$n = 1024; // in Binary M= 10011$m = 19;$i = 2;$j = 6; echo updateBits($n, $m, $i, $j); // This code is contributed by Ajit?> <script> // JavaScript program for implementation of updateBits() // Function to updateBits M insert to N. function updateBits(n,m,i,j) { /* Create a mask to clear bits i through j in n. EXAMPLE: i = 2, j = 4. Result should be 11100011. For simplicity, we'll use just 8 bits for the example. */ let allOnes = ~0; // will equal sequence of all ls // ls before position j, then 0s. left = 11100000 let left= allOnes << (j + 1); // l's after position i. right = 00000011 let right = ((1 << i) - 1); // All ls, except for 0s between i and j. mask 11100011 let mask = left | right; /* Clear bits j through i then put min there */ // Clear bits j through i. let n_cleared = n & mask; // Move m into correct position. let m_shifted = m << i; // OR them, and we're done! return (n_cleared | m_shifted); } // in Binary N= 10000000000 let n = 1024; // in Binary M= 10011 let m = 19; let i = 2, j = 6; document.write(updateBits(n,m,i,j)); // This code is contributed by sravan </script> Output: 1100 // in Binary (10001001100)2 This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t sravankumar8128 Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to find whether a given number is power of 2 Little and Big Endian Mystery Bits manipulation (Important tactics) Binary representation of a given number Josephus problem | Set 1 (A O(n) Solution) Divide two integers without using multiplication, division and mod operator Bit Fields in C Find the element that appears once Add two numbers without using arithmetic operators C++ bitset and its application
[ { "code": null, "e": 52, "s": 24, "text": "\n31 May, 2021" }, { "code": null, "e": 443, "s": 52, "text": "We are given two numbers n and m, and two-bit positions, i and j. Insert bits of m into n starting from j to i. We can assume that the bits j through i have enough space to fit all of m. That is, if m = 10011, you can assume that there are at least 5 bits between j and i. You would not, for example, have j = 3 and i = 2, because m could not fully fit between bit 3 and bit 2. Examples : " }, { "code": null, "e": 739, "s": 443, "text": "Input : n = 1024\n m = 19\n i = 2\n j = 6;\nOutput : n = 1100\nBinary representations of input numbers\nm in binary is (10011)2\nn in binary is (10000000000)2\nBinary representations of output number\n(10000000000)2\n\nInput : n = 5\n m = 3\n i = 1\n j = 2\nOutput : 7" }, { "code": null, "e": 755, "s": 741, "text": "Algorithm : " }, { "code": null, "e": 882, "s": 755, "text": "1. Clear the bits j through i in n \n\n2. Shift m so that it lines up with bits j through i \n\n3. Return Bitwise AND of m and n. " }, { "code": null, "e": 1184, "s": 882, "text": "The trickiest part is Step 1. How do we clear the bits in n? We can do this with a mask. This mask will have all 1s, except for 0s in the bits j through i. We create this mask by creating the left half of the mask first, and then the right half. Following is the implementation of the above approach. " }, { "code": null, "e": 1188, "s": 1184, "text": "C++" }, { "code": null, "e": 1193, "s": 1188, "text": "Java" }, { "code": null, "e": 1201, "s": 1193, "text": "Python3" }, { "code": null, "e": 1204, "s": 1201, "text": "C#" }, { "code": null, "e": 1208, "s": 1204, "text": "PHP" }, { "code": null, "e": 1219, "s": 1208, "text": "Javascript" }, { "code": "// C++ program for implementation of updateBits()#include <bits/stdc++.h>using namespace std; // Function to updateBits M insert to N.int updateBits(int n, int m, int i, int j){ /* Create a mask to clear bits i through j in n. EXAMPLE: i = 2, j = 4. Result should be 11100011. For simplicity, we'll use just 8 bits for the example. */ int allOnes = ~0; // will equal sequence of all ls // ls before position j, then 0s. left = 11100000 int left= allOnes << (j + 1); // l's after position i. right = 00000011 int right = ((1 << i) - 1); // All ls, except for 0s between i and j. mask 11100011 int mask = left | right; /* Clear bits j through i then put min there */ int n_cleared = n & mask; // Clear bits j through i. int m_shifted = m << i; // Move m into correct position. return (n_cleared | m_shifted); // OR them, and we're done!} // Driver Codeint main(){ int n = 1024; // in Binary N= 10000000000 int m = 19; // in Binary M= 10011 int i = 2, j = 6; cout << updateBits(n,m,i,j); return 0;}", "e": 2293, "s": 1219, "text": null }, { "code": "// Java program for implementation of updateBits() class UpdateBits{ // Function to updateBits M insert to N. static int updateBits(int n, int m, int i, int j) { /* Create a mask to clear bits i through j in n. EXAMPLE: i = 2, j = 4. Result should be 11100011. For simplicity, we'll use just 8 bits for the example. */ int allOnes = ~0; // will equal sequence of all ls // ls before position j, then 0s. left = 11100000 int left= allOnes << (j + 1); // l's after position i. right = 00000011 int right = ((1 << i) - 1); // All ls, except for 0s between i and j. mask 11100011 int mask = left | right; /* Clear bits j through i then put min there */ // Clear bits j through i. int n_cleared = n & mask; // Move m into correct position. int m_shifted = m << i; // OR them, and we're done! return (n_cleared | m_shifted); } public static void main (String[] args) { // in Binary N= 10000000000 int n = 1024; // in Binary M= 10011 int m = 19; int i = 2, j = 6; System.out.println(updateBits(n,m,i,j)); }}", "e": 3560, "s": 2293, "text": null }, { "code": "# Python3 program for implementation# of updateBits() # Function to updateBits M insert to N.def updateBits(n, m, i, j): # Create a mask to clear bits i through # j in n. EXAMPLE: i = 2, j = 4. Result # should be 11100011. For simplicity, # we'll use just 8 bits for the example. # will equal sequence of all ls allOnes = ~0 # ls before position j, # then 0s. left = 11100000 left = allOnes << (j + 1) # l's after position i. right = 00000011 right = ((1 << i) - 1) # All ls, except for 0s between # i and j. mask 11100011 mask = left | right # Clear bits j through i then put min there n_cleared = n & mask # Move m into correct position. m_shifted = m << i return (n_cleared | m_shifted) # Driver Coden = 1024 # in Binary N = 10000000000m = 19 # in Binary M = 10011i = 2; j = 6print(updateBits(n, m, i, j)) # This code is contributed by Anant Agarwal.", "e": 4486, "s": 3560, "text": null }, { "code": "// C# program for implementation of// updateBits()using System; class GFG { // Function to updateBits M // insert to N. static int updateBits(int n, int m, int i, int j) { /* Create a mask to clear bits i through j in n. EXAMPLE: i = 2, j = 4. Result should be 11100011. For simplicity, we'll use just 8 bits for the example. */ // will equal sequence of all ls int allOnes = ~0; // ls before position j, then 0s. // left = 11100000 int left= allOnes << (j + 1); // l's after position i. // right = 00000011 int right = ((1 << i) - 1); // All ls, except for 0s between i // and j. mask 11100011 int mask = left | right; /* Clear bits j through i then put min there */ // Clear bits j through i. int n_cleared = n & mask; // Move m into correct position. int m_shifted = m << i; // OR them, and we're done! return (n_cleared | m_shifted); } public static void Main() { // in Binary N= 10000000000 int n = 1024; // in Binary M= 10011 int m = 19; int i = 2, j = 6; Console.WriteLine(updateBits(n, m, i, j)); }} //This code is contributed by Anant Agarwal.", "e": 5910, "s": 4486, "text": null }, { "code": "<?php// PHP program for implementation// of updateBits() // Function to updateBits// M insert to N. function updateBits($n, $m, $i, $j){ // Create a mask to clear // bits i through j in n. // EXAMPLE: i = 2, j = 4. // Result should be 11100011. // For simplicity, we'll use // just 8 bits for the example. // will equal sequence of all ls $allOnes = ~0; // ls before position j, then // 0s. left = 11100000 $left= $allOnes << ($j + 1); // l's after position i. // right = 00000011 $right = ((1 << $i) - 1); // All ls, except for 0s between // i and j. mask 11100011 $mask = $left | $right; // Clear bits j through i // then put min there // Clear bits j through i. $n_cleared = $n & $mask; // Move m into correct position. $m_shifted = $m << $i; // OR them, and we're done! return ($n_cleared | $m_shifted);} // Driver Code // in Binary N= 10000000000$n = 1024; // in Binary M= 10011$m = 19;$i = 2;$j = 6; echo updateBits($n, $m, $i, $j); // This code is contributed by Ajit?>", "e": 6978, "s": 5910, "text": null }, { "code": "<script> // JavaScript program for implementation of updateBits() // Function to updateBits M insert to N. function updateBits(n,m,i,j) { /* Create a mask to clear bits i through j in n. EXAMPLE: i = 2, j = 4. Result should be 11100011. For simplicity, we'll use just 8 bits for the example. */ let allOnes = ~0; // will equal sequence of all ls // ls before position j, then 0s. left = 11100000 let left= allOnes << (j + 1); // l's after position i. right = 00000011 let right = ((1 << i) - 1); // All ls, except for 0s between i and j. mask 11100011 let mask = left | right; /* Clear bits j through i then put min there */ // Clear bits j through i. let n_cleared = n & mask; // Move m into correct position. let m_shifted = m << i; // OR them, and we're done! return (n_cleared | m_shifted); } // in Binary N= 10000000000 let n = 1024; // in Binary M= 10011 let m = 19; let i = 2, j = 6; document.write(updateBits(n,m,i,j)); // This code is contributed by sravan </script>", "e": 8208, "s": 6978, "text": null }, { "code": null, "e": 8218, "s": 8208, "text": "Output: " }, { "code": null, "e": 8253, "s": 8218, "text": " 1100 // in Binary (10001001100)2" }, { "code": null, "e": 8679, "s": 8253, "text": "This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 8685, "s": 8679, "text": "jit_t" }, { "code": null, "e": 8701, "s": 8685, "text": "sravankumar8128" }, { "code": null, "e": 8711, "s": 8701, "text": "Bit Magic" }, { "code": null, "e": 8721, "s": 8711, "text": "Bit Magic" }, { "code": null, "e": 8819, "s": 8721, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8872, "s": 8819, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 8902, "s": 8872, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 8940, "s": 8902, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 8980, "s": 8940, "text": "Binary representation of a given number" }, { "code": null, "e": 9023, "s": 8980, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 9099, "s": 9023, "text": "Divide two integers without using multiplication, division and mod operator" }, { "code": null, "e": 9115, "s": 9099, "text": "Bit Fields in C" }, { "code": null, "e": 9150, "s": 9115, "text": "Find the element that appears once" }, { "code": null, "e": 9201, "s": 9150, "text": "Add two numbers without using arithmetic operators" } ]
Double Hashing
Difficulty Level : Medium Double hashing is a collision resolving technique in Open Addressed Hash tables. Double hashing uses the idea of applying a second hash function to key when a collision occurs. Advantages of Double hashing The advantage of Double hashing is that it is one of the best form of probing, producing a uniform distribution of records throughout a hash table. This technique does not yield any clusters. It is one of effective method for resolving collisions. Double hashing can be done using : (hash1(key) + i * hash2(key)) % TABLE_SIZE Here hash1() and hash2() are hash functions and TABLE_SIZE is size of hash table. (We repeat by increasing i when collision occurs) First hash function is typically hash1(key) = key % TABLE_SIZEA popular second hash function is : hash2(key) = PRIME – (key % PRIME) where PRIME is a prime smaller than the TABLE_SIZE.A good second Hash function is: It must never evaluate to zero Must make sure that all cells can be probed CPP /*** Handling of collision via open addressing** Method for Probing: Double Hashing*/ #include <iostream>#include <vector>#include <bitset>using namespace std;#define MAX_SIZE 10000001ll class doubleHash { int TABLE_SIZE, keysPresent, PRIME; vector<int> hashTable; bitset<MAX_SIZE> isPrime; /* Function to set sieve of Eratosthenes. */ void __setSieve(){ isPrime[0] = isPrime[1] = 1; for(long long i = 2; i*i <= MAX_SIZE; i++) if(isPrime[i] == 0) for(long long j = i*i; j <= MAX_SIZE; j += i) isPrime[j] = 1; } int inline hash1(int value){ return value%TABLE_SIZE; } int inline hash2(int value){ return PRIME - (value%PRIME); } bool inline isFull(){ return (TABLE_SIZE == keysPresent); } public: doubleHash(int n){ __setSieve(); TABLE_SIZE = n; /* Find the largest prime number smaller than hash table's size. */ PRIME = TABLE_SIZE - 1; while(isPrime[PRIME] == 1) PRIME--; keysPresent = 0; /* Fill the hash table with -1 (empty entries). */ for(int i = 0; i < TABLE_SIZE; i++) hashTable.push_back(-1); } void __printPrime(long long n){ for(long long i = 0; i <= n; i++) if(isPrime[i] == 0) cout<<i<<", "; cout<<endl; } /* Function to insert value in hash table */ void insert(int value){ if(value == -1 || value == -2){ cout<<("ERROR : -1 and -2 can't be inserted in the table\n"); } if(isFull()){ cout<<("ERROR : Hash Table Full\n"); return; } int probe = hash1(value), offset = hash2(value); // in linear probing offset = 1; while(hashTable[probe] != -1){ if(-2 == hashTable[probe]) break; // insert at deleted element's location probe = (probe+offset) % TABLE_SIZE; } hashTable[probe] = value; keysPresent += 1; } void erase(int value){ /* Return if element is not present */ if(!search(value)) return; int probe = hash1(value), offset = hash2(value); while(hashTable[probe] != -1) if(hashTable[probe] == value){ hashTable[probe] = -2; // mark element as deleted (rather than unvisited(-1)). keysPresent--; return; } else probe = (probe + offset) % TABLE_SIZE; } bool search(int value){ int probe = hash1(value), offset = hash2(value), initialPos = probe; bool firstItr = true; while(1){ if(hashTable[probe] == -1) // Stop search if -1 is encountered. break; else if(hashTable[probe] == value) // Stop search after finding the element. return true; else if(probe == initialPos && !firstItr) // Stop search if one complete traversal of hash table is completed. return false; else probe = ((probe + offset) % TABLE_SIZE); // if none of the above cases occur then update the index and check at it. firstItr = false; } return false; } /* Function to display the hash table. */ void print(){ for(int i = 0; i < TABLE_SIZE; i++) cout<<hashTable[i]<<", "; cout<<"\n"; } }; int main(){ doubleHash myHash(13); // creates an empty hash table of size 13 /* Inserts random element in the hash table */ int insertions[] = {115, 12, 87, 66, 123}, n1 = sizeof(insertions)/sizeof(insertions[0]); for(int i = 0; i < n1; i++) myHash.insert(insertions[i]); cout<< "Status of hash table after initial insertions : "; myHash.print(); /* ** Searches for random element in the hash table, ** and prints them if found. */ int queries[] = {1, 12, 2, 3, 69, 88, 115}, n2 = sizeof(queries)/sizeof(queries[0]); cout<<"\n"<<"Search operation after insertion : \n"; for(int i = 0; i < n2; i++) if(myHash.search(queries[i])) cout<<queries[i]<<" present\n"; /* Deletes random element from the hash table. */ int deletions[] = {123, 87, 66}, n3 = sizeof(deletions)/sizeof(deletions[0]); for(int i = 0; i < n3; i++) myHash.erase(deletions[i]); cout<< "Status of hash table after deleting elements : "; myHash.print(); return 0;} Status of hash table after initial insertions : -1, 66, -1, -1, -1, -1, 123, -1, -1, 87, -1, 115, 12, Search operation after insertion : 12 present 115 present Status of hash table after deleting elements : -1, -2, -1, -1, -1, -1, -2, -1, -1, -2, -1, 115, 12, Here is an Easy implementation of Double Hashing in Python. Note: It’s written in python3. Python3 class DoubleHashing: def __init__(self, TableSize = 1111111): self.ts = TableSize self.List = [None]*self.ts self.count = 0 #to count element in list def nearestPrime(self): for l in range((self.ts-1),1,-1): flag = True for i in range(2, int(l**0.5)+1): if l%i == 0: flag = False break if flag: return l return 3 #default prime number def Hx1(self,key): #HashFunction 1 or Default Hash function when there is no collision. return key%self.ts def Hx2(self, key): #Hash Function 2 only used when collision occurs. return self.nearestPrime() - (key% self.nearestPrime()) #Formula: PRIME - (KEY % PRIME), Here always PRIME < TABLE_SIZE def dHasing(self, key): if self.count == self.ts: print("List is Full") return self.List elif self.List[self.Hx1(key)] == None: self.List[self.Hx1(key)] = key self.count +=1 print(f"Entered key: {key} at index {self.Hx1(key)}") else: comp = False i = 1 while not comp: index = (self.Hx1(key) + i*self.Hx2(key))%self.ts # Index = ( HashFunc1 - i*HashFunc2)%TABle_SIZE if self.List[index] == None: self.List[index] = key print(f"Entered key: {key} at index {index}") comp = True self.count +=1 else: i +=1 return self.List def PrintHashList(self): for i in range(0, len(self.List)): print(self.List[i]) def main(): tableSize = 5 #Taking 5 as size of the hash Table DHash = DoubleHashing(tableSize) InputElements = [4,11, 29, 1, 5] for i in InputElements: DHash.dHasing(i) print('\n') print("The Hash List After Entering Elements") DHash.PrintHashList() #Printing the resultant HashList. if __name__ =="__main__": main() Entered key: 4 at index 4 Entered key: 11 at index 1 Entered key: 29 at index 0 Entered key: 1 at index 3 Entered key: 5 at index 2 The Hash List After Entering Elements 29 11 5 1 4 rahuliitkgp itskawal2000 harshupadhayay906 maityashis766 Hash Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 26, "s": 0, "text": "Difficulty Level :\nMedium" }, { "code": null, "e": 203, "s": 26, "text": "Double hashing is a collision resolving technique in Open Addressed Hash tables. Double hashing uses the idea of applying a second hash function to key when a collision occurs." }, { "code": null, "e": 232, "s": 203, "text": "Advantages of Double hashing" }, { "code": null, "e": 380, "s": 232, "text": "The advantage of Double hashing is that it is one of the best form of probing, producing a uniform distribution of records throughout a hash table." }, { "code": null, "e": 424, "s": 380, "text": "This technique does not yield any clusters." }, { "code": null, "e": 480, "s": 424, "text": "It is one of effective method for resolving collisions." }, { "code": null, "e": 690, "s": 480, "text": "Double hashing can be done using : (hash1(key) + i * hash2(key)) % TABLE_SIZE Here hash1() and hash2() are hash functions and TABLE_SIZE is size of hash table. (We repeat by increasing i when collision occurs)" }, { "code": null, "e": 908, "s": 690, "text": "First hash function is typically hash1(key) = key % TABLE_SIZEA popular second hash function is : hash2(key) = PRIME – (key % PRIME) where PRIME is a prime smaller than the TABLE_SIZE.A good second Hash function is: " }, { "code": null, "e": 939, "s": 908, "text": "It must never evaluate to zero" }, { "code": null, "e": 983, "s": 939, "text": "Must make sure that all cells can be probed" }, { "code": null, "e": 991, "s": 987, "text": "CPP" }, { "code": "/*** Handling of collision via open addressing** Method for Probing: Double Hashing*/ #include <iostream>#include <vector>#include <bitset>using namespace std;#define MAX_SIZE 10000001ll class doubleHash { int TABLE_SIZE, keysPresent, PRIME; vector<int> hashTable; bitset<MAX_SIZE> isPrime; /* Function to set sieve of Eratosthenes. */ void __setSieve(){ isPrime[0] = isPrime[1] = 1; for(long long i = 2; i*i <= MAX_SIZE; i++) if(isPrime[i] == 0) for(long long j = i*i; j <= MAX_SIZE; j += i) isPrime[j] = 1; } int inline hash1(int value){ return value%TABLE_SIZE; } int inline hash2(int value){ return PRIME - (value%PRIME); } bool inline isFull(){ return (TABLE_SIZE == keysPresent); } public: doubleHash(int n){ __setSieve(); TABLE_SIZE = n; /* Find the largest prime number smaller than hash table's size. */ PRIME = TABLE_SIZE - 1; while(isPrime[PRIME] == 1) PRIME--; keysPresent = 0; /* Fill the hash table with -1 (empty entries). */ for(int i = 0; i < TABLE_SIZE; i++) hashTable.push_back(-1); } void __printPrime(long long n){ for(long long i = 0; i <= n; i++) if(isPrime[i] == 0) cout<<i<<\", \"; cout<<endl; } /* Function to insert value in hash table */ void insert(int value){ if(value == -1 || value == -2){ cout<<(\"ERROR : -1 and -2 can't be inserted in the table\\n\"); } if(isFull()){ cout<<(\"ERROR : Hash Table Full\\n\"); return; } int probe = hash1(value), offset = hash2(value); // in linear probing offset = 1; while(hashTable[probe] != -1){ if(-2 == hashTable[probe]) break; // insert at deleted element's location probe = (probe+offset) % TABLE_SIZE; } hashTable[probe] = value; keysPresent += 1; } void erase(int value){ /* Return if element is not present */ if(!search(value)) return; int probe = hash1(value), offset = hash2(value); while(hashTable[probe] != -1) if(hashTable[probe] == value){ hashTable[probe] = -2; // mark element as deleted (rather than unvisited(-1)). keysPresent--; return; } else probe = (probe + offset) % TABLE_SIZE; } bool search(int value){ int probe = hash1(value), offset = hash2(value), initialPos = probe; bool firstItr = true; while(1){ if(hashTable[probe] == -1) // Stop search if -1 is encountered. break; else if(hashTable[probe] == value) // Stop search after finding the element. return true; else if(probe == initialPos && !firstItr) // Stop search if one complete traversal of hash table is completed. return false; else probe = ((probe + offset) % TABLE_SIZE); // if none of the above cases occur then update the index and check at it. firstItr = false; } return false; } /* Function to display the hash table. */ void print(){ for(int i = 0; i < TABLE_SIZE; i++) cout<<hashTable[i]<<\", \"; cout<<\"\\n\"; } }; int main(){ doubleHash myHash(13); // creates an empty hash table of size 13 /* Inserts random element in the hash table */ int insertions[] = {115, 12, 87, 66, 123}, n1 = sizeof(insertions)/sizeof(insertions[0]); for(int i = 0; i < n1; i++) myHash.insert(insertions[i]); cout<< \"Status of hash table after initial insertions : \"; myHash.print(); /* ** Searches for random element in the hash table, ** and prints them if found. */ int queries[] = {1, 12, 2, 3, 69, 88, 115}, n2 = sizeof(queries)/sizeof(queries[0]); cout<<\"\\n\"<<\"Search operation after insertion : \\n\"; for(int i = 0; i < n2; i++) if(myHash.search(queries[i])) cout<<queries[i]<<\" present\\n\"; /* Deletes random element from the hash table. */ int deletions[] = {123, 87, 66}, n3 = sizeof(deletions)/sizeof(deletions[0]); for(int i = 0; i < n3; i++) myHash.erase(deletions[i]); cout<< \"Status of hash table after deleting elements : \"; myHash.print(); return 0;}", "e": 5623, "s": 991, "text": null }, { "code": null, "e": 5887, "s": 5623, "text": "Status of hash table after initial insertions : -1, 66, -1, -1, -1, -1, 123, -1, -1, 87, -1, 115, 12, \n\nSearch operation after insertion : \n12 present\n115 present\nStatus of hash table after deleting elements : -1, -2, -1, -1, -1, -1, -2, -1, -1, -2, -1, 115, 12, " }, { "code": null, "e": 5947, "s": 5887, "text": "Here is an Easy implementation of Double Hashing in Python." }, { "code": null, "e": 5978, "s": 5947, "text": "Note: It’s written in python3." }, { "code": null, "e": 5986, "s": 5978, "text": "Python3" }, { "code": "class DoubleHashing: def __init__(self, TableSize = 1111111): self.ts = TableSize self.List = [None]*self.ts self.count = 0 #to count element in list def nearestPrime(self): for l in range((self.ts-1),1,-1): flag = True for i in range(2, int(l**0.5)+1): if l%i == 0: flag = False break if flag: return l return 3 #default prime number def Hx1(self,key): #HashFunction 1 or Default Hash function when there is no collision. return key%self.ts def Hx2(self, key): #Hash Function 2 only used when collision occurs. return self.nearestPrime() - (key% self.nearestPrime()) #Formula: PRIME - (KEY % PRIME), Here always PRIME < TABLE_SIZE def dHasing(self, key): if self.count == self.ts: print(\"List is Full\") return self.List elif self.List[self.Hx1(key)] == None: self.List[self.Hx1(key)] = key self.count +=1 print(f\"Entered key: {key} at index {self.Hx1(key)}\") else: comp = False i = 1 while not comp: index = (self.Hx1(key) + i*self.Hx2(key))%self.ts # Index = ( HashFunc1 - i*HashFunc2)%TABle_SIZE if self.List[index] == None: self.List[index] = key print(f\"Entered key: {key} at index {index}\") comp = True self.count +=1 else: i +=1 return self.List def PrintHashList(self): for i in range(0, len(self.List)): print(self.List[i]) def main(): tableSize = 5 #Taking 5 as size of the hash Table DHash = DoubleHashing(tableSize) InputElements = [4,11, 29, 1, 5] for i in InputElements: DHash.dHasing(i) print('\\n') print(\"The Hash List After Entering Elements\") DHash.PrintHashList() #Printing the resultant HashList. if __name__ ==\"__main__\": main() ", "e": 8124, "s": 5986, "text": null }, { "code": null, "e": 8308, "s": 8124, "text": "Entered key: 4 at index 4\nEntered key: 11 at index 1\nEntered key: 29 at index 0\nEntered key: 1 at index 3\nEntered key: 5 at index 2\n\n\nThe Hash List After Entering Elements\n29\n11\n5\n1\n4" }, { "code": null, "e": 8320, "s": 8308, "text": "rahuliitkgp" }, { "code": null, "e": 8333, "s": 8320, "text": "itskawal2000" }, { "code": null, "e": 8351, "s": 8333, "text": "harshupadhayay906" }, { "code": null, "e": 8365, "s": 8351, "text": "maityashis766" }, { "code": null, "e": 8370, "s": 8365, "text": "Hash" }, { "code": null, "e": 8375, "s": 8370, "text": "Hash" } ]
MATLAB - Arrays
All variables of all data types in MATLAB are multidimensional arrays. A vector is a one-dimensional array and a matrix is a two-dimensional array. We have already discussed vectors and matrices. In this chapter, we will discuss multidimensional arrays. However, before that, let us discuss some special types of arrays. In this section, we will discuss some functions that create some special arrays. For all these functions, a single argument creates a square array, double arguments create rectangular array. The zeros() function creates an array of all zeros − For example − zeros(5) MATLAB will execute the above statement and return the following result − ans = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 The ones() function creates an array of all ones − For example − ones(4,3) MATLAB will execute the above statement and return the following result − ans = 1 1 1 1 1 1 1 1 1 1 1 1 The eye() function creates an identity matrix. For example − eye(4) MATLAB will execute the above statement and return the following result − ans = 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 The rand() function creates an array of uniformly distributed random numbers on (0,1) − For example − rand(3, 5) MATLAB will execute the above statement and return the following result − ans = 0.8147 0.9134 0.2785 0.9649 0.9572 0.9058 0.6324 0.5469 0.1576 0.4854 0.1270 0.0975 0.9575 0.9706 0.8003 A magic square is a square that produces the same sum, when its elements are added row-wise, column-wise or diagonally. The magic() function creates a magic square array. It takes a singular argument that gives the size of the square. The argument must be a scalar greater than or equal to 3. magic(4) MATLAB will execute the above statement and return the following result − ans = 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1 An array having more than two dimensions is called a multidimensional array in MATLAB. Multidimensional arrays in MATLAB are an extension of the normal two-dimensional matrix. Generally to generate a multidimensional array, we first create a two-dimensional array and extend it. For example, let's create a two-dimensional array a. a = [7 9 5; 6 1 9; 4 3 2] MATLAB will execute the above statement and return the following result − a = 7 9 5 6 1 9 4 3 2 The array a is a 3-by-3 array; we can add a third dimension to a, by providing the values like − a(:, :, 2)= [ 1 2 3; 4 5 6; 7 8 9] MATLAB will execute the above statement and return the following result − a = ans(:,:,1) = 0 0 0 0 0 0 0 0 0 ans(:,:,2) = 1 2 3 4 5 6 7 8 9 We can also create multidimensional arrays using the ones(), zeros() or the rand() functions. For example, b = rand(4,3,2) MATLAB will execute the above statement and return the following result − b(:,:,1) = 0.0344 0.7952 0.6463 0.4387 0.1869 0.7094 0.3816 0.4898 0.7547 0.7655 0.4456 0.2760 b(:,:,2) = 0.6797 0.4984 0.2238 0.6551 0.9597 0.7513 0.1626 0.3404 0.2551 0.1190 0.5853 0.5060 We can also use the cat() function to build multidimensional arrays. It concatenates a list of arrays along a specified dimension − Syntax for the cat() function is − B = cat(dim, A1, A2...) Where, B is the new array created B is the new array created A1, A2, ... are the arrays to be concatenated A1, A2, ... are the arrays to be concatenated dim is the dimension along which to concatenate the arrays dim is the dimension along which to concatenate the arrays Create a script file and type the following code into it − a = [9 8 7; 6 5 4; 3 2 1]; b = [1 2 3; 4 5 6; 7 8 9]; c = cat(3, a, b, [ 2 3 1; 4 7 8; 3 9 0]) When you run the file, it displays − c(:,:,1) = 9 8 7 6 5 4 3 2 1 c(:,:,2) = 1 2 3 4 5 6 7 8 9 c(:,:,3) = 2 3 1 4 7 8 3 9 0 MATLAB provides the following functions to sort, rotate, permute, reshape, or shift array contents. The following examples illustrate some of the functions mentioned above. Length, Dimension and Number of elements − Create a script file and type the following code into it − x = [7.1, 3.4, 7.2, 28/4, 3.6, 17, 9.4, 8.9]; length(x) % length of x vector y = rand(3, 4, 5, 2); ndims(y) % no of dimensions in array y s = ['Zara', 'Nuha', 'Shamim', 'Riz', 'Shadab']; numel(s) % no of elements in s When you run the file, it displays the following result − ans = 8 ans = 4 ans = 23 Circular Shifting of the Array Elements − Create a script file and type the following code into it − a = [1 2 3; 4 5 6; 7 8 9] % the original array a b = circshift(a,1) % circular shift first dimension values down by 1. c = circshift(a,[1 -1]) % circular shift first dimension values % down by 1 % and second dimension values to the left % by 1. When you run the file, it displays the following result − a = 1 2 3 4 5 6 7 8 9 b = 7 8 9 1 2 3 4 5 6 c = 8 9 7 2 3 1 5 6 4 Create a script file and type the following code into it − v = [ 23 45 12 9 5 0 19 17] % horizontal vector sort(v) % sorting v m = [2 6 4; 5 3 9; 2 0 1] % two dimensional array sort(m, 1) % sorting m along the row sort(m, 2) % sorting m along the column When you run the file, it displays the following result − v = 23 45 12 9 5 0 19 17 ans = 0 5 9 12 17 19 23 45 m = 2 6 4 5 3 9 2 0 1 ans = 2 0 1 2 3 4 5 6 9 ans = 2 4 6 3 5 9 0 1 2 Cell arrays are arrays of indexed cells where each cell can store an array of a different dimensions and data types. The cell function is used for creating a cell array. Syntax for the cell function is − C = cell(dim) C = cell(dim1,...,dimN) D = cell(obj) C is the cell array; C is the cell array; dim is a scalar integer or vector of integers that specifies the dimensions of cell array C; dim is a scalar integer or vector of integers that specifies the dimensions of cell array C; dim1, ... , dimN are scalar integers that specify the dimensions of C; dim1, ... , dimN are scalar integers that specify the dimensions of C; obj is One of the following − Java array or object .NET array of type System.String or System.Object obj is One of the following − Java array or object .NET array of type System.String or System.Object Create a script file and type the following code into it − c = cell(2, 5); c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5} When you run the file, it displays the following result − c = { [1,1] = Red [2,1] = 1 [1,2] = Blue [2,2] = 2 [1,3] = Green [2,3] = 3 [1,4] = Yellow [2,4] = 4 [1,5] = White [2,5] = 5 } There are two ways to refer to the elements of a cell array − Enclosing the indices in first bracket (), to refer to sets of cells Enclosing the indices in braces {}, to refer to the data within individual cells When you enclose the indices in first bracket, it refers to the set of cells. Cell array indices in smooth parentheses refer to sets of cells. For example − c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5}; c(1:2,1:2) MATLAB will execute the above statement and return the following result − ans = { [1,1] = Red [2,1] = 1 [1,2] = Blue [2,2] = 2 } You can also access the contents of cells by indexing with curly braces. For example − c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5}; c{1, 2:4} MATLAB will execute the above statement and return the following result − ans = Blue ans = Green ans = Yellow
[ { "code": null, "e": 2423, "s": 2275, "text": "All variables of all data types in MATLAB are multidimensional arrays. A vector is a one-dimensional array and a matrix is a two-dimensional array." }, { "code": null, "e": 2596, "s": 2423, "text": "We have already discussed vectors and matrices. In this chapter, we will discuss multidimensional arrays. However, before that, let us discuss some special types of arrays." }, { "code": null, "e": 2787, "s": 2596, "text": "In this section, we will discuss some functions that create some special arrays. For all these functions, a single argument creates a square array, double arguments create rectangular array." }, { "code": null, "e": 2840, "s": 2787, "text": "The zeros() function creates an array of all zeros −" }, { "code": null, "e": 2854, "s": 2840, "text": "For example −" }, { "code": null, "e": 2863, "s": 2854, "text": "zeros(5)" }, { "code": null, "e": 2937, "s": 2863, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 3104, "s": 2937, "text": "ans =\n 0 0 0 0 0\n 0 0 0 0 0\n 0 0 0 0 0\n 0 0 0 0 0\n 0 0 0 0 0\n" }, { "code": null, "e": 3155, "s": 3104, "text": "The ones() function creates an array of all ones −" }, { "code": null, "e": 3169, "s": 3155, "text": "For example −" }, { "code": null, "e": 3179, "s": 3169, "text": "ones(4,3)" }, { "code": null, "e": 3253, "s": 3179, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 3340, "s": 3253, "text": "ans =\n 1 1 1\n 1 1 1\n 1 1 1\n 1 1 1\n" }, { "code": null, "e": 3387, "s": 3340, "text": "The eye() function creates an identity matrix." }, { "code": null, "e": 3401, "s": 3387, "text": "For example −" }, { "code": null, "e": 3408, "s": 3401, "text": "eye(4)" }, { "code": null, "e": 3482, "s": 3408, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 3593, "s": 3482, "text": "ans =\n 1 0 0 0\n 0 1 0 0\n 0 0 1 0\n 0 0 0 1\n" }, { "code": null, "e": 3681, "s": 3593, "text": "The rand() function creates an array of uniformly distributed random numbers on (0,1) −" }, { "code": null, "e": 3695, "s": 3681, "text": "For example −" }, { "code": null, "e": 3706, "s": 3695, "text": "rand(3, 5)" }, { "code": null, "e": 3780, "s": 3706, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 3937, "s": 3780, "text": "ans =\n 0.8147 0.9134 0.2785 0.9649 0.9572\n 0.9058 0.6324 0.5469 0.1576 0.4854\n 0.1270 0.0975 0.9575 0.9706 0.8003\n" }, { "code": null, "e": 4057, "s": 3937, "text": "A magic square is a square that produces the same sum, when its elements are added row-wise, column-wise or diagonally." }, { "code": null, "e": 4230, "s": 4057, "text": "The magic() function creates a magic square array. It takes a singular argument that gives the size of the square. The argument must be a scalar greater than or equal to 3." }, { "code": null, "e": 4239, "s": 4230, "text": "magic(4)" }, { "code": null, "e": 4313, "s": 4239, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 4413, "s": 4313, "text": "ans =\n 16 2 3 13\n 5 11 10 8\n 9 7 6 12\n 4 14 15 1\n" }, { "code": null, "e": 4589, "s": 4413, "text": "An array having more than two dimensions is called a multidimensional array in MATLAB. Multidimensional arrays in MATLAB are an extension of the normal two-dimensional matrix." }, { "code": null, "e": 4692, "s": 4589, "text": "Generally to generate a multidimensional array, we first create a two-dimensional array and extend it." }, { "code": null, "e": 4745, "s": 4692, "text": "For example, let's create a two-dimensional array a." }, { "code": null, "e": 4771, "s": 4745, "text": "a = [7 9 5; 6 1 9; 4 3 2]" }, { "code": null, "e": 4845, "s": 4771, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 4901, "s": 4845, "text": "a =\n 7 9 5\n 6 1 9\n 4 3 2\n" }, { "code": null, "e": 4998, "s": 4901, "text": "The array a is a 3-by-3 array; we can add a third dimension to a, by providing the values like −" }, { "code": null, "e": 5033, "s": 4998, "text": "a(:, :, 2)= [ 1 2 3; 4 5 6; 7 8 9]" }, { "code": null, "e": 5107, "s": 5033, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 5220, "s": 5107, "text": "a =\n\nans(:,:,1) =\n\n 0 0 0\n 0 0 0\n 0 0 0\n\nans(:,:,2) =\n\n 1 2 3\n 4 5 6\n 7 8 9\n" }, { "code": null, "e": 5314, "s": 5220, "text": "We can also create multidimensional arrays using the ones(), zeros() or the rand() functions." }, { "code": null, "e": 5327, "s": 5314, "text": "For example," }, { "code": null, "e": 5343, "s": 5327, "text": "b = rand(4,3,2)" }, { "code": null, "e": 5417, "s": 5343, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 5681, "s": 5417, "text": "b(:,:,1) =\n 0.0344 0.7952 0.6463\n 0.4387 0.1869 0.7094\n 0.3816 0.4898 0.7547\n 0.7655 0.4456 0.2760\n\nb(:,:,2) =\n 0.6797 0.4984 0.2238\n 0.6551 0.9597 0.7513\n 0.1626 0.3404 0.2551\n 0.1190 0.5853 0.5060\n" }, { "code": null, "e": 5813, "s": 5681, "text": "We can also use the cat() function to build multidimensional arrays. It concatenates a list of arrays along a specified dimension −" }, { "code": null, "e": 5848, "s": 5813, "text": "Syntax for the cat() function is −" }, { "code": null, "e": 5872, "s": 5848, "text": "B = cat(dim, A1, A2...)" }, { "code": null, "e": 5879, "s": 5872, "text": "Where," }, { "code": null, "e": 5906, "s": 5879, "text": "B is the new array created" }, { "code": null, "e": 5933, "s": 5906, "text": "B is the new array created" }, { "code": null, "e": 5979, "s": 5933, "text": "A1, A2, ... are the arrays to be concatenated" }, { "code": null, "e": 6025, "s": 5979, "text": "A1, A2, ... are the arrays to be concatenated" }, { "code": null, "e": 6084, "s": 6025, "text": "dim is the dimension along which to concatenate the arrays" }, { "code": null, "e": 6143, "s": 6084, "text": "dim is the dimension along which to concatenate the arrays" }, { "code": null, "e": 6202, "s": 6143, "text": "Create a script file and type the following code into it −" }, { "code": null, "e": 6297, "s": 6202, "text": "a = [9 8 7; 6 5 4; 3 2 1];\nb = [1 2 3; 4 5 6; 7 8 9];\nc = cat(3, a, b, [ 2 3 1; 4 7 8; 3 9 0])" }, { "code": null, "e": 6334, "s": 6297, "text": "When you run the file, it displays −" }, { "code": null, "e": 6548, "s": 6334, "text": "c(:,:,1) =\n 9 8 7\n 6 5 4\n 3 2 1\nc(:,:,2) =\n 1 2 3\n 4 5 6\n 7 8 9\nc(:,:,3) =\n 2 3 1\n 4 7 8\n 3 9 0\n" }, { "code": null, "e": 6649, "s": 6548, "text": "MATLAB provides the following functions to sort, rotate, permute, reshape, or shift array contents. " }, { "code": null, "e": 6722, "s": 6649, "text": "The following examples illustrate some of the functions mentioned above." }, { "code": null, "e": 6765, "s": 6722, "text": "Length, Dimension and Number of elements −" }, { "code": null, "e": 6824, "s": 6765, "text": "Create a script file and type the following code into it −" }, { "code": null, "e": 7059, "s": 6824, "text": "x = [7.1, 3.4, 7.2, 28/4, 3.6, 17, 9.4, 8.9];\nlength(x) % length of x vector\ny = rand(3, 4, 5, 2);\nndims(y) % no of dimensions in array y\ns = ['Zara', 'Nuha', 'Shamim', 'Riz', 'Shadab'];\nnumel(s) % no of elements in s" }, { "code": null, "e": 7117, "s": 7059, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 7146, "s": 7117, "text": "ans = 8\nans = 4\nans = 23\n" }, { "code": null, "e": 7188, "s": 7146, "text": "Circular Shifting of the Array Elements −" }, { "code": null, "e": 7247, "s": 7188, "text": "Create a script file and type the following code into it −" }, { "code": null, "e": 7533, "s": 7247, "text": "a = [1 2 3; 4 5 6; 7 8 9] % the original array a\nb = circshift(a,1) % circular shift first dimension values down by 1.\nc = circshift(a,[1 -1]) % circular shift first dimension values % down by 1 \n % and second dimension values to the left % by 1." }, { "code": null, "e": 7591, "s": 7533, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 7759, "s": 7591, "text": "a =\n 1 2 3\n 4 5 6\n 7 8 9\n\nb =\n 7 8 9\n 1 2 3\n 4 5 6\n\nc =\n 8 9 7\n 2 3 1\n 5 6 4\n" }, { "code": null, "e": 7818, "s": 7759, "text": "Create a script file and type the following code into it −" }, { "code": null, "e": 8074, "s": 7818, "text": "v = [ 23 45 12 9 5 0 19 17] % horizontal vector\nsort(v) % sorting v\nm = [2 6 4; 5 3 9; 2 0 1] % two dimensional array\nsort(m, 1) % sorting m along the row\nsort(m, 2) % sorting m along the column" }, { "code": null, "e": 8132, "s": 8074, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 8407, "s": 8132, "text": "v =\n 23 45 12 9 5 0 19 17\nans =\n 0 5 9 12 17 19 23 45\nm =\n 2 6 4\n 5 3 9\n 2 0 1\nans =\n 2 0 1\n 2 3 4\n 5 6 9\nans =\n 2 4 6\n 3 5 9\n 0 1 2\n" }, { "code": null, "e": 8524, "s": 8407, "text": "Cell arrays are arrays of indexed cells where each cell can store an array of a different dimensions and data types." }, { "code": null, "e": 8611, "s": 8524, "text": "The cell function is used for creating a cell array. Syntax for the cell function is −" }, { "code": null, "e": 8663, "s": 8611, "text": "C = cell(dim)\nC = cell(dim1,...,dimN)\nD = cell(obj)" }, { "code": null, "e": 8684, "s": 8663, "text": "C is the cell array;" }, { "code": null, "e": 8705, "s": 8684, "text": "C is the cell array;" }, { "code": null, "e": 8798, "s": 8705, "text": "dim is a scalar integer or vector of integers that specifies the dimensions of cell array C;" }, { "code": null, "e": 8891, "s": 8798, "text": "dim is a scalar integer or vector of integers that specifies the dimensions of cell array C;" }, { "code": null, "e": 8962, "s": 8891, "text": "dim1, ... , dimN are scalar integers that specify the dimensions of C;" }, { "code": null, "e": 9033, "s": 8962, "text": "dim1, ... , dimN are scalar integers that specify the dimensions of C;" }, { "code": null, "e": 9137, "s": 9033, "text": "obj is One of the following −\n\nJava array or object\n.NET array of type System.String or System.Object\n\n" }, { "code": null, "e": 9167, "s": 9137, "text": "obj is One of the following −" }, { "code": null, "e": 9188, "s": 9167, "text": "Java array or object" }, { "code": null, "e": 9238, "s": 9188, "text": ".NET array of type System.String or System.Object" }, { "code": null, "e": 9297, "s": 9238, "text": "Create a script file and type the following code into it −" }, { "code": null, "e": 9372, "s": 9297, "text": "c = cell(2, 5);\nc = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5}" }, { "code": null, "e": 9430, "s": 9372, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 9593, "s": 9430, "text": "c = \n{\n [1,1] = Red\n [2,1] = 1\n [1,2] = Blue\n [2,2] = 2\n [1,3] = Green\n [2,3] = 3\n [1,4] = Yellow\n [2,4] = 4\n [1,5] = White\n [2,5] = 5\n}\n" }, { "code": null, "e": 9655, "s": 9593, "text": "There are two ways to refer to the elements of a cell array −" }, { "code": null, "e": 9724, "s": 9655, "text": "Enclosing the indices in first bracket (), to refer to sets of cells" }, { "code": null, "e": 9805, "s": 9724, "text": "Enclosing the indices in braces {}, to refer to the data within individual cells" }, { "code": null, "e": 9883, "s": 9805, "text": "When you enclose the indices in first bracket, it refers to the set of cells." }, { "code": null, "e": 9948, "s": 9883, "text": "Cell array indices in smooth parentheses refer to sets of cells." }, { "code": null, "e": 9962, "s": 9948, "text": "For example −" }, { "code": null, "e": 10033, "s": 9962, "text": "c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5};\nc(1:2,1:2)" }, { "code": null, "e": 10107, "s": 10033, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 10178, "s": 10107, "text": "ans = \n{\n [1,1] = Red\n [2,1] = 1\n [1,2] = Blue\n [2,2] = 2\n}\n" }, { "code": null, "e": 10251, "s": 10178, "text": "You can also access the contents of cells by indexing with curly braces." }, { "code": null, "e": 10265, "s": 10251, "text": "For example −" }, { "code": null, "e": 10335, "s": 10265, "text": "c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5};\nc{1, 2:4}" }, { "code": null, "e": 10409, "s": 10335, "text": "MATLAB will execute the above statement and return the following result −" } ]
How to Create Option Menu in Android using Kotlin?
04 Oct, 2021 In this article, we will learn how to create an options menu in the Android app using Kotlin. To have an options menu in an Activity, we need to create a new menu XML file and inflate it using menuInflator.inflate( ) method. In menu.xml we will design the options menu as the requirement of the app. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language. Step 2: Implement Option Menu We need to create a new menu XML file and using the <item> tag we can create items inside the menu. Step 3: Create vector assets for icons of items in menu options Refer to this link for Vector Assets. Step 4: Refer to this code for the menu.xml file XML <?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/overflowMenu" android:icon="@drawable/ic_3_dots" android:title="" app:showAsAction="always"> <menu> <item android:id="@+id/settings" android:icon="@drawable/ic_settings" android:title="SETTINGS" app:showAsAction="never" /> <item android:id="@+id/about" android:icon="@drawable/ic_about" android:title="ABOUT" app:showAsAction="never" /> <item android:id="@+id/exit" android:icon="@drawable/ic_exit" android:title="EXIT" app:showAsAction="never" /> </menu> </item></menu> Step 5: Working with the MainActivity.kt file We don’t need to change anything in the activity_main.xml file. Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Kotlin package com.ayush.optionmenu import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.Menuimport android.view.MenuItemimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu,menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId){ R.id.about -> Toast.makeText(this,"About Selected",Toast.LENGTH_SHORT).show() R.id.settings -> Toast.makeText(this,"Settings Selected",Toast.LENGTH_SHORT).show() R.id.exit -> Toast.makeText(this,"Exit Selected",Toast.LENGTH_SHORT).show() } return super.onOptionsItemSelected(item) }} So our app is ready. Output: We can see when we click on any menu option a Toast is displayed. Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android How to Add Views Dynamically and Store Data in Arraylist in Android? Android UI Layouts Kotlin Array How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Oct, 2021" }, { "code": null, "e": 328, "s": 28, "text": "In this article, we will learn how to create an options menu in the Android app using Kotlin. To have an options menu in an Activity, we need to create a new menu XML file and inflate it using menuInflator.inflate( ) method. In menu.xml we will design the options menu as the requirement of the app." }, { "code": null, "e": 357, "s": 328, "text": "Step 1: Create a New Project" }, { "code": null, "e": 521, "s": 357, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language." }, { "code": null, "e": 551, "s": 521, "text": "Step 2: Implement Option Menu" }, { "code": null, "e": 652, "s": 551, "text": "We need to create a new menu XML file and using the <item> tag we can create items inside the menu. " }, { "code": null, "e": 716, "s": 652, "text": "Step 3: Create vector assets for icons of items in menu options" }, { "code": null, "e": 755, "s": 716, "text": "Refer to this link for Vector Assets. " }, { "code": null, "e": 804, "s": 755, "text": "Step 4: Refer to this code for the menu.xml file" }, { "code": null, "e": 808, "s": 804, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><menu xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\"> <item android:id=\"@+id/overflowMenu\" android:icon=\"@drawable/ic_3_dots\" android:title=\"\" app:showAsAction=\"always\"> <menu> <item android:id=\"@+id/settings\" android:icon=\"@drawable/ic_settings\" android:title=\"SETTINGS\" app:showAsAction=\"never\" /> <item android:id=\"@+id/about\" android:icon=\"@drawable/ic_about\" android:title=\"ABOUT\" app:showAsAction=\"never\" /> <item android:id=\"@+id/exit\" android:icon=\"@drawable/ic_exit\" android:title=\"EXIT\" app:showAsAction=\"never\" /> </menu> </item></menu>", "e": 1724, "s": 808, "text": null }, { "code": null, "e": 1770, "s": 1724, "text": "Step 5: Working with the MainActivity.kt file" }, { "code": null, "e": 1947, "s": 1770, "text": "We don’t need to change anything in the activity_main.xml file. Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. " }, { "code": null, "e": 1954, "s": 1947, "text": "Kotlin" }, { "code": "package com.ayush.optionmenu import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.Menuimport android.view.MenuItemimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu,menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId){ R.id.about -> Toast.makeText(this,\"About Selected\",Toast.LENGTH_SHORT).show() R.id.settings -> Toast.makeText(this,\"Settings Selected\",Toast.LENGTH_SHORT).show() R.id.exit -> Toast.makeText(this,\"Exit Selected\",Toast.LENGTH_SHORT).show() } return super.onOptionsItemSelected(item) }}", "e": 2915, "s": 1954, "text": null }, { "code": null, "e": 2937, "s": 2915, "text": "So our app is ready. " }, { "code": null, "e": 2945, "s": 2937, "text": "Output:" }, { "code": null, "e": 3011, "s": 2945, "text": "We can see when we click on any menu option a Toast is displayed." }, { "code": null, "e": 3019, "s": 3011, "text": "Android" }, { "code": null, "e": 3026, "s": 3019, "text": "Kotlin" }, { "code": null, "e": 3034, "s": 3026, "text": "Android" }, { "code": null, "e": 3132, "s": 3034, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3201, "s": 3132, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 3233, "s": 3201, "text": "Android SDK and it's Components" }, { "code": null, "e": 3272, "s": 3233, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 3321, "s": 3272, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 3363, "s": 3321, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 3432, "s": 3363, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 3451, "s": 3432, "text": "Android UI Layouts" }, { "code": null, "e": 3464, "s": 3451, "text": "Kotlin Array" }, { "code": null, "e": 3513, "s": 3464, "text": "How to Communicate Between Fragments in Android?" } ]
response.cookies – Python requests
01 Mar, 2020 Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.cookies out of a response object. response.cookies returns a CookieJar object with the cookies sent back from the server. To illustrate use of response.cookies, let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC. Download and Install Python 3 Latest Version How to install requests in Python – For windows, linux, mac import requests # Making a get requestresponse = requests.get('https://api.github.com') # printing request cookiesprint(response.cookies) Save above file as request.py and run using Python request.py Check that at the start of output, it means the reference to a cookies object. There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute. requests.status_code If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources. Python-requests Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Mar, 2020" }, { "code": null, "e": 483, "s": 28, "text": "Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.cookies out of a response object. response.cookies returns a CookieJar object with the cookies sent back from the server." }, { "code": null, "e": 627, "s": 483, "text": "To illustrate use of response.cookies, let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC." }, { "code": null, "e": 672, "s": 627, "text": "Download and Install Python 3 Latest Version" }, { "code": null, "e": 732, "s": 672, "text": "How to install requests in Python – For windows, linux, mac" }, { "code": "import requests # Making a get requestresponse = requests.get('https://api.github.com') # printing request cookiesprint(response.cookies)", "e": 872, "s": 732, "text": null }, { "code": null, "e": 916, "s": 872, "text": "Save above file as request.py and run using" }, { "code": null, "e": 935, "s": 916, "text": "Python request.py\n" }, { "code": null, "e": 1014, "s": 935, "text": "Check that at the start of output, it means the reference to a cookies object." }, { "code": null, "e": 1265, "s": 1014, "text": "There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute." }, { "code": null, "e": 1286, "s": 1265, "text": "requests.status_code" }, { "code": null, "e": 1443, "s": 1286, "text": "If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources." }, { "code": null, "e": 1459, "s": 1443, "text": "Python-requests" }, { "code": null, "e": 1466, "s": 1459, "text": "Python" }, { "code": null, "e": 1564, "s": 1466, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1606, "s": 1564, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1628, "s": 1606, "text": "Enumerate() in Python" }, { "code": null, "e": 1654, "s": 1628, "text": "Python String | replace()" }, { "code": null, "e": 1686, "s": 1654, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1715, "s": 1686, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1742, "s": 1715, "text": "Python Classes and Objects" }, { "code": null, "e": 1763, "s": 1742, "text": "Python OOPs Concepts" }, { "code": null, "e": 1799, "s": 1763, "text": "Convert integer to string in Python" }, { "code": null, "e": 1822, "s": 1799, "text": "Introduction To PYTHON" } ]
PostgreSQL - Environment Setup
To start understanding the PostgreSQL basics, first let us install the PostgreSQL. This chapter explains about installing the PostgreSQL on Linux, Windows and Mac OS platforms. Follow the given steps to install PostgreSQL on your Linux machine. Make sure you are logged in as root before you proceed for the installation. Pick the version number of PostgreSQL you want and, as exactly as possible, the platform you want from EnterpriseDB Pick the version number of PostgreSQL you want and, as exactly as possible, the platform you want from EnterpriseDB I downloaded postgresql-9.2.4-1-linux-x64.run for my 64 bit CentOS-6 machine. Now, let us execute it as follows − I downloaded postgresql-9.2.4-1-linux-x64.run for my 64 bit CentOS-6 machine. Now, let us execute it as follows − [root@host]# chmod +x postgresql-9.2.4-1-linux-x64.run [root@host]# ./postgresql-9.2.4-1-linux-x64.run ------------------------------------------------------------------------ Welcome to the PostgreSQL Setup Wizard. ------------------------------------------------------------------------ Please specify the directory where PostgreSQL will be installed. Installation Directory [/opt/PostgreSQL/9.2]: Once you launch the installer, it asks you a few basic questions like location of the installation, password of the user who will use database, port number, etc. So keep all of them at their default values except password, which you can provide password as per your choice. It will install PostgreSQL at your Linux machine and will display the following message − Once you launch the installer, it asks you a few basic questions like location of the installation, password of the user who will use database, port number, etc. So keep all of them at their default values except password, which you can provide password as per your choice. It will install PostgreSQL at your Linux machine and will display the following message − Please wait while Setup installs PostgreSQL on your computer. Installing 0% ______________ 50% ______________ 100% ######################################### ----------------------------------------------------------------------- Setup has finished installing PostgreSQL on your computer. Follow the following post-installation steps to create your database − Follow the following post-installation steps to create your database − [root@host]# su - postgres Password: bash-4.1$ createdb testdb bash-4.1$ psql testdb psql (8.4.13, server 9.2.4) test=# You can start/restart postgres server in case it is not running using the following command − You can start/restart postgres server in case it is not running using the following command − [root@host]# service postgresql restart Stopping postgresql service: [ OK ] Starting postgresql service: [ OK ] If your installation was correct, you will have PotsgreSQL prompt test=# as shown above. If your installation was correct, you will have PotsgreSQL prompt test=# as shown above. Follow the given steps to install PostgreSQL on your Windows machine. Make sure you have turned Third Party Antivirus off while installing. Pick the version number of PostgreSQL you want and, as exactly as possible, the platform you want from EnterpriseDB Pick the version number of PostgreSQL you want and, as exactly as possible, the platform you want from EnterpriseDB I downloaded postgresql-9.2.4-1-windows.exe for my Windows PC running in 32bit mode, so let us run postgresql-9.2.4-1-windows.exe as administrator to install PostgreSQL. Select the location where you want to install it. By default, it is installed within Program Files folder. I downloaded postgresql-9.2.4-1-windows.exe for my Windows PC running in 32bit mode, so let us run postgresql-9.2.4-1-windows.exe as administrator to install PostgreSQL. Select the location where you want to install it. By default, it is installed within Program Files folder. The next step of the installation process would be to select the directory where your data would be stored. By default, it is stored under the "data" directory. The next step of the installation process would be to select the directory where your data would be stored. By default, it is stored under the "data" directory. Next, the setup asks for password, so you can use your favorite password. Next, the setup asks for password, so you can use your favorite password. The next step; keep the port as default. The next step; keep the port as default. In the next step, when asked for "Locale", I selected "English, United States". In the next step, when asked for "Locale", I selected "English, United States". It takes a while to install PostgreSQL on your system. On completion of the installation process, you will get the following screen. Uncheck the checkbox and click the Finish button. It takes a while to install PostgreSQL on your system. On completion of the installation process, you will get the following screen. Uncheck the checkbox and click the Finish button. After the installation process is completed, you can access pgAdmin III, StackBuilder and PostgreSQL shell from your Program Menu under PostgreSQL 9.2. Follow the given steps to install PostgreSQL on your Mac machine. Make sure you are logged in as administrator before you proceed for the installation. Pick the latest version number of PostgreSQL for Mac OS available at EnterpriseDB Pick the latest version number of PostgreSQL for Mac OS available at EnterpriseDB I downloaded postgresql-9.2.4-1-osx.dmg for my Mac OS running with OS X version 10.8.3. Now, let us open the dmg image in finder and just double click it which will give you PostgreSQL installer in the following window − I downloaded postgresql-9.2.4-1-osx.dmg for my Mac OS running with OS X version 10.8.3. Now, let us open the dmg image in finder and just double click it which will give you PostgreSQL installer in the following window − Next, click the postgres-9.2.4-1-osx icon, which will give a warning message. Accept the warning and proceed for further installation. It will ask for the administrator password as seen in the following window − Next, click the postgres-9.2.4-1-osx icon, which will give a warning message. Accept the warning and proceed for further installation. It will ask for the administrator password as seen in the following window − Enter the password, proceed for the installation, and after this step, restart your Mac machine. If you do not see the following window, start your installation once again. Once you launch the installer, it asks you a few basic questions like location of the installation, password of the user who will use database, port number etc. Therefore, keep all of them at their default values except the password, which you can provide as per your choice. It will install PostgreSQL in your Mac machine in the Application folder which you can check − Once you launch the installer, it asks you a few basic questions like location of the installation, password of the user who will use database, port number etc. Therefore, keep all of them at their default values except the password, which you can provide as per your choice. It will install PostgreSQL in your Mac machine in the Application folder which you can check − Now, you can launch any of the program to start with. Let us start with SQL Shell. When you launch SQL Shell, just use all the default values it displays except, enter your password, which you had selected at the time of installation. If everything goes fine, then you will be inside postgres database and a postgress# prompt will be displayed as shown below − Now, you can launch any of the program to start with. Let us start with SQL Shell. When you launch SQL Shell, just use all the default values it displays except, enter your password, which you had selected at the time of installation. If everything goes fine, then you will be inside postgres database and a postgress# prompt will be displayed as shown below − Congratulations!!! Now you have your environment ready to start with PostgreSQL database programming.
[ { "code": null, "e": 3136, "s": 2959, "text": "To start understanding the PostgreSQL basics, first let us install the PostgreSQL. This chapter explains about installing the PostgreSQL on Linux, Windows and Mac OS platforms." }, { "code": null, "e": 3281, "s": 3136, "text": "Follow the given steps to install PostgreSQL on your Linux machine. Make sure you are logged in as root before you proceed for the installation." }, { "code": null, "e": 3397, "s": 3281, "text": "Pick the version number of PostgreSQL you want and, as exactly as possible, the platform you want from EnterpriseDB" }, { "code": null, "e": 3513, "s": 3397, "text": "Pick the version number of PostgreSQL you want and, as exactly as possible, the platform you want from EnterpriseDB" }, { "code": null, "e": 3627, "s": 3513, "text": "I downloaded postgresql-9.2.4-1-linux-x64.run for my 64 bit CentOS-6 machine. Now, let us execute it as follows −" }, { "code": null, "e": 3741, "s": 3627, "text": "I downloaded postgresql-9.2.4-1-linux-x64.run for my 64 bit CentOS-6 machine. Now, let us execute it as follows −" }, { "code": null, "e": 4143, "s": 3741, "text": "[root@host]# chmod +x postgresql-9.2.4-1-linux-x64.run\n[root@host]# ./postgresql-9.2.4-1-linux-x64.run\n------------------------------------------------------------------------\nWelcome to the PostgreSQL Setup Wizard.\n\n------------------------------------------------------------------------\nPlease specify the directory where PostgreSQL will be installed.\n\nInstallation Directory [/opt/PostgreSQL/9.2]:" }, { "code": null, "e": 4507, "s": 4143, "text": "Once you launch the installer, it asks you a few basic questions like location of the installation, password of the user who will use database, port number, etc. So keep all of them at their default values except password, which you can provide password as per your choice. It will install PostgreSQL at your Linux machine and will display the following message −" }, { "code": null, "e": 4871, "s": 4507, "text": "Once you launch the installer, it asks you a few basic questions like location of the installation, password of the user who will use database, port number, etc. So keep all of them at their default values except password, which you can provide password as per your choice. It will install PostgreSQL at your Linux machine and will display the following message −" }, { "code": null, "e": 5164, "s": 4871, "text": "Please wait while Setup installs PostgreSQL on your computer.\n\n Installing\n 0% ______________ 50% ______________ 100%\n #########################################\n\n-----------------------------------------------------------------------\nSetup has finished installing PostgreSQL on your computer." }, { "code": null, "e": 5235, "s": 5164, "text": "Follow the following post-installation steps to create your database −" }, { "code": null, "e": 5306, "s": 5235, "text": "Follow the following post-installation steps to create your database −" }, { "code": null, "e": 5427, "s": 5306, "text": "[root@host]# su - postgres\nPassword:\nbash-4.1$ createdb testdb\nbash-4.1$ psql testdb\npsql (8.4.13, server 9.2.4)\n\ntest=#" }, { "code": null, "e": 5521, "s": 5427, "text": "You can start/restart postgres server in case it is not running using the following command −" }, { "code": null, "e": 5615, "s": 5521, "text": "You can start/restart postgres server in case it is not running using the following command −" }, { "code": null, "e": 5791, "s": 5615, "text": "[root@host]# service postgresql restart\nStopping postgresql service: [ OK ]\nStarting postgresql service: [ OK ]" }, { "code": null, "e": 5880, "s": 5791, "text": "If your installation was correct, you will have PotsgreSQL prompt test=# as shown above." }, { "code": null, "e": 5969, "s": 5880, "text": "If your installation was correct, you will have PotsgreSQL prompt test=# as shown above." }, { "code": null, "e": 6109, "s": 5969, "text": "Follow the given steps to install PostgreSQL on your Windows machine. Make sure you have turned Third Party Antivirus off while installing." }, { "code": null, "e": 6225, "s": 6109, "text": "Pick the version number of PostgreSQL you want and, as exactly as possible, the platform you want from EnterpriseDB" }, { "code": null, "e": 6341, "s": 6225, "text": "Pick the version number of PostgreSQL you want and, as exactly as possible, the platform you want from EnterpriseDB" }, { "code": null, "e": 6618, "s": 6341, "text": "I downloaded postgresql-9.2.4-1-windows.exe for my Windows PC running in 32bit mode, so let us run postgresql-9.2.4-1-windows.exe as administrator to install PostgreSQL. Select the location where you want to install it. By default, it is installed within Program Files folder." }, { "code": null, "e": 6895, "s": 6618, "text": "I downloaded postgresql-9.2.4-1-windows.exe for my Windows PC running in 32bit mode, so let us run postgresql-9.2.4-1-windows.exe as administrator to install PostgreSQL. Select the location where you want to install it. By default, it is installed within Program Files folder." }, { "code": null, "e": 7056, "s": 6895, "text": "The next step of the installation process would be to select the directory where your data would be stored. By default, it is stored under the \"data\" directory." }, { "code": null, "e": 7217, "s": 7056, "text": "The next step of the installation process would be to select the directory where your data would be stored. By default, it is stored under the \"data\" directory." }, { "code": null, "e": 7291, "s": 7217, "text": "Next, the setup asks for password, so you can use your favorite password." }, { "code": null, "e": 7365, "s": 7291, "text": "Next, the setup asks for password, so you can use your favorite password." }, { "code": null, "e": 7406, "s": 7365, "text": "The next step; keep the port as default." }, { "code": null, "e": 7447, "s": 7406, "text": "The next step; keep the port as default." }, { "code": null, "e": 7528, "s": 7447, "text": "In the next step, when asked for \"Locale\", I selected \"English, United States\".\n" }, { "code": null, "e": 7608, "s": 7528, "text": "In the next step, when asked for \"Locale\", I selected \"English, United States\"." }, { "code": null, "e": 7791, "s": 7608, "text": "It takes a while to install PostgreSQL on your system. On completion of the installation process, you will get the following screen. Uncheck the checkbox and click the Finish button." }, { "code": null, "e": 7974, "s": 7791, "text": "It takes a while to install PostgreSQL on your system. On completion of the installation process, you will get the following screen. Uncheck the checkbox and click the Finish button." }, { "code": null, "e": 8126, "s": 7974, "text": "After the installation process is completed, you can access pgAdmin III, StackBuilder and PostgreSQL shell from your Program Menu under PostgreSQL 9.2." }, { "code": null, "e": 8278, "s": 8126, "text": "Follow the given steps to install PostgreSQL on your Mac machine. Make sure you are logged in as administrator before you proceed for the installation." }, { "code": null, "e": 8360, "s": 8278, "text": "Pick the latest version number of PostgreSQL for Mac OS available at EnterpriseDB" }, { "code": null, "e": 8442, "s": 8360, "text": "Pick the latest version number of PostgreSQL for Mac OS available at EnterpriseDB" }, { "code": null, "e": 8664, "s": 8442, "text": "I downloaded postgresql-9.2.4-1-osx.dmg for my Mac OS running with OS X version 10.8.3. Now, let us open the dmg image in finder and just double click it which will give you PostgreSQL installer in the following window −" }, { "code": null, "e": 8886, "s": 8664, "text": "I downloaded postgresql-9.2.4-1-osx.dmg for my Mac OS running with OS X version 10.8.3. Now, let us open the dmg image in finder and just double click it which will give you PostgreSQL installer in the following window −" }, { "code": null, "e": 9098, "s": 8886, "text": "Next, click the postgres-9.2.4-1-osx icon, which will give a warning message. Accept the warning and proceed for further installation. It will ask for the administrator password as seen in the following window −" }, { "code": null, "e": 9310, "s": 9098, "text": "Next, click the postgres-9.2.4-1-osx icon, which will give a warning message. Accept the warning and proceed for further installation. It will ask for the administrator password as seen in the following window −" }, { "code": null, "e": 9483, "s": 9310, "text": "Enter the password, proceed for the installation, and after this step, restart your Mac machine. If you do not see the following window, start your installation once again." }, { "code": null, "e": 9854, "s": 9483, "text": "Once you launch the installer, it asks you a few basic questions like location of the installation, password of the user who will use database, port number etc. Therefore, keep all of them at their default values except the password, which you can provide as per your choice. It will install PostgreSQL in your Mac machine in the Application folder which you can check −" }, { "code": null, "e": 10225, "s": 9854, "text": "Once you launch the installer, it asks you a few basic questions like location of the installation, password of the user who will use database, port number etc. Therefore, keep all of them at their default values except the password, which you can provide as per your choice. It will install PostgreSQL in your Mac machine in the Application folder which you can check −" }, { "code": null, "e": 10586, "s": 10225, "text": "Now, you can launch any of the program to start with. Let us start with SQL Shell. When you launch SQL Shell, just use all the default values it displays except, enter your password, which you had selected at the time of installation. If everything goes fine, then you will be inside postgres database and a postgress# prompt will be displayed as shown below −" }, { "code": null, "e": 10947, "s": 10586, "text": "Now, you can launch any of the program to start with. Let us start with SQL Shell. When you launch SQL Shell, just use all the default values it displays except, enter your password, which you had selected at the time of installation. If everything goes fine, then you will be inside postgres database and a postgress# prompt will be displayed as shown below −" } ]
Pandas.DataFrame.iterrows() function in Python
23 May, 2022 Pandas DataFrame.iterrows() is used to iterate over a pandas Data frame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in form of series. Syntax: DataFrame.iterrows() Yields: index- The index of the row. A tuple for a MultiIndex data- The data of the row as a Series Returns: it: A generator that iterates over the rows of the frame Example 1: Sometimes we need to iter over the data frame rows and columns without using any loops, in this situation Pandas DataFrame.iterrows() plays a crucial role. Python3 import pandas as pd # Creating a data frame along with column namedf = pd.DataFrame([[2, 2.5, 100, 4.5, 8.8, 95]], columns=[ 'int', 'float', 'int', 'float', 'float', 'int']) # Iter over the data frame rows# # using df.iterrows()itr = next(df.iterrows())[1]itr Output: In the above example, we use Pandas DataFrame.iterrows() to iter over numeric data frame rows. Example 2: Python3 import pandas as pd # Creating a data framedf = pd.DataFrame([['Animal', 'Baby', 'Cat', 'Dog', 'Elephant', 'Frog', 'Gragor']]) # Iterating over the data frame rows# using df.iterrows()itr = next(df.iterrows())[1]itr Output : In the above example, we iter over the data frame having no column names using Pandas DataFrame.iterrows() Note: As iterrows returns a Series for each row, it does not preserve dtypes across the rows. sumitgumber28 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 ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Introduction To PYTHON
[ { "code": null, "e": 53, "s": 25, "text": "\n23 May, 2022" }, { "code": null, "e": 296, "s": 53, "text": "Pandas DataFrame.iterrows() is used to iterate over a pandas Data frame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in form of series. " }, { "code": null, "e": 491, "s": 296, "text": "Syntax: DataFrame.iterrows() Yields: index- The index of the row. A tuple for a MultiIndex data- The data of the row as a Series Returns: it: A generator that iterates over the rows of the frame" }, { "code": null, "e": 503, "s": 491, "text": "Example 1: " }, { "code": null, "e": 659, "s": 503, "text": "Sometimes we need to iter over the data frame rows and columns without using any loops, in this situation Pandas DataFrame.iterrows() plays a crucial role." }, { "code": null, "e": 667, "s": 659, "text": "Python3" }, { "code": "import pandas as pd # Creating a data frame along with column namedf = pd.DataFrame([[2, 2.5, 100, 4.5, 8.8, 95]], columns=[ 'int', 'float', 'int', 'float', 'float', 'int']) # Iter over the data frame rows# # using df.iterrows()itr = next(df.iterrows())[1]itr", "e": 944, "s": 667, "text": null }, { "code": null, "e": 952, "s": 944, "text": "Output:" }, { "code": null, "e": 1047, "s": 952, "text": "In the above example, we use Pandas DataFrame.iterrows() to iter over numeric data frame rows." }, { "code": null, "e": 1058, "s": 1047, "text": "Example 2:" }, { "code": null, "e": 1066, "s": 1058, "text": "Python3" }, { "code": "import pandas as pd # Creating a data framedf = pd.DataFrame([['Animal', 'Baby', 'Cat', 'Dog', 'Elephant', 'Frog', 'Gragor']]) # Iterating over the data frame rows# using df.iterrows()itr = next(df.iterrows())[1]itr", "e": 1301, "s": 1066, "text": null }, { "code": null, "e": 1310, "s": 1301, "text": "Output :" }, { "code": null, "e": 1417, "s": 1310, "text": "In the above example, we iter over the data frame having no column names using Pandas DataFrame.iterrows()" }, { "code": null, "e": 1511, "s": 1417, "text": "Note: As iterrows returns a Series for each row, it does not preserve dtypes across the rows." }, { "code": null, "e": 1525, "s": 1511, "text": "sumitgumber28" }, { "code": null, "e": 1549, "s": 1525, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1581, "s": 1549, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 1595, "s": 1581, "text": "Python-pandas" }, { "code": null, "e": 1602, "s": 1595, "text": "Python" }, { "code": null, "e": 1700, "s": 1602, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1718, "s": 1700, "text": "Python Dictionary" }, { "code": null, "e": 1760, "s": 1718, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1782, "s": 1760, "text": "Enumerate() in Python" }, { "code": null, "e": 1817, "s": 1782, "text": "Read a file line by line in Python" }, { "code": null, "e": 1849, "s": 1817, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1878, "s": 1849, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1905, "s": 1878, "text": "Python Classes and Objects" }, { "code": null, "e": 1935, "s": 1905, "text": "Iterate over a list in Python" }, { "code": null, "e": 1956, "s": 1935, "text": "Python OOPs Concepts" } ]
How to create a multiline entry with Tkinter?
16 Mar, 2021 Tkinter is a library in Python for developing GUI. It provides various widgets for developing GUI(Graphical User Interface). The Entry widget in tkinter helps to take user input, but it collects the input limited to a single line of text. Therefore, to create a Multiline entry text in tkinter there are a number of ways. Methods to create multiline entry with tkinter: Using Text WidgetUsing ScrolledText widget Using Text Widget Using ScrolledText widget Method 1: Using Tkinter Text Widget A text widget provides a multi-line text area for the user. The text widget instance is created with the help of the text class. It is also used to display text lines and also allows editing the text. Syntax: Text( root, optional parameters, ... ) Example 1: Python3 import tkinter as tkfrom tkinter import ttk window = tk.Tk()window.title("Text Widget Example")window.geometry('400x200') ttk.Label(window, text="Enter your comment :", font=("Times New Roman", 15)).grid( column=0, row=15, padx=10, pady=25) # Text Widgett = tk.Text(window, width=20, height=3) t.grid(column=1, row=15) window.mainloop() Output: The above output of the example lets the user enter text in multiple lines. But it does not show all the text entered by the user beyond the height of the text widget i.e., height=3. As it shows only 3 lines of text, therefore using a scroll bar for such multiline texts will solve the problem. Example 2: Adding Scrollbar to text widget Python3 import tkinter as tk window = tk.Tk()window.title("Text Widget with Scrollbar") text = tk.Text(window, height=8, width=40)scroll = tk.Scrollbar(window)text.configure(yscrollcommand=scroll.set)text.pack(side=tk.LEFT) scroll.config(command=text.yview)scroll.pack(side=tk.RIGHT, fill=tk.Y) insert_text = """GEEKSFORGEEKS :A Computer Science portal for geeks.It contains well written, well thoughtand well explained computer science andprogramming articles, quizzes andmany more.GeeksforGeeks realises the importance of programming practice in the field ofComputer Science.That is why, it also provides an option of practicing problems.This huge database of problems is created by programming experts.The active team of GeeksforGeeks makes the learning processinteresting and fun.""" text.insert(tk.END, insert_text)tk.mainloop() Output: Method 2: Using ScrolledText tkinter Widget Instead of adding a scroll bar to a text widget as seen in example 2, we can directly use the ScrolledText tkinter widget for multiline entry by the user. This widget automatically adds the scroll bar as the text gets increased than the height of the scrolledText widget. Example: Python3 import tkinter as tkfrom tkinter import ttkfrom tkinter import scrolledtext root = tk.Tk() root.title("ScrolledText Widget Example") ttk.Label(root, text="ScrolledText Widget Example", font=("Times New Roman", 15)).grid(column=0, row=0)ttk.Label(root, text="Enter your comments :", font=("Bold", 12)).grid(column=0, row=1) text_area = scrolledtext.ScrolledText(root, wrap=tk.WORD, width=40, height=8, font=("Times New Roman", 15)) text_area.grid(column=0, row=2, pady=10, padx=10) # placing cursor in text areatext_area.focus()root.mainloop() Output: Picked Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Rotate axis tick labels in Seaborn and Matplotlib Deque in Python Queue in Python Defaultdict in Python Check if element exists in list in Python Python Classes and Objects Bar Plot in Matplotlib reduce() in Python Python | Get unique values from a list
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Mar, 2021" }, { "code": null, "e": 377, "s": 54, "text": "Tkinter is a library in Python for developing GUI. It provides various widgets for developing GUI(Graphical User Interface). The Entry widget in tkinter helps to take user input, but it collects the input limited to a single line of text. Therefore, to create a Multiline entry text in tkinter there are a number of ways. " }, { "code": null, "e": 425, "s": 377, "text": "Methods to create multiline entry with tkinter:" }, { "code": null, "e": 468, "s": 425, "text": "Using Text WidgetUsing ScrolledText widget" }, { "code": null, "e": 486, "s": 468, "text": "Using Text Widget" }, { "code": null, "e": 512, "s": 486, "text": "Using ScrolledText widget" }, { "code": null, "e": 548, "s": 512, "text": "Method 1: Using Tkinter Text Widget" }, { "code": null, "e": 749, "s": 548, "text": "A text widget provides a multi-line text area for the user. The text widget instance is created with the help of the text class. It is also used to display text lines and also allows editing the text." }, { "code": null, "e": 757, "s": 749, "text": "Syntax:" }, { "code": null, "e": 796, "s": 757, "text": "Text( root, optional parameters, ... )" }, { "code": null, "e": 807, "s": 796, "text": "Example 1:" }, { "code": null, "e": 815, "s": 807, "text": "Python3" }, { "code": "import tkinter as tkfrom tkinter import ttk window = tk.Tk()window.title(\"Text Widget Example\")window.geometry('400x200') ttk.Label(window, text=\"Enter your comment :\", font=(\"Times New Roman\", 15)).grid( column=0, row=15, padx=10, pady=25) # Text Widgett = tk.Text(window, width=20, height=3) t.grid(column=1, row=15) window.mainloop()", "e": 1169, "s": 815, "text": null }, { "code": null, "e": 1177, "s": 1169, "text": "Output:" }, { "code": null, "e": 1472, "s": 1177, "text": "The above output of the example lets the user enter text in multiple lines. But it does not show all the text entered by the user beyond the height of the text widget i.e., height=3. As it shows only 3 lines of text, therefore using a scroll bar for such multiline texts will solve the problem." }, { "code": null, "e": 1515, "s": 1472, "text": "Example 2: Adding Scrollbar to text widget" }, { "code": null, "e": 1523, "s": 1515, "text": "Python3" }, { "code": "import tkinter as tk window = tk.Tk()window.title(\"Text Widget with Scrollbar\") text = tk.Text(window, height=8, width=40)scroll = tk.Scrollbar(window)text.configure(yscrollcommand=scroll.set)text.pack(side=tk.LEFT) scroll.config(command=text.yview)scroll.pack(side=tk.RIGHT, fill=tk.Y) insert_text = \"\"\"GEEKSFORGEEKS :A Computer Science portal for geeks.It contains well written, well thoughtand well explained computer science andprogramming articles, quizzes andmany more.GeeksforGeeks realises the importance of programming practice in the field ofComputer Science.That is why, it also provides an option of practicing problems.This huge database of problems is created by programming experts.The active team of GeeksforGeeks makes the learning processinteresting and fun.\"\"\" text.insert(tk.END, insert_text)tk.mainloop()", "e": 2356, "s": 1523, "text": null }, { "code": null, "e": 2364, "s": 2356, "text": "Output:" }, { "code": null, "e": 2408, "s": 2364, "text": "Method 2: Using ScrolledText tkinter Widget" }, { "code": null, "e": 2680, "s": 2408, "text": "Instead of adding a scroll bar to a text widget as seen in example 2, we can directly use the ScrolledText tkinter widget for multiline entry by the user. This widget automatically adds the scroll bar as the text gets increased than the height of the scrolledText widget." }, { "code": null, "e": 2689, "s": 2680, "text": "Example:" }, { "code": null, "e": 2697, "s": 2689, "text": "Python3" }, { "code": "import tkinter as tkfrom tkinter import ttkfrom tkinter import scrolledtext root = tk.Tk() root.title(\"ScrolledText Widget Example\") ttk.Label(root, text=\"ScrolledText Widget Example\", font=(\"Times New Roman\", 15)).grid(column=0, row=0)ttk.Label(root, text=\"Enter your comments :\", font=(\"Bold\", 12)).grid(column=0, row=1) text_area = scrolledtext.ScrolledText(root, wrap=tk.WORD, width=40, height=8, font=(\"Times New Roman\", 15)) text_area.grid(column=0, row=2, pady=10, padx=10) # placing cursor in text areatext_area.focus()root.mainloop()", "e": 3331, "s": 2697, "text": null }, { "code": null, "e": 3339, "s": 3331, "text": "Output:" }, { "code": null, "e": 3346, "s": 3339, "text": "Picked" }, { "code": null, "e": 3361, "s": 3346, "text": "Python-tkinter" }, { "code": null, "e": 3368, "s": 3361, "text": "Python" }, { "code": null, "e": 3466, "s": 3368, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3511, "s": 3466, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 3561, "s": 3511, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 3577, "s": 3561, "text": "Deque in Python" }, { "code": null, "e": 3593, "s": 3577, "text": "Queue in Python" }, { "code": null, "e": 3615, "s": 3593, "text": "Defaultdict in Python" }, { "code": null, "e": 3657, "s": 3615, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3684, "s": 3657, "text": "Python Classes and Objects" }, { "code": null, "e": 3707, "s": 3684, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 3726, "s": 3707, "text": "reduce() in Python" } ]
Node.js This Binding
08 Oct, 2021 Arrow functions don’t bind their own ‘this’ value. Instead, the ‘this’ value of the scope in which it was defined is accessible. This makes arrow functions bad candidates for methods, as this won’t be a reference to the object the method is defined on. For methods, ES6 provides a new method definition syntax. You can see this in the definition of the printGuestList method below. That function is a standard function, just with a shorthand syntax which allows for the removal of the colon and the function keyword. Because arrow functions don’t bind this, they work well for everything except methods. As shown below, the arrow function passed to forEach is able to access this.name correctly, as it’s defined as an arrow function and doesn’t have this binding of its own. That code wouldn’t work if you swapped out the arrow function for a standard function. Create a folder and add a file for example index.js. To run this file you need to run the following command. node index.js Filename: index.js // 'This' in Arrow functionconst eventOne = { name: 'Birthday Party', guestList: ['Gourav', 'Vijay'], printGuestList() { console.log('Guest list for ' + this.name); this.guestList.forEach((guest) => { console.log(guest + ' is attending ' + this.name) }); }} // 'This' in normal functionconst eventTwo = { name: 'Birthday Party', guestList: ['Gourav', 'Vijay'], printGuestList() { console.log('Guest list for ' + this.name); this.guestList.forEach(function (guest) { console.log(guest + ' is attending ' + this.name) }); }} eventOne.printGuestList();console.log('---------------------');eventTwo.printGuestList(); Steps to run the program: Run index.js file using the following command:node index.js node index.js So this is how ‘this’ binding works on arrow functions and normal functions. Node.js-Basics Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Oct, 2021" }, { "code": null, "e": 281, "s": 28, "text": "Arrow functions don’t bind their own ‘this’ value. Instead, the ‘this’ value of the scope in which it was defined is accessible. This makes arrow functions bad candidates for methods, as this won’t be a reference to the object the method is defined on." }, { "code": null, "e": 545, "s": 281, "text": "For methods, ES6 provides a new method definition syntax. You can see this in the definition of the printGuestList method below. That function is a standard function, just with a shorthand syntax which allows for the removal of the colon and the function keyword." }, { "code": null, "e": 890, "s": 545, "text": "Because arrow functions don’t bind this, they work well for everything except methods. As shown below, the arrow function passed to forEach is able to access this.name correctly, as it’s defined as an arrow function and doesn’t have this binding of its own. That code wouldn’t work if you swapped out the arrow function for a standard function." }, { "code": null, "e": 999, "s": 890, "text": "Create a folder and add a file for example index.js. To run this file you need to run the following command." }, { "code": null, "e": 1013, "s": 999, "text": "node index.js" }, { "code": null, "e": 1032, "s": 1013, "text": "Filename: index.js" }, { "code": "// 'This' in Arrow functionconst eventOne = { name: 'Birthday Party', guestList: ['Gourav', 'Vijay'], printGuestList() { console.log('Guest list for ' + this.name); this.guestList.forEach((guest) => { console.log(guest + ' is attending ' + this.name) }); }} // 'This' in normal functionconst eventTwo = { name: 'Birthday Party', guestList: ['Gourav', 'Vijay'], printGuestList() { console.log('Guest list for ' + this.name); this.guestList.forEach(function (guest) { console.log(guest + ' is attending ' + this.name) }); }} eventOne.printGuestList();console.log('---------------------');eventTwo.printGuestList();", "e": 1735, "s": 1032, "text": null }, { "code": null, "e": 1761, "s": 1735, "text": "Steps to run the program:" }, { "code": null, "e": 1821, "s": 1761, "text": "Run index.js file using the following command:node index.js" }, { "code": null, "e": 1835, "s": 1821, "text": "node index.js" }, { "code": null, "e": 1912, "s": 1835, "text": "So this is how ‘this’ binding works on arrow functions and normal functions." }, { "code": null, "e": 1927, "s": 1912, "text": "Node.js-Basics" }, { "code": null, "e": 1935, "s": 1927, "text": "Node.js" }, { "code": null, "e": 1952, "s": 1935, "text": "Web Technologies" } ]
How to Check Internet Connection in Android with No Internet Connection Dialog?
18 Jul, 2021 Hello geeks, today we are going to learn that how we can add the functionality of Internet Alert to our application. You have definitely seen in almost all applications that when data is turned off or application is not able to get Internet then it pops up a message of “No Internet Connection” and then again it is connected to data is displays message as “Back Online’ or “Internet in connected”, we are going to implement the same in our application. Goals/purposes of Internet Alert: To inform the user that he/she is not connected to the network. To stop all internet-related activities or services in the application. Here, we will be creating a button. Whenever the user will press the button message of Internet Connectivity will be displayed. Note that we are going to implement this application using Java language. A sample video is given below to get an idea about what we are going to do in this article. Step 1: Creating a new project Open a new project. We will be working on Empty Activity with language as Java. Leave all other options unchanged. You can change the name of the project at your convenience. There will be two default files named activity_main.xml and MainActivity.java. If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? Step 2: Navigate to app > manifests > AndroidManifest.xml file and paste the following piece of code to add internet permission <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.INTERNET"/> Step 3: Working with activity_main.xml file We are using a button in the activity_main.xml file to perform the action. Use the following code in the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?> <!-- Relative layout as parent layout--><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" tools:context=".MainActivity"> <!-- Button to perform the action of Internet alert--> <Button android:id="@+id/btn_check" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Check Internet Connection" /> </RelativeLayout> After implementing the above code, the design of the activity_main.xml file will look like this. Step 4: Working with java files Create a new java class named as ConnectionReceiver using the following method Use the below code in the ConnectionReceiver.java file. Java import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.net.ConnectivityManager;import android.net.NetworkInfo; public class ConnectionReceiver extends BroadcastReceiver { // initialize listener public static ReceiverListener Listener; @Override public void onReceive(Context context, Intent intent) { // initialize connectivity manager ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // Initialize network info NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); // check condition if (Listener != null) { // when connectivity receiver // listener not null // get connection status boolean isConnected = networkInfo != null && networkInfo.isConnectedOrConnecting(); // call listener method Listener.onNetworkChange(isConnected); } } public interface ReceiverListener { // create method void onNetworkChange(boolean isConnected); }} Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.Context;import android.content.IntentFilter;import android.graphics.Color;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.snackbar.Snackbar; public class MainActivity extends AppCompatActivity implements ConnectionReceiver.ReceiverListener { Button btn_check; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // assign variable btn_check = findViewById(R.id.btn_check); // create method checkConnection(); btn_check.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // call method checkConnection(); } }); } private void checkConnection() { // initialize intent filter IntentFilter intentFilter = new IntentFilter(); // add action intentFilter.addAction("android.new.conn.CONNECTIVITY_CHANGE"); // register receiver registerReceiver(new ConnectionReceiver(), intentFilter); // Initialize listener ConnectionReceiver.Listener = this; // Initialize connectivity manager ConnectivityManager manager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); // Initialize network info NetworkInfo networkInfo = manager.getActiveNetworkInfo(); // get connection status boolean isConnected = networkInfo != null && networkInfo.isConnectedOrConnecting(); // display snack bar showSnackBar(isConnected); } private void showSnackBar(boolean isConnected) { // initialize color and message String message; int color; // check condition if (isConnected) { // when internet is connected // set message message = "Connected to Internet"; // set text color color = Color.WHITE; } else { // when internet // is disconnected // set message message = "Not Connected to Internet"; // set text color color = Color.RED; } // initialize snack bar Snackbar snackbar = Snackbar.make(findViewById(R.id.btn_check), message, Snackbar.LENGTH_LONG); // initialize view View view = snackbar.getView(); // Assign variable TextView textView = view.findViewById(R.id.snackbar_text); // set text color textView.setTextColor(color); // show snack bar snackbar.show(); } @Override public void onNetworkChange(boolean isConnected) { // display snack bar showSnackBar(isConnected); } @Override protected void onResume() { super.onResume(); // call method checkConnection(); } @Override protected void onPause() { super.onPause(); // call method checkConnection(); }} Congratulations! we have successfully made the application to check Internet Connection and alert it to the user. Here is the final output of our application. Output: Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android Arrays.sort() in Java with examples For-each loop in Java Arrays in Java Multidimensional Arrays in Java Split() String method in Java with examples
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jul, 2021" }, { "code": null, "e": 483, "s": 28, "text": "Hello geeks, today we are going to learn that how we can add the functionality of Internet Alert to our application. You have definitely seen in almost all applications that when data is turned off or application is not able to get Internet then it pops up a message of “No Internet Connection” and then again it is connected to data is displays message as “Back Online’ or “Internet in connected”, we are going to implement the same in our application. " }, { "code": null, "e": 517, "s": 483, "text": "Goals/purposes of Internet Alert:" }, { "code": null, "e": 581, "s": 517, "text": "To inform the user that he/she is not connected to the network." }, { "code": null, "e": 653, "s": 581, "text": "To stop all internet-related activities or services in the application." }, { "code": null, "e": 947, "s": 653, "text": "Here, we will be creating a button. Whenever the user will press the button message of Internet Connectivity will be displayed. Note that we are going to implement this application using Java language. A sample video is given below to get an idea about what we are going to do in this article." }, { "code": null, "e": 978, "s": 947, "text": "Step 1: Creating a new project" }, { "code": null, "e": 998, "s": 978, "text": "Open a new project." }, { "code": null, "e": 1093, "s": 998, "text": "We will be working on Empty Activity with language as Java. Leave all other options unchanged." }, { "code": null, "e": 1153, "s": 1093, "text": "You can change the name of the project at your convenience." }, { "code": null, "e": 1232, "s": 1153, "text": "There will be two default files named activity_main.xml and MainActivity.java." }, { "code": null, "e": 1372, "s": 1232, "text": "If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? " }, { "code": null, "e": 1500, "s": 1372, "text": "Step 2: Navigate to app > manifests > AndroidManifest.xml file and paste the following piece of code to add internet permission" }, { "code": null, "e": 1636, "s": 1500, "text": "<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>\n<uses-permission android:name=\"android.permission.INTERNET\"/>" }, { "code": null, "e": 1680, "s": 1636, "text": "Step 3: Working with activity_main.xml file" }, { "code": null, "e": 1809, "s": 1680, "text": "We are using a button in the activity_main.xml file to perform the action. Use the following code in the activity_main.xml file." }, { "code": null, "e": 1813, "s": 1809, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <!-- Relative layout as parent layout--><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\" tools:context=\".MainActivity\"> <!-- Button to perform the action of Internet alert--> <Button android:id=\"@+id/btn_check\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"Check Internet Connection\" /> </RelativeLayout>", "e": 2442, "s": 1813, "text": null }, { "code": null, "e": 2539, "s": 2442, "text": "After implementing the above code, the design of the activity_main.xml file will look like this." }, { "code": null, "e": 2571, "s": 2539, "text": "Step 4: Working with java files" }, { "code": null, "e": 2653, "s": 2571, "text": "Create a new java class named as ConnectionReceiver using the following method " }, { "code": null, "e": 2709, "s": 2653, "text": "Use the below code in the ConnectionReceiver.java file." }, { "code": null, "e": 2714, "s": 2709, "text": "Java" }, { "code": "import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.net.ConnectivityManager;import android.net.NetworkInfo; public class ConnectionReceiver extends BroadcastReceiver { // initialize listener public static ReceiverListener Listener; @Override public void onReceive(Context context, Intent intent) { // initialize connectivity manager ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // Initialize network info NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); // check condition if (Listener != null) { // when connectivity receiver // listener not null // get connection status boolean isConnected = networkInfo != null && networkInfo.isConnectedOrConnecting(); // call listener method Listener.onNetworkChange(isConnected); } } public interface ReceiverListener { // create method void onNetworkChange(boolean isConnected); }}", "e": 3921, "s": 2714, "text": null }, { "code": null, "e": 4111, "s": 3921, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 4116, "s": 4111, "text": "Java" }, { "code": "import android.content.Context;import android.content.IntentFilter;import android.graphics.Color;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.snackbar.Snackbar; public class MainActivity extends AppCompatActivity implements ConnectionReceiver.ReceiverListener { Button btn_check; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // assign variable btn_check = findViewById(R.id.btn_check); // create method checkConnection(); btn_check.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // call method checkConnection(); } }); } private void checkConnection() { // initialize intent filter IntentFilter intentFilter = new IntentFilter(); // add action intentFilter.addAction(\"android.new.conn.CONNECTIVITY_CHANGE\"); // register receiver registerReceiver(new ConnectionReceiver(), intentFilter); // Initialize listener ConnectionReceiver.Listener = this; // Initialize connectivity manager ConnectivityManager manager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); // Initialize network info NetworkInfo networkInfo = manager.getActiveNetworkInfo(); // get connection status boolean isConnected = networkInfo != null && networkInfo.isConnectedOrConnecting(); // display snack bar showSnackBar(isConnected); } private void showSnackBar(boolean isConnected) { // initialize color and message String message; int color; // check condition if (isConnected) { // when internet is connected // set message message = \"Connected to Internet\"; // set text color color = Color.WHITE; } else { // when internet // is disconnected // set message message = \"Not Connected to Internet\"; // set text color color = Color.RED; } // initialize snack bar Snackbar snackbar = Snackbar.make(findViewById(R.id.btn_check), message, Snackbar.LENGTH_LONG); // initialize view View view = snackbar.getView(); // Assign variable TextView textView = view.findViewById(R.id.snackbar_text); // set text color textView.setTextColor(color); // show snack bar snackbar.show(); } @Override public void onNetworkChange(boolean isConnected) { // display snack bar showSnackBar(isConnected); } @Override protected void onResume() { super.onResume(); // call method checkConnection(); } @Override protected void onPause() { super.onPause(); // call method checkConnection(); }}", "e": 7474, "s": 4116, "text": null }, { "code": null, "e": 7633, "s": 7474, "text": "Congratulations! we have successfully made the application to check Internet Connection and alert it to the user. Here is the final output of our application." }, { "code": null, "e": 7641, "s": 7633, "text": "Output:" }, { "code": null, "e": 7649, "s": 7641, "text": "Android" }, { "code": null, "e": 7654, "s": 7649, "text": "Java" }, { "code": null, "e": 7659, "s": 7654, "text": "Java" }, { "code": null, "e": 7667, "s": 7659, "text": "Android" }, { "code": null, "e": 7765, "s": 7667, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7834, "s": 7765, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 7866, "s": 7834, "text": "Android SDK and it's Components" }, { "code": null, "e": 7905, "s": 7866, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 7954, "s": 7905, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 7996, "s": 7954, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 8032, "s": 7996, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 8054, "s": 8032, "text": "For-each loop in Java" }, { "code": null, "e": 8069, "s": 8054, "text": "Arrays in Java" }, { "code": null, "e": 8101, "s": 8069, "text": "Multidimensional Arrays in Java" } ]
Pure CSS Tables
28 Sep, 2021 Introduction: Before starting with Pure we must know the basics of plain CSS. Basically, Pure CSS is a Cascading Style Sheet framework developed by YAHOO. The main reason for developing Pure CSS is used to develop responsive and reactive websites like Bootstrap which is also compatible with mobile devices and it is an open-source CSS framework and free to use. It can be the best alternative to Materialize CSS. In this article, we will understand what is Pure CSS Table is? and learn how to use it in our project. As we think of creating web pages, we know that tables are a nice and easy way to organize a lot of data in websites into the form of rows and columns. By using the Pure CSS framework, we will be able to design different types of tables. Pure CSS provides a number of utility classes to style tables, there basically 5 main classes as listed below: pure-table: This class is used to style the table with default padding and border assign to table elements with an emphasized header. pure-table-bordered: This class is used to draw borders on the table vertical and horizontal to all the table cells. pure-table-horizontal: This class is used to draw the table with only horizontal lines. pure-table-odd: This class is used to create a striped table with the zebra-styled effect which is more visible and attractive for the users. pure-table-striped: Basically it is used to display striped tables. It Automatically Striped a table after pass to the <table> element alongside the pure-table class. Examples: Now here we learn how to use table classes in HTML. 1. Default Table: The pure-table class is used in <table> tag to create a basic table with some basic CSS styling, these tables are just like the normal HTML tables with some padding and border added to table elements with the header. HTML <!DOCTYPE html><html> <head> <!-- Import Pure CSS --> <link rel="stylesheet" href="https://unpkg.com/purecss@2.0.6/build/pure-min.css" integrity="sha384-Uu6IeWbM+gzNVXJcM9XV3SohHtmWE+3VGi496jvgX1jyvDTXfdK+rfZc8C1Aehk5" crossorigin="anonymous" origin="anonymous" /> <!-- Used to optimized Website for mobile --> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <style> .container { margin-top: 20px; display: flex; align-items: center; justify-content: center; flex-direction: column; } h1 { color: green; } </style> </head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <h2>Default Table</h2> <!-- Here pure-table class is used --> <table class="pure-table"> <thead> <tr> <th>Rank</th> <th>Name</th> <th>Runs</th> <th>Centuries</th> <th>Strike Rate</th> <th>Avg</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Rohit</td> <td>10000</td> <td>29</td> <td>97</td> <td>55</td> </tr> <tr> <td>2</td> <td>Virat</td> <td>12000</td> <td>40</td> <td>91</td> <td>49</td> </tr> <tr> <td>3</td> <td>Rahul</td> <td>5000</td> <td>8</td> <td>85</td> <td>45</td> </tr> <tr> <td>4</td> <td>Rishabh</td> <td>4000</td> <td>2</td> <td>89</td> <td>39</td> </tr> </tbody> </table> </div> </body></html> Output: 2. Bordered Table: Here we use the pure-table-bordered class is used to create a bordered table. This class will add vertical and horizontal borders to all the cells of the table. HTML <!DOCTYPE html><html> <head> <!-- Import Pure CSS --> <link rel="stylesheet" href="https://unpkg.com/purecss@2.0.6/build/pure-min.css" integrity="sha384-Uu6IeWbM+gzNVXJcM9XV3SohHtmWE+3VGi496jvgX1jyvDTXfdK+rfZc8C1Aehk5" crossorigin="anonymous" origin="anonymous" /> <!-- Used to optimized Website for mobile --> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <style> .container { margin-top: 20px; display: flex; align-items: center; justify-content: center; flex-direction: column; } h1 { color: green; } </style> </head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <h2>Bordered Table</h2> <!-- Here pure-table and pure-table-bordered class is used --> <table class="pure-table pure-table-bordered"> <thead> <tr> <th>Rank</th> <th>Name</th> <th>Runs</th> <th>Centuries</th> <th>Strike Rate</th> <th>Avg</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Rohit</td> <td>10000</td> <td>29</td> <td>97</td> <td>55</td> </tr> <tr> <td>2</td> <td>Virat</td> <td>12000</td> <td>40</td> <td>91</td> <td>49</td> </tr> <tr> <td>3</td> <td>Rahul</td> <td>5000</td> <td>8</td> <td>85</td> <td>45</td> </tr> <tr> <td>4</td> <td>Rishabh</td> <td>4000</td> <td>2</td> <td>89</td> <td>39</td> </tr> </tbody> </table> </div> </body></html> Output: 3. Table with Horizontal Borders: Here we used the pure-table-horizontal class to create this type of table. This will create a table with horizontal lines only. HTML <!DOCTYPE html><html> <head> <!-- Import Pure CSS --> <link rel="stylesheet" href="https://unpkg.com/purecss@2.0.6/build/pure-min.css" integrity="sha384-Uu6IeWbM+gzNVXJcM9XV3SohHtmWE+3VGi496jvgX1jyvDTXfdK+rfZc8C1Aehk5" crossorigin="anonymous" origin="anonymous" /> <!-- Used to optimized Website for mobile --> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <style> .container { margin-top: 20px; display: flex; align-items: center; justify-content: center; flex-direction: column; } h1 { color: green; } </style> </head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <h2>Horizontal Bordered Table</h2> <!-- Here pure-table and pure-table-horizontal class is used --> <table class="pure-table pure-table-horizontal"> <thead> <tr> <th>Rank</th> <th>Name</th> <th>Runs</th> <th>Centuries</th> <th>Strike Rate</th> <th>Avg</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Rohit</td> <td>10000</td> <td>29</td> <td>97</td> <td>55</td> </tr> <tr> <td>2</td> <td>Virat</td> <td>12000</td> <td>40</td> <td>91</td> <td>49</td> </tr> <tr> <td>3</td> <td>Rahul</td> <td>5000</td> <td>8</td> <td>85</td> <td>45</td> </tr> <tr> <td>4</td> <td>Rishabh</td> <td>4000</td> <td>2</td> <td>89</td> <td>39</td> </tr> </tbody> </table> </div> </body></html> Output: 4. Striped Table: For better visualization of large-size tables we can use striped cells. For a striped table here we used the pure-table-odd Pure CSS class in the every <tr> element tag to change the background of the odd rows. This will create a striped table with the zebra-styled effect which is more visible and attractive for a large number of data to the user. HTML <!DOCTYPE html><html> <head> <!-- Import Pure CSS --> <link rel="stylesheet" href="https://unpkg.com/purecss@2.0.6/build/pure-min.css" integrity="sha384-Uu6IeWbM+gzNVXJcM9XV3SohHtmWE+3VGi496jvgX1jyvDTXfdK+rfZc8C1Aehk5" crossorigin="anonymous" origin="anonymous" /> <!-- Used to optimized Website for mobile --> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <style> .container { margin-top: 20px; display: flex; align-items: center; justify-content: center; flex-direction: column; } h1 { color: green; } </style> </head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <h2>Horizontal Bordered Table</h2> <!-- Here pure-table class is used --> <table class="pure-table"> <thead> <tr> <th>Rank</th> <th>Name</th> <th>Runs</th> <th>Centuries</th> <th>Strike Rate</th> <th>Avg</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Rohit</td> <td>10000</td> <td>29</td> <td>97</td> <td>55</td> </tr> <!--Here pure-table-odd class used to change background of row--> <tr class="pure-table-odd"> <td>2</td> <td>Virat</td> <td>12000</td> <td>40</td> <td>91</td> <td>49</td> </tr> <tr> <td>3</td> <td>Rahul</td> <td>5000</td> <td>8</td> <td>85</td> <td>45</td> </tr> <tr class="pure-table-odd"> <td>4</td> <td>Rishabh</td> <td>4000</td> <td>2</td> <td>89</td> <td>39</td> </tr> </tbody> </table> </div> </body></html> Output: In this article, we learn what is Pure CSS Table is, its classes, and how to use it in various tables. omkarbhusnale Pure CSS CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Sep, 2021" }, { "code": null, "e": 466, "s": 52, "text": "Introduction: Before starting with Pure we must know the basics of plain CSS. Basically, Pure CSS is a Cascading Style Sheet framework developed by YAHOO. The main reason for developing Pure CSS is used to develop responsive and reactive websites like Bootstrap which is also compatible with mobile devices and it is an open-source CSS framework and free to use. It can be the best alternative to Materialize CSS." }, { "code": null, "e": 569, "s": 466, "text": "In this article, we will understand what is Pure CSS Table is? and learn how to use it in our project." }, { "code": null, "e": 807, "s": 569, "text": "As we think of creating web pages, we know that tables are a nice and easy way to organize a lot of data in websites into the form of rows and columns. By using the Pure CSS framework, we will be able to design different types of tables." }, { "code": null, "e": 918, "s": 807, "text": "Pure CSS provides a number of utility classes to style tables, there basically 5 main classes as listed below:" }, { "code": null, "e": 1052, "s": 918, "text": "pure-table: This class is used to style the table with default padding and border assign to table elements with an emphasized header." }, { "code": null, "e": 1169, "s": 1052, "text": "pure-table-bordered: This class is used to draw borders on the table vertical and horizontal to all the table cells." }, { "code": null, "e": 1257, "s": 1169, "text": "pure-table-horizontal: This class is used to draw the table with only horizontal lines." }, { "code": null, "e": 1399, "s": 1257, "text": "pure-table-odd: This class is used to create a striped table with the zebra-styled effect which is more visible and attractive for the users." }, { "code": null, "e": 1567, "s": 1399, "text": "pure-table-striped: Basically it is used to display striped tables. It Automatically Striped a table after pass to the <table> element alongside the pure-table class. " }, { "code": null, "e": 1629, "s": 1567, "text": "Examples: Now here we learn how to use table classes in HTML." }, { "code": null, "e": 1865, "s": 1629, "text": "1. Default Table: The pure-table class is used in <table> tag to create a basic table with some basic CSS styling, these tables are just like the normal HTML tables with some padding and border added to table elements with the header. " }, { "code": null, "e": 1870, "s": 1865, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Import Pure CSS --> <link rel=\"stylesheet\" href=\"https://unpkg.com/purecss@2.0.6/build/pure-min.css\" integrity=\"sha384-Uu6IeWbM+gzNVXJcM9XV3SohHtmWE+3VGi496jvgX1jyvDTXfdK+rfZc8C1Aehk5\" crossorigin=\"anonymous\" origin=\"anonymous\" /> <!-- Used to optimized Website for mobile --> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <style> .container { margin-top: 20px; display: flex; align-items: center; justify-content: center; flex-direction: column; } h1 { color: green; } </style> </head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <h2>Default Table</h2> <!-- Here pure-table class is used --> <table class=\"pure-table\"> <thead> <tr> <th>Rank</th> <th>Name</th> <th>Runs</th> <th>Centuries</th> <th>Strike Rate</th> <th>Avg</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Rohit</td> <td>10000</td> <td>29</td> <td>97</td> <td>55</td> </tr> <tr> <td>2</td> <td>Virat</td> <td>12000</td> <td>40</td> <td>91</td> <td>49</td> </tr> <tr> <td>3</td> <td>Rahul</td> <td>5000</td> <td>8</td> <td>85</td> <td>45</td> </tr> <tr> <td>4</td> <td>Rishabh</td> <td>4000</td> <td>2</td> <td>89</td> <td>39</td> </tr> </tbody> </table> </div> </body></html>", "e": 3697, "s": 1870, "text": null }, { "code": null, "e": 3705, "s": 3697, "text": "Output:" }, { "code": null, "e": 3885, "s": 3705, "text": "2. Bordered Table: Here we use the pure-table-bordered class is used to create a bordered table. This class will add vertical and horizontal borders to all the cells of the table." }, { "code": null, "e": 3890, "s": 3885, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Import Pure CSS --> <link rel=\"stylesheet\" href=\"https://unpkg.com/purecss@2.0.6/build/pure-min.css\" integrity=\"sha384-Uu6IeWbM+gzNVXJcM9XV3SohHtmWE+3VGi496jvgX1jyvDTXfdK+rfZc8C1Aehk5\" crossorigin=\"anonymous\" origin=\"anonymous\" /> <!-- Used to optimized Website for mobile --> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <style> .container { margin-top: 20px; display: flex; align-items: center; justify-content: center; flex-direction: column; } h1 { color: green; } </style> </head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <h2>Bordered Table</h2> <!-- Here pure-table and pure-table-bordered class is used --> <table class=\"pure-table pure-table-bordered\"> <thead> <tr> <th>Rank</th> <th>Name</th> <th>Runs</th> <th>Centuries</th> <th>Strike Rate</th> <th>Avg</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Rohit</td> <td>10000</td> <td>29</td> <td>97</td> <td>55</td> </tr> <tr> <td>2</td> <td>Virat</td> <td>12000</td> <td>40</td> <td>91</td> <td>49</td> </tr> <tr> <td>3</td> <td>Rahul</td> <td>5000</td> <td>8</td> <td>85</td> <td>45</td> </tr> <tr> <td>4</td> <td>Rishabh</td> <td>4000</td> <td>2</td> <td>89</td> <td>39</td> </tr> </tbody> </table> </div> </body></html>", "e": 5757, "s": 3890, "text": null }, { "code": null, "e": 5765, "s": 5757, "text": "Output:" }, { "code": null, "e": 5927, "s": 5765, "text": "3. Table with Horizontal Borders: Here we used the pure-table-horizontal class to create this type of table. This will create a table with horizontal lines only." }, { "code": null, "e": 5932, "s": 5927, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Import Pure CSS --> <link rel=\"stylesheet\" href=\"https://unpkg.com/purecss@2.0.6/build/pure-min.css\" integrity=\"sha384-Uu6IeWbM+gzNVXJcM9XV3SohHtmWE+3VGi496jvgX1jyvDTXfdK+rfZc8C1Aehk5\" crossorigin=\"anonymous\" origin=\"anonymous\" /> <!-- Used to optimized Website for mobile --> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <style> .container { margin-top: 20px; display: flex; align-items: center; justify-content: center; flex-direction: column; } h1 { color: green; } </style> </head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <h2>Horizontal Bordered Table</h2> <!-- Here pure-table and pure-table-horizontal class is used --> <table class=\"pure-table pure-table-horizontal\"> <thead> <tr> <th>Rank</th> <th>Name</th> <th>Runs</th> <th>Centuries</th> <th>Strike Rate</th> <th>Avg</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Rohit</td> <td>10000</td> <td>29</td> <td>97</td> <td>55</td> </tr> <tr> <td>2</td> <td>Virat</td> <td>12000</td> <td>40</td> <td>91</td> <td>49</td> </tr> <tr> <td>3</td> <td>Rahul</td> <td>5000</td> <td>8</td> <td>85</td> <td>45</td> </tr> <tr> <td>4</td> <td>Rishabh</td> <td>4000</td> <td>2</td> <td>89</td> <td>39</td> </tr> </tbody> </table> </div> </body></html>", "e": 7814, "s": 5932, "text": null }, { "code": null, "e": 7822, "s": 7814, "text": "Output:" }, { "code": null, "e": 8190, "s": 7822, "text": "4. Striped Table: For better visualization of large-size tables we can use striped cells. For a striped table here we used the pure-table-odd Pure CSS class in the every <tr> element tag to change the background of the odd rows. This will create a striped table with the zebra-styled effect which is more visible and attractive for a large number of data to the user." }, { "code": null, "e": 8195, "s": 8190, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Import Pure CSS --> <link rel=\"stylesheet\" href=\"https://unpkg.com/purecss@2.0.6/build/pure-min.css\" integrity=\"sha384-Uu6IeWbM+gzNVXJcM9XV3SohHtmWE+3VGi496jvgX1jyvDTXfdK+rfZc8C1Aehk5\" crossorigin=\"anonymous\" origin=\"anonymous\" /> <!-- Used to optimized Website for mobile --> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <style> .container { margin-top: 20px; display: flex; align-items: center; justify-content: center; flex-direction: column; } h1 { color: green; } </style> </head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <h2>Horizontal Bordered Table</h2> <!-- Here pure-table class is used --> <table class=\"pure-table\"> <thead> <tr> <th>Rank</th> <th>Name</th> <th>Runs</th> <th>Centuries</th> <th>Strike Rate</th> <th>Avg</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Rohit</td> <td>10000</td> <td>29</td> <td>97</td> <td>55</td> </tr> <!--Here pure-table-odd class used to change background of row--> <tr class=\"pure-table-odd\"> <td>2</td> <td>Virat</td> <td>12000</td> <td>40</td> <td>91</td> <td>49</td> </tr> <tr> <td>3</td> <td>Rahul</td> <td>5000</td> <td>8</td> <td>85</td> <td>45</td> </tr> <tr class=\"pure-table-odd\"> <td>4</td> <td>Rishabh</td> <td>4000</td> <td>2</td> <td>89</td> <td>39</td> </tr> </tbody> </table> </div> </body></html>", "e": 10160, "s": 8195, "text": null }, { "code": null, "e": 10168, "s": 10160, "text": "Output:" }, { "code": null, "e": 10271, "s": 10168, "text": "In this article, we learn what is Pure CSS Table is, its classes, and how to use it in various tables." }, { "code": null, "e": 10285, "s": 10271, "text": "omkarbhusnale" }, { "code": null, "e": 10294, "s": 10285, "text": "Pure CSS" }, { "code": null, "e": 10298, "s": 10294, "text": "CSS" }, { "code": null, "e": 10303, "s": 10298, "text": "HTML" }, { "code": null, "e": 10320, "s": 10303, "text": "Web Technologies" }, { "code": null, "e": 10325, "s": 10320, "text": "HTML" }, { "code": null, "e": 10423, "s": 10325, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10471, "s": 10423, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 10533, "s": 10471, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 10583, "s": 10533, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 10641, "s": 10583, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 10691, "s": 10641, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 10739, "s": 10691, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 10801, "s": 10739, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 10851, "s": 10801, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 10875, "s": 10851, "text": "REST API (Introduction)" } ]
ReactJS htmlFor Attribute
25 May, 2021 React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In class-based components, the htmlFor attribute is used to get the HTML for the given HTML elements. 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 Project Structure: It will look like the following. Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react'; // Defining our App Componentconst App = () => { // Function to demonstrate htmlFor attribute function printHtmlForValue() { var element = document.getElementById('abc'); // Printing element console.log(element) } // Returning our JSX code return <> <div> <h1>GeeksforGeeks</h1> <div id='abc'> ReactJS htmlFor Attribute </div> <button onClick={printHtmlForValue}> click </button> </div> </>;} // Exporting your Default App Componentexport default App Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference:https://reactjs.org/docs/dom-elements.html#htmlfor ReactJS Attributes ReactJS DOM Elements ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS useNavigate() Hook How to install bootstrap in React.js ? How to create a multi-page website using React.js ? How to do crud operations in ReactJS ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n25 May, 2021" }, { "code": null, "e": 257, "s": 28, "text": "React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component." }, { "code": null, "e": 359, "s": 257, "text": "In class-based components, the htmlFor attribute is used to get the HTML for the given HTML elements." }, { "code": null, "e": 409, "s": 359, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 504, "s": 409, "text": "Step 1: Create a React application using the following command.npx create-react-app foldername" }, { "code": null, "e": 568, "s": 504, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 600, "s": 568, "text": "npx create-react-app foldername" }, { "code": null, "e": 713, "s": 600, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername" }, { "code": null, "e": 813, "s": 713, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 827, "s": 813, "text": "cd foldername" }, { "code": null, "e": 879, "s": 827, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 1009, "s": 879, "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": 1016, "s": 1009, "text": "App.js" }, { "code": "import React from 'react'; // Defining our App Componentconst App = () => { // Function to demonstrate htmlFor attribute function printHtmlForValue() { var element = document.getElementById('abc'); // Printing element console.log(element) } // Returning our JSX code return <> <div> <h1>GeeksforGeeks</h1> <div id='abc'> ReactJS htmlFor Attribute </div> <button onClick={printHtmlForValue}> click </button> </div> </>;} // Exporting your Default App Componentexport default App", "e": 1567, "s": 1016, "text": null }, { "code": null, "e": 1680, "s": 1567, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 1690, "s": 1680, "text": "npm start" }, { "code": null, "e": 1789, "s": 1690, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 1850, "s": 1789, "text": "Reference:https://reactjs.org/docs/dom-elements.html#htmlfor" }, { "code": null, "e": 1869, "s": 1850, "text": "ReactJS Attributes" }, { "code": null, "e": 1890, "s": 1869, "text": "ReactJS DOM Elements" }, { "code": null, "e": 1898, "s": 1890, "text": "ReactJS" }, { "code": null, "e": 1915, "s": 1898, "text": "Web Technologies" }, { "code": null, "e": 2013, "s": 1915, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2051, "s": 2013, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 2078, "s": 2051, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 2117, "s": 2078, "text": "How to install bootstrap in React.js ?" }, { "code": null, "e": 2169, "s": 2117, "text": "How to create a multi-page website using React.js ?" }, { "code": null, "e": 2208, "s": 2169, "text": "How to do crud operations in ReactJS ?" }, { "code": null, "e": 2241, "s": 2208, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2303, "s": 2241, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2364, "s": 2303, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2414, "s": 2364, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
new operator in Java
30 May, 2018 When you are declaring a class in java, you are just creating a new data type. A class provides the blueprint for objects. You can create an object from a class. However obtaining objects of a class is a two-step process : Declaration : First, you must declare a variable of the class type. This variable does not define an object. Instead, it is simply a variable that can refer to an object. Below is general syntax of declaration with an example :Syntax : class-name var-name; Example : // declare reference to an object of class Box Box mybox; A variable in this state, which currently references no object, can be illustrated as follows (the variable name, mybox, plus a reference pointing to nothing):Instantiation and Initialization : Second, you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the new operator. The new operator instantiates a class by dynamically allocating(i.e, allocation at run time) memory for a new object and returning a reference to that memory. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated.The new operator is also followed by a call to a class constructor, which initializes the new object. A constructor defines what occurs when an object of a class is created. Constructors are an important part of all classes and have many significant attributes. In below example we will use the default constructor. Below is general syntax of instantiation and initialization with an example :Syntax : var-name = new class-name(); Example : // instantiation via new operator and // initialization via default constructor of class Box mybox = new Box(); Before understanding, how new dynamically allocates memory, let us see class Box prototype.class Box { double width; double height; double depth; } A variable after second step, currently refer to a class object, can be illustrated as follows (the variable name, mybox, plus a reference pointing to Box object): Declaration : First, you must declare a variable of the class type. This variable does not define an object. Instead, it is simply a variable that can refer to an object. Below is general syntax of declaration with an example :Syntax : class-name var-name; Example : // declare reference to an object of class Box Box mybox; A variable in this state, which currently references no object, can be illustrated as follows (the variable name, mybox, plus a reference pointing to nothing): Syntax : class-name var-name; Example : // declare reference to an object of class Box Box mybox; A variable in this state, which currently references no object, can be illustrated as follows (the variable name, mybox, plus a reference pointing to nothing): Instantiation and Initialization : Second, you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the new operator. The new operator instantiates a class by dynamically allocating(i.e, allocation at run time) memory for a new object and returning a reference to that memory. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated.The new operator is also followed by a call to a class constructor, which initializes the new object. A constructor defines what occurs when an object of a class is created. Constructors are an important part of all classes and have many significant attributes. In below example we will use the default constructor. Below is general syntax of instantiation and initialization with an example :Syntax : var-name = new class-name(); Example : // instantiation via new operator and // initialization via default constructor of class Box mybox = new Box(); Before understanding, how new dynamically allocates memory, let us see class Box prototype.class Box { double width; double height; double depth; } A variable after second step, currently refer to a class object, can be illustrated as follows (the variable name, mybox, plus a reference pointing to Box object): The new operator is also followed by a call to a class constructor, which initializes the new object. A constructor defines what occurs when an object of a class is created. Constructors are an important part of all classes and have many significant attributes. In below example we will use the default constructor. Below is general syntax of instantiation and initialization with an example : Syntax : var-name = new class-name(); Example : // instantiation via new operator and // initialization via default constructor of class Box mybox = new Box(); Before understanding, how new dynamically allocates memory, let us see class Box prototype. class Box { double width; double height; double depth; } A variable after second step, currently refer to a class object, can be illustrated as follows (the variable name, mybox, plus a reference pointing to Box object): Hence declaration of a class variable, instantiation of a class and initialization of an object of class can be together illustrated as follows : Important points : The above two statements can be rewritten as one statement.Box mybox = new Box(); The reference returned by the new operator does not have to be assigned to a class variable. It can also be used directly in an expression. For example:double height = new Box().height; Since arrays are object in java, hence while instantiating arrays, we use new operator. For example:int arr[] = new int[5]; At this point, you might be wondering why you do not need to use new operator for primitives data types. The answer is that Java’s primitive types are not implemented as objects. Rather, they are implemented as “normal” variables. This is done in the interest of efficiency. For object versions of the primitive data types, refer Wrapper Classes.The phrase “instantiating a class” means the same thing as “creating an object.” When you create an object, you are creating an “instance” of a class, therefore “instantiating” a class. The above two statements can be rewritten as one statement.Box mybox = new Box(); Box mybox = new Box(); The reference returned by the new operator does not have to be assigned to a class variable. It can also be used directly in an expression. For example:double height = new Box().height; double height = new Box().height; Since arrays are object in java, hence while instantiating arrays, we use new operator. For example:int arr[] = new int[5]; int arr[] = new int[5]; At this point, you might be wondering why you do not need to use new operator for primitives data types. The answer is that Java’s primitive types are not implemented as objects. Rather, they are implemented as “normal” variables. This is done in the interest of efficiency. For object versions of the primitive data types, refer Wrapper Classes. The phrase “instantiating a class” means the same thing as “creating an object.” When you create an object, you are creating an “instance” of a class, therefore “instantiating” a class. Assigning object reference variables When you assign one object reference variable to another object reference variable, you are not creating a copy of the object, you are only making a copy of the reference. Let us understand this with an example. // Java program to demonstrate assigning // of object reference variables // Box classclass Box{ double width; double height; double depth;} // Driver classpublic class Test{ // Driver method public static void main(String[] args) { // creating box object Box b1 = new Box(); // assigning b2 to b1 Box b2 = b1; // height via b1 and b2 System.out.println(b1.height); System.out.println(b2.height); // changing height via b2 b2.height = 20; // height via b1 and b2 // after modification through b2 System.out.println(b1.height); System.out.println(b2.height); } } Output : 0.0 0.0 20.0 20.0 Explanation : First let us understand what the following fragment does in above program. Box b1 = new Box(); Box b2 = b1; You might think that b2 is being assigned a reference to a copy of the object referred to by b1. That is, you might think that b1 and b2 refer to separate and distinct objects. However, this would be wrong. Instead, after this fragment executes, b1 and b2 will both refer to the same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same object as does b1. Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they are the same object. Same can be verified by output when we change height of box via b2. This situation can be illustrated as follows : Note : Although b1 and b2 both refer to the same object, they are not linked in any other way. For example, a subsequent assignment to b1 will simply unhook b1 from the original object without affecting the object or affecting b2.For example : Box b1 = new Box(); Box b2 = b1; // ... b1 = null; Here, b1 has been set to null, but b2 still points to the original object. Passing object references variables to methods When we pass object reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument. To know more with examples, refer Passing and Returning Objects in Java. This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Arrays.sort() in Java with examples Split() String method in Java with examples Reverse a string in Java For-each loop in Java How to iterate any Map in Java HashMap in Java with Examples ArrayList in Java Collections in Java Stream In Java
[ { "code": null, "e": 52, "s": 24, "text": "\n30 May, 2018" }, { "code": null, "e": 275, "s": 52, "text": "When you are declaring a class in java, you are just creating a new data type. A class provides the blueprint for objects. You can create an object from a class. However obtaining objects of a class is a two-step process :" }, { "code": null, "e": 2079, "s": 275, "text": "Declaration : First, you must declare a variable of the class type. This variable does not define an object. Instead, it is simply a variable that can refer to an object. Below is general syntax of declaration with an example :Syntax :\nclass-name var-name;\n\nExample :\n// declare reference to an object of class Box\nBox mybox;\nA variable in this state, which currently references no object, can be illustrated as follows (the variable name, mybox, plus a reference pointing to nothing):Instantiation and Initialization : Second, you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the new operator. The new operator instantiates a class by dynamically allocating(i.e, allocation at run time) memory for a new object and returning a reference to that memory. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated.The new operator is also followed by a call to a class constructor, which initializes the new object. A constructor defines what occurs when an object of a class is created. Constructors are an important part of all classes and have many significant attributes. In below example we will use the default constructor. Below is general syntax of instantiation and initialization with an example :Syntax :\nvar-name = new class-name();\n\nExample :\n// instantiation via new operator and \n// initialization via default constructor of class Box\nmybox = new Box();\nBefore understanding, how new dynamically allocates memory, let us see class Box prototype.class Box\n{\n double width;\n double height;\n double depth;\n}\nA variable after second step, currently refer to a class object, can be illustrated as follows (the variable name, mybox, plus a reference pointing to Box object):" }, { "code": null, "e": 2565, "s": 2079, "text": "Declaration : First, you must declare a variable of the class type. This variable does not define an object. Instead, it is simply a variable that can refer to an object. Below is general syntax of declaration with an example :Syntax :\nclass-name var-name;\n\nExample :\n// declare reference to an object of class Box\nBox mybox;\nA variable in this state, which currently references no object, can be illustrated as follows (the variable name, mybox, plus a reference pointing to nothing):" }, { "code": null, "e": 2665, "s": 2565, "text": "Syntax :\nclass-name var-name;\n\nExample :\n// declare reference to an object of class Box\nBox mybox;\n" }, { "code": null, "e": 2825, "s": 2665, "text": "A variable in this state, which currently references no object, can be illustrated as follows (the variable name, mybox, plus a reference pointing to nothing):" }, { "code": null, "e": 4144, "s": 2825, "text": "Instantiation and Initialization : Second, you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the new operator. The new operator instantiates a class by dynamically allocating(i.e, allocation at run time) memory for a new object and returning a reference to that memory. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated.The new operator is also followed by a call to a class constructor, which initializes the new object. A constructor defines what occurs when an object of a class is created. Constructors are an important part of all classes and have many significant attributes. In below example we will use the default constructor. Below is general syntax of instantiation and initialization with an example :Syntax :\nvar-name = new class-name();\n\nExample :\n// instantiation via new operator and \n// initialization via default constructor of class Box\nmybox = new Box();\nBefore understanding, how new dynamically allocates memory, let us see class Box prototype.class Box\n{\n double width;\n double height;\n double depth;\n}\nA variable after second step, currently refer to a class object, can be illustrated as follows (the variable name, mybox, plus a reference pointing to Box object):" }, { "code": null, "e": 4538, "s": 4144, "text": "The new operator is also followed by a call to a class constructor, which initializes the new object. A constructor defines what occurs when an object of a class is created. Constructors are an important part of all classes and have many significant attributes. In below example we will use the default constructor. Below is general syntax of instantiation and initialization with an example :" }, { "code": null, "e": 4701, "s": 4538, "text": "Syntax :\nvar-name = new class-name();\n\nExample :\n// instantiation via new operator and \n// initialization via default constructor of class Box\nmybox = new Box();\n" }, { "code": null, "e": 4793, "s": 4701, "text": "Before understanding, how new dynamically allocates memory, let us see class Box prototype." }, { "code": null, "e": 4863, "s": 4793, "text": "class Box\n{\n double width;\n double height;\n double depth;\n}\n" }, { "code": null, "e": 5027, "s": 4863, "text": "A variable after second step, currently refer to a class object, can be illustrated as follows (the variable name, mybox, plus a reference pointing to Box object):" }, { "code": null, "e": 5173, "s": 5027, "text": "Hence declaration of a class variable, instantiation of a class and initialization of an object of class can be together illustrated as follows :" }, { "code": null, "e": 5192, "s": 5173, "text": "Important points :" }, { "code": null, "e": 6116, "s": 5192, "text": "The above two statements can be rewritten as one statement.Box mybox = new Box();\nThe reference returned by the new operator does not have to be assigned to a class variable. It can also be used directly in an expression. For example:double height = new Box().height;\nSince arrays are object in java, hence while instantiating arrays, we use new operator. For example:int arr[] = new int[5];\nAt this point, you might be wondering why you do not need to use new operator for primitives data types. The answer is that Java’s primitive types are not implemented as objects. Rather, they are implemented as “normal” variables. This is done in the interest of efficiency. For object versions of the primitive data types, refer Wrapper Classes.The phrase “instantiating a class” means the same thing as “creating an object.” When you create an object, you are creating an “instance” of a class, therefore “instantiating” a class." }, { "code": null, "e": 6199, "s": 6116, "text": "The above two statements can be rewritten as one statement.Box mybox = new Box();\n" }, { "code": null, "e": 6223, "s": 6199, "text": "Box mybox = new Box();\n" }, { "code": null, "e": 6410, "s": 6223, "text": "The reference returned by the new operator does not have to be assigned to a class variable. It can also be used directly in an expression. For example:double height = new Box().height;\n" }, { "code": null, "e": 6445, "s": 6410, "text": "double height = new Box().height;\n" }, { "code": null, "e": 6570, "s": 6445, "text": "Since arrays are object in java, hence while instantiating arrays, we use new operator. For example:int arr[] = new int[5];\n" }, { "code": null, "e": 6595, "s": 6570, "text": "int arr[] = new int[5];\n" }, { "code": null, "e": 6942, "s": 6595, "text": "At this point, you might be wondering why you do not need to use new operator for primitives data types. The answer is that Java’s primitive types are not implemented as objects. Rather, they are implemented as “normal” variables. This is done in the interest of efficiency. For object versions of the primitive data types, refer Wrapper Classes." }, { "code": null, "e": 7128, "s": 6942, "text": "The phrase “instantiating a class” means the same thing as “creating an object.” When you create an object, you are creating an “instance” of a class, therefore “instantiating” a class." }, { "code": null, "e": 7165, "s": 7128, "text": "Assigning object reference variables" }, { "code": null, "e": 7377, "s": 7165, "text": "When you assign one object reference variable to another object reference variable, you are not creating a copy of the object, you are only making a copy of the reference. Let us understand this with an example." }, { "code": "// Java program to demonstrate assigning // of object reference variables // Box classclass Box{ double width; double height; double depth;} // Driver classpublic class Test{ // Driver method public static void main(String[] args) { // creating box object Box b1 = new Box(); // assigning b2 to b1 Box b2 = b1; // height via b1 and b2 System.out.println(b1.height); System.out.println(b2.height); // changing height via b2 b2.height = 20; // height via b1 and b2 // after modification through b2 System.out.println(b1.height); System.out.println(b2.height); } }", "e": 8099, "s": 7377, "text": null }, { "code": null, "e": 8108, "s": 8099, "text": "Output :" }, { "code": null, "e": 8127, "s": 8108, "text": "0.0\n0.0\n20.0\n20.0\n" }, { "code": null, "e": 8141, "s": 8127, "text": "Explanation :" }, { "code": null, "e": 8216, "s": 8141, "text": "First let us understand what the following fragment does in above program." }, { "code": null, "e": 8250, "s": 8216, "text": "Box b1 = new Box();\nBox b2 = b1;\n" }, { "code": null, "e": 8891, "s": 8250, "text": "You might think that b2 is being assigned a reference to a copy of the object referred to by b1. That is, you might think that b1 and b2 refer to separate and distinct objects. However, this would be wrong. Instead, after this fragment executes, b1 and b2 will both refer to the same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same object as does b1. Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they are the same object. Same can be verified by output when we change height of box via b2." }, { "code": null, "e": 8938, "s": 8891, "text": "This situation can be illustrated as follows :" }, { "code": null, "e": 9182, "s": 8938, "text": "Note : Although b1 and b2 both refer to the same object, they are not linked in any other way. For example, a subsequent assignment to b1 will simply unhook b1 from the original object without affecting the object or affecting b2.For example :" }, { "code": null, "e": 9234, "s": 9182, "text": "Box b1 = new Box();\nBox b2 = b1;\n// ...\nb1 = null;\n" }, { "code": null, "e": 9309, "s": 9234, "text": "Here, b1 has been set to null, but b2 still points to the original object." }, { "code": null, "e": 9356, "s": 9309, "text": "Passing object references variables to methods" }, { "code": null, "e": 9570, "s": 9356, "text": "When we pass object reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument. To know more with examples, refer Passing and Returning Objects in Java." }, { "code": null, "e": 9872, "s": 9570, "text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 9997, "s": 9872, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 10002, "s": 9997, "text": "Java" }, { "code": null, "e": 10007, "s": 10002, "text": "Java" }, { "code": null, "e": 10105, "s": 10007, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10120, "s": 10105, "text": "Arrays in Java" }, { "code": null, "e": 10156, "s": 10120, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 10200, "s": 10156, "text": "Split() String method in Java with examples" }, { "code": null, "e": 10225, "s": 10200, "text": "Reverse a string in Java" }, { "code": null, "e": 10247, "s": 10225, "text": "For-each loop in Java" }, { "code": null, "e": 10278, "s": 10247, "text": "How to iterate any Map in Java" }, { "code": null, "e": 10308, "s": 10278, "text": "HashMap in Java with Examples" }, { "code": null, "e": 10326, "s": 10308, "text": "ArrayList in Java" }, { "code": null, "e": 10346, "s": 10326, "text": "Collections in Java" } ]
goto statement in C/C++
The goto statement is a jump statement. Within a function, it is used to jump from one statement to another. The use of this statement is highly discouraged. It makes the program complex and difficult to trace the control flow of program. It makes hard to modify the program. Here is the syntax of goto statement in C language, goto label; . . . label: statement; Here is an example of goto statement in C language, Live Demo #include <stdio.h> int main () { int a = 10; LOOP:do { if( a == 12) { a = a + 1; goto LOOP; } printf("Value of a: %d\n", a); a++; }while( a < 15 ); return 0; } Value of a: 10 value of a: 11 value of a: 13 value of a: 14
[ { "code": null, "e": 1338, "s": 1062, "text": "The goto statement is a jump statement. Within a function, it is used to jump from one statement to another. The use of this statement is highly discouraged. It makes the program complex and difficult to trace the control flow of program. It makes hard to modify the program." }, { "code": null, "e": 1390, "s": 1338, "text": "Here is the syntax of goto statement in C language," }, { "code": null, "e": 1426, "s": 1390, "text": "goto label;\n.\n.\n.\nlabel: statement;" }, { "code": null, "e": 1478, "s": 1426, "text": "Here is an example of goto statement in C language," }, { "code": null, "e": 1489, "s": 1478, "text": " Live Demo" }, { "code": null, "e": 1705, "s": 1489, "text": "#include <stdio.h>\nint main () {\n int a = 10;\n LOOP:do { \n if( a == 12) {\n a = a + 1;\n goto LOOP;\n }\n printf(\"Value of a: %d\\n\", a);\n a++;\n }while( a < 15 );\n return 0;\n}" }, { "code": null, "e": 1765, "s": 1705, "text": "Value of a: 10\nvalue of a: 11\nvalue of a: 13\nvalue of a: 14" } ]
PostgreSQL - DELETE USING - GeeksforGeeks
28 Aug, 2020 PostgreSQL has various techniques to delete duplicate rows. One of them is using the DELETE USING statement. Syntax: DELETE FROM table_name row1 USING table_name row2 WHERE condition; For the purpose of demonstration let’s set up a sample table(say, basket) that stores fruits as follows: CREATE TABLE basket( id SERIAL PRIMARY KEY, fruit VARCHAR(50) NOT NULL ); Now let’s add some data to the newly created basket table. INSERT INTO basket(fruit) values('apple'); INSERT INTO basket(fruit) values('apple'); INSERT INTO basket(fruit) values('orange'); INSERT INTO basket(fruit) values('orange'); INSERT INTO basket(fruit) values('orange'); INSERT INTO basket(fruit) values('banana'); Now let’s verify the basket table using the below statement: SELECT * FROM basket; This should result into below: Now that we have set up the sample table, we will query for the duplicates using the following: SELECT fruit, COUNT( fruit ) FROM basket GROUP BY fruit HAVING COUNT( fruit )> 1 ORDER BY fruit; This should lead to the following results: Now that we know the duplicate rows we can use the DELETE USING statement to remove duplicate rows as follows: DELETE FROM basket a USING basket b WHERE a.id < b.id AND a.fruit = b.fruit; This should remove all duplicate from the table basket, and to verify so use the below query: SELECT fruit, COUNT( fruit ) FROM basket GROUP BY fruit HAVING COUNT( fruit )> 1 ORDER BY fruit; This should result in the following: postgreSQL-clauses PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - GROUP BY clause PostgreSQL - DROP INDEX PostgreSQL - Copy Table PostgreSQL - Interval Data Type PostgreSQL - Rename Table PostgreSQL - LEFT JOIN PostgreSQL - TEXT Data Type PostgreSQL - TIME Data Type PostgreSQL - Record type variable PostgreSQL - CREATE PROCEDURE
[ { "code": null, "e": 24036, "s": 24008, "text": "\n28 Aug, 2020" }, { "code": null, "e": 24145, "s": 24036, "text": "PostgreSQL has various techniques to delete duplicate rows. One of them is using the DELETE USING statement." }, { "code": null, "e": 24222, "s": 24145, "text": "Syntax: DELETE FROM table_name row1 USING table_name row2 WHERE condition;\n\n" }, { "code": null, "e": 24327, "s": 24222, "text": "For the purpose of demonstration let’s set up a sample table(say, basket) that stores fruits as follows:" }, { "code": null, "e": 24411, "s": 24327, "text": "CREATE TABLE basket(\n id SERIAL PRIMARY KEY,\n fruit VARCHAR(50) NOT NULL\n);\n\n" }, { "code": null, "e": 24470, "s": 24411, "text": "Now let’s add some data to the newly created basket table." }, { "code": null, "e": 24736, "s": 24470, "text": "INSERT INTO basket(fruit) values('apple');\nINSERT INTO basket(fruit) values('apple');\n\nINSERT INTO basket(fruit) values('orange');\nINSERT INTO basket(fruit) values('orange');\nINSERT INTO basket(fruit) values('orange');\n\nINSERT INTO basket(fruit) values('banana');\n\n" }, { "code": null, "e": 24797, "s": 24736, "text": "Now let’s verify the basket table using the below statement:" }, { "code": null, "e": 24821, "s": 24797, "text": "SELECT * FROM basket;\n\n" }, { "code": null, "e": 24852, "s": 24821, "text": "This should result into below:" }, { "code": null, "e": 24948, "s": 24852, "text": "Now that we have set up the sample table, we will query for the duplicates using the following:" }, { "code": null, "e": 25071, "s": 24948, "text": "SELECT\n fruit,\n COUNT( fruit )\nFROM\n basket\nGROUP BY\n fruit\nHAVING\n COUNT( fruit )> 1\nORDER BY\n fruit;\n\n" }, { "code": null, "e": 25114, "s": 25071, "text": "This should lead to the following results:" }, { "code": null, "e": 25225, "s": 25114, "text": "Now that we know the duplicate rows we can use the DELETE USING statement to remove duplicate rows as follows:" }, { "code": null, "e": 25324, "s": 25225, "text": "DELETE FROM\n basket a\n USING basket b\nWHERE\n a.id < b.id\n AND a.fruit = b.fruit;\n\n" }, { "code": null, "e": 25418, "s": 25324, "text": "This should remove all duplicate from the table basket, and to verify so use the below query:" }, { "code": null, "e": 25541, "s": 25418, "text": "SELECT\n fruit,\n COUNT( fruit )\nFROM\n basket\nGROUP BY\n fruit\nHAVING\n COUNT( fruit )> 1\nORDER BY\n fruit;\n\n" }, { "code": null, "e": 25578, "s": 25541, "text": "This should result in the following:" }, { "code": null, "e": 25597, "s": 25578, "text": "postgreSQL-clauses" }, { "code": null, "e": 25608, "s": 25597, "text": "PostgreSQL" }, { "code": null, "e": 25706, "s": 25608, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25735, "s": 25706, "text": "PostgreSQL - GROUP BY clause" }, { "code": null, "e": 25759, "s": 25735, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 25783, "s": 25759, "text": "PostgreSQL - Copy Table" }, { "code": null, "e": 25815, "s": 25783, "text": "PostgreSQL - Interval Data Type" }, { "code": null, "e": 25841, "s": 25815, "text": "PostgreSQL - Rename Table" }, { "code": null, "e": 25864, "s": 25841, "text": "PostgreSQL - LEFT JOIN" }, { "code": null, "e": 25892, "s": 25864, "text": "PostgreSQL - TEXT Data Type" }, { "code": null, "e": 25920, "s": 25892, "text": "PostgreSQL - TIME Data Type" }, { "code": null, "e": 25954, "s": 25920, "text": "PostgreSQL - Record type variable" } ]
How to join two Vectors using STL in C++? - GeeksforGeeks
28 May, 2021 Given two vectors, join these two vectors using STL in C++.Example: Input: vec1 = {1, 45, 54, 71, 76, 12}, vec2 = {1, 7, 5, 4, 6, 12} Output: {1, 4, 5, 6, 7, 12, 45, 54, 71, 76}Input: vec1 = {1, 7, 5, 4, 6, 12}, vec2 = {10, 12, 11} Output: {1, 4, 5, 6, 7, 10, 11, 12} Approach: Joining can be done with the help of set_union() function provided in STL.Syntax: set_union (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result); CPP // C++ program to join two Vectors// using set_union() in STL #include <bits/stdc++.h>using namespace std; int main(){ // Get the vector vector<int> vector1 = { 1, 45, 54, 71, 76, 12 }; vector<int> vector2 = { 1, 7, 5, 4, 6, 12 }; // Sort the vector sort(vector1.begin(), vector1.end()); sort(vector2.begin(), vector2.end()); // Print the vector cout << "First Vector: "; for (int i = 0; i < vector1.size(); i++) cout << vector1[i] << " "; cout << endl; cout << "Second Vector: "; for (int i = 0; i < vector2.size(); i++) cout << vector2[i] << " "; cout << endl; // Initialise a vector // to store the common values // and an iterator // to traverse this vector vector<int> v(vector1.size() + vector2.size()); vector<int>::iterator it, st; it = set_union(vector1.begin(), vector1.end(), vector2.begin(), vector2.end(), v.begin()); cout << "\nAfter joining:\n"; for (st = v.begin(); st != it; ++st) cout << *st << ", "; cout << '\n'; return 0;} First Vector: 1 12 45 54 71 76 Second Vector: 1 4 5 6 7 12 After joining: 1, 4, 5, 6, 7, 12, 45, 54, 71, 76, Note that the vector should not contain 1 element twice: In case you enter same elements, the set_union function will only consider 1 instance of the element, and default rest to 0. Kaustubh_Gupta cpp-vector STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Bitwise Operators in C/C++ Operator Overloading in C++ Socket Programming in C/C++ Constructors in C++ Virtual Function in C++ Templates in C++ with Examples Copy Constructor in C++
[ { "code": null, "e": 24385, "s": 24357, "text": "\n28 May, 2021" }, { "code": null, "e": 24455, "s": 24385, "text": "Given two vectors, join these two vectors using STL in C++.Example: " }, { "code": null, "e": 24657, "s": 24455, "text": "Input: vec1 = {1, 45, 54, 71, 76, 12}, vec2 = {1, 7, 5, 4, 6, 12} Output: {1, 4, 5, 6, 7, 12, 45, 54, 71, 76}Input: vec1 = {1, 7, 5, 4, 6, 12}, vec2 = {10, 12, 11} Output: {1, 4, 5, 6, 7, 10, 11, 12} " }, { "code": null, "e": 24751, "s": 24657, "text": "Approach: Joining can be done with the help of set_union() function provided in STL.Syntax: " }, { "code": null, "e": 24898, "s": 24751, "text": "set_union (InputIterator1 first1, InputIterator1 last1,\n InputIterator2 first2, InputIterator2 last2,\n OutputIterator result);" }, { "code": null, "e": 24902, "s": 24898, "text": "CPP" }, { "code": "// C++ program to join two Vectors// using set_union() in STL #include <bits/stdc++.h>using namespace std; int main(){ // Get the vector vector<int> vector1 = { 1, 45, 54, 71, 76, 12 }; vector<int> vector2 = { 1, 7, 5, 4, 6, 12 }; // Sort the vector sort(vector1.begin(), vector1.end()); sort(vector2.begin(), vector2.end()); // Print the vector cout << \"First Vector: \"; for (int i = 0; i < vector1.size(); i++) cout << vector1[i] << \" \"; cout << endl; cout << \"Second Vector: \"; for (int i = 0; i < vector2.size(); i++) cout << vector2[i] << \" \"; cout << endl; // Initialise a vector // to store the common values // and an iterator // to traverse this vector vector<int> v(vector1.size() + vector2.size()); vector<int>::iterator it, st; it = set_union(vector1.begin(), vector1.end(), vector2.begin(), vector2.end(), v.begin()); cout << \"\\nAfter joining:\\n\"; for (st = v.begin(); st != it; ++st) cout << *st << \", \"; cout << '\\n'; return 0;}", "e": 26018, "s": 24902, "text": null }, { "code": null, "e": 26130, "s": 26018, "text": "First Vector: 1 12 45 54 71 76 \nSecond Vector: 1 4 5 6 7 12 \n\nAfter joining:\n1, 4, 5, 6, 7, 12, 45, 54, 71, 76," }, { "code": null, "e": 26189, "s": 26132, "text": "Note that the vector should not contain 1 element twice:" }, { "code": null, "e": 26314, "s": 26189, "text": "In case you enter same elements, the set_union function will only consider 1 instance of the element, and default rest to 0." }, { "code": null, "e": 26329, "s": 26314, "text": "Kaustubh_Gupta" }, { "code": null, "e": 26340, "s": 26329, "text": "cpp-vector" }, { "code": null, "e": 26344, "s": 26340, "text": "STL" }, { "code": null, "e": 26348, "s": 26344, "text": "C++" }, { "code": null, "e": 26352, "s": 26348, "text": "STL" }, { "code": null, "e": 26356, "s": 26352, "text": "CPP" }, { "code": null, "e": 26454, "s": 26356, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26473, "s": 26454, "text": "Inheritance in C++" }, { "code": null, "e": 26516, "s": 26473, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 26540, "s": 26516, "text": "C++ Classes and Objects" }, { "code": null, "e": 26567, "s": 26540, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 26595, "s": 26567, "text": "Operator Overloading in C++" }, { "code": null, "e": 26623, "s": 26595, "text": "Socket Programming in C/C++" }, { "code": null, "e": 26643, "s": 26623, "text": "Constructors in C++" }, { "code": null, "e": 26667, "s": 26643, "text": "Virtual Function in C++" }, { "code": null, "e": 26698, "s": 26667, "text": "Templates in C++ with Examples" } ]
Advanced monitoring of AWS glue jobs by enabling spark UI | by Shubham Jain | Towards Data Science
Apache spark is currently an indispensable framework when it comes to processing huge datasets. Most of the data engineers and data scientists who are dealing with large amounts of data leverages spark capabilities at some point in time. When it comes to understanding of spark, 20% comprises of the code syntax, 30% are the data engineering concepts and the rest 50% is the optimization Code syntax consists of the use of functions and the syntax, data engineering concepts reflects the knowledge of SQL, efficient query building and creating optimized query and optimization includes how well the cluster is managed and running the code with the minimal shuffle, dealing with inevitable small files, optimizing joins, dealing with long-running jobs, optimization of skewed datasets and utilizing the complete cluster. The syntax definition and data engineering concepts can be learned over time but to optimize the cluster you need to visualize how your cluster is responding to the queries executed over it. SparkUI is needed to identify the root cause behind long-running jobs, Visualizing DAGs, OOM issues, disk spills, excessive shuffling, skewed datasets, and overall health of the cluster. To use apache spark we need large clusters but sometimes, managing these clusters becomes a bit of additional overhead. So we started leveraging clusters on the cloud using AWS EMR or GCP Dataproc but again we need to manage these clusters and make the most of them. Now there was a need for something where we can run our spark workloads and pay for only what we use. That’s where AWS glue comes into the picture. Aws Glue is serverless, therefore we don’t need to manage the clusters or worry about the running cost associated with it. We pay only for the time we utilize the resources and as soon our job is done, the resources are deallocated. Every good thing comes with a price, so the catch here is we cannot fully configure our glue jobs in terms of optimization. Also, we cannot view the spark UI for the jobs in realtime, instead, we need to run a Spark History server which allows us to see the Spark UI for the glue jobs. To enable the spark UI we need to follow some steps: Enable spark UI option in glue jobs.Specify the s3 path where the logs will be generated.Start a Spark History Server using docker and EC2.Access spark UI on the History server. Enable spark UI option in glue jobs. Specify the s3 path where the logs will be generated. Start a Spark History Server using docker and EC2. Access spark UI on the History server. Create a new job and in the monitoring section enable the spark UI option and provide an s3 path for logs generation. We will now be creating a Spark History server from which we can visualize the DAG and task details for the glue jobs. The Dockerfile for the same is: I am taking alpine as the base image as I want this docker container to be very lite in size. Installing Java 8, Maven and bash shell RUN apk add --no-cache openjdk8RUN apk add --no-cache mavenRUN apk add --no-cache bash Fetching spark 2.4 and unzipping as this contains the class for enabling the history server RUN wget https://archive.apache.org/dist/spark/spark-2.4.3/spark-2.4.3-bin-without-hadoop.tgzRUN mv spark-2.4.3-bin-without-hadoop.tgz sparkRUN tar -zxf sparkRUN rm -rf sparkRUN mv spark-2.4.3-bin-without-hadoop/ spark/ Copy pom.xml to the container for installing the dependency and build it using maven COPY pom.xml .RUN mvn dependency:copy-dependencies -DoutputDirectory = /sparkui/spark/jars/ Removing maven as the build is now successful and also removing the conflicting jars RUN apk del mavenRUN rm /sparkui/spark/jars/servlet-api-2.5.jar && \ rm /sparkui/spark/jars/jsr305-1.3.9.jar && \ rm /sparkui/spark/jars/jersey-*-1.9.jar Adding the port number to enable the history server, you can change it according to your requirement. We need to add the property to the spark-defaults.conf file. You can also change the port number here. RUN echo $’\n\spark.eventLog.enabled true\n\spark.history.ui.port 18080\n\’ > /sparkui/spark/conf/spark-defaults.conf Adding the entrypoint to the docker container, this entrypoint will enable the spark history server. ENTRYPOINT [“/sparkui/spark/bin/spark-class”, “org.apache.spark.deploy.history.HistoryServer”] Now build and run the docker container from this file. To build the image out of this Dockerfile run the following command: docker build -t jnshubham/glue_sparkui . You can pull the pre-build image available on the docker hub also. To pull the image run the following command: docker pull jnshubham/glue_sparkui:latest Check downloaded image by running docker images To run the container and start the history server run the following commands: To run the container with Access key and secret key $ LOG_DIR="s3a://path_to_eventlog/"$ AWS_ACCESS_KEY_ID="AKIAxxxxxxxxxxxx"$ AWS_SECRET_ACCESS_KEY="yyyyyyyyyyyyyyy"$ docker run -itd -e SPARK_HISTORY_OPTS="$SPARK_HISTORY_OPTS -Dspark.history.fs.logDirectory=$LOG_DIR -Dspark.hadoop.fs.s3a.access.key=$AWS_ACCESS_KEY_ID -Dspark.hadoop.fs.s3a.secret.key=$AWS_SECRET_ACCESS_KEY" -p 18080:18080 jnshubham/glue_sparkui To run the container with the IAM role configured to your EC2 for accessing s3 bucket $ export LOG_DIR=s3a://bucket_name/logs_path/$ docker run -itd -e SPARK_HISTORY_OPTS="$SPARK_HISTORY_OPTS -Dspark.history.fs.logDirectory=$LOG_DIR" -p 18080:18080 jnshubham/glue_sparkui To access the history server enable the port 18080 in security groups inbound rule to allow traffic. Once you have some successful logs open the ip:18080 to open the history server which will show the spark ui for the glue jobs: You can now visualize the DAGs generated and the query performance. You can also track the time taken by each task and then work on the optimization of the same. Hope you all liked the article. For more information, visit my GitHub or dockerhub. Some rights reserved
[ { "code": null, "e": 410, "s": 172, "text": "Apache spark is currently an indispensable framework when it comes to processing huge datasets. Most of the data engineers and data scientists who are dealing with large amounts of data leverages spark capabilities at some point in time." }, { "code": null, "e": 560, "s": 410, "text": "When it comes to understanding of spark, 20% comprises of the code syntax, 30% are the data engineering concepts and the rest 50% is the optimization" }, { "code": null, "e": 992, "s": 560, "text": "Code syntax consists of the use of functions and the syntax, data engineering concepts reflects the knowledge of SQL, efficient query building and creating optimized query and optimization includes how well the cluster is managed and running the code with the minimal shuffle, dealing with inevitable small files, optimizing joins, dealing with long-running jobs, optimization of skewed datasets and utilizing the complete cluster." }, { "code": null, "e": 1183, "s": 992, "text": "The syntax definition and data engineering concepts can be learned over time but to optimize the cluster you need to visualize how your cluster is responding to the queries executed over it." }, { "code": null, "e": 1370, "s": 1183, "text": "SparkUI is needed to identify the root cause behind long-running jobs, Visualizing DAGs, OOM issues, disk spills, excessive shuffling, skewed datasets, and overall health of the cluster." }, { "code": null, "e": 1785, "s": 1370, "text": "To use apache spark we need large clusters but sometimes, managing these clusters becomes a bit of additional overhead. So we started leveraging clusters on the cloud using AWS EMR or GCP Dataproc but again we need to manage these clusters and make the most of them. Now there was a need for something where we can run our spark workloads and pay for only what we use. That’s where AWS glue comes into the picture." }, { "code": null, "e": 2018, "s": 1785, "text": "Aws Glue is serverless, therefore we don’t need to manage the clusters or worry about the running cost associated with it. We pay only for the time we utilize the resources and as soon our job is done, the resources are deallocated." }, { "code": null, "e": 2304, "s": 2018, "text": "Every good thing comes with a price, so the catch here is we cannot fully configure our glue jobs in terms of optimization. Also, we cannot view the spark UI for the jobs in realtime, instead, we need to run a Spark History server which allows us to see the Spark UI for the glue jobs." }, { "code": null, "e": 2357, "s": 2304, "text": "To enable the spark UI we need to follow some steps:" }, { "code": null, "e": 2535, "s": 2357, "text": "Enable spark UI option in glue jobs.Specify the s3 path where the logs will be generated.Start a Spark History Server using docker and EC2.Access spark UI on the History server." }, { "code": null, "e": 2572, "s": 2535, "text": "Enable spark UI option in glue jobs." }, { "code": null, "e": 2626, "s": 2572, "text": "Specify the s3 path where the logs will be generated." }, { "code": null, "e": 2677, "s": 2626, "text": "Start a Spark History Server using docker and EC2." }, { "code": null, "e": 2716, "s": 2677, "text": "Access spark UI on the History server." }, { "code": null, "e": 2834, "s": 2716, "text": "Create a new job and in the monitoring section enable the spark UI option and provide an s3 path for logs generation." }, { "code": null, "e": 2953, "s": 2834, "text": "We will now be creating a Spark History server from which we can visualize the DAG and task details for the glue jobs." }, { "code": null, "e": 2985, "s": 2953, "text": "The Dockerfile for the same is:" }, { "code": null, "e": 3079, "s": 2985, "text": "I am taking alpine as the base image as I want this docker container to be very lite in size." }, { "code": null, "e": 3119, "s": 3079, "text": "Installing Java 8, Maven and bash shell" }, { "code": null, "e": 3206, "s": 3119, "text": "RUN apk add --no-cache openjdk8RUN apk add --no-cache mavenRUN apk add --no-cache bash" }, { "code": null, "e": 3298, "s": 3206, "text": "Fetching spark 2.4 and unzipping as this contains the class for enabling the history server" }, { "code": null, "e": 3518, "s": 3298, "text": "RUN wget https://archive.apache.org/dist/spark/spark-2.4.3/spark-2.4.3-bin-without-hadoop.tgzRUN mv spark-2.4.3-bin-without-hadoop.tgz sparkRUN tar -zxf sparkRUN rm -rf sparkRUN mv spark-2.4.3-bin-without-hadoop/ spark/" }, { "code": null, "e": 3603, "s": 3518, "text": "Copy pom.xml to the container for installing the dependency and build it using maven" }, { "code": null, "e": 3695, "s": 3603, "text": "COPY pom.xml .RUN mvn dependency:copy-dependencies -DoutputDirectory = /sparkui/spark/jars/" }, { "code": null, "e": 3780, "s": 3695, "text": "Removing maven as the build is now successful and also removing the conflicting jars" }, { "code": null, "e": 3940, "s": 3780, "text": "RUN apk del mavenRUN rm /sparkui/spark/jars/servlet-api-2.5.jar && \\ rm /sparkui/spark/jars/jsr305-1.3.9.jar && \\ rm /sparkui/spark/jars/jersey-*-1.9.jar" }, { "code": null, "e": 4103, "s": 3940, "text": "Adding the port number to enable the history server, you can change it according to your requirement. We need to add the property to the spark-defaults.conf file." }, { "code": null, "e": 4145, "s": 4103, "text": "You can also change the port number here." }, { "code": null, "e": 4264, "s": 4145, "text": "RUN echo $’\\n\\spark.eventLog.enabled true\\n\\spark.history.ui.port 18080\\n\\’ > /sparkui/spark/conf/spark-defaults.conf " }, { "code": null, "e": 4365, "s": 4264, "text": "Adding the entrypoint to the docker container, this entrypoint will enable the spark history server." }, { "code": null, "e": 4460, "s": 4365, "text": "ENTRYPOINT [“/sparkui/spark/bin/spark-class”, “org.apache.spark.deploy.history.HistoryServer”]" }, { "code": null, "e": 4515, "s": 4460, "text": "Now build and run the docker container from this file." }, { "code": null, "e": 4584, "s": 4515, "text": "To build the image out of this Dockerfile run the following command:" }, { "code": null, "e": 4625, "s": 4584, "text": "docker build -t jnshubham/glue_sparkui ." }, { "code": null, "e": 4692, "s": 4625, "text": "You can pull the pre-build image available on the docker hub also." }, { "code": null, "e": 4737, "s": 4692, "text": "To pull the image run the following command:" }, { "code": null, "e": 4779, "s": 4737, "text": "docker pull jnshubham/glue_sparkui:latest" }, { "code": null, "e": 4813, "s": 4779, "text": "Check downloaded image by running" }, { "code": null, "e": 4827, "s": 4813, "text": "docker images" }, { "code": null, "e": 4905, "s": 4827, "text": "To run the container and start the history server run the following commands:" }, { "code": null, "e": 4957, "s": 4905, "text": "To run the container with Access key and secret key" }, { "code": null, "e": 5320, "s": 4957, "text": "$ LOG_DIR=\"s3a://path_to_eventlog/\"$ AWS_ACCESS_KEY_ID=\"AKIAxxxxxxxxxxxx\"$ AWS_SECRET_ACCESS_KEY=\"yyyyyyyyyyyyyyy\"$ docker run -itd -e SPARK_HISTORY_OPTS=\"$SPARK_HISTORY_OPTS -Dspark.history.fs.logDirectory=$LOG_DIR -Dspark.hadoop.fs.s3a.access.key=$AWS_ACCESS_KEY_ID -Dspark.hadoop.fs.s3a.secret.key=$AWS_SECRET_ACCESS_KEY\" -p 18080:18080 jnshubham/glue_sparkui" }, { "code": null, "e": 5406, "s": 5320, "text": "To run the container with the IAM role configured to your EC2 for accessing s3 bucket" }, { "code": null, "e": 5592, "s": 5406, "text": "$ export LOG_DIR=s3a://bucket_name/logs_path/$ docker run -itd -e SPARK_HISTORY_OPTS=\"$SPARK_HISTORY_OPTS -Dspark.history.fs.logDirectory=$LOG_DIR\" -p 18080:18080 jnshubham/glue_sparkui" }, { "code": null, "e": 5693, "s": 5592, "text": "To access the history server enable the port 18080 in security groups inbound rule to allow traffic." }, { "code": null, "e": 5821, "s": 5693, "text": "Once you have some successful logs open the ip:18080 to open the history server which will show the spark ui for the glue jobs:" }, { "code": null, "e": 5983, "s": 5821, "text": "You can now visualize the DAGs generated and the query performance. You can also track the time taken by each task and then work on the optimization of the same." }, { "code": null, "e": 6015, "s": 5983, "text": "Hope you all liked the article." }, { "code": null, "e": 6067, "s": 6015, "text": "For more information, visit my GitHub or dockerhub." } ]
How to hide axes and gridlines in Matplotlib?
To hide axes (X and Y) and gridlines, we can take the following steps − Create x and y points using numpy. Create x and y points using numpy. Plot a horizontal line (y=0) for X-Axis, using the plot() method with linestyle, labels. Plot a horizontal line (y=0) for X-Axis, using the plot() method with linestyle, labels. Plot x and y points using the plot() method with linestyle, labels. Plot x and y points using the plot() method with linestyle, labels. To hide the grid, use plt.grid(False). To hide the grid, use plt.grid(False). To hide the axes, use plt.axis('off') To hide the axes, use plt.axis('off') To activate the labels' legend, use the legend() method. To activate the labels' legend, use the legend() method. To display the figure, use the show() method. To display the figure, use the show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = np.linspace(-10, 10, 50) y = np.sin(x) plt.axhline(y=0, c="green", linestyle="dashdot", label="y=0") plt.plot(x, y, c="red", lw=5, linestyle="dashdot", label="y=sin(x)") plt.grid(False) plt.axis('off') plt.legend() plt.show()
[ { "code": null, "e": 1134, "s": 1062, "text": "To hide axes (X and Y) and gridlines, we can take the following steps −" }, { "code": null, "e": 1169, "s": 1134, "text": "Create x and y points using numpy." }, { "code": null, "e": 1204, "s": 1169, "text": "Create x and y points using numpy." }, { "code": null, "e": 1293, "s": 1204, "text": "Plot a horizontal line (y=0) for X-Axis, using the plot() method with linestyle, labels." }, { "code": null, "e": 1382, "s": 1293, "text": "Plot a horizontal line (y=0) for X-Axis, using the plot() method with linestyle, labels." }, { "code": null, "e": 1450, "s": 1382, "text": "Plot x and y points using the plot() method with linestyle, labels." }, { "code": null, "e": 1518, "s": 1450, "text": "Plot x and y points using the plot() method with linestyle, labels." }, { "code": null, "e": 1557, "s": 1518, "text": "To hide the grid, use plt.grid(False)." }, { "code": null, "e": 1596, "s": 1557, "text": "To hide the grid, use plt.grid(False)." }, { "code": null, "e": 1634, "s": 1596, "text": "To hide the axes, use plt.axis('off')" }, { "code": null, "e": 1672, "s": 1634, "text": "To hide the axes, use plt.axis('off')" }, { "code": null, "e": 1729, "s": 1672, "text": "To activate the labels' legend, use the legend() method." }, { "code": null, "e": 1786, "s": 1729, "text": "To activate the labels' legend, use the legend() method." }, { "code": null, "e": 1832, "s": 1786, "text": "To display the figure, use the show() method." }, { "code": null, "e": 1878, "s": 1832, "text": "To display the figure, use the show() method." }, { "code": null, "e": 2251, "s": 1878, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.linspace(-10, 10, 50)\ny = np.sin(x)\nplt.axhline(y=0, c=\"green\", linestyle=\"dashdot\", label=\"y=0\")\nplt.plot(x, y, c=\"red\", lw=5, linestyle=\"dashdot\", label=\"y=sin(x)\")\nplt.grid(False)\nplt.axis('off')\nplt.legend()\nplt.show()" } ]
dir command in Linux with examples - GeeksforGeeks
15 May, 2019 dir command in Linux is used to list the contents of a directory. dir command differs from ls command in the format of listing contents that is in default listing options.By default, dir command lists the files and folders in columns, sorted vertically and special characters are represented by backslash escape sequences. But unlike ls, when the output is on terminal, it does not produce colored output as ls does. SYNTAX: dir [OPTION] [FILE] 1. -a or –all option: It displays all the hidden files(starting with `.`) along with two files denoted by `.` and `..` which signals for current and previous directory respectively.SYNTAX: dir -a EXAMPLE: 2. -A or –almost-all option: It is similar to -a option except that it does not display files that signals the current directory and previous directory.SYNTAX: dir -A EXAMPLE: 3. -l –author option: Displays author of all the files. -l is required to display the contents in the form of a list.SYNTAX: dir -l --author EXAMPLE: 4. -B or –ignore-backups option: Ignores listing of backed up files. These files end with a `~`.SYNTAX: dir -B 5. –color option: (can be followed by =[TIME]).It is used to colorize the output. In the absence of time specification which can be auto, never or always, it colorizes the output always (default behavior).SYNTAX: dir --color EXAMPLE: 6. -F, –classify option: Append indicator (one of */=>@|) to the file names which classifies them into their type. The meanings of symbols are as follows: A slash (`/`) indicates a directory. An asterisk (`*`) indicates an executable. An at sign (`@`) indicates a symbolic link. A percent sign (`%`) indicates a whiteout. An equal sign (`=`) indicates a socket. A vertical bar (`|`) indicates a FIFO. SYNTAX: dir -F EXAMPLE: 7. –file-type option: It is same as -F option, except that it does not append `*` to the executables.SYNTAX: dir --file-type EXAMPLE: 8. –format=WORD option: It formats the listing of entries. The WORD can take the following values: across, commas, horizontal, long, single-column, verbose, vertical. The same can be achieved by passing -x, -m, -x, -l, -1, -l, -C options to dir command for each of the respective values.SYNTAX: dir --format=WORD EXAMPLE 1:EXAMPLE 2: 9. –hide=PATTERN or –ignore=PATTERN option: It ignores files described by shell PATTERN while listing the contents of a directory.SYNTAX: dir --hide=PATTERN EXAMPLE: 10. -n, –numeric-uid-gid option: This option is similar to the long listing that is -l option except that it lists numeric user and group IDs.SYNTAX: dir -n 11. -r, –reverse option: List files in reverse order while sorting.SYNTAX: dir -r EXAMPLE: 12.-R, –recursive option: List subdirectories recursively.SYNTAX: dir -R EXAMPLE: 13.–sort=PARAMETER: To list files in a sorted manner described by the PARAMETER. The PARAMETER can take the following values: none (-U), size (-S), time (-t), version (-v), extension (-X).Instead of passing –sort option, the flags indicated in the brackets can directly be passed as options to sort the listing.SYNTAX: dir --sort=PARAMETER EXAMPLE 1:EXAMPLE 2: 14. –help option: Display the help options and exit.SYNTAX: dir --help EXAMPLE: 15. –version option: Outputs version information and exit.SYNTAX: dir --version linux-command Linux-directory-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Thread functions in C/C++ nohup Command in Linux with Examples scp command in Linux with Examples chown command in Linux with Examples Array Basics in Shell Scripting | Set 1 mv command in Linux with examples Basic Operators in Shell Scripting SED command in Linux | Set 2 Docker - COPY Instruction Named Pipe or FIFO with example C program
[ { "code": null, "e": 24432, "s": 24404, "text": "\n15 May, 2019" }, { "code": null, "e": 24498, "s": 24432, "text": "dir command in Linux is used to list the contents of a directory." }, { "code": null, "e": 24849, "s": 24498, "text": "dir command differs from ls command in the format of listing contents that is in default listing options.By default, dir command lists the files and folders in columns, sorted vertically and special characters are represented by backslash escape sequences. But unlike ls, when the output is on terminal, it does not produce colored output as ls does." }, { "code": null, "e": 24857, "s": 24849, "text": "SYNTAX:" }, { "code": null, "e": 24879, "s": 24857, "text": " dir [OPTION] [FILE] " }, { "code": null, "e": 25068, "s": 24879, "text": "1. -a or –all option: It displays all the hidden files(starting with `.`) along with two files denoted by `.` and `..` which signals for current and previous directory respectively.SYNTAX:" }, { "code": null, "e": 25077, "s": 25068, "text": " dir -a " }, { "code": null, "e": 25086, "s": 25077, "text": "EXAMPLE:" }, { "code": null, "e": 25246, "s": 25086, "text": "2. -A or –almost-all option: It is similar to -a option except that it does not display files that signals the current directory and previous directory.SYNTAX:" }, { "code": null, "e": 25255, "s": 25246, "text": " dir -A " }, { "code": null, "e": 25264, "s": 25255, "text": "EXAMPLE:" }, { "code": null, "e": 25389, "s": 25264, "text": "3. -l –author option: Displays author of all the files. -l is required to display the contents in the form of a list.SYNTAX:" }, { "code": null, "e": 25407, "s": 25389, "text": " dir -l --author " }, { "code": null, "e": 25416, "s": 25407, "text": "EXAMPLE:" }, { "code": null, "e": 25520, "s": 25416, "text": "4. -B or –ignore-backups option: Ignores listing of backed up files. These files end with a `~`.SYNTAX:" }, { "code": null, "e": 25529, "s": 25520, "text": " dir -B " }, { "code": null, "e": 25742, "s": 25529, "text": "5. –color option: (can be followed by =[TIME]).It is used to colorize the output. In the absence of time specification which can be auto, never or always, it colorizes the output always (default behavior).SYNTAX:" }, { "code": null, "e": 25756, "s": 25742, "text": " dir --color " }, { "code": null, "e": 25765, "s": 25756, "text": "EXAMPLE:" }, { "code": null, "e": 25920, "s": 25765, "text": "6. -F, –classify option: Append indicator (one of */=>@|) to the file names which classifies them into their type. The meanings of symbols are as follows:" }, { "code": null, "e": 25957, "s": 25920, "text": "A slash (`/`) indicates a directory." }, { "code": null, "e": 26000, "s": 25957, "text": "An asterisk (`*`) indicates an executable." }, { "code": null, "e": 26044, "s": 26000, "text": "An at sign (`@`) indicates a symbolic link." }, { "code": null, "e": 26087, "s": 26044, "text": "A percent sign (`%`) indicates a whiteout." }, { "code": null, "e": 26127, "s": 26087, "text": "An equal sign (`=`) indicates a socket." }, { "code": null, "e": 26166, "s": 26127, "text": "A vertical bar (`|`) indicates a FIFO." }, { "code": null, "e": 26174, "s": 26166, "text": "SYNTAX:" }, { "code": null, "e": 26183, "s": 26174, "text": " dir -F " }, { "code": null, "e": 26192, "s": 26183, "text": "EXAMPLE:" }, { "code": null, "e": 26301, "s": 26192, "text": "7. –file-type option: It is same as -F option, except that it does not append `*` to the executables.SYNTAX:" }, { "code": null, "e": 26319, "s": 26301, "text": " dir --file-type " }, { "code": null, "e": 26328, "s": 26319, "text": "EXAMPLE:" }, { "code": null, "e": 26623, "s": 26328, "text": "8. –format=WORD option: It formats the listing of entries. The WORD can take the following values: across, commas, horizontal, long, single-column, verbose, vertical. The same can be achieved by passing -x, -m, -x, -l, -1, -l, -C options to dir command for each of the respective values.SYNTAX:" }, { "code": null, "e": 26643, "s": 26623, "text": " dir --format=WORD " }, { "code": null, "e": 26664, "s": 26643, "text": "EXAMPLE 1:EXAMPLE 2:" }, { "code": null, "e": 26802, "s": 26664, "text": "9. –hide=PATTERN or –ignore=PATTERN option: It ignores files described by shell PATTERN while listing the contents of a directory.SYNTAX:" }, { "code": null, "e": 26823, "s": 26802, "text": " dir --hide=PATTERN " }, { "code": null, "e": 26832, "s": 26823, "text": "EXAMPLE:" }, { "code": null, "e": 26982, "s": 26832, "text": "10. -n, –numeric-uid-gid option: This option is similar to the long listing that is -l option except that it lists numeric user and group IDs.SYNTAX:" }, { "code": null, "e": 26991, "s": 26982, "text": " dir -n " }, { "code": null, "e": 27066, "s": 26991, "text": "11. -r, –reverse option: List files in reverse order while sorting.SYNTAX:" }, { "code": null, "e": 27075, "s": 27066, "text": " dir -r " }, { "code": null, "e": 27084, "s": 27075, "text": "EXAMPLE:" }, { "code": null, "e": 27150, "s": 27084, "text": "12.-R, –recursive option: List subdirectories recursively.SYNTAX:" }, { "code": null, "e": 27159, "s": 27150, "text": " dir -R " }, { "code": null, "e": 27168, "s": 27159, "text": "EXAMPLE:" }, { "code": null, "e": 27487, "s": 27168, "text": "13.–sort=PARAMETER: To list files in a sorted manner described by the PARAMETER. The PARAMETER can take the following values: none (-U), size (-S), time (-t), version (-v), extension (-X).Instead of passing –sort option, the flags indicated in the brackets can directly be passed as options to sort the listing.SYNTAX:" }, { "code": null, "e": 27510, "s": 27487, "text": " dir --sort=PARAMETER " }, { "code": null, "e": 27531, "s": 27510, "text": "EXAMPLE 1:EXAMPLE 2:" }, { "code": null, "e": 27591, "s": 27531, "text": "14. –help option: Display the help options and exit.SYNTAX:" }, { "code": null, "e": 27604, "s": 27591, "text": " dir --help " }, { "code": null, "e": 27613, "s": 27604, "text": "EXAMPLE:" }, { "code": null, "e": 27679, "s": 27613, "text": "15. –version option: Outputs version information and exit.SYNTAX:" }, { "code": null, "e": 27695, "s": 27679, "text": " dir --version " }, { "code": null, "e": 27709, "s": 27695, "text": "linux-command" }, { "code": null, "e": 27734, "s": 27709, "text": "Linux-directory-commands" }, { "code": null, "e": 27741, "s": 27734, "text": "Picked" }, { "code": null, "e": 27752, "s": 27741, "text": "Linux-Unix" }, { "code": null, "e": 27850, "s": 27752, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27859, "s": 27850, "text": "Comments" }, { "code": null, "e": 27872, "s": 27859, "text": "Old Comments" }, { "code": null, "e": 27898, "s": 27872, "text": "Thread functions in C/C++" }, { "code": null, "e": 27935, "s": 27898, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 27970, "s": 27935, "text": "scp command in Linux with Examples" }, { "code": null, "e": 28007, "s": 27970, "text": "chown command in Linux with Examples" }, { "code": null, "e": 28047, "s": 28007, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 28081, "s": 28047, "text": "mv command in Linux with examples" }, { "code": null, "e": 28116, "s": 28081, "text": "Basic Operators in Shell Scripting" }, { "code": null, "e": 28145, "s": 28116, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 28171, "s": 28145, "text": "Docker - COPY Instruction" } ]
Prolog - Conjunctions & Disjunctions
In this chapter, we shall discuss Conjunction and Disjunction properties. These properties are used in other programming languages using AND and OR logics. Prolog also uses the same logic in its syntax. Conjunction (AND logic) can be implemented using the comma (,) operator. So two predicates separated by comma are joined with AND statement. Suppose we have a predicate, parent(jhon, bob), which means “Jhon is parent of Bob”, and another predicate, male(jhon), which means “Jhon is male”. So we can make another predicate that father(jhon,bob), which means “Jhon is father of Bob”. We can define predicate father, when he is parent AND he is male. Disjunction (OR logic) can be implemented using the semi-colon (;) operator. So two predicates separated by semi-colon are joined with OR statement. Suppose we have a predicate, father(jhon, bob). This tells that “Jhon is father of Bob”, and another predicate, mother(lili,bob), this tells that “lili is mother of bob”. If we create another predicate as child(), this will be true when father(jhon, bob) is true OR mother(lili,bob) is true. parent(jhon,bob). parent(lili,bob). male(jhon). female(lili). % Conjunction Logic father(X,Y) :- parent(X,Y),male(X). mother(X,Y) :- parent(X,Y),female(X). % Disjunction Logic child_of(X,Y) :- father(X,Y);mother(X,Y). | ?- [conj_disj]. compiling D:/TP Prolog/Sample_Codes/conj_disj.pl for byte code... D:/TP Prolog/Sample_Codes/conj_disj.pl compiled, 11 lines read - 1513 bytes written, 24 ms yes | ?- father(jhon,bob). yes | ?- child_of(jhon,bob). true ? yes | ?- child_of(lili,bob). yes | ?- 65 Lectures 5 hours Arnab Chakraborty 78 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2295, "s": 2092, "text": "In this chapter, we shall discuss Conjunction and Disjunction properties. These properties are used in other programming languages using AND and OR logics. Prolog also uses the same logic in its syntax." }, { "code": null, "e": 2743, "s": 2295, "text": "Conjunction (AND logic) can be implemented using the comma (,) operator. So two predicates separated by comma are joined with AND statement. Suppose we have a predicate, parent(jhon, bob), which means “Jhon is parent of Bob”, and another predicate, male(jhon), which means “Jhon is male”. So we can make another predicate that father(jhon,bob), which means “Jhon is father of Bob”. We can define predicate father, when he is parent AND he is male." }, { "code": null, "e": 3184, "s": 2743, "text": "Disjunction (OR logic) can be implemented using the semi-colon (;) operator. So two predicates separated by semi-colon are joined with OR statement. Suppose we have a predicate, father(jhon, bob). This tells that “Jhon is father of Bob”, and another predicate, mother(lili,bob), this tells that “lili is mother of bob”. If we create another predicate as child(), this will be true when father(jhon, bob) is true OR mother(lili,bob) is true." }, { "code": null, "e": 3405, "s": 3184, "text": "parent(jhon,bob).\nparent(lili,bob).\n\nmale(jhon).\nfemale(lili).\n\n% Conjunction Logic\nfather(X,Y) :- parent(X,Y),male(X).\nmother(X,Y) :- parent(X,Y),female(X).\n\n% Disjunction Logic\nchild_of(X,Y) :- father(X,Y);mother(X,Y)." }, { "code": null, "e": 3687, "s": 3405, "text": "| ?- [conj_disj].\ncompiling D:/TP Prolog/Sample_Codes/conj_disj.pl for byte code...\nD:/TP Prolog/Sample_Codes/conj_disj.pl compiled, 11 lines read - 1513 bytes written, 24 ms\n\nyes\n| ?- father(jhon,bob).\n\nyes\n| ?- child_of(jhon,bob).\n\ntrue ?\n\nyes\n| ?- child_of(lili,bob).\n\nyes\n| ?-\n" }, { "code": null, "e": 3720, "s": 3687, "text": "\n 65 Lectures \n 5 hours \n" }, { "code": null, "e": 3739, "s": 3720, "text": " Arnab Chakraborty" }, { "code": null, "e": 3772, "s": 3739, "text": "\n 78 Lectures \n 7 hours \n" }, { "code": null, "e": 3791, "s": 3772, "text": " Arnab Chakraborty" }, { "code": null, "e": 3798, "s": 3791, "text": " Print" }, { "code": null, "e": 3809, "s": 3798, "text": " Add Notes" } ]
Byte Class Fields in Java with example - GeeksforGeeks
12 Oct, 2018 Byte class is a wrapper class for the primitive type byte which contains several methods to effectively deal with a byte value like converting it to a string representation, and vice-versa. An object of Byte class can hold a single byte value. Byte class offers four constants in the form of Fields. These are: MAX_VALUE:The MAX_VALUE is a instance variable of Byte class which is used to return the maximum byte value.Syntax:public static final byte MAX_VALUEUsage:Byte.MAX_VALUEReturn Value: It returns a byte value equal to 127.Below is the implementation of MAX_VALUE:// Java code to implement// MAX_VALUE of Byte class class GFG { public static void main(String[] args) { // byte variable byte max_value; // MAX_VALUE Byte class max_value = Byte.MAX_VALUE; // printing the MAX_VALUE System.out.println(max_value); }}Output:127 Syntax: public static final byte MAX_VALUE Usage: Byte.MAX_VALUE Return Value: It returns a byte value equal to 127. Below is the implementation of MAX_VALUE: // Java code to implement// MAX_VALUE of Byte class class GFG { public static void main(String[] args) { // byte variable byte max_value; // MAX_VALUE Byte class max_value = Byte.MAX_VALUE; // printing the MAX_VALUE System.out.println(max_value); }} 127 MIN_VALUE:The MIN_VALUE is a instance variable of Byte class which is used to return the minimum byte value.Syntax:public static final byte MIN_VALUEUsage:Byte.MIN_VALUEReturn Value: It returns a byte value equal to -128.Below is the implementation of MIN_VALUE:// Java code to implement// MIN_VALUE of Byte class class GFG { public static void main(String[] args) { // byte variable byte min_value; // MIN_VALUE Byte class min_value = Byte.MIN_VALUE; // printing the MIN_VALUE System.out.println(min_value); }}Output:-128 Syntax: public static final byte MIN_VALUE Usage: Byte.MIN_VALUE Return Value: It returns a byte value equal to -128. Below is the implementation of MIN_VALUE: // Java code to implement// MIN_VALUE of Byte class class GFG { public static void main(String[] args) { // byte variable byte min_value; // MIN_VALUE Byte class min_value = Byte.MIN_VALUE; // printing the MIN_VALUE System.out.println(min_value); }} -128 SIZE:The SIZE is a instance variable of Byte class which is used to return number of bits required to represent a byte value in binary representation (two’s complement).Syntax:public static final int SIZEUsage:Byte.SIZEReturn Value: It returns a int value equal to 8.Below is the implementation of SIZE:// Java code to implement// SIZE of Byte class class GFG { public static void main(String[] args) { // SIZE Byte class int output = Byte.SIZE; // printing the output System.out.println(output); }}Output:8 Syntax: public static final int SIZE Usage: Byte.SIZE Return Value: It returns a int value equal to 8. Below is the implementation of SIZE: // Java code to implement// SIZE of Byte class class GFG { public static void main(String[] args) { // SIZE Byte class int output = Byte.SIZE; // printing the output System.out.println(output); }} 8 TYPE: The TYPE is a instance variable of Byte class which is used to return Class instance representing the primitive data type byte.Syntax:public static final Class<Byte> TYPEUsage:Byte.TYPEReturn Value: It returns an Class instance representing the primitive data type byte.Below is the implementation of TYPE:// Java code to implement// TYPE of Byte class class GFG { public static void main(String[] args) { // TYPE variable of Byte class Class<Byte> output = Byte.TYPE; // printing the output System.out.println(output); }}Output:byte Syntax: public static final Class<Byte> TYPE Usage: Byte.TYPE Return Value: It returns an Class instance representing the primitive data type byte. Below is the implementation of TYPE: // Java code to implement// TYPE of Byte class class GFG { public static void main(String[] args) { // TYPE variable of Byte class Class<Byte> output = Byte.TYPE; // printing the output System.out.println(output); }} byte Java-Byte Java-Class and Object Java-Library Java Java-Class and Object Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Stream In Java Singleton Class in Java
[ { "code": null, "e": 24466, "s": 24438, "text": "\n12 Oct, 2018" }, { "code": null, "e": 24710, "s": 24466, "text": "Byte class is a wrapper class for the primitive type byte which contains several methods to effectively deal with a byte value like converting it to a string representation, and vice-versa. An object of Byte class can hold a single byte value." }, { "code": null, "e": 24777, "s": 24710, "text": "Byte class offers four constants in the form of Fields. These are:" }, { "code": null, "e": 25357, "s": 24777, "text": "MAX_VALUE:The MAX_VALUE is a instance variable of Byte class which is used to return the maximum byte value.Syntax:public static final byte MAX_VALUEUsage:Byte.MAX_VALUEReturn Value: It returns a byte value equal to 127.Below is the implementation of MAX_VALUE:// Java code to implement// MAX_VALUE of Byte class class GFG { public static void main(String[] args) { // byte variable byte max_value; // MAX_VALUE Byte class max_value = Byte.MAX_VALUE; // printing the MAX_VALUE System.out.println(max_value); }}Output:127\n" }, { "code": null, "e": 25365, "s": 25357, "text": "Syntax:" }, { "code": null, "e": 25400, "s": 25365, "text": "public static final byte MAX_VALUE" }, { "code": null, "e": 25407, "s": 25400, "text": "Usage:" }, { "code": null, "e": 25422, "s": 25407, "text": "Byte.MAX_VALUE" }, { "code": null, "e": 25474, "s": 25422, "text": "Return Value: It returns a byte value equal to 127." }, { "code": null, "e": 25516, "s": 25474, "text": "Below is the implementation of MAX_VALUE:" }, { "code": "// Java code to implement// MAX_VALUE of Byte class class GFG { public static void main(String[] args) { // byte variable byte max_value; // MAX_VALUE Byte class max_value = Byte.MAX_VALUE; // printing the MAX_VALUE System.out.println(max_value); }}", "e": 25824, "s": 25516, "text": null }, { "code": null, "e": 25829, "s": 25824, "text": "127\n" }, { "code": null, "e": 26411, "s": 25829, "text": "MIN_VALUE:The MIN_VALUE is a instance variable of Byte class which is used to return the minimum byte value.Syntax:public static final byte MIN_VALUEUsage:Byte.MIN_VALUEReturn Value: It returns a byte value equal to -128.Below is the implementation of MIN_VALUE:// Java code to implement// MIN_VALUE of Byte class class GFG { public static void main(String[] args) { // byte variable byte min_value; // MIN_VALUE Byte class min_value = Byte.MIN_VALUE; // printing the MIN_VALUE System.out.println(min_value); }}Output:-128\n" }, { "code": null, "e": 26419, "s": 26411, "text": "Syntax:" }, { "code": null, "e": 26454, "s": 26419, "text": "public static final byte MIN_VALUE" }, { "code": null, "e": 26461, "s": 26454, "text": "Usage:" }, { "code": null, "e": 26476, "s": 26461, "text": "Byte.MIN_VALUE" }, { "code": null, "e": 26529, "s": 26476, "text": "Return Value: It returns a byte value equal to -128." }, { "code": null, "e": 26571, "s": 26529, "text": "Below is the implementation of MIN_VALUE:" }, { "code": "// Java code to implement// MIN_VALUE of Byte class class GFG { public static void main(String[] args) { // byte variable byte min_value; // MIN_VALUE Byte class min_value = Byte.MIN_VALUE; // printing the MIN_VALUE System.out.println(min_value); }}", "e": 26879, "s": 26571, "text": null }, { "code": null, "e": 26885, "s": 26879, "text": "-128\n" }, { "code": null, "e": 27436, "s": 26885, "text": "SIZE:The SIZE is a instance variable of Byte class which is used to return number of bits required to represent a byte value in binary representation (two’s complement).Syntax:public static final int SIZEUsage:Byte.SIZEReturn Value: It returns a int value equal to 8.Below is the implementation of SIZE:// Java code to implement// SIZE of Byte class class GFG { public static void main(String[] args) { // SIZE Byte class int output = Byte.SIZE; // printing the output System.out.println(output); }}Output:8\n" }, { "code": null, "e": 27444, "s": 27436, "text": "Syntax:" }, { "code": null, "e": 27473, "s": 27444, "text": "public static final int SIZE" }, { "code": null, "e": 27480, "s": 27473, "text": "Usage:" }, { "code": null, "e": 27490, "s": 27480, "text": "Byte.SIZE" }, { "code": null, "e": 27539, "s": 27490, "text": "Return Value: It returns a int value equal to 8." }, { "code": null, "e": 27576, "s": 27539, "text": "Below is the implementation of SIZE:" }, { "code": "// Java code to implement// SIZE of Byte class class GFG { public static void main(String[] args) { // SIZE Byte class int output = Byte.SIZE; // printing the output System.out.println(output); }}", "e": 27815, "s": 27576, "text": null }, { "code": null, "e": 27818, "s": 27815, "text": "8\n" }, { "code": null, "e": 28401, "s": 27818, "text": "TYPE: The TYPE is a instance variable of Byte class which is used to return Class instance representing the primitive data type byte.Syntax:public static final Class<Byte> TYPEUsage:Byte.TYPEReturn Value: It returns an Class instance representing the primitive data type byte.Below is the implementation of TYPE:// Java code to implement// TYPE of Byte class class GFG { public static void main(String[] args) { // TYPE variable of Byte class Class<Byte> output = Byte.TYPE; // printing the output System.out.println(output); }}Output:byte\n" }, { "code": null, "e": 28409, "s": 28401, "text": "Syntax:" }, { "code": null, "e": 28446, "s": 28409, "text": "public static final Class<Byte> TYPE" }, { "code": null, "e": 28453, "s": 28446, "text": "Usage:" }, { "code": null, "e": 28463, "s": 28453, "text": "Byte.TYPE" }, { "code": null, "e": 28549, "s": 28463, "text": "Return Value: It returns an Class instance representing the primitive data type byte." }, { "code": null, "e": 28586, "s": 28549, "text": "Below is the implementation of TYPE:" }, { "code": "// Java code to implement// TYPE of Byte class class GFG { public static void main(String[] args) { // TYPE variable of Byte class Class<Byte> output = Byte.TYPE; // printing the output System.out.println(output); }}", "e": 28845, "s": 28586, "text": null }, { "code": null, "e": 28851, "s": 28845, "text": "byte\n" }, { "code": null, "e": 28861, "s": 28851, "text": "Java-Byte" }, { "code": null, "e": 28883, "s": 28861, "text": "Java-Class and Object" }, { "code": null, "e": 28896, "s": 28883, "text": "Java-Library" }, { "code": null, "e": 28901, "s": 28896, "text": "Java" }, { "code": null, "e": 28923, "s": 28901, "text": "Java-Class and Object" }, { "code": null, "e": 28928, "s": 28923, "text": "Java" }, { "code": null, "e": 29026, "s": 28928, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29058, "s": 29026, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29109, "s": 29058, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29139, "s": 29109, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29158, "s": 29139, "text": "Interfaces in Java" }, { "code": null, "e": 29189, "s": 29158, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29207, "s": 29189, "text": "ArrayList in Java" }, { "code": null, "e": 29239, "s": 29207, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 29259, "s": 29239, "text": "Stack Class in Java" }, { "code": null, "e": 29274, "s": 29259, "text": "Stream In Java" } ]
How to Visualize Social Network With Graph Theory | by Khuyen Tran | Towards Data Science
After reading the books in the series A Song of Ice and Fired by G. R. R. Martin, as a true fan of Game of Thrones, you might be curious about who is the most influential person in Westeros. Or you know that Eddard Stark and Randyll Tarly are connected but not quite sure how exactly they are connected. Are they connected by a third, or fourth person? Would it be great if you can visualize the network? As data enthusiastic, you decide to do a search on relevant data to analyze. Luckily, you find the data of character interaction networks for George R. R. Martin’s “A Song of Ice and Fire”. How exciting it is! But the data contains a list of nodes and edges. What do they even mean and where should you start? Don’t worry. I get your back. Let’s understand what is a graph and how the graph helps us to understand social networks. A graph is a structure that contains vertices (or nodes) and each of the related pairs of vertices is called an edge. The edges may be directed or undirected. Directed means one direction. Person A might like person B but person B may not like person A. Undirected means 2 directions. If person A shakes hands with person B, that also means the person B shakes hands with the person A With the structure of the graph, it can be utilized to visualize social networks efficiently. Want to know the influencer of members in a team? We can immediately see that the person (node) with the most connections (edges) is the influencer. Great! We know why the graph is useful in visualizing the network. Let’s find out how we can create the graph and use it to visualize the network of characters in Game of Thrones! I merged multiples data from several books into 2 files: data of nodes ‘ASOIAF_nodes.csv’, and data of edges ‘ASOIAF_edges.csv’. You can find the data here import pandas as pdnodes = pd.read_csv('ASOIAF_nodes.csv')nodes = nodes['Id']num_nodes = nodes.shape[0]nodes Cool! So we have a list of characters in the variable node. There is a total of 276 nodes (characters). Now let’s explore edges. In the ‘ASOIAF_edges.csv’ file, there is also information about weight (number of interactions), and the kind of graph (undirected). But since we simply care about the connections, we use the first 2 columns edges = pd.read_csv('ASOIAF_edges.csv',usecols=[0,1] )edges There is a total of 683 connections! Wow. Many connections established throughout the series. But how do we make these data into a graph? We can regard: Each character as a vertex Two connected vertices as an edge Now we are ready to visualize the network! Graphviz is a Python interface for drawing graphs. To install it, run $ pip install graphviz Create a graph by instantiating a new Digraph object from graphviz import Digraphdot = Digraph(comment='VIP graph') Let’s visualize the first ten nodes nodes_G = []for node in edges[:10]['Source']: if node not in nodes_G: nodes_G.append(node)for node in edges[:10]['Target']: if node not in nodes_G: nodes_G.append(node) Add nodes and edges into the graph dot = Digraph(comment='VIP graph')for i in range(len(nodes_G)): dot.node(nodes_G[i])for i in range(len(edges[:10])): edge = edges.iloc[i] dot.edge(edge['Source'], edge['Target']) Visualize: dot.render('VIP-graph_10.gv', view=True) Nice! We can see the interactions between characters clearly in the graph. But how about visualizing the entire network. Of course, we can do that. But we should anticipate that the network of characters in 5 chapters of this series would be huge dot = Digraph(comment='VIP graph')for i in range(num_nodes): dot.node(nodes[i])for i in range(len(edges)): edge = edges.iloc[i] dot.edge(edge['Source'], edge['Target'])dot.render('VIP-graph.gv', view=True) It is time for the show! Cool! With graph, we can visualize the network efficiently. But can we create our own graph class? Start with creating the vertex (node) class. What attributes and methods do we want our vertex class to have? Hmm. Add connections (addNeighbor), know which nodes the current node connect with (getConnections), find out the name of the node (getId ), and how strong is the connection (getWeight) Create a graph class with some basic methods of a graph: Congratulation! In this article, you have learned what graph is and how to use a graph to visualize the social network. So what can you do with this knowledge? Maybe access to the data in this article and create the graph of the characters you are curious about to analyze their relationship? Or if you are not at all a fan of Game of Thrones, you can analyze data about other social networks you care about such as Twitter, Facebook to analyze the network between you and your friends or followers. You will get to practice using the graph as well as understand your relationship with your friends. Do you know them directly or from the connections with others? It would be so fascinating to know! You can find the code of this article in my Github. In my notebook, I also cover how to traverse the disconnected nodes with depth-first search, and find the distance between 2 characters with breadth-first search. I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter. Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
[ { "code": null, "e": 577, "s": 172, "text": "After reading the books in the series A Song of Ice and Fired by G. R. R. Martin, as a true fan of Game of Thrones, you might be curious about who is the most influential person in Westeros. Or you know that Eddard Stark and Randyll Tarly are connected but not quite sure how exactly they are connected. Are they connected by a third, or fourth person? Would it be great if you can visualize the network?" }, { "code": null, "e": 1008, "s": 577, "text": "As data enthusiastic, you decide to do a search on relevant data to analyze. Luckily, you find the data of character interaction networks for George R. R. Martin’s “A Song of Ice and Fire”. How exciting it is! But the data contains a list of nodes and edges. What do they even mean and where should you start? Don’t worry. I get your back. Let’s understand what is a graph and how the graph helps us to understand social networks." }, { "code": null, "e": 1393, "s": 1008, "text": "A graph is a structure that contains vertices (or nodes) and each of the related pairs of vertices is called an edge. The edges may be directed or undirected. Directed means one direction. Person A might like person B but person B may not like person A. Undirected means 2 directions. If person A shakes hands with person B, that also means the person B shakes hands with the person A" }, { "code": null, "e": 1636, "s": 1393, "text": "With the structure of the graph, it can be utilized to visualize social networks efficiently. Want to know the influencer of members in a team? We can immediately see that the person (node) with the most connections (edges) is the influencer." }, { "code": null, "e": 1816, "s": 1636, "text": "Great! We know why the graph is useful in visualizing the network. Let’s find out how we can create the graph and use it to visualize the network of characters in Game of Thrones!" }, { "code": null, "e": 1972, "s": 1816, "text": "I merged multiples data from several books into 2 files: data of nodes ‘ASOIAF_nodes.csv’, and data of edges ‘ASOIAF_edges.csv’. You can find the data here" }, { "code": null, "e": 2081, "s": 1972, "text": "import pandas as pdnodes = pd.read_csv('ASOIAF_nodes.csv')nodes = nodes['Id']num_nodes = nodes.shape[0]nodes" }, { "code": null, "e": 2418, "s": 2081, "text": "Cool! So we have a list of characters in the variable node. There is a total of 276 nodes (characters). Now let’s explore edges. In the ‘ASOIAF_edges.csv’ file, there is also information about weight (number of interactions), and the kind of graph (undirected). But since we simply care about the connections, we use the first 2 columns" }, { "code": null, "e": 2478, "s": 2418, "text": "edges = pd.read_csv('ASOIAF_edges.csv',usecols=[0,1] )edges" }, { "code": null, "e": 2631, "s": 2478, "text": "There is a total of 683 connections! Wow. Many connections established throughout the series. But how do we make these data into a graph? We can regard:" }, { "code": null, "e": 2658, "s": 2631, "text": "Each character as a vertex" }, { "code": null, "e": 2692, "s": 2658, "text": "Two connected vertices as an edge" }, { "code": null, "e": 2735, "s": 2692, "text": "Now we are ready to visualize the network!" }, { "code": null, "e": 2805, "s": 2735, "text": "Graphviz is a Python interface for drawing graphs. To install it, run" }, { "code": null, "e": 2828, "s": 2805, "text": "$ pip install graphviz" }, { "code": null, "e": 2881, "s": 2828, "text": "Create a graph by instantiating a new Digraph object" }, { "code": null, "e": 2944, "s": 2881, "text": "from graphviz import Digraphdot = Digraph(comment='VIP graph')" }, { "code": null, "e": 2980, "s": 2944, "text": "Let’s visualize the first ten nodes" }, { "code": null, "e": 3169, "s": 2980, "text": "nodes_G = []for node in edges[:10]['Source']: if node not in nodes_G: nodes_G.append(node)for node in edges[:10]['Target']: if node not in nodes_G: nodes_G.append(node)" }, { "code": null, "e": 3204, "s": 3169, "text": "Add nodes and edges into the graph" }, { "code": null, "e": 3392, "s": 3204, "text": "dot = Digraph(comment='VIP graph')for i in range(len(nodes_G)): dot.node(nodes_G[i])for i in range(len(edges[:10])): edge = edges.iloc[i] dot.edge(edge['Source'], edge['Target'])" }, { "code": null, "e": 3403, "s": 3392, "text": "Visualize:" }, { "code": null, "e": 3444, "s": 3403, "text": "dot.render('VIP-graph_10.gv', view=True)" }, { "code": null, "e": 3691, "s": 3444, "text": "Nice! We can see the interactions between characters clearly in the graph. But how about visualizing the entire network. Of course, we can do that. But we should anticipate that the network of characters in 5 chapters of this series would be huge" }, { "code": null, "e": 3906, "s": 3691, "text": "dot = Digraph(comment='VIP graph')for i in range(num_nodes): dot.node(nodes[i])for i in range(len(edges)): edge = edges.iloc[i] dot.edge(edge['Source'], edge['Target'])dot.render('VIP-graph.gv', view=True)" }, { "code": null, "e": 3931, "s": 3906, "text": "It is time for the show!" }, { "code": null, "e": 4030, "s": 3931, "text": "Cool! With graph, we can visualize the network efficiently. But can we create our own graph class?" }, { "code": null, "e": 4326, "s": 4030, "text": "Start with creating the vertex (node) class. What attributes and methods do we want our vertex class to have? Hmm. Add connections (addNeighbor), know which nodes the current node connect with (getConnections), find out the name of the node (getId ), and how strong is the connection (getWeight)" }, { "code": null, "e": 4383, "s": 4326, "text": "Create a graph class with some basic methods of a graph:" }, { "code": null, "e": 4676, "s": 4383, "text": "Congratulation! In this article, you have learned what graph is and how to use a graph to visualize the social network. So what can you do with this knowledge? Maybe access to the data in this article and create the graph of the characters you are curious about to analyze their relationship?" }, { "code": null, "e": 5082, "s": 4676, "text": "Or if you are not at all a fan of Game of Thrones, you can analyze data about other social networks you care about such as Twitter, Facebook to analyze the network between you and your friends or followers. You will get to practice using the graph as well as understand your relationship with your friends. Do you know them directly or from the connections with others? It would be so fascinating to know!" }, { "code": null, "e": 5297, "s": 5082, "text": "You can find the code of this article in my Github. In my notebook, I also cover how to traverse the disconnected nodes with depth-first search, and find the distance between 2 characters with breadth-first search." }, { "code": null, "e": 5457, "s": 5297, "text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter." } ]
Create Python Datetime from string - GeeksforGeeks
31 Aug, 2021 In this article, we are going to see how to create a python DateTime object from a given string. For this, we will use the datetime.strptime() method. The strptime() method returns a DateTime object corresponding to date_string, parsed according to the format string given by the user. Syntax: datetime.strptime(date_string, format) Here we are going to convert a simple string into datetime object, for this we will pass the string into strptime() and objectify the datetime object through this. Python3 from datetime import datetime input_str = '21/01/24 11:04:19' dt_object = datetime.strptime( input_str, '%d/%m/%y %H:%M:%S') print("The type of the input date string now is: ", type(dt_object)) print("The date is", dt_object) Output: The type of the input date string now is: <class ‘datetime.datetime’> The date is 2024-01-21 11:04:19 The strptime() method allows you to convert timestamps in “words” to date-time objects too. The snippet below shows it can be done: Python3 from datetime import datetime time_str = 'May 17 2019 11:33PM'dt_object = datetime.strptime( time_str, '%b %d %Y %I:%M%p') print(dt_object) Output: 2019-05-17 23:33:00 DateTime format for the given string must be known, failing which can cause unnecessary problems and errors. the snippet below shows what problems can be caused: Python3 from datetime import datetime time_str = '201123101455' dt_obj = datetime.strptime(time_str, '%y%m%d%H%M%S')dt_obj2 = datetime.strptime(time_str, '%d%m%y%H%S%M') print ("1st interpretation of date from string is: ",dt_obj) print ("2nd interpretation of date from same string is", dt_obj2) Output : 1st interpretation of date from string is: 2020-11-23 10:14:55 2nd interpretation of date from same string is 2023-11-20 10:55:14 The strptime() method will not work if the string argument is not consistent with the format parameter. The following snippets show an error occurring due to the mismatch in the format specifier. Python3 from datetime import datetime time_str = '220917 114519'dt_obj = datetime.strptime(time_str, '%d/%m/%y %H:%M:%S') print ("The type is", type(dt_obj))print ("The date is", date_time_obj) Output: ValueError(“time data %r does not match format %r” %(data_string, format)) The format specifiers are mostly the same as for strftime() method. These specifiers are: Picked Python-datetime 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 | os.path.join() method Python | Get unique values from a list Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n31 Aug, 2021" }, { "code": null, "e": 24389, "s": 24292, "text": "In this article, we are going to see how to create a python DateTime object from a given string." }, { "code": null, "e": 24578, "s": 24389, "text": "For this, we will use the datetime.strptime() method. The strptime() method returns a DateTime object corresponding to date_string, parsed according to the format string given by the user." }, { "code": null, "e": 24625, "s": 24578, "text": "Syntax: datetime.strptime(date_string, format)" }, { "code": null, "e": 24789, "s": 24625, "text": "Here we are going to convert a simple string into datetime object, for this we will pass the string into strptime() and objectify the datetime object through this." }, { "code": null, "e": 24797, "s": 24789, "text": "Python3" }, { "code": "from datetime import datetime input_str = '21/01/24 11:04:19' dt_object = datetime.strptime( input_str, '%d/%m/%y %H:%M:%S') print(\"The type of the input date string now is: \", type(dt_object)) print(\"The date is\", dt_object)", "e": 25034, "s": 24797, "text": null }, { "code": null, "e": 25043, "s": 25034, "text": "Output: " }, { "code": null, "e": 25114, "s": 25043, "text": "The type of the input date string now is: <class ‘datetime.datetime’>" }, { "code": null, "e": 25146, "s": 25114, "text": "The date is 2024-01-21 11:04:19" }, { "code": null, "e": 25278, "s": 25146, "text": "The strptime() method allows you to convert timestamps in “words” to date-time objects too. The snippet below shows it can be done:" }, { "code": null, "e": 25286, "s": 25278, "text": "Python3" }, { "code": "from datetime import datetime time_str = 'May 17 2019 11:33PM'dt_object = datetime.strptime( time_str, '%b %d %Y %I:%M%p') print(dt_object)", "e": 25430, "s": 25286, "text": null }, { "code": null, "e": 25439, "s": 25430, "text": "Output: " }, { "code": null, "e": 25459, "s": 25439, "text": "2019-05-17 23:33:00" }, { "code": null, "e": 25621, "s": 25459, "text": "DateTime format for the given string must be known, failing which can cause unnecessary problems and errors. the snippet below shows what problems can be caused:" }, { "code": null, "e": 25629, "s": 25621, "text": "Python3" }, { "code": "from datetime import datetime time_str = '201123101455' dt_obj = datetime.strptime(time_str, '%y%m%d%H%M%S')dt_obj2 = datetime.strptime(time_str, '%d%m%y%H%S%M') print (\"1st interpretation of date from string is: \",dt_obj) print (\"2nd interpretation of date from same string is\", dt_obj2)", "e": 25921, "s": 25629, "text": null }, { "code": null, "e": 25931, "s": 25921, "text": "Output : " }, { "code": null, "e": 25995, "s": 25931, "text": "1st interpretation of date from string is: 2020-11-23 10:14:55" }, { "code": null, "e": 26062, "s": 25995, "text": "2nd interpretation of date from same string is 2023-11-20 10:55:14" }, { "code": null, "e": 26258, "s": 26062, "text": "The strptime() method will not work if the string argument is not consistent with the format parameter. The following snippets show an error occurring due to the mismatch in the format specifier." }, { "code": null, "e": 26266, "s": 26258, "text": "Python3" }, { "code": "from datetime import datetime time_str = '220917 114519'dt_obj = datetime.strptime(time_str, '%d/%m/%y %H:%M:%S') print (\"The type is\", type(dt_obj))print (\"The date is\", date_time_obj)", "e": 26454, "s": 26266, "text": null }, { "code": null, "e": 26462, "s": 26454, "text": "Output:" }, { "code": null, "e": 26537, "s": 26462, "text": "ValueError(“time data %r does not match format %r” %(data_string, format))" }, { "code": null, "e": 26627, "s": 26537, "text": "The format specifiers are mostly the same as for strftime() method. These specifiers are:" }, { "code": null, "e": 26634, "s": 26627, "text": "Picked" }, { "code": null, "e": 26650, "s": 26634, "text": "Python-datetime" }, { "code": null, "e": 26657, "s": 26650, "text": "Python" }, { "code": null, "e": 26755, "s": 26657, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26787, "s": 26755, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26843, "s": 26787, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26885, "s": 26843, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26927, "s": 26885, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26949, "s": 26927, "text": "Defaultdict in Python" }, { "code": null, "e": 26980, "s": 26949, "text": "Python | os.path.join() method" }, { "code": null, "e": 27019, "s": 26980, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27074, "s": 27019, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27103, "s": 27074, "text": "Create a directory in Python" } ]
How to Write and Call DLL's within Delphi
The following code creates a DLL containing two functions, Min and Max, with the objective of returning the larger of two integers. Start a new DLL project in Delphi (Click File −> New, select DLL). Save the project as delhpdll. Fill in the code in the library as given below. // Uffe wrote: This is a toy dll to demonstrate the // use of dll's // // The libary export two functions Max and Min // // The dll matches the MainProject which is a Delphi // project which calls the DLL. //{ // DELPHI WROTE THIS: // Important note about DLL memory management: ShareMem // must be the first unit in your library's USES clause // AND your project's (select Project-View Source) USES // clause if your DLL exports any procedures or functions // that pass strings as parameters or function results. // This applies to all strings passed to and from your // DLL--even those that are nested in records and classes. // ShareMem is the interface unit to the BORLNDMM.DLL // shared memory manager, which must be deployed along // with your DLL. To avoid using BORLNDMM.DLL, pass // string information using PChar or ShortString // parameters. //} uses SysUtils, Classes; // Declare stdcall to make interface to other languages function Min(X, Y: Integer): Integer; stdcall; begin if X < Y then Min := X else Min := Y; end; function Max(X, Y: Integer): Integer; stdcall; begin if X > Y then Max := X else Max := Y; end; exports // Make available to calling applications Min index 1, Max index 2; begin end. Build and Save the DLL project. (If you are a command line kind of guy, then you can just execute "dcc32 delhpdll.dpr" from the command line ... that will give you the same DLL but without the IDE stuff ...). Then you need an application, to call the DLL: Start a new "main" application project. Make whatever GUI controls you need to test the DLL. Fill in the source code for interfacing the DLL as given below. //Main Applet to demonstrate how to call a dll. // // SEARCH PATHS: // The code makes no special effort to search for the DLL. // Easiest if everything (including DLL) is in the same // directory. // //DLL CALLING: // This applet demonstrates both Win API calling and // external calling (see below) // // // NOTICE: I wasted a lot of time not declaring the // functions "stdcall" throughout. If you // declare it "stdcall" in the DLL and not // in the calling application, then you get hard-to-find // errors - "external" will crash on you, // the Win API does not type-check so the function // just gives "weird" results. (OK this is // obvious when you think about it .. problem is, // I didn't) // Jump to "implementation" section, // no DLL specs before. interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Edit1: TEdit; Edit2: TEdit; Button1: TButton; Label1: TLabel; Label2: TLabel; Button2: TButton; Label3: TLabel; Label4: TLabel; Label5: TLabel; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } end; // TMaxFun becomes a function variable (think of // a "pointer to function" without the pointer) TMaxFun = function(i,j: integer):integer; stdcall; var Form1: TForm1; implementation {$R *.DFM} // This declares Max as a function which should be found // externally, in the dll function Max(i,j:integer): integer; stdcall; external 'delhpdll.dll'; // This procedure uses the "external" call to the DLL procedure TForm1.Button1Click(Sender: TObject); var i,j: integer; begin i := strtoint(Edit1.Text); j := strtoint(Edit2.Text); Label1.Caption := inttostr(Max(i,j)); // Easy, eh? end; // This calls the DLL directly through the Win API. // More code, more control. procedure TForm1.Button2Click(Sender: TObject); var i,j,k: integer; Handle: THandle; // mmax is a function variable; see type declaration // of TMaxFun above. mmax : TMaxFun; begin i := strtoint(Edit1.Text); j := strtoint(Edit2.Text); // Load the library Handle := LoadLibrary('DELHPDLL.DLL'); // If succesful ... if Handle <> 0 then begin // Assign function Max from the DLL to the // function variable mmax @mmax := GetProcAddress(Handle, 'Max'); // If successful if @mmax <> nil then begin k := mmax(i,j); Label1.Caption := inttostr(k); end; // Unload library FreeLibrary(Handle); end; end; end. Go, fly, run your program. Print Add Notes Bookmark this page
[ { "code": null, "e": 1784, "s": 1652, "text": "The following code creates a DLL containing two functions, Min and Max, with the objective of returning the larger of two integers." }, { "code": null, "e": 1851, "s": 1784, "text": "Start a new DLL project in Delphi (Click File −> New, select DLL)." }, { "code": null, "e": 1881, "s": 1851, "text": "Save the project as delhpdll." }, { "code": null, "e": 1929, "s": 1881, "text": "Fill in the code in the library as given below." }, { "code": null, "e": 3204, "s": 1929, "text": "// Uffe wrote: This is a toy dll to demonstrate the\n// use of dll's\n//\n// The libary export two functions Max and Min\n//\n// The dll matches the MainProject which is a Delphi\n// project which calls the DLL.\n\n//{ \n// DELPHI WROTE THIS:\n// Important note about DLL memory management: ShareMem\n// must be the first unit in your library's USES clause\n// AND your project's (select Project-View Source) USES\n// clause if your DLL exports any procedures or functions\n// that pass strings as parameters or function results. \n// This applies to all strings passed to and from your \n// DLL--even those that are nested in records and classes. \n// ShareMem is the interface unit to the BORLNDMM.DLL \n// shared memory manager, which must be deployed along\n// with your DLL. To avoid using BORLNDMM.DLL, pass \n// string information using PChar or ShortString \n// parameters. \n//}\n\nuses\n SysUtils,\n Classes;\n\n// Declare stdcall to make interface to other languages\n\nfunction Min(X, Y: Integer): Integer; stdcall;\nbegin\n if X < Y then Min := X else Min := Y;\nend;\n\nfunction Max(X, Y: Integer): Integer; stdcall;\nbegin\n if X > Y then Max := X else Max := Y;\nend;\n\nexports // Make available to calling applications\n Min index 1,\n Max index 2;\n\nbegin\nend." }, { "code": null, "e": 3236, "s": 3204, "text": "Build and Save the DLL project." }, { "code": null, "e": 3413, "s": 3236, "text": "(If you are a command line kind of guy, then you can just execute \"dcc32 delhpdll.dpr\" from the command line ... that will give you the same DLL but without the IDE stuff ...)." }, { "code": null, "e": 3460, "s": 3413, "text": "Then you need an application, to call the DLL:" }, { "code": null, "e": 3500, "s": 3460, "text": "Start a new \"main\" application project." }, { "code": null, "e": 3553, "s": 3500, "text": "Make whatever GUI controls you need to test the DLL." }, { "code": null, "e": 3617, "s": 3553, "text": "Fill in the source code for interfacing the DLL as given below." }, { "code": null, "e": 6343, "s": 3617, "text": "//Main Applet to demonstrate how to call a dll.\n//\n\n// SEARCH PATHS:\n// The code makes no special effort to search for the DLL.\n// Easiest if everything (including DLL) is in the same\n// directory.\n//\n\n//DLL CALLING:\n// This applet demonstrates both Win API calling and\n// external calling (see below)\n//\n//\n\n// NOTICE: I wasted a lot of time not declaring the\n// functions \"stdcall\" throughout. If you \n// declare it \"stdcall\" in the DLL and not\n// in the calling application, then you get hard-to-find\n// errors - \"external\" will crash on you, \n// the Win API does not type-check so the function\n// just gives \"weird\" results. (OK this is\n// obvious when you think about it .. problem is,\n// I didn't)\t\t\t\t\n\n// Jump to \"implementation\" section, \n// no DLL specs before.\ninterface\n\nuses\n Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;\n\ntype\n TForm1 = class(TForm)\n\t\n Edit1: TEdit;\n Edit2: TEdit;\n\t\n Button1: TButton;\n Label1: TLabel;\n Label2: TLabel;\n\t\n Button2: TButton;\n Label3: TLabel;\n Label4: TLabel;\n Label5: TLabel;\n\t\n procedure Button1Click(Sender: TObject);\n procedure Button2Click(Sender: TObject);\n\t\n private\n { Private declarations }\n\t\n public\n { Public declarations }\n end;\n\n // TMaxFun becomes a function variable (think of\n // a \"pointer to function\" without the pointer)\n\t\n TMaxFun = function(i,j: integer):integer; stdcall;\n\nvar\n Form1: TForm1;\n\nimplementation\n\n{$R *.DFM}\n\n// This declares Max as a function which should be found\n// externally, in the dll\nfunction Max(i,j:integer): integer; stdcall; external 'delhpdll.dll';\n\n// This procedure uses the \"external\" call to the DLL\n procedure TForm1.Button1Click(Sender: TObject);\nvar\n i,j: integer;\n\t\nbegin\n i := strtoint(Edit1.Text);\n j := strtoint(Edit2.Text);\n\n Label1.Caption := inttostr(Max(i,j));\n // Easy, eh?\nend;\n\n// This calls the DLL directly through the Win API.\n// More code, more control.\n\nprocedure TForm1.Button2Click(Sender: TObject);\nvar\n i,j,k: integer;\n Handle: THandle;\n\t\n // mmax is a function variable; see type declaration\n // of TMaxFun above.\n mmax : TMaxFun;\n\t\nbegin\n i := strtoint(Edit1.Text);\n j := strtoint(Edit2.Text);\n\n // Load the library\n Handle := LoadLibrary('DELHPDLL.DLL');\n\n // If succesful ...\n\t\n if Handle <> 0 then\n begin\n \n // Assign function Max from the DLL to the\n // function variable mmax\n\n @mmax := GetProcAddress(Handle, 'Max');\n \n // If successful\n\n if @mmax <> nil then\n begin\n k := mmax(i,j);\n Label1.Caption := inttostr(k);\n end;\n\n // Unload library\n FreeLibrary(Handle);\n end;\nend;\nend." }, { "code": null, "e": 6370, "s": 6343, "text": "Go, fly, run your program." }, { "code": null, "e": 6377, "s": 6370, "text": " Print" }, { "code": null, "e": 6388, "s": 6377, "text": " Add Notes" } ]
Font Awesome Icons
Font Awesome icons library provides 519 free scalable vector icons. This library is completely free for both personal and commercial use. Originally designed for Bootstrap, these icons can be customized easily. To load the Font Awesome library, copy and paste the following line in the <head> section of the webpage. <head> <link rel = "stylesheet" href = "http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"> </head> Font Awesome provides several icons. Choose one of them and add the name of the icon class to any HTML element within the <body> tag. In the following example, we have used the icon of the Indian currency. <html> <head> <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"> </head> <body> <i class = "fa fa-inr"></i> </body> </html> It will produce the following output − You can increase or decrease the size of an icon by defining its size using CSS and using it along with the class name, as shown below. In the given example, we have declared the size as 6 em. <html> <head> <link rel = "stylesheet" href = "http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"> <style> i.mysize {font-size: 10em;} </style> </head> <body> <i class = "fa fa-inr mysize"></i> </body> </html> It will produce the following output − Just like size, you can define the color of the icons using CSS. The following example shows how to change the color of the Indian currency icon. <html> <head> <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"> <style> i.custom {font-size: 6em; color: red;} </style> </head> <body> <i class = "fa fa-inr custom"></i> </body> </html> Font Awesome provides 519 icons in the following categories − Web Application Icons Hand Icons Transportation Icons Gender Icons File Type Icons Spinner Icons Form Control Icons Payment Icons Chart Icons Currency Icons Text editor Icons Directional Icons Video Player Icons Brand Icons To use any of these icons, you have to replace the class name in the programs given in this chapter with the class name of the desired icon. In the coming chapters of this Unit (Font Awesome), we have explained category-wise the usage and the respective outputs of various Font Awesome icons. 26 Lectures 2 hours Neha Gupta 20 Lectures 2 hours Asif Hussain 43 Lectures 5 hours Sharad Kumar 411 Lectures 38.5 hours In28Minutes Official 71 Lectures 10 hours Chaand Sheikh 207 Lectures 33 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2777, "s": 2566, "text": "Font Awesome icons library provides 519 free scalable vector icons. This library is completely free for both personal and commercial use. Originally designed for Bootstrap, these icons can be customized easily." }, { "code": null, "e": 2883, "s": 2777, "text": "To load the Font Awesome library, copy and paste the following line in the <head> section of the webpage." }, { "code": null, "e": 3018, "s": 2883, "text": "<head>\n <link rel = \"stylesheet\" href = \"http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css\">\n</head>" }, { "code": null, "e": 3224, "s": 3018, "text": "Font Awesome provides several icons. Choose one of them and add the name of the icon class to any HTML element within the <body> tag. In the following example, we have used the icon of the Indian currency." }, { "code": null, "e": 3443, "s": 3224, "text": "<html>\n <head>\n <link rel = \"stylesheet\" href = \"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css\">\n </head>\n\t\n <body>\n <i class = \"fa fa-inr\"></i>\n </body>\n\t\n</html>" }, { "code": null, "e": 3482, "s": 3443, "text": "It will produce the following output −" }, { "code": null, "e": 3675, "s": 3482, "text": "You can increase or decrease the size of an icon by defining its size using CSS and using it along with the class name, as shown below. In the given example, we have declared the size as 6 em." }, { "code": null, "e": 3972, "s": 3675, "text": "<html>\n <head>\n <link rel = \"stylesheet\" href = \"http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css\">\n\t\t\n <style>\n i.mysize {font-size: 10em;}\n </style>\n\t\t\n </head>\n\t\n <body>\n <i class = \"fa fa-inr mysize\"></i>\n </body>\n\t\n</html>" }, { "code": null, "e": 4011, "s": 3972, "text": "It will produce the following output −" }, { "code": null, "e": 4157, "s": 4011, "text": "Just like size, you can define the color of the icons using CSS. The following example shows how to change the color of the Indian currency icon." }, { "code": null, "e": 4466, "s": 4157, "text": "<html>\n <head>\n <link rel = \"stylesheet\" href = \"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css\">\n\t\t\n <style>\n i.custom {font-size: 6em; color: red;}\n </style>\n\t\t\n </head>\n\t\n <body>\n <i class = \"fa fa-inr custom\"></i>\n </body>\n\t\n</html>" }, { "code": null, "e": 4528, "s": 4466, "text": "Font Awesome provides 519 icons in the following categories −" }, { "code": null, "e": 4550, "s": 4528, "text": "Web Application Icons" }, { "code": null, "e": 4561, "s": 4550, "text": "Hand Icons" }, { "code": null, "e": 4582, "s": 4561, "text": "Transportation Icons" }, { "code": null, "e": 4595, "s": 4582, "text": "Gender Icons" }, { "code": null, "e": 4611, "s": 4595, "text": "File Type Icons" }, { "code": null, "e": 4625, "s": 4611, "text": "Spinner Icons" }, { "code": null, "e": 4644, "s": 4625, "text": "Form Control Icons" }, { "code": null, "e": 4658, "s": 4644, "text": "Payment Icons" }, { "code": null, "e": 4670, "s": 4658, "text": "Chart Icons" }, { "code": null, "e": 4685, "s": 4670, "text": "Currency Icons" }, { "code": null, "e": 4703, "s": 4685, "text": "Text editor Icons" }, { "code": null, "e": 4721, "s": 4703, "text": "Directional Icons" }, { "code": null, "e": 4740, "s": 4721, "text": "Video Player Icons" }, { "code": null, "e": 4752, "s": 4740, "text": "Brand Icons" }, { "code": null, "e": 5045, "s": 4752, "text": "To use any of these icons, you have to replace the class name in the programs given in this chapter with the class name of the desired icon. In the coming chapters of this Unit (Font Awesome), we have explained category-wise the usage and the respective outputs of various Font Awesome icons." }, { "code": null, "e": 5078, "s": 5045, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 5090, "s": 5078, "text": " Neha Gupta" }, { "code": null, "e": 5123, "s": 5090, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 5137, "s": 5123, "text": " Asif Hussain" }, { "code": null, "e": 5170, "s": 5137, "text": "\n 43 Lectures \n 5 hours \n" }, { "code": null, "e": 5184, "s": 5170, "text": " Sharad Kumar" }, { "code": null, "e": 5221, "s": 5184, "text": "\n 411 Lectures \n 38.5 hours \n" }, { "code": null, "e": 5243, "s": 5221, "text": " In28Minutes Official" }, { "code": null, "e": 5277, "s": 5243, "text": "\n 71 Lectures \n 10 hours \n" }, { "code": null, "e": 5292, "s": 5277, "text": " Chaand Sheikh" }, { "code": null, "e": 5327, "s": 5292, "text": "\n 207 Lectures \n 33 hours \n" }, { "code": null, "e": 5355, "s": 5327, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5362, "s": 5355, "text": " Print" }, { "code": null, "e": 5373, "s": 5362, "text": " Add Notes" } ]
JavaScript ReferenceError - Can't access lexical declaration`variable' before initialization - GeeksforGeeks
29 Jul, 2021 This JavaScript exception can’t access the lexical declaration `variable’ before initialization occurs if a lexical variable has been accessed before initialization. This could happen inside any block statement when let or const declarations are accessed when they are undefined. Message: ReferenceError: Use before declaration (Edge) ReferenceError: can't access lexical declaration `variable' before initialization (Firefox) ReferenceError: 'variable' is not defined (Chrome) Error Type: ReferenceError Cause of the error: Somewhere in the code, there is a lexical variable that was accessed before initialization. Example 1: In this example, the const keyword is used with the variable inside the if statement, So the error has occurred. HTML <!DOCTYPE html><html> <head> </head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <p> JavaScript ReferenceError - Can't access lexical declaration`variable' before initialization </p> <button onclick="Geeks();"> click here </button> <p id="GFG_DOWN"></p> <script> var el_down = document.getElementById("GFG_DOWN"); function GFG() { const var_1 = "This is"; if (true) { const var_1 = var_1 + "GeeksforGeeks"; } } function Geeks() { try { GFG(); el_down.innerHTML = "'Can't access lexical declaration"+ "`variable'before initialization' "+ "error has not occurred"; } catch (e) { el_down.innerHTML = "'Can't access lexical declaration"+ "`variable' before initialization'"+ " error has occurred"; } } </script> </body></html> Output: Example 2: In this example, the keyword is used with the variable, So the error has occurred. HTML <!DOCTYPE html><html> <head> </head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <p> JavaScript ReferenceError - Can't access lexical declaration`variable' before initialization </p> <button onclick="Geeks();"> click here </button> <p id="GFG_DOWN"></p> <script> var el_down = document.getElementById("GFG_DOWN"); function GFG() { let var_1 = 3; if (true) { var_1 = var_1 + 5; } } function Geeks() { try { GFG(); el_down.innerHTML = "'Can't access lexical declaration"+ "`variable' before initialization'"+ " error has not occurred"; } catch (e) { el_down.innerHTML = "'Can't access lexical declaration"+ "`variable'before initialization'"+ " error has occurred"; } } </script> </body></html> Output: surindertarika1234 JavaScript-Errors JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? Remove elements from a JavaScript Array How to filter object array based on attributes? 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": 25300, "s": 25272, "text": "\n29 Jul, 2021" }, { "code": null, "e": 25580, "s": 25300, "text": "This JavaScript exception can’t access the lexical declaration `variable’ before initialization occurs if a lexical variable has been accessed before initialization. This could happen inside any block statement when let or const declarations are accessed when they are undefined." }, { "code": null, "e": 25590, "s": 25580, "text": "Message: " }, { "code": null, "e": 25796, "s": 25590, "text": "ReferenceError: Use before declaration (Edge)\nReferenceError: can't access lexical declaration `variable' before \n initialization (Firefox)\nReferenceError: 'variable' is not defined (Chrome)" }, { "code": null, "e": 25809, "s": 25796, "text": "Error Type: " }, { "code": null, "e": 25824, "s": 25809, "text": "ReferenceError" }, { "code": null, "e": 25936, "s": 25824, "text": "Cause of the error: Somewhere in the code, there is a lexical variable that was accessed before initialization." }, { "code": null, "e": 26060, "s": 25936, "text": "Example 1: In this example, the const keyword is used with the variable inside the if statement, So the error has occurred." }, { "code": null, "e": 26065, "s": 26060, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> </head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <p> JavaScript ReferenceError - Can't access lexical declaration`variable' before initialization </p> <button onclick=\"Geeks();\"> click here </button> <p id=\"GFG_DOWN\"></p> <script> var el_down = document.getElementById(\"GFG_DOWN\"); function GFG() { const var_1 = \"This is\"; if (true) { const var_1 = var_1 + \"GeeksforGeeks\"; } } function Geeks() { try { GFG(); el_down.innerHTML = \"'Can't access lexical declaration\"+ \"`variable'before initialization' \"+ \"error has not occurred\"; } catch (e) { el_down.innerHTML = \"'Can't access lexical declaration\"+ \"`variable' before initialization'\"+ \" error has occurred\"; } } </script> </body></html>", "e": 27311, "s": 26065, "text": null }, { "code": null, "e": 27320, "s": 27311, "text": "Output: " }, { "code": null, "e": 27414, "s": 27320, "text": "Example 2: In this example, the keyword is used with the variable, So the error has occurred." }, { "code": null, "e": 27419, "s": 27414, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> </head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <p> JavaScript ReferenceError - Can't access lexical declaration`variable' before initialization </p> <button onclick=\"Geeks();\"> click here </button> <p id=\"GFG_DOWN\"></p> <script> var el_down = document.getElementById(\"GFG_DOWN\"); function GFG() { let var_1 = 3; if (true) { var_1 = var_1 + 5; } } function Geeks() { try { GFG(); el_down.innerHTML = \"'Can't access lexical declaration\"+ \"`variable' before initialization'\"+ \" error has not occurred\"; } catch (e) { el_down.innerHTML = \"'Can't access lexical declaration\"+ \"`variable'before initialization'\"+ \" error has occurred\"; } } </script> </body></html>", "e": 28636, "s": 27419, "text": null }, { "code": null, "e": 28645, "s": 28636, "text": "Output: " }, { "code": null, "e": 28664, "s": 28645, "text": "surindertarika1234" }, { "code": null, "e": 28682, "s": 28664, "text": "JavaScript-Errors" }, { "code": null, "e": 28693, "s": 28682, "text": "JavaScript" }, { "code": null, "e": 28710, "s": 28693, "text": "Web Technologies" }, { "code": null, "e": 28808, "s": 28710, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28869, "s": 28808, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28910, "s": 28869, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28964, "s": 28910, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29004, "s": 28964, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29052, "s": 29004, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 29094, "s": 29052, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29127, "s": 29094, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29170, "s": 29127, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29232, "s": 29170, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Encapsulation in C++
Encapsulation brings together the data and the methods that manipulate the data into a single component and protects them from outside interference. In essence, encapsulation involves bundling the data as well as the functions that use the data. Data encapsulation in lead to the very important concept of data hiding. Encapsulation in C++ is implemented using classes that are user defined data types. These classes contain data types as well as methods that are bound together. A program that represents encapsulation in C++ using classes is given as follows. Live Demo #include <iostream> using namespace std; class EncapsulationDemo { private: int length, breath, height; public: void setValues(int l, int b,int h) { length = l; breath = b; height = h; } void calcVolume() { cout<<"Length = " << length << endl; cout<<"Breath = " << breath << endl; cout<<"Height = " << height << endl; cout<<"Volume = " << length*breath*height << endl; } }; int main() { EncapsulationDemo obj; obj.setValues(5, 3, 2); obj.calcVolume(); return 0; } Length = 5 Breath = 3 Height = 2 Volume = 30 In the above program, the variables and methods are wrapped in a single unit i.e the class Encapsulation. So, this program demonstrates the concept of encapsulation. The length, breadth and height in class Encapsulation are private variables. There are public functions that initialize these variables and also calculate the volume by multiplying length, breadth and height. The code snippet for this is as follows. class Encapsulation { private: int length, breadth, height; public: void setValues(int l, int b,int h) { length = l; breadth = b; height = h; } void calcVolume() { cout<<"Length = " << length << endl; cout<<"Breadth = " << breadth << endl; cout<<"Height = " << height << endl; cout<<"Volume = " << length*breadth*height << endl; } }; In the function main(), first an object of type Encapsulation is defined. Then the function setValues() is called with the values 5, 3 and 2. Finally, these values and the volume are displayed using the function calcVolume(). The code snippet for this is as follows. Encapsulation obj; obj.setValues(5, 3, 2); obj.calcVolume();
[ { "code": null, "e": 1381, "s": 1062, "text": "Encapsulation brings together the data and the methods that manipulate the data into a single component and protects them from outside interference. In essence, encapsulation involves bundling the data as well as the functions that use the data. Data encapsulation in lead to the very important concept of data hiding." }, { "code": null, "e": 1542, "s": 1381, "text": "Encapsulation in C++ is implemented using classes that are user defined data types. These classes contain data types as well as methods that are bound together." }, { "code": null, "e": 1624, "s": 1542, "text": "A program that represents encapsulation in C++ using classes is given as follows." }, { "code": null, "e": 1635, "s": 1624, "text": " Live Demo" }, { "code": null, "e": 2174, "s": 1635, "text": "#include <iostream>\nusing namespace std;\nclass EncapsulationDemo {\n private:\n int length, breath, height;\n public:\n void setValues(int l, int b,int h) {\n length = l;\n breath = b;\n height = h;\n }\n void calcVolume() {\n cout<<\"Length = \" << length << endl;\n cout<<\"Breath = \" << breath << endl;\n cout<<\"Height = \" << height << endl;\n cout<<\"Volume = \" << length*breath*height << endl;\n }\n};\nint main() {\n EncapsulationDemo obj;\n obj.setValues(5, 3, 2);\n obj.calcVolume();\n return 0;\n}" }, { "code": null, "e": 2219, "s": 2174, "text": "Length = 5\nBreath = 3\nHeight = 2\nVolume = 30" }, { "code": null, "e": 2385, "s": 2219, "text": "In the above program, the variables and methods are wrapped in a single unit i.e the class Encapsulation. So, this program demonstrates the concept of encapsulation." }, { "code": null, "e": 2635, "s": 2385, "text": "The length, breadth and height in class Encapsulation are private variables. There are public functions that initialize these variables and also calculate the volume by multiplying length, breadth and height. The code snippet for this is as follows." }, { "code": null, "e": 3032, "s": 2635, "text": "class Encapsulation {\n private:\n int length, breadth, height;\n public:\n void setValues(int l, int b,int h) {\n length = l;\n breadth = b;\n height = h;\n }\n void calcVolume() {\n cout<<\"Length = \" << length << endl;\n cout<<\"Breadth = \" << breadth << endl;\n cout<<\"Height = \" << height << endl;\n cout<<\"Volume = \" << length*breadth*height << endl;\n }\n};" }, { "code": null, "e": 3299, "s": 3032, "text": "In the function main(), first an object of type Encapsulation is defined. Then the function setValues() is called with the values 5, 3 and 2. Finally, these values and the volume are displayed using the function calcVolume(). The code snippet for this is as follows." }, { "code": null, "e": 3360, "s": 3299, "text": "Encapsulation obj;\nobj.setValues(5, 3, 2);\nobj.calcVolume();" } ]
iText - Drawing a Circle
In this chapter, we will see how to draw a circle on a PDF document using iText library. You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter to its constructor. To draw a circle on a PdfDocument, instantiate the PdfCanvas class of the package com.itextpdf.kernel.pdf.canvas and invoke the circle() method of this class. Following are the steps to draw a circle on a PDF document. The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created. Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below. // Creating a PdfWriter String dest = "C:/itextExamples/drawingCircle.pdf"; PdfWriter writer = new PdfWriter(dest); When an object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified. The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor. Instantiate the PdfDocument class by passing PdfWriter object to its constructor, as shown below. // Creating a PdfDocument PdfDocument pdfDoc = new PdfDocument(writer); Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class. The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument. Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps, as shown below. // Creating a Document Document document = new Document(pdfDoc); Create a new PdfPage class using the addNewPage() method of the PdfDocument class. Instantiate the PdfCanvas object of the package com.itextpdf.kernel.pdf.canvas by passing the PdfPage object to the constructor of this class, as shown below. // Creating a new page PdfPage pdfPage = pdfDoc.addNewPage(); // Creating a PdfCanvas object PdfCanvas canvas = new PdfCanvas(pdfPage); Set the color of the circle using the setColor() method of the Canvas class, as shown below. // Setting color to the circle Color color = Color.GREEN; canvas.setColor(color, true); Draw a circle by invoking the circle() method of the Canvas, as shown below. // creating a circle canvas.circle(300, 400, 200); Close the document using the close() method of the Document class, as shown below. // Closing the document document.close(); The following Java program demonstrates how to draw a circle on a pdf document using the iText library. It creates a PDF document with the name drawingCircle.pdf, draws a circle in it, and saves it in the path C:/itextExamples/ Save this code in a file with the name DrawingCircle.java. import com.itextpdf.kernel.color.Color; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfPage; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.kernel.pdf.canvas.PdfCanvas; import com.itextpdf.layout.Document; public class DrawingCircle { public static void main(String args[]) throws Exception { // Creating a PdfWriter String dest = "C:/itextExamples/drawingCircle.pdf"; PdfWriter writer = new PdfWriter(dest); // Creating a PdfDocument object PdfDocument pdfDoc = new PdfDocument(writer); // Creating a Document object Document doc = new Document(pdfDoc); // Creating a new page PdfPage pdfPage = pdfDoc.addNewPage(); // Creating a PdfCanvas object PdfCanvas canvas = new PdfCanvas(pdfPage); // Setting color to the circle Color color = Color.GREEN; canvas.setColor(color, true); // creating a circle canvas.circle(300, 400, 200); // Filling the circle canvas.fill(); // Closing the document doc.close(); System.out.println("Object drawn on pdf successfully"); } } Compile and execute the saved Java file from the Command prompt using the following commands. javac DrawingCircle.java java DrawingCircle Upon execution, the above program creates a PDF document displaying the following message. Object drawn on pdf successfully If you verify the specified path, you can find the created PDF document, as shown below. Print Add Notes Bookmark this page
[ { "code": null, "e": 2457, "s": 2368, "text": "In this chapter, we will see how to draw a circle on a PDF document using iText library." }, { "code": null, "e": 2636, "s": 2457, "text": "You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter to its constructor." }, { "code": null, "e": 2795, "s": 2636, "text": "To draw a circle on a PdfDocument, instantiate the PdfCanvas class of the package com.itextpdf.kernel.pdf.canvas and invoke the circle() method of this class." }, { "code": null, "e": 2855, "s": 2795, "text": "Following are the steps to draw a circle on a PDF document." }, { "code": null, "e": 3084, "s": 2855, "text": "The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created." }, { "code": null, "e": 3233, "s": 3084, "text": "Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below." }, { "code": null, "e": 3353, "s": 3233, "text": "// Creating a PdfWriter \nString dest = \"C:/itextExamples/drawingCircle.pdf\"; \nPdfWriter writer = new PdfWriter(dest); \n" }, { "code": null, "e": 3493, "s": 3353, "text": "When an object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified." }, { "code": null, "e": 3745, "s": 3493, "text": "The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor." }, { "code": null, "e": 3843, "s": 3745, "text": "Instantiate the PdfDocument class by passing PdfWriter object to its constructor, as shown below." }, { "code": null, "e": 3919, "s": 3843, "text": "// Creating a PdfDocument \nPdfDocument pdfDoc = new PdfDocument(writer); \n" }, { "code": null, "e": 4090, "s": 3919, "text": "Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class." }, { "code": null, "e": 4284, "s": 4090, "text": "The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument." }, { "code": null, "e": 4409, "s": 4284, "text": "Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps, as shown below." }, { "code": null, "e": 4478, "s": 4409, "text": "// Creating a Document \nDocument document = new Document(pdfDoc); \n" }, { "code": null, "e": 4720, "s": 4478, "text": "Create a new PdfPage class using the addNewPage() method of the PdfDocument class. Instantiate the PdfCanvas object of the package com.itextpdf.kernel.pdf.canvas by passing the PdfPage object to the constructor of this class, as shown below." }, { "code": null, "e": 4872, "s": 4720, "text": "// Creating a new page \nPdfPage pdfPage = pdfDoc.addNewPage(); \n\n// Creating a PdfCanvas object \nPdfCanvas canvas = new PdfCanvas(pdfPage); \n" }, { "code": null, "e": 4965, "s": 4872, "text": "Set the color of the circle using the setColor() method of the Canvas class, as shown below." }, { "code": null, "e": 5057, "s": 4965, "text": "// Setting color to the circle \nColor color = Color.GREEN; \ncanvas.setColor(color, true); \n" }, { "code": null, "e": 5134, "s": 5057, "text": "Draw a circle by invoking the circle() method of the Canvas, as shown below." }, { "code": null, "e": 5188, "s": 5134, "text": "// creating a circle \ncanvas.circle(300, 400, 200); \n" }, { "code": null, "e": 5271, "s": 5188, "text": "Close the document using the close() method of the Document class, as shown below." }, { "code": null, "e": 5316, "s": 5271, "text": "// Closing the document \ndocument.close(); \n" }, { "code": null, "e": 5544, "s": 5316, "text": "The following Java program demonstrates how to draw a circle on a pdf document using the iText library. It creates a PDF document with the name drawingCircle.pdf, draws a circle in it, and saves it in the path C:/itextExamples/" }, { "code": null, "e": 5603, "s": 5544, "text": "Save this code in a file with the name DrawingCircle.java." }, { "code": null, "e": 6916, "s": 5603, "text": "import com.itextpdf.kernel.color.Color; \nimport com.itextpdf.kernel.pdf.PdfDocument; \nimport com.itextpdf.kernel.pdf.PdfPage; \nimport com.itextpdf.kernel.pdf.PdfWriter; \nimport com.itextpdf.kernel.pdf.canvas.PdfCanvas; \nimport com.itextpdf.layout.Document; \n\npublic class DrawingCircle { \n public static void main(String args[]) throws Exception { \n // Creating a PdfWriter \n String dest = \"C:/itextExamples/drawingCircle.pdf\"; \n PdfWriter writer = new PdfWriter(dest); \n \n // Creating a PdfDocument object \n PdfDocument pdfDoc = new PdfDocument(writer);\n\n // Creating a Document object\n Document doc = new Document(pdfDoc);\n \n // Creating a new page\n PdfPage pdfPage = pdfDoc.addNewPage();\n \n // Creating a PdfCanvas object\n PdfCanvas canvas = new PdfCanvas(pdfPage); \n \n // Setting color to the circle\n Color color = Color.GREEN; \n canvas.setColor(color, true); \n \n // creating a circle\n canvas.circle(300, 400, 200);\n \n // Filling the circle \n canvas.fill(); \n \n // Closing the document \n doc.close(); \n \n System.out.println(\"Object drawn on pdf successfully\");\n } \n} " }, { "code": null, "e": 7010, "s": 6916, "text": "Compile and execute the saved Java file from the Command prompt using the following commands." }, { "code": null, "e": 7056, "s": 7010, "text": "javac DrawingCircle.java \njava DrawingCircle\n" }, { "code": null, "e": 7147, "s": 7056, "text": "Upon execution, the above program creates a PDF document displaying the following message." }, { "code": null, "e": 7182, "s": 7147, "text": "Object drawn on pdf successfully \n" }, { "code": null, "e": 7271, "s": 7182, "text": "If you verify the specified path, you can find the created PDF document, as shown below." }, { "code": null, "e": 7278, "s": 7271, "text": " Print" }, { "code": null, "e": 7289, "s": 7278, "text": " Add Notes" } ]
BigDecimal subtract() Method in Java with Examples - GeeksforGeeks
27 May, 2019 The java.math.BigDecimal.subtract(BigDecimal val) is used to calculate the Arithmetic difference of two BigDecimals. This method is used to find the arithmetic difference of large numbers without compromising with the precision of the result. This method performs an operation upon the current BigDecimal by which this method is called and BigDecimal passed as the parameter. There are two overloads of subtract method available in java which are listed below: subtract(BigDecimal val) subtract(BigDecimal val, MathContext mc) Syntax: public BigDecimal subtract(BigDecimal val) Parameters: This method accepts a parameter val which is the value to be subtracted from this BigDecimal. Return value: This method returns a BigDecimal which holds difference (this – val), and whose scale is max(this.scale(), val.scale()). Below programs is used to illustrate the subtract() method of BigDecimal. // Java program to demonstrate// subtract() method of BigDecimal import java.math.BigDecimal; public class GFG { public static void main(String[] args) { // BigDecimal object to store result BigDecimal diff; // For user input // Use Scanner or BufferedReader // Two objects of String created // Holds the values to calculate the difference String input1 = "545456468445645468464645"; String input2 = "425645648446468486486452"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); BigDecimal b = new BigDecimal(input2); // Using subtract() method diff = a.subtract(b); // Display the result in BigDecimal System.out.println("The difference of\n" + a + " \nand\n" + b + " " + "\nis\n" + diff + "\n"); }} Output: The difference of545456468445645468464645and425645648446468486486452is119810819999176981978193 Syntax: public BigDecimal subtract(BigDecimal val, MathContext mc) Parameters: This method accepts two parameter, one is val which is the value to be subtracted from this BigDecimal and a mc of type MathContext. Return value: This method returns a BigDecimal which holds difference (this – val), with rounding according to the context settings. Below programs is used to illustrate the subtract() method of BigDecimal. // Java program to demonstrate// subtract() method of BigDecimal import java.math.*; public class GFG { public static void main(String[] args) { // BigDecimal object to store result BigDecimal diff; // For user input // Use Scanner or BufferedReader // Two objects of String created // Holds the values to calculate the difference String input1 = "468445645468464645"; String input2 = "4256456484464684864864"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); BigDecimal b = new BigDecimal(input2); // Set precision to 10 MathContext mc = new MathContext(10); // Using subtract() method diff = a.subtract(b, mc); // Display the result in BigDecimal System.out.println("The difference of\n" + a + " \nand\n" + b + " " + "\nis\n" + diff + "\n"); }} Output: The difference of468445645468464645and4256456484464684864864is-4.255988039E+21 References: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#subtract(java.math.BigDecimal) Java-BigDecimal Java-Functions Java-math-package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Stream In Java Singleton Class in Java Set in Java Multithreading in Java Collections in Java Queue Interface In Java LinkedList in Java Overriding in Java Constructors in Java
[ { "code": null, "e": 25689, "s": 25661, "text": "\n27 May, 2019" }, { "code": null, "e": 26065, "s": 25689, "text": "The java.math.BigDecimal.subtract(BigDecimal val) is used to calculate the Arithmetic difference of two BigDecimals. This method is used to find the arithmetic difference of large numbers without compromising with the precision of the result. This method performs an operation upon the current BigDecimal by which this method is called and BigDecimal passed as the parameter." }, { "code": null, "e": 26150, "s": 26065, "text": "There are two overloads of subtract method available in java which are listed below:" }, { "code": null, "e": 26175, "s": 26150, "text": "subtract(BigDecimal val)" }, { "code": null, "e": 26216, "s": 26175, "text": "subtract(BigDecimal val, MathContext mc)" }, { "code": null, "e": 26224, "s": 26216, "text": "Syntax:" }, { "code": null, "e": 26268, "s": 26224, "text": "public BigDecimal subtract(BigDecimal val)\n" }, { "code": null, "e": 26374, "s": 26268, "text": "Parameters: This method accepts a parameter val which is the value to be subtracted from this BigDecimal." }, { "code": null, "e": 26509, "s": 26374, "text": "Return value: This method returns a BigDecimal which holds difference (this – val), and whose scale is max(this.scale(), val.scale())." }, { "code": null, "e": 26583, "s": 26509, "text": "Below programs is used to illustrate the subtract() method of BigDecimal." }, { "code": "// Java program to demonstrate// subtract() method of BigDecimal import java.math.BigDecimal; public class GFG { public static void main(String[] args) { // BigDecimal object to store result BigDecimal diff; // For user input // Use Scanner or BufferedReader // Two objects of String created // Holds the values to calculate the difference String input1 = \"545456468445645468464645\"; String input2 = \"425645648446468486486452\"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); BigDecimal b = new BigDecimal(input2); // Using subtract() method diff = a.subtract(b); // Display the result in BigDecimal System.out.println(\"The difference of\\n\" + a + \" \\nand\\n\" + b + \" \" + \"\\nis\\n\" + diff + \"\\n\"); }}", "e": 27536, "s": 26583, "text": null }, { "code": null, "e": 27544, "s": 27536, "text": "Output:" }, { "code": null, "e": 27639, "s": 27544, "text": "The difference of545456468445645468464645and425645648446468486486452is119810819999176981978193" }, { "code": null, "e": 27647, "s": 27639, "text": "Syntax:" }, { "code": null, "e": 27707, "s": 27647, "text": "public BigDecimal subtract(BigDecimal val, MathContext mc)\n" }, { "code": null, "e": 27852, "s": 27707, "text": "Parameters: This method accepts two parameter, one is val which is the value to be subtracted from this BigDecimal and a mc of type MathContext." }, { "code": null, "e": 27985, "s": 27852, "text": "Return value: This method returns a BigDecimal which holds difference (this – val), with rounding according to the context settings." }, { "code": null, "e": 28059, "s": 27985, "text": "Below programs is used to illustrate the subtract() method of BigDecimal." }, { "code": "// Java program to demonstrate// subtract() method of BigDecimal import java.math.*; public class GFG { public static void main(String[] args) { // BigDecimal object to store result BigDecimal diff; // For user input // Use Scanner or BufferedReader // Two objects of String created // Holds the values to calculate the difference String input1 = \"468445645468464645\"; String input2 = \"4256456484464684864864\"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); BigDecimal b = new BigDecimal(input2); // Set precision to 10 MathContext mc = new MathContext(10); // Using subtract() method diff = a.subtract(b, mc); // Display the result in BigDecimal System.out.println(\"The difference of\\n\" + a + \" \\nand\\n\" + b + \" \" + \"\\nis\\n\" + diff + \"\\n\"); }}", "e": 29085, "s": 28059, "text": null }, { "code": null, "e": 29093, "s": 29085, "text": "Output:" }, { "code": null, "e": 29172, "s": 29093, "text": "The difference of468445645468464645and4256456484464684864864is-4.255988039E+21" }, { "code": null, "e": 29283, "s": 29172, "text": "References: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#subtract(java.math.BigDecimal)" }, { "code": null, "e": 29299, "s": 29283, "text": "Java-BigDecimal" }, { "code": null, "e": 29314, "s": 29299, "text": "Java-Functions" }, { "code": null, "e": 29332, "s": 29314, "text": "Java-math-package" }, { "code": null, "e": 29337, "s": 29332, "text": "Java" }, { "code": null, "e": 29342, "s": 29337, "text": "Java" }, { "code": null, "e": 29440, "s": 29342, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29459, "s": 29440, "text": "Interfaces in Java" }, { "code": null, "e": 29474, "s": 29459, "text": "Stream In Java" }, { "code": null, "e": 29498, "s": 29474, "text": "Singleton Class in Java" }, { "code": null, "e": 29510, "s": 29498, "text": "Set in Java" }, { "code": null, "e": 29533, "s": 29510, "text": "Multithreading in Java" }, { "code": null, "e": 29553, "s": 29533, "text": "Collections in Java" }, { "code": null, "e": 29577, "s": 29553, "text": "Queue Interface In Java" }, { "code": null, "e": 29596, "s": 29577, "text": "LinkedList in Java" }, { "code": null, "e": 29615, "s": 29596, "text": "Overriding in Java" } ]
Find, Set, Clear, Toggle and Modify bits in C - GeeksforGeeks
11 Dec, 2020 Given a positive integer N, the task is to perform the following sequence of operations on the binary representation of N in C. Finding a bit: Find the Kth bit in binary representation of N. Setting a bit: If Kth bit is 0, then set it to 1. Otherwise, leave it unchanged. Clearing a bit: If Kth bit is 1, then clear it to 0. Otherwise, leave it unchanged. Toggling a bit: If Kth bit is 1, then change it to 0 and vice-versa. Modifying a bit: Replace the Kth bit with a given bit. Examples: Input:N = 5, K = 1, P = 0Output:K(= 1)th bit of 5 is 1.Setting the K(= 1)th bit modifies N to 5Clearing the K(= 1)th bit modifies N to 4.Toggling the K(= 1)th bit modifies N to 4.Replacing the K(= 1)th bit with P(= 0) modifies N to 4 Input: N = 10, K = 2, P = 1Output:Kth(= 2) bit of 5 is 1.Setting the K(= 2)th bit modifies N to 10.Clearing the K(= 2)th bit modifies N to 8.Toggling the K(= 2)th bit modifies N to 8.Replacing the K(= 2)th bit with P(= 1) modifies N to 10. Approach: Follow the steps below to find, set, clear, toggle and modify the Kth bit in the binary representation of N. Finding a bit: (N >> K) & 1 Setting a bit: N = N | (1 << K) Clearing a bit: N = N & ~(1 << K) Toggle a bit: N = N ^ (1 << K) Modify a bit: N = N | (P << K) Below is the implementation of the above approach: C // C program to implement// the above approach #include <stdio.h> // Function to set the kth bit of nint setBit(int n, int k){ return (n | (1 << (k - 1)));} // Function to clear the kth bit of nint clearBit(int n, int k){ return (n & (~(1 << (k - 1))));} // Function to toggle the kth bit of nint toggleBit(int n, int k){ return (n ^ (1 << (k - 1)));} // Function to modify k-th bit with pint modifyBit(int n, int k, int p){ return (n | (p << k));} // Function to find the kth bit of nint findBit(int n, int k){ return ((n >> k) & 1);} // Utility function to perform// the specified Bit Operationsvoid bitOperations(int n, int k, int p){ printf("K(= %d)-th bit of %d is %d\n", k, n, findBit(n, k)); printf("Setting K(= %d)th bit modifies N to %d\n", k, setBit(n, k)); printf("Clearing K(= %d)th bit modifies N to %d\n", k, clearBit(n, k)); printf("Toggling K(= %d)th bit modifies N to %d\n", k, toggleBit(n, k)); printf("Replacing the K(= %d)<sup>th</sup> bit", k); printf(" with P(= %d) modifies N to 10\n", modifyBit(n, k, p));} // Driver Codeint main(){ int n = 5, k = 1, p = 1; bitOperations(n, k, p); return 0;} K(= 1)-th bit of 5 is 0 Setting K(= 1)th bit modifies N to 5 Clearing K(= 1)th bit modifies N to 4 Toggling K(= 1)th bit modifies N to 4 Replacing the K(= 1)th bit with P(= 7) modifies N to 10 Time Complexity: O(log(N))Auxiliary Space: O(1) Bit Algorithms Bitwise-AND Bitwise-OR Bitwise-XOR Technical Scripter 2020 Bit Magic Mathematical Technical Scripter Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set, Clear and Toggle a given bit of a number in C Write an Efficient Method to Check if a Number is Multiple of 3 Swap two nibbles in a byte Highest power of 2 less than or equal to given number Swap bits in a given number Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26279, "s": 26251, "text": "\n11 Dec, 2020" }, { "code": null, "e": 26407, "s": 26279, "text": "Given a positive integer N, the task is to perform the following sequence of operations on the binary representation of N in C." }, { "code": null, "e": 26470, "s": 26407, "text": "Finding a bit: Find the Kth bit in binary representation of N." }, { "code": null, "e": 26551, "s": 26470, "text": "Setting a bit: If Kth bit is 0, then set it to 1. Otherwise, leave it unchanged." }, { "code": null, "e": 26635, "s": 26551, "text": "Clearing a bit: If Kth bit is 1, then clear it to 0. Otherwise, leave it unchanged." }, { "code": null, "e": 26704, "s": 26635, "text": "Toggling a bit: If Kth bit is 1, then change it to 0 and vice-versa." }, { "code": null, "e": 26759, "s": 26704, "text": "Modifying a bit: Replace the Kth bit with a given bit." }, { "code": null, "e": 26769, "s": 26759, "text": "Examples:" }, { "code": null, "e": 27003, "s": 26769, "text": "Input:N = 5, K = 1, P = 0Output:K(= 1)th bit of 5 is 1.Setting the K(= 1)th bit modifies N to 5Clearing the K(= 1)th bit modifies N to 4.Toggling the K(= 1)th bit modifies N to 4.Replacing the K(= 1)th bit with P(= 0) modifies N to 4" }, { "code": null, "e": 27243, "s": 27003, "text": "Input: N = 10, K = 2, P = 1Output:Kth(= 2) bit of 5 is 1.Setting the K(= 2)th bit modifies N to 10.Clearing the K(= 2)th bit modifies N to 8.Toggling the K(= 2)th bit modifies N to 8.Replacing the K(= 2)th bit with P(= 1) modifies N to 10." }, { "code": null, "e": 27362, "s": 27243, "text": "Approach: Follow the steps below to find, set, clear, toggle and modify the Kth bit in the binary representation of N." }, { "code": null, "e": 27377, "s": 27362, "text": "Finding a bit:" }, { "code": null, "e": 27391, "s": 27377, "text": " (N >> K) & 1" }, { "code": null, "e": 27406, "s": 27391, "text": "Setting a bit:" }, { "code": null, "e": 27424, "s": 27406, "text": " N = N | (1 << K)" }, { "code": null, "e": 27440, "s": 27424, "text": "Clearing a bit:" }, { "code": null, "e": 27459, "s": 27440, "text": " N = N & ~(1 << K)" }, { "code": null, "e": 27473, "s": 27459, "text": "Toggle a bit:" }, { "code": null, "e": 27491, "s": 27473, "text": " N = N ^ (1 << K)" }, { "code": null, "e": 27505, "s": 27491, "text": "Modify a bit:" }, { "code": null, "e": 27523, "s": 27505, "text": " N = N | (P << K)" }, { "code": null, "e": 27574, "s": 27523, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27576, "s": 27574, "text": "C" }, { "code": "// C program to implement// the above approach #include <stdio.h> // Function to set the kth bit of nint setBit(int n, int k){ return (n | (1 << (k - 1)));} // Function to clear the kth bit of nint clearBit(int n, int k){ return (n & (~(1 << (k - 1))));} // Function to toggle the kth bit of nint toggleBit(int n, int k){ return (n ^ (1 << (k - 1)));} // Function to modify k-th bit with pint modifyBit(int n, int k, int p){ return (n | (p << k));} // Function to find the kth bit of nint findBit(int n, int k){ return ((n >> k) & 1);} // Utility function to perform// the specified Bit Operationsvoid bitOperations(int n, int k, int p){ printf(\"K(= %d)-th bit of %d is %d\\n\", k, n, findBit(n, k)); printf(\"Setting K(= %d)th bit modifies N to %d\\n\", k, setBit(n, k)); printf(\"Clearing K(= %d)th bit modifies N to %d\\n\", k, clearBit(n, k)); printf(\"Toggling K(= %d)th bit modifies N to %d\\n\", k, toggleBit(n, k)); printf(\"Replacing the K(= %d)<sup>th</sup> bit\", k); printf(\" with P(= %d) modifies N to 10\\n\", modifyBit(n, k, p));} // Driver Codeint main(){ int n = 5, k = 1, p = 1; bitOperations(n, k, p); return 0;}", "e": 28823, "s": 27576, "text": null }, { "code": null, "e": 29017, "s": 28823, "text": "K(= 1)-th bit of 5 is 0\nSetting K(= 1)th bit modifies N to 5\nClearing K(= 1)th bit modifies N to 4\nToggling K(= 1)th bit modifies N to 4\nReplacing the K(= 1)th bit with P(= 7) modifies N to 10\n" }, { "code": null, "e": 29065, "s": 29017, "text": "Time Complexity: O(log(N))Auxiliary Space: O(1)" }, { "code": null, "e": 29080, "s": 29065, "text": "Bit Algorithms" }, { "code": null, "e": 29092, "s": 29080, "text": "Bitwise-AND" }, { "code": null, "e": 29103, "s": 29092, "text": "Bitwise-OR" }, { "code": null, "e": 29115, "s": 29103, "text": "Bitwise-XOR" }, { "code": null, "e": 29139, "s": 29115, "text": "Technical Scripter 2020" }, { "code": null, "e": 29149, "s": 29139, "text": "Bit Magic" }, { "code": null, "e": 29162, "s": 29149, "text": "Mathematical" }, { "code": null, "e": 29181, "s": 29162, "text": "Technical Scripter" }, { "code": null, "e": 29194, "s": 29181, "text": "Mathematical" }, { "code": null, "e": 29204, "s": 29194, "text": "Bit Magic" }, { "code": null, "e": 29302, "s": 29204, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29353, "s": 29302, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 29417, "s": 29353, "text": "Write an Efficient Method to Check if a Number is Multiple of 3" }, { "code": null, "e": 29444, "s": 29417, "text": "Swap two nibbles in a byte" }, { "code": null, "e": 29498, "s": 29444, "text": "Highest power of 2 less than or equal to given number" }, { "code": null, "e": 29526, "s": 29498, "text": "Swap bits in a given number" }, { "code": null, "e": 29556, "s": 29526, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 29616, "s": 29556, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 29631, "s": 29616, "text": "C++ Data Types" }, { "code": null, "e": 29674, "s": 29631, "text": "Set in C++ Standard Template Library (STL)" } ]
Python | Make a list of intervals with sequential numbers - GeeksforGeeks
20 Nov, 2019 Given a list of sequential numbers, Write a Python program to convert the given list into list of intervals. Examples: Input : [2, 3, 4, 5, 7, 8, 9, 11, 15, 16] Output : [[2, 5], [7, 11], [15, 16]] Input : [1, 2, 3, 6, 7, 8, 9, 10] Output : [[1, 3], [6, 10]] Method #1 : Naive Approach First, we use the brute force approach to Convert list of sequential number into intervals. Start a loop till the length of the list. In every iteration, use another loop to check the continuity of the sequence. As soon as the sequence stop, yield the lower and higher bound of each interval. # Python3 program to Convert list of # sequential number into intervals def interval_extract(list): length = len(list) i = 0 while (i< length): low = list[i] while i <length-1 and list[i]+1 == list[i + 1]: i += 1 high = list[i] if (high - low >= 1): yield [low, high] elif (high - low == 1): yield [low, ] yield [high, ] else: yield [low, ] i += 1 # Driver codel = [2, 3, 4, 5, 7, 8, 9, 11, 15, 16]print( list(interval_extract(l))) [[2, 5], [7, 9], [11], [15, 16]] Method #2 : Pythonic NaiveFirst, sort the given list. Initialize previous_number and range_start with first element. Start a loop and check if the next number is additive of the previous number, If yes, Initialize this number to previous number otherwise yield the new interval starting with range_start and ending with previous_number. # Python3 program to Convert list of # sequential number into intervals def interval_extract(list): list = sorted(set(list)) range_start = previous_number = list[0] for number in list[1:]: if number == previous_number + 1: previous_number = number else: yield [range_start, previous_number] range_start = previous_number = number yield [range_start, previous_number] # Driver codel = [2, 3, 4, 5, 7, 8, 9, 11, 15, 16]print( list(interval_extract(l))) [[2, 5], [7, 9], [11, 11], [15, 16]] Method #3 : Using itertoolsThe other pythonic method is to use Python itertools. We use itertools.groupby(). Where enumerate(iterable) is taken as iterable and lambda t: t[1] – t[0]) as key function to find the sequence for intervals. # Python3 program to Convert list of # sequential number into intervalsimport itertools def intervals_extract(iterable): iterable = sorted(set(iterable)) for key, group in itertools.groupby(enumerate(iterable), lambda t: t[1] - t[0]): group = list(group) yield [group[0][1], group[-1][1]] # Driver codel = [2, 3, 4, 5, 7, 8, 9, 11, 15, 16]print( list(intervals_extract(l))) [[2, 5], [7, 9], [11, 11], [15, 16]] ManasChhabra2 Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python
[ { "code": null, "e": 25497, "s": 25469, "text": "\n20 Nov, 2019" }, { "code": null, "e": 25606, "s": 25497, "text": "Given a list of sequential numbers, Write a Python program to convert the given list into list of intervals." }, { "code": null, "e": 25616, "s": 25606, "text": "Examples:" }, { "code": null, "e": 25758, "s": 25616, "text": "Input : [2, 3, 4, 5, 7, 8, 9, 11, 15, 16]\nOutput : [[2, 5], [7, 11], [15, 16]]\n\nInput : [1, 2, 3, 6, 7, 8, 9, 10]\nOutput : [[1, 3], [6, 10]]\n" }, { "code": null, "e": 25786, "s": 25758, "text": " Method #1 : Naive Approach" }, { "code": null, "e": 26079, "s": 25786, "text": "First, we use the brute force approach to Convert list of sequential number into intervals. Start a loop till the length of the list. In every iteration, use another loop to check the continuity of the sequence. As soon as the sequence stop, yield the lower and higher bound of each interval." }, { "code": "# Python3 program to Convert list of # sequential number into intervals def interval_extract(list): length = len(list) i = 0 while (i< length): low = list[i] while i <length-1 and list[i]+1 == list[i + 1]: i += 1 high = list[i] if (high - low >= 1): yield [low, high] elif (high - low == 1): yield [low, ] yield [high, ] else: yield [low, ] i += 1 # Driver codel = [2, 3, 4, 5, 7, 8, 9, 11, 15, 16]print( list(interval_extract(l)))", "e": 26627, "s": 26079, "text": null }, { "code": null, "e": 26661, "s": 26627, "text": "[[2, 5], [7, 9], [11], [15, 16]]\n" }, { "code": null, "e": 26999, "s": 26661, "text": " Method #2 : Pythonic NaiveFirst, sort the given list. Initialize previous_number and range_start with first element. Start a loop and check if the next number is additive of the previous number, If yes, Initialize this number to previous number otherwise yield the new interval starting with range_start and ending with previous_number." }, { "code": "# Python3 program to Convert list of # sequential number into intervals def interval_extract(list): list = sorted(set(list)) range_start = previous_number = list[0] for number in list[1:]: if number == previous_number + 1: previous_number = number else: yield [range_start, previous_number] range_start = previous_number = number yield [range_start, previous_number] # Driver codel = [2, 3, 4, 5, 7, 8, 9, 11, 15, 16]print( list(interval_extract(l)))", "e": 27513, "s": 26999, "text": null }, { "code": null, "e": 27551, "s": 27513, "text": "[[2, 5], [7, 9], [11, 11], [15, 16]]\n" }, { "code": null, "e": 27787, "s": 27551, "text": " Method #3 : Using itertoolsThe other pythonic method is to use Python itertools. We use itertools.groupby(). Where enumerate(iterable) is taken as iterable and lambda t: t[1] – t[0]) as key function to find the sequence for intervals." }, { "code": "# Python3 program to Convert list of # sequential number into intervalsimport itertools def intervals_extract(iterable): iterable = sorted(set(iterable)) for key, group in itertools.groupby(enumerate(iterable), lambda t: t[1] - t[0]): group = list(group) yield [group[0][1], group[-1][1]] # Driver codel = [2, 3, 4, 5, 7, 8, 9, 11, 15, 16]print( list(intervals_extract(l)))", "e": 28192, "s": 27787, "text": null }, { "code": null, "e": 28230, "s": 28192, "text": "[[2, 5], [7, 9], [11, 11], [15, 16]]\n" }, { "code": null, "e": 28244, "s": 28230, "text": "ManasChhabra2" }, { "code": null, "e": 28265, "s": 28244, "text": "Python list-programs" }, { "code": null, "e": 28277, "s": 28265, "text": "python-list" }, { "code": null, "e": 28284, "s": 28277, "text": "Python" }, { "code": null, "e": 28296, "s": 28284, "text": "python-list" }, { "code": null, "e": 28394, "s": 28296, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28429, "s": 28394, "text": "Read a file line by line in Python" }, { "code": null, "e": 28461, "s": 28429, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28483, "s": 28461, "text": "Enumerate() in Python" }, { "code": null, "e": 28525, "s": 28483, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28555, "s": 28525, "text": "Iterate over a list in Python" }, { "code": null, "e": 28581, "s": 28555, "text": "Python String | replace()" }, { "code": null, "e": 28610, "s": 28581, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28654, "s": 28610, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28691, "s": 28654, "text": "Create a Pandas DataFrame from Lists" } ]
PostgreSQL - NULLIF() Function - GeeksforGeeks
28 Aug, 2020 PostgreSQL has a NULLIF function to handle null values. The NULLIF function is one of the most common conditional expressions provided by PostgreSQL. Syntax:NULLIF(argument_1,argument_2); The NULLIF function returns a null value if argument_1 equals to argument_2, otherwise it returns argument_1. Example : First, we create a table named posts as follows: CREATE TABLE posts ( id serial primary key, title VARCHAR (255) NOT NULL, excerpt VARCHAR (150), body TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP ); Now we insert some sample data to the table as follows: INSERT INTO posts (title, excerpt, body) VALUES ('test post 1','test post excerpt 1','test post body 1'), ('test post 2','','test post body 2'), ('test post 3', null ,'test post body 3'); Our aim is to display the posts overview page that shows the title and excerpt of each post. In case the excerpt is not provided, we use the first 40 characters of the post body. We can simply use the following query to get all rows in the posts table. SELECT ID, title, excerpt FROM posts; This leads to the following: The null value in the excerpt column. To substitute this null value, we can use the COALESCE function as follows: SELECT id, title, COALESCE (excerpt, LEFT(body, 40)) FROM posts; This will result in the following: Unfortunately, there is a mix between null value and ” (empty) in the excerpt column. This is why we need to use the NULLIF function: SELECT id, title, COALESCE ( NULLIF (excerpt, ''), LEFT (body, 40) ) FROM posts; Output: PostgreSQL-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 - Function Returning A Table PostgreSQL - Create Auto-increment Column using SERIAL PostgreSQL - CREATE PROCEDURE PostgreSQL - ARRAY_AGG() Function PostgreSQL - DROP INDEX PostgreSQL - Copy Table PostgreSQL - Identity Column
[ { "code": null, "e": 29245, "s": 29217, "text": "\n28 Aug, 2020" }, { "code": null, "e": 29395, "s": 29245, "text": "PostgreSQL has a NULLIF function to handle null values. The NULLIF function is one of the most common conditional expressions provided by PostgreSQL." }, { "code": null, "e": 29435, "s": 29395, "text": "Syntax:NULLIF(argument_1,argument_2);\n\n" }, { "code": null, "e": 29545, "s": 29435, "text": "The NULLIF function returns a null value if argument_1 equals to argument_2, otherwise it returns argument_1." }, { "code": null, "e": 29555, "s": 29545, "text": "Example :" }, { "code": null, "e": 29604, "s": 29555, "text": "First, we create a table named posts as follows:" }, { "code": null, "e": 29808, "s": 29604, "text": "CREATE TABLE posts (\n id serial primary key,\n title VARCHAR (255) NOT NULL,\n excerpt VARCHAR (150),\n body TEXT,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP\n);\n\n" }, { "code": null, "e": 29864, "s": 29808, "text": "Now we insert some sample data to the table as follows:" }, { "code": null, "e": 30072, "s": 29864, "text": "INSERT INTO posts (title, excerpt, body)\nVALUES\n ('test post 1','test post excerpt 1','test post body 1'),\n ('test post 2','','test post body 2'),\n ('test post 3', null ,'test post body 3');\n\n" }, { "code": null, "e": 30325, "s": 30072, "text": "Our aim is to display the posts overview page that shows the title and excerpt of each post. In case the excerpt is not provided, we use the first 40 characters of the post body. We can simply use the following query to get all rows in the posts table." }, { "code": null, "e": 30381, "s": 30325, "text": "SELECT\n ID,\n title,\n excerpt\nFROM\n posts;\n\n" }, { "code": null, "e": 30410, "s": 30381, "text": "This leads to the following:" }, { "code": null, "e": 30524, "s": 30410, "text": "The null value in the excerpt column. To substitute this null value, we can use the COALESCE function as follows:" }, { "code": null, "e": 30607, "s": 30524, "text": "SELECT\n id,\n title,\n COALESCE (excerpt, LEFT(body, 40))\nFROM\n posts;\n\n" }, { "code": null, "e": 30642, "s": 30607, "text": "This will result in the following:" }, { "code": null, "e": 30776, "s": 30642, "text": "Unfortunately, there is a mix between null value and ” (empty) in the excerpt column. This is why we need to use the NULLIF function:" }, { "code": null, "e": 30895, "s": 30776, "text": "SELECT\n id,\n title,\n COALESCE (\n NULLIF (excerpt, ''),\n LEFT (body, 40)\n )\nFROM\n posts;\n\n" }, { "code": null, "e": 30903, "s": 30895, "text": "Output:" }, { "code": null, "e": 30923, "s": 30903, "text": "PostgreSQL-function" }, { "code": null, "e": 30934, "s": 30923, "text": "PostgreSQL" }, { "code": null, "e": 31032, "s": 30934, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31059, "s": 31032, "text": "PostgreSQL - Psql commands" }, { "code": null, "e": 31091, "s": 31059, "text": "PostgreSQL - Change Column Type" }, { "code": null, "e": 31114, "s": 31091, "text": "PostgreSQL - For Loops" }, { "code": null, "e": 31154, "s": 31114, "text": "PostgreSQL - Function Returning A Table" }, { "code": null, "e": 31209, "s": 31154, "text": "PostgreSQL - Create Auto-increment Column using SERIAL" }, { "code": null, "e": 31239, "s": 31209, "text": "PostgreSQL - CREATE PROCEDURE" }, { "code": null, "e": 31273, "s": 31239, "text": "PostgreSQL - ARRAY_AGG() Function" }, { "code": null, "e": 31297, "s": 31273, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 31321, "s": 31297, "text": "PostgreSQL - Copy Table" } ]
NOW() function in MYSQL - GeeksforGeeks
11 Jan, 2021 NOW() :This function in MySQL is used to check the current date and time value. The return type for NOW() function is either in ‘YYYY-MM-DD HH:MM:SS’ format or YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a string or numeric context. Syntax : NOW() Parameter :This method does not accept any parameter. Returns :It returns the current date and time value. Example-1 :Finding the current date and time using NOW Function. Here we will get the result in ‘YYYY-MM-DD HH:MM:SS’ format. SELECT NOW() as CurrDateTime ; Output : Example-2 :Getting the current date and time using NOW Function in numeric format. Here the result will be in YYYYMMDDHHMMSS.uuuuuu format. SELECT NOW()+ 0 as CurrDateTime ; Output : Example-3 :We can also use The NOW function to set value of columns. To demonstrate create a table named DeliveryDetails. CREATE TABLE Product ( ProductId INT NOT NULL, ProductName VARCHAR(20) NOT NULL, Delivered_At TIMESTAMP NOT NULL, PRIMARY KEY(ProductId) ); Here, we will use NOW function when a delivery will be completed. The value in Delivered_At column will be the value given by NOW Function. INSERT INTO Product (ProductId, ProductName, Delivered_At) VALUES (1010, 'Apple MacBook', NOW()); Now, checking the Product table : SELECT * FROM Product; Output : DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL using Python How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n11 Jan, 2021" }, { "code": null, "e": 25777, "s": 25513, "text": "NOW() :This function in MySQL is used to check the current date and time value. The return type for NOW() function is either in ‘YYYY-MM-DD HH:MM:SS’ format or YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a string or numeric context." }, { "code": null, "e": 25786, "s": 25777, "text": "Syntax :" }, { "code": null, "e": 25792, "s": 25786, "text": "NOW()" }, { "code": null, "e": 25846, "s": 25792, "text": "Parameter :This method does not accept any parameter." }, { "code": null, "e": 25899, "s": 25846, "text": "Returns :It returns the current date and time value." }, { "code": null, "e": 26025, "s": 25899, "text": "Example-1 :Finding the current date and time using NOW Function. Here we will get the result in ‘YYYY-MM-DD HH:MM:SS’ format." }, { "code": null, "e": 26057, "s": 26025, "text": "SELECT NOW() \nas CurrDateTime ;" }, { "code": null, "e": 26066, "s": 26057, "text": "Output :" }, { "code": null, "e": 26206, "s": 26066, "text": "Example-2 :Getting the current date and time using NOW Function in numeric format. Here the result will be in YYYYMMDDHHMMSS.uuuuuu format." }, { "code": null, "e": 26241, "s": 26206, "text": "SELECT NOW()+ 0 \nas CurrDateTime ;" }, { "code": null, "e": 26250, "s": 26241, "text": "Output :" }, { "code": null, "e": 26372, "s": 26250, "text": "Example-3 :We can also use The NOW function to set value of columns. To demonstrate create a table named DeliveryDetails." }, { "code": null, "e": 26512, "s": 26372, "text": "CREATE TABLE Product (\nProductId INT NOT NULL,\nProductName VARCHAR(20) NOT NULL,\nDelivered_At TIMESTAMP NOT NULL,\nPRIMARY KEY(ProductId)\n);" }, { "code": null, "e": 26652, "s": 26512, "text": "Here, we will use NOW function when a delivery will be completed. The value in Delivered_At column will be the value given by NOW Function." }, { "code": null, "e": 26752, "s": 26652, "text": "INSERT INTO \nProduct (ProductId, ProductName, Delivered_At)\nVALUES\n(1010, 'Apple MacBook', NOW());" }, { "code": null, "e": 26786, "s": 26752, "text": "Now, checking the Product table :" }, { "code": null, "e": 26809, "s": 26786, "text": "SELECT * FROM Product;" }, { "code": null, "e": 26818, "s": 26809, "text": "Output :" }, { "code": null, "e": 26827, "s": 26818, "text": "DBMS-SQL" }, { "code": null, "e": 26833, "s": 26827, "text": "mysql" }, { "code": null, "e": 26837, "s": 26833, "text": "SQL" }, { "code": null, "e": 26841, "s": 26837, "text": "SQL" }, { "code": null, "e": 26939, "s": 26841, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27005, "s": 26939, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27020, "s": 27005, "text": "SQL | Subquery" }, { "code": null, "e": 27077, "s": 27020, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 27109, "s": 27077, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27187, "s": 27109, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 27223, "s": 27187, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 27240, "s": 27223, "text": "SQL using Python" }, { "code": null, "e": 27306, "s": 27240, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 27368, "s": 27306, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
Replace each element of Array with it's corresponding rank - GeeksforGeeks
18 May, 2021 Given an array arr[] of N integers, the task is to replace each element of Array with their rank in array. The rank of an element is defined as the distance between the element with the first element of the array when the array is arranged in ascending order. If two or more are same in the array then their rank is also the same as the rank of the first occurrence of the element. For Example: Let the given array arr[] = {2, 2, 1, 6}, then rank of elements is given by: sorted array is: arr[] = {1, 2, 2, 6} Rank(1) = 1 (at index 0) Rank(2) = 2 (at index 1) Rank(2) = 2 (at index 2) Rank(6) = 4 (at index 3) Examples: Input: arr[] = [100, 5, 70, 2] Output: [4, 2, 3, 1] Explanation: Rank of 2 is 1, 5 is 2, 70 is 3 and 100 is 4.Input: arr[] = [100, 2, 70, 2] Output: [3, 1, 2, 1] Explanation: Rank of 2 is 1, 70 is 2 and 100 is 3. Naive Approach: The naive approach is to find the rank of each element is 1 + the count of smaller elements in the array for the current element.Time Complexity: O(N2) Auxiliary Space: O(1)Efficient Approach: To optimize the above naive approach find ranks of elements and then assign the rank to the elements. Below are the steps: To compute the rank of the element first make a copy of given arr[] then sort that copied array in ascending order.Then traverse in the copied array and put their rank in HashMap by taking a rank variable.If the element is already present in HashMap then don’t update rank otherwise update rank of the element in HashMap and increment rank variable as well.Traverse the given array arr[] assign the rank of each element using the rank stored in HashMap. To compute the rank of the element first make a copy of given arr[] then sort that copied array in ascending order. Then traverse in the copied array and put their rank in HashMap by taking a rank variable. If the element is already present in HashMap then don’t update rank otherwise update rank of the element in HashMap and increment rank variable as well. Traverse the given array arr[] assign the rank of each element using the rank stored in HashMap. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to assign rank to// array elementsvoid changeArr(int input[], int N){ // Copy input array into newArray int newArray[N]; copy(input, input + N, newArray); // Sort newArray[] in ascending order sort(newArray, newArray + N); int i; // Map to store the rank of // the array element map<int, int> ranks; int rank = 1; for(int index = 0; index < N; index++) { int element = newArray[index]; // Update rank of element if (ranks[element] == 0) { ranks[element] = rank; rank++; } } // Assign ranks to elements for(int index = 0; index < N; index++) { int element = input[index]; input[index] = ranks[input[index]]; }} // Driver code int main(){ // Given array arr[] int arr[] = { 100, 2, 70, 2 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call changeArr(arr, N); // Print the array elements cout << "["; for(int i = 0; i < N - 1; i++) { cout << arr[i] << ", "; } cout << arr[N - 1] << "]"; return 0;} // This code is contributed by divyeshrabadiya07 // Java program for the above approachimport java.util.*; class GFG { // Function to assign rank to // array elements static void changeArr(int[] input) { // Copy input array into newArray int newArray[] = Arrays .copyOfRange(input, 0, input.length); // Sort newArray[] in ascending order Arrays.sort(newArray); int i; // Map to store the rank of // the array element Map<Integer, Integer> ranks = new HashMap<>(); int rank = 1; for (int index = 0; index < newArray.length; index++) { int element = newArray[index]; // Update rank of element if (ranks.get(element) == null) { ranks.put(element, rank); rank++; } } // Assign ranks to elements for (int index = 0; index < input.length; index++) { int element = input[index]; input[index] = ranks.get(input[index]); } } // Driver Code public static void main(String[] args) { // Given array arr[] int[] arr = { 100, 2, 70, 2 }; // Function Call changeArr(arr); // Print the array elements System .out .println(Arrays .toString(arr)); }} # Python3 program for the above approach # Function to assign rank to# array elementsdef changeArr(input1): # Copy input array into newArray newArray = input1.copy() # Sort newArray[] in ascending order newArray.sort() # Dictionary to store the rank of # the array element ranks = {} rank = 1 for index in range(len(newArray)): element = newArray[index]; # Update rank of element if element not in ranks: ranks[element] = rank rank += 1 # Assign ranks to elements for index in range(len(input1)): element = input1[index] input1[index] = ranks[input1[index]] # Driver Codeif __name__ == "__main__": # Given array arr[] arr = [ 100, 2, 70, 2 ] # Function call changeArr(arr) # Print the array elements print(arr) # This code is contributed by chitranayal // C# program for the above approachusing System;using System.Collections.Generic;using System.Text; class GFG{ // Function to assign rank to// array elementsstatic void changeArr(int[] input){ // Copy input array into newArray int []newArray = new int[input.Length]; Array.Copy(input, newArray, input.Length); // Sort newArray[] in ascending order Array.Sort(newArray); // To store the rank of // the array element Dictionary<int, int> ranks= new Dictionary<int, int>(); int rank = 1; for(int index = 0; index < newArray.Length; index++) { int element = newArray[index]; // Update rank of element if (!ranks.ContainsKey(element)) { ranks[element] = rank; rank++; } } // Assign ranks to elements for(int index = 0; index < input.Length; index++) { input[index] = ranks[input[index]]; }} // Driver Codepublic static void Main(string[] args){ // Given array arr[] int[] arr = { 100, 2, 70, 2 }; // Function call changeArr(arr); // Print the array elements Console.WriteLine("[{0}]", string.Join(", ", arr));}} // This code is contributed by rutvik_56 <script> // Javascript program for the above approach // Function to assign rank to// array elementsfunction changeArr(input, N){ // Copy input array into newArray var newArray = JSON.parse(JSON.stringify(input)); // Sort newArray[] in ascending order newArray.sort((a,b)=> a-b); var i; // Map to store the rank of // the array element var ranks = new Map(); var rank = 1; for(var index = 0; index < N; index++) { var element = newArray[index]; // Update rank of element if (!ranks.has(element)) { ranks.set(element, rank); rank++; } } // Assign ranks to elements for(var index = 0; index < N; index++) { var element = input[index]; input[index] = ranks.get(input[index]); } return input;} // Driver code // Given array arr[]var arr = [100, 2, 70, 2];var N = arr.length; // Function callarr = changeArr(arr, N); // Print the array elementsdocument.write( "[");for(var i = 0; i < N - 1; i++){ document.write( arr[i] + ", ");}document.write( arr[N - 1] + "]"); // This code is contributed by famously.</script> [3, 1, 2, 1] Time Complexity: O(N * log N) Auxiliary Space: O(N) ukasp rutvik_56 divyeshrabadiya07 simmytarika5 famously Hash HashTable Java-HashMap Arrays Competitive Programming Greedy Hash Mathematical Searching Sorting Arrays Searching Hash Greedy Mathematical Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Python | Using 2D arrays/lists the right way Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Top 10 Algorithms and Data Structures for Competitive Programming
[ { "code": null, "e": 26747, "s": 26719, "text": "\n18 May, 2021" }, { "code": null, "e": 26854, "s": 26747, "text": "Given an array arr[] of N integers, the task is to replace each element of Array with their rank in array." }, { "code": null, "e": 27357, "s": 26854, "text": "The rank of an element is defined as the distance between the element with the first element of the array when the array is arranged in ascending order. If two or more are same in the array then their rank is also the same as the rank of the first occurrence of the element. For Example: Let the given array arr[] = {2, 2, 1, 6}, then rank of elements is given by: sorted array is: arr[] = {1, 2, 2, 6} Rank(1) = 1 (at index 0) Rank(2) = 2 (at index 1) Rank(2) = 2 (at index 2) Rank(6) = 4 (at index 3)" }, { "code": null, "e": 27367, "s": 27357, "text": "Examples:" }, { "code": null, "e": 27580, "s": 27367, "text": "Input: arr[] = [100, 5, 70, 2] Output: [4, 2, 3, 1] Explanation: Rank of 2 is 1, 5 is 2, 70 is 3 and 100 is 4.Input: arr[] = [100, 2, 70, 2] Output: [3, 1, 2, 1] Explanation: Rank of 2 is 1, 70 is 2 and 100 is 3." }, { "code": null, "e": 27912, "s": 27580, "text": "Naive Approach: The naive approach is to find the rank of each element is 1 + the count of smaller elements in the array for the current element.Time Complexity: O(N2) Auxiliary Space: O(1)Efficient Approach: To optimize the above naive approach find ranks of elements and then assign the rank to the elements. Below are the steps:" }, { "code": null, "e": 28366, "s": 27912, "text": "To compute the rank of the element first make a copy of given arr[] then sort that copied array in ascending order.Then traverse in the copied array and put their rank in HashMap by taking a rank variable.If the element is already present in HashMap then don’t update rank otherwise update rank of the element in HashMap and increment rank variable as well.Traverse the given array arr[] assign the rank of each element using the rank stored in HashMap." }, { "code": null, "e": 28482, "s": 28366, "text": "To compute the rank of the element first make a copy of given arr[] then sort that copied array in ascending order." }, { "code": null, "e": 28573, "s": 28482, "text": "Then traverse in the copied array and put their rank in HashMap by taking a rank variable." }, { "code": null, "e": 28726, "s": 28573, "text": "If the element is already present in HashMap then don’t update rank otherwise update rank of the element in HashMap and increment rank variable as well." }, { "code": null, "e": 28823, "s": 28726, "text": "Traverse the given array arr[] assign the rank of each element using the rank stored in HashMap." }, { "code": null, "e": 28874, "s": 28823, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28878, "s": 28874, "text": "C++" }, { "code": null, "e": 28883, "s": 28878, "text": "Java" }, { "code": null, "e": 28891, "s": 28883, "text": "Python3" }, { "code": null, "e": 28894, "s": 28891, "text": "C#" }, { "code": null, "e": 28905, "s": 28894, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to assign rank to// array elementsvoid changeArr(int input[], int N){ // Copy input array into newArray int newArray[N]; copy(input, input + N, newArray); // Sort newArray[] in ascending order sort(newArray, newArray + N); int i; // Map to store the rank of // the array element map<int, int> ranks; int rank = 1; for(int index = 0; index < N; index++) { int element = newArray[index]; // Update rank of element if (ranks[element] == 0) { ranks[element] = rank; rank++; } } // Assign ranks to elements for(int index = 0; index < N; index++) { int element = input[index]; input[index] = ranks[input[index]]; }} // Driver code int main(){ // Given array arr[] int arr[] = { 100, 2, 70, 2 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call changeArr(arr, N); // Print the array elements cout << \"[\"; for(int i = 0; i < N - 1; i++) { cout << arr[i] << \", \"; } cout << arr[N - 1] << \"]\"; return 0;} // This code is contributed by divyeshrabadiya07", "e": 30144, "s": 28905, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG { // Function to assign rank to // array elements static void changeArr(int[] input) { // Copy input array into newArray int newArray[] = Arrays .copyOfRange(input, 0, input.length); // Sort newArray[] in ascending order Arrays.sort(newArray); int i; // Map to store the rank of // the array element Map<Integer, Integer> ranks = new HashMap<>(); int rank = 1; for (int index = 0; index < newArray.length; index++) { int element = newArray[index]; // Update rank of element if (ranks.get(element) == null) { ranks.put(element, rank); rank++; } } // Assign ranks to elements for (int index = 0; index < input.length; index++) { int element = input[index]; input[index] = ranks.get(input[index]); } } // Driver Code public static void main(String[] args) { // Given array arr[] int[] arr = { 100, 2, 70, 2 }; // Function Call changeArr(arr); // Print the array elements System .out .println(Arrays .toString(arr)); }}", "e": 31616, "s": 30144, "text": null }, { "code": "# Python3 program for the above approach # Function to assign rank to# array elementsdef changeArr(input1): # Copy input array into newArray newArray = input1.copy() # Sort newArray[] in ascending order newArray.sort() # Dictionary to store the rank of # the array element ranks = {} rank = 1 for index in range(len(newArray)): element = newArray[index]; # Update rank of element if element not in ranks: ranks[element] = rank rank += 1 # Assign ranks to elements for index in range(len(input1)): element = input1[index] input1[index] = ranks[input1[index]] # Driver Codeif __name__ == \"__main__\": # Given array arr[] arr = [ 100, 2, 70, 2 ] # Function call changeArr(arr) # Print the array elements print(arr) # This code is contributed by chitranayal", "e": 32527, "s": 31616, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;using System.Text; class GFG{ // Function to assign rank to// array elementsstatic void changeArr(int[] input){ // Copy input array into newArray int []newArray = new int[input.Length]; Array.Copy(input, newArray, input.Length); // Sort newArray[] in ascending order Array.Sort(newArray); // To store the rank of // the array element Dictionary<int, int> ranks= new Dictionary<int, int>(); int rank = 1; for(int index = 0; index < newArray.Length; index++) { int element = newArray[index]; // Update rank of element if (!ranks.ContainsKey(element)) { ranks[element] = rank; rank++; } } // Assign ranks to elements for(int index = 0; index < input.Length; index++) { input[index] = ranks[input[index]]; }} // Driver Codepublic static void Main(string[] args){ // Given array arr[] int[] arr = { 100, 2, 70, 2 }; // Function call changeArr(arr); // Print the array elements Console.WriteLine(\"[{0}]\", string.Join(\", \", arr));}} // This code is contributed by rutvik_56", "e": 33829, "s": 32527, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to assign rank to// array elementsfunction changeArr(input, N){ // Copy input array into newArray var newArray = JSON.parse(JSON.stringify(input)); // Sort newArray[] in ascending order newArray.sort((a,b)=> a-b); var i; // Map to store the rank of // the array element var ranks = new Map(); var rank = 1; for(var index = 0; index < N; index++) { var element = newArray[index]; // Update rank of element if (!ranks.has(element)) { ranks.set(element, rank); rank++; } } // Assign ranks to elements for(var index = 0; index < N; index++) { var element = input[index]; input[index] = ranks.get(input[index]); } return input;} // Driver code // Given array arr[]var arr = [100, 2, 70, 2];var N = arr.length; // Function callarr = changeArr(arr, N); // Print the array elementsdocument.write( \"[\");for(var i = 0; i < N - 1; i++){ document.write( arr[i] + \", \");}document.write( arr[N - 1] + \"]\"); // This code is contributed by famously.</script>", "e": 34981, "s": 33829, "text": null }, { "code": null, "e": 34994, "s": 34981, "text": "[3, 1, 2, 1]" }, { "code": null, "e": 35047, "s": 34994, "text": "Time Complexity: O(N * log N) Auxiliary Space: O(N) " }, { "code": null, "e": 35053, "s": 35047, "text": "ukasp" }, { "code": null, "e": 35063, "s": 35053, "text": "rutvik_56" }, { "code": null, "e": 35081, "s": 35063, "text": "divyeshrabadiya07" }, { "code": null, "e": 35094, "s": 35081, "text": "simmytarika5" }, { "code": null, "e": 35103, "s": 35094, "text": "famously" }, { "code": null, "e": 35108, "s": 35103, "text": "Hash" }, { "code": null, "e": 35118, "s": 35108, "text": "HashTable" }, { "code": null, "e": 35131, "s": 35118, "text": "Java-HashMap" }, { "code": null, "e": 35138, "s": 35131, "text": "Arrays" }, { "code": null, "e": 35162, "s": 35138, "text": "Competitive Programming" }, { "code": null, "e": 35169, "s": 35162, "text": "Greedy" }, { "code": null, "e": 35174, "s": 35169, "text": "Hash" }, { "code": null, "e": 35187, "s": 35174, "text": "Mathematical" }, { "code": null, "e": 35197, "s": 35187, "text": "Searching" }, { "code": null, "e": 35205, "s": 35197, "text": "Sorting" }, { "code": null, "e": 35212, "s": 35205, "text": "Arrays" }, { "code": null, "e": 35222, "s": 35212, "text": "Searching" }, { "code": null, "e": 35227, "s": 35222, "text": "Hash" }, { "code": null, "e": 35234, "s": 35227, "text": "Greedy" }, { "code": null, "e": 35247, "s": 35234, "text": "Mathematical" }, { "code": null, "e": 35255, "s": 35247, "text": "Sorting" }, { "code": null, "e": 35353, "s": 35255, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35376, "s": 35353, "text": "Introduction to Arrays" }, { "code": null, "e": 35408, "s": 35376, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 35422, "s": 35408, "text": "Linear Search" }, { "code": null, "e": 35443, "s": 35422, "text": "Linked List vs Array" }, { "code": null, "e": 35488, "s": 35443, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 35531, "s": 35488, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 35574, "s": 35531, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 35615, "s": 35574, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 35693, "s": 35615, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
Python isinstance() method - GeeksforGeeks
23 Sep, 2021 Python isinstance() function returns True if the object is specified types, and it will not match then return False. Syntax : isinstance(obj, class) Parameters : obj : The object that need to be checked as a part of class or not. class : class/type/tuple of class or type, against which object is needed to be checked. Returns : True, if object belongs to the given class/type if single class is passed or any of the class/type if tuple of class/type is passed, else returns False. Raises TypeError: if anything other than mentioned valid class type. Python3 # Python 3 code to demonstrate# working of isinstance()# with native types # initializing native typestest_int = 5test_list = [1, 2, 3] # testing with isinstanceprint("Is test_int integer? : " + str(isinstance(test_int, int)))print("Is test_int string? : " + str(isinstance(test_int, str)))print("Is test_list integer? : " + str(isinstance(test_list, int)))print("Is test_list list? : " + str(isinstance(test_list, list))) # testing with tupleprint("Is test_int integer or list or string? : " + str(isinstance(test_int, (list, int)))) Output: Is test_int integer? : True Is test_int string? : False Is test_list integer? : False Is test_list list? : True Is test_int integer or list or string? : True Python3 # Python 3 code to demonstrate# working of isinstance()# with objects # declaring classesclass gfg1: a = 10 # inherited classclass gfg2(gfg1): string = 'GeeksforGeeks' # initializing objectsobj1 = gfg1()obj2 = gfg2() # checking instancesprint("Is obj1 instance of gfg1? : " + str(isinstance(obj1, gfg1)))print("Is obj2 instance of gfg2? : " + str(isinstance(obj2, gfg2)))print("Is obj1 instance of gfg2? : " + str(isinstance(obj1, gfg2))) # check inheritance case# return trueprint("Is obj2 instance of gfg1? : " + str(isinstance(obj2, gfg1))) Output: Is obj1 instance of gfg1? : True Is obj2 instance of gfg2? : True Is obj1 instance of gfg2? : False Is obj2 instance of gfg1? : True Python3 test_list = [1, 2, 3]print ("Is test_list list? : " + str(isinstance(test_list, list))) Output: Is test_list list? : True Python3 test_str = "GeeksforGeeks"print ("Is test_str string? : " + str(isinstance(test_str, str))) Output: Is test_str string? : True Python3 test_dict = {"apple" : 1, "Ball" : 2 }print ("Is test_str dictionary? : " + str(isinstance(test_dict, dict))) Output: Is test_str dictionary? : True Python class geeks: course = 'DSA' def purchase(obj): return obj.course geeks.purchase = classmethod(geeks.purchase)str(isinstance(geeks.purchase(), str )) Output: True anikakapoor surinderdawra388 kumar_satyam Python-Built-in-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n23 Sep, 2021" }, { "code": null, "e": 25655, "s": 25537, "text": "Python isinstance() function returns True if the object is specified types, and it will not match then return False. " }, { "code": null, "e": 25687, "s": 25655, "text": "Syntax : isinstance(obj, class)" }, { "code": null, "e": 25701, "s": 25687, "text": "Parameters : " }, { "code": null, "e": 25769, "s": 25701, "text": "obj : The object that need to be checked as a part of class or not." }, { "code": null, "e": 25858, "s": 25769, "text": "class : class/type/tuple of class or type, against which object is needed to be checked." }, { "code": null, "e": 26028, "s": 25858, "text": "Returns : True, if object belongs to the given class/type if single class is passed or any of the class/type if tuple of class/type is passed, else returns False. Raises" }, { "code": null, "e": 26091, "s": 26028, "text": "TypeError: if anything other than mentioned valid class type. " }, { "code": null, "e": 26099, "s": 26091, "text": "Python3" }, { "code": "# Python 3 code to demonstrate# working of isinstance()# with native types # initializing native typestest_int = 5test_list = [1, 2, 3] # testing with isinstanceprint(\"Is test_int integer? : \" + str(isinstance(test_int, int)))print(\"Is test_int string? : \" + str(isinstance(test_int, str)))print(\"Is test_list integer? : \" + str(isinstance(test_list, int)))print(\"Is test_list list? : \" + str(isinstance(test_list, list))) # testing with tupleprint(\"Is test_int integer or list or string? : \" + str(isinstance(test_int, (list, int))))", "e": 26639, "s": 26099, "text": null }, { "code": null, "e": 26648, "s": 26639, "text": "Output: " }, { "code": null, "e": 26806, "s": 26648, "text": "Is test_int integer? : True\nIs test_int string? : False\nIs test_list integer? : False\nIs test_list list? : True\nIs test_int integer or list or string? : True" }, { "code": null, "e": 26814, "s": 26806, "text": "Python3" }, { "code": "# Python 3 code to demonstrate# working of isinstance()# with objects # declaring classesclass gfg1: a = 10 # inherited classclass gfg2(gfg1): string = 'GeeksforGeeks' # initializing objectsobj1 = gfg1()obj2 = gfg2() # checking instancesprint(\"Is obj1 instance of gfg1? : \" + str(isinstance(obj1, gfg1)))print(\"Is obj2 instance of gfg2? : \" + str(isinstance(obj2, gfg2)))print(\"Is obj1 instance of gfg2? : \" + str(isinstance(obj1, gfg2))) # check inheritance case# return trueprint(\"Is obj2 instance of gfg1? : \" + str(isinstance(obj2, gfg1)))", "e": 27366, "s": 26814, "text": null }, { "code": null, "e": 27375, "s": 27366, "text": "Output: " }, { "code": null, "e": 27508, "s": 27375, "text": "Is obj1 instance of gfg1? : True\nIs obj2 instance of gfg2? : True\nIs obj1 instance of gfg2? : False\nIs obj2 instance of gfg1? : True" }, { "code": null, "e": 27516, "s": 27508, "text": "Python3" }, { "code": "test_list = [1, 2, 3]print (\"Is test_list list? : \" + str(isinstance(test_list, list)))", "e": 27604, "s": 27516, "text": null }, { "code": null, "e": 27612, "s": 27604, "text": "Output:" }, { "code": null, "e": 27638, "s": 27612, "text": "Is test_list list? : True" }, { "code": null, "e": 27646, "s": 27638, "text": "Python3" }, { "code": "test_str = \"GeeksforGeeks\"print (\"Is test_str string? : \" + str(isinstance(test_str, str)))", "e": 27738, "s": 27646, "text": null }, { "code": null, "e": 27746, "s": 27738, "text": "Output:" }, { "code": null, "e": 27773, "s": 27746, "text": "Is test_str string? : True" }, { "code": null, "e": 27781, "s": 27773, "text": "Python3" }, { "code": "test_dict = {\"apple\" : 1, \"Ball\" : 2 }print (\"Is test_str dictionary? : \" + str(isinstance(test_dict, dict)))", "e": 27891, "s": 27781, "text": null }, { "code": null, "e": 27899, "s": 27891, "text": "Output:" }, { "code": null, "e": 27930, "s": 27899, "text": "Is test_str dictionary? : True" }, { "code": null, "e": 27937, "s": 27930, "text": "Python" }, { "code": "class geeks: course = 'DSA' def purchase(obj): return obj.course geeks.purchase = classmethod(geeks.purchase)str(isinstance(geeks.purchase(), str ))", "e": 28107, "s": 27937, "text": null }, { "code": null, "e": 28115, "s": 28107, "text": "Output:" }, { "code": null, "e": 28120, "s": 28115, "text": "True" }, { "code": null, "e": 28132, "s": 28120, "text": "anikakapoor" }, { "code": null, "e": 28149, "s": 28132, "text": "surinderdawra388" }, { "code": null, "e": 28162, "s": 28149, "text": "kumar_satyam" }, { "code": null, "e": 28188, "s": 28162, "text": "Python-Built-in-functions" }, { "code": null, "e": 28195, "s": 28188, "text": "Python" }, { "code": null, "e": 28293, "s": 28195, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28325, "s": 28293, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28367, "s": 28325, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28409, "s": 28367, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28436, "s": 28409, "text": "Python Classes and Objects" }, { "code": null, "e": 28492, "s": 28436, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28531, "s": 28492, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28553, "s": 28531, "text": "Defaultdict in Python" }, { "code": null, "e": 28584, "s": 28553, "text": "Python | os.path.join() method" }, { "code": null, "e": 28613, "s": 28584, "text": "Create a directory in Python" } ]
How to encode/decode URL using AngularJS ? - GeeksforGeeks
16 Aug, 2021 Encode URL Given an URL and the task is to encode the URL in AngularJS. Approach: The approach is to use the encodeURIComponent() method to encode the URL. In the first example the URL(‘https://ide.geeksforgeeks.org/tryit.php’) is encoded and in the second example the URL(‘https://www.geeksforgeeks.org’) is encoded. Example 1: html <!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.url1 = 'https://ide.geeksforgeeks.org/tryit.php'; $scope.url2 = ''; $scope.encodeUrl = function () { $scope.url2 = encodeURIComponent($scope.url1); } }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to encode URL in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> URL = '{{url1}}'<br><br> <button ng-click="encodeUrl()"> Click here</button> <br><br> Encoded URL = '{{url2}}' </div> </div></body> </html> Output: Example 2: html <!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.url1 = 'https://www.geeksforgeeks.org'; $scope.url2 = ''; $scope.encodeUrl = function () { $scope.url2 = encodeURIComponent($scope.url1); } }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to encode URL in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> URL = '{{url1}}'<br><br> <button ng-click="encodeUrl()"> Click here </button> <br><br> Encoded URL = '{{url2}}' </div> </div></body> </html> Output: Decode URL Given an encoded URL and the task is to decode the encoded URL using AngularJS. Approach: The approach is to use the decodeURIComponent() method to decode the URL. In the first example the URL(‘https%3A%2F%2Fide.geeksforgeeks.org%2Ftryit.php’) is decoded and in the second example the URL(‘https%3A%2F%2Fwww.geeksforgeeks.org’) is decoded. Example 1: html <!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.url1 = 'https%3A%2F%2Fide.geeksforgeeks.org%2Ftryit.php'; $scope.url2 = ''; $scope.decodeUrl = function () { $scope.url2 = decodeURIComponent($scope.url1); } }); </script></head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksForGeeks </h1> <p> How to decode URL in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> URL = '{{url1}}'<br><br> <button ng-click="decodeUrl()"> Click here </button> <br><br> Decoded URL = '{{url2}}' </div> </div></body> </html> Output: Example 2: html <!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.url1 = 'https%3A%2F%2Fwww.geeksforgeeks.org'; $scope.url2 = ''; $scope.decodeUrl = function () { $scope.url2 = decodeURIComponent($scope.url1); } }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to decode URL in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> URL = '{{url1}}'<br><br> <button ng-click="decodeUrl()"> Click here </button> <br><br> Decoded URL = '{{url2}}' </div> </div></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. sumitgumber28 AngularJS-Misc HTML-Misc AngularJS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event Angular PrimeNG Messages Component How to make a Bootstrap Modal Popup in Angular 9/8 ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property
[ { "code": null, "e": 26354, "s": 26326, "text": "\n16 Aug, 2021" }, { "code": null, "e": 26365, "s": 26354, "text": "Encode URL" }, { "code": null, "e": 26426, "s": 26365, "text": "Given an URL and the task is to encode the URL in AngularJS." }, { "code": null, "e": 26672, "s": 26426, "text": "Approach: The approach is to use the encodeURIComponent() method to encode the URL. In the first example the URL(‘https://ide.geeksforgeeks.org/tryit.php’) is encoded and in the second example the URL(‘https://www.geeksforgeeks.org’) is encoded." }, { "code": null, "e": 26683, "s": 26672, "text": "Example 1:" }, { "code": null, "e": 26688, "s": 26683, "text": "html" }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.url1 = 'https://ide.geeksforgeeks.org/tryit.php'; $scope.url2 = ''; $scope.encodeUrl = function () { $scope.url2 = encodeURIComponent($scope.url1); } }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to encode URL in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> URL = '{{url1}}'<br><br> <button ng-click=\"encodeUrl()\"> Click here</button> <br><br> Encoded URL = '{{url2}}' </div> </div></body> </html>", "e": 27614, "s": 26688, "text": null }, { "code": null, "e": 27622, "s": 27614, "text": "Output:" }, { "code": null, "e": 27633, "s": 27622, "text": "Example 2:" }, { "code": null, "e": 27638, "s": 27633, "text": "html" }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.url1 = 'https://www.geeksforgeeks.org'; $scope.url2 = ''; $scope.encodeUrl = function () { $scope.url2 = encodeURIComponent($scope.url1); } }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to encode URL in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> URL = '{{url1}}'<br><br> <button ng-click=\"encodeUrl()\"> Click here </button> <br><br> Encoded URL = '{{url2}}' </div> </div></body> </html>", "e": 28551, "s": 27638, "text": null }, { "code": null, "e": 28559, "s": 28551, "text": "Output:" }, { "code": null, "e": 28570, "s": 28559, "text": "Decode URL" }, { "code": null, "e": 28650, "s": 28570, "text": "Given an encoded URL and the task is to decode the encoded URL using AngularJS." }, { "code": null, "e": 28910, "s": 28650, "text": "Approach: The approach is to use the decodeURIComponent() method to decode the URL. In the first example the URL(‘https%3A%2F%2Fide.geeksforgeeks.org%2Ftryit.php’) is decoded and in the second example the URL(‘https%3A%2F%2Fwww.geeksforgeeks.org’) is decoded." }, { "code": null, "e": 28921, "s": 28910, "text": "Example 1:" }, { "code": null, "e": 28926, "s": 28921, "text": "html" }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.url1 = 'https%3A%2F%2Fide.geeksforgeeks.org%2Ftryit.php'; $scope.url2 = ''; $scope.decodeUrl = function () { $scope.url2 = decodeURIComponent($scope.url1); } }); </script></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksForGeeks </h1> <p> How to decode URL in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> URL = '{{url1}}'<br><br> <button ng-click=\"decodeUrl()\"> Click here </button> <br><br> Decoded URL = '{{url2}}' </div> </div></body> </html>", "e": 29885, "s": 28926, "text": null }, { "code": null, "e": 29893, "s": 29885, "text": "Output:" }, { "code": null, "e": 29904, "s": 29893, "text": "Example 2:" }, { "code": null, "e": 29909, "s": 29904, "text": "html" }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.url1 = 'https%3A%2F%2Fwww.geeksforgeeks.org'; $scope.url2 = ''; $scope.decodeUrl = function () { $scope.url2 = decodeURIComponent($scope.url1); } }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to decode URL in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> URL = '{{url1}}'<br><br> <button ng-click=\"decodeUrl()\"> Click here </button> <br><br> Decoded URL = '{{url2}}' </div> </div></body> </html> ", "e": 30850, "s": 29909, "text": null }, { "code": null, "e": 30858, "s": 30850, "text": "Output:" }, { "code": null, "e": 30995, "s": 30858, "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": 31009, "s": 30995, "text": "sumitgumber28" }, { "code": null, "e": 31024, "s": 31009, "text": "AngularJS-Misc" }, { "code": null, "e": 31034, "s": 31024, "text": "HTML-Misc" }, { "code": null, "e": 31044, "s": 31034, "text": "AngularJS" }, { "code": null, "e": 31049, "s": 31044, "text": "HTML" }, { "code": null, "e": 31066, "s": 31049, "text": "Web Technologies" }, { "code": null, "e": 31071, "s": 31066, "text": "HTML" }, { "code": null, "e": 31169, "s": 31071, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31204, "s": 31169, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 31239, "s": 31204, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 31263, "s": 31239, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 31298, "s": 31263, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 31351, "s": 31298, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 31401, "s": 31351, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 31463, "s": 31401, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31511, "s": 31463, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 31571, "s": 31511, "text": "How to set the default value for an HTML <select> element ?" } ]
How to move MongoDB document from one collections to another ? - GeeksforGeeks
24 May, 2021 The following approach covers move MongoDB documents from one collection to another. With the help of mongoose, we will move a MongoDB document from one collection to another. Make sure that in the schema of both the collections all the fields are the same. Install mongoose: Step 1: You can visit the link Install mongoose to install the mongoose module. You can install this package by using this command. npm install mongoose Step 2: Now you can import the mongoose module in your file using: const mongoose = require('mongoose'); Database: We already have documents in our Source and Destination collection before moving as shown below: Source Collection before moving: Our source collection before the movement will look like this. Source collection before moving Destination Collection before moving: Our destination collection before the movement will look like this. Destination collection before moving Implementation: Create a folder in which you can add two files model.js and index.js which are shown below: model.js: It contains schemas for the source collection and destination collection and exports models of both the schemas. index.js: It contains code for moving a document from the source schema to destination schema. index.js // Requiring moduleconst mongoose = require('mongoose'); // Importing models from model.jsconst { Source, Destination } = require('./model'); // Connecting to databasemongoose.connect('mongodb://localhost:27017/geeksforgeeks', { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true }); // Finding a doc in the source collection by any // field and moving it to the destination collectionSource.findOne({ field_2: "Nodejs" }) .then(doc => { console.log(doc); // Inserting the doc in destination collection Destination.insertMany([doc]) .then(d => { console.log("Saved Successfully"); }) .catch(error => { console.log(error); }) // Removing doc from the source collection Source.deleteOne({ field_2: doc.field_2 }) .then(d => { console.log("Removed succesfully") }) .catch(error => { console.log(error); }); }) .catch(error => { console.log(error);}) model.js // Requiring moduleconst mongoose = require('mongoose'); // Defining source schemaconst sourceSchema = new mongoose.Schema({ field_1: String, field_2: String}); // Defining destination schemaconst destinationSchema = new mongoose.Schema({ field_1: String, field_2: String}); // Creating model for both schemasconst Source = mongoose.model('source', sourceSchema);const Destination = mongoose.model( 'destination', destinationSchema); // Exporting our modalsmodule.exports = { Source, Destination} Run index.js using the command: node index.js Output: Output in the console after executing index.js Source Collection after moving: Our source collection after the movement will look like this. Source Collection after moving Destination Collection after moving: Our destination collection after the movement will look like this. Destination Collection after moving MongoDB-method Node.js-Methods NodeJS-Questions Picked MongoDB Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect MongoDB with ReactJS ? MongoDB - limit() Method MongoDB - FindOne() Method Create user and add role in MongoDB MongoDB - sort() Method Installation of Node.js on Linux How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method Node.js fs.readFile() Method
[ { "code": null, "e": 25779, "s": 25751, "text": "\n24 May, 2021" }, { "code": null, "e": 26037, "s": 25779, "text": "The following approach covers move MongoDB documents from one collection to another. With the help of mongoose, we will move a MongoDB document from one collection to another. Make sure that in the schema of both the collections all the fields are the same." }, { "code": null, "e": 26055, "s": 26037, "text": "Install mongoose:" }, { "code": null, "e": 26187, "s": 26055, "text": "Step 1: You can visit the link Install mongoose to install the mongoose module. You can install this package by using this command." }, { "code": null, "e": 26208, "s": 26187, "text": "npm install mongoose" }, { "code": null, "e": 26275, "s": 26208, "text": "Step 2: Now you can import the mongoose module in your file using:" }, { "code": null, "e": 26313, "s": 26275, "text": "const mongoose = require('mongoose');" }, { "code": null, "e": 26420, "s": 26313, "text": "Database: We already have documents in our Source and Destination collection before moving as shown below:" }, { "code": null, "e": 26516, "s": 26420, "text": "Source Collection before moving: Our source collection before the movement will look like this." }, { "code": null, "e": 26548, "s": 26516, "text": "Source collection before moving" }, { "code": null, "e": 26654, "s": 26548, "text": "Destination Collection before moving: Our destination collection before the movement will look like this." }, { "code": null, "e": 26691, "s": 26654, "text": "Destination collection before moving" }, { "code": null, "e": 26707, "s": 26691, "text": "Implementation:" }, { "code": null, "e": 26799, "s": 26707, "text": "Create a folder in which you can add two files model.js and index.js which are shown below:" }, { "code": null, "e": 26922, "s": 26799, "text": "model.js: It contains schemas for the source collection and destination collection and exports models of both the schemas." }, { "code": null, "e": 27017, "s": 26922, "text": "index.js: It contains code for moving a document from the source schema to destination schema." }, { "code": null, "e": 27026, "s": 27017, "text": "index.js" }, { "code": "// Requiring moduleconst mongoose = require('mongoose'); // Importing models from model.jsconst { Source, Destination } = require('./model'); // Connecting to databasemongoose.connect('mongodb://localhost:27017/geeksforgeeks', { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true }); // Finding a doc in the source collection by any // field and moving it to the destination collectionSource.findOne({ field_2: \"Nodejs\" }) .then(doc => { console.log(doc); // Inserting the doc in destination collection Destination.insertMany([doc]) .then(d => { console.log(\"Saved Successfully\"); }) .catch(error => { console.log(error); }) // Removing doc from the source collection Source.deleteOne({ field_2: doc.field_2 }) .then(d => { console.log(\"Removed succesfully\") }) .catch(error => { console.log(error); }); }) .catch(error => { console.log(error);})", "e": 28157, "s": 27026, "text": null }, { "code": null, "e": 28166, "s": 28157, "text": "model.js" }, { "code": "// Requiring moduleconst mongoose = require('mongoose'); // Defining source schemaconst sourceSchema = new mongoose.Schema({ field_1: String, field_2: String}); // Defining destination schemaconst destinationSchema = new mongoose.Schema({ field_1: String, field_2: String}); // Creating model for both schemasconst Source = mongoose.model('source', sourceSchema);const Destination = mongoose.model( 'destination', destinationSchema); // Exporting our modalsmodule.exports = { Source, Destination}", "e": 28685, "s": 28166, "text": null }, { "code": null, "e": 28718, "s": 28685, "text": "Run index.js using the command: " }, { "code": null, "e": 28732, "s": 28718, "text": "node index.js" }, { "code": null, "e": 28740, "s": 28732, "text": "Output:" }, { "code": null, "e": 28787, "s": 28740, "text": "Output in the console after executing index.js" }, { "code": null, "e": 28881, "s": 28787, "text": "Source Collection after moving: Our source collection after the movement will look like this." }, { "code": null, "e": 28912, "s": 28881, "text": "Source Collection after moving" }, { "code": null, "e": 29016, "s": 28912, "text": "Destination Collection after moving: Our destination collection after the movement will look like this." }, { "code": null, "e": 29052, "s": 29016, "text": "Destination Collection after moving" }, { "code": null, "e": 29067, "s": 29052, "text": "MongoDB-method" }, { "code": null, "e": 29083, "s": 29067, "text": "Node.js-Methods" }, { "code": null, "e": 29100, "s": 29083, "text": "NodeJS-Questions" }, { "code": null, "e": 29107, "s": 29100, "text": "Picked" }, { "code": null, "e": 29115, "s": 29107, "text": "MongoDB" }, { "code": null, "e": 29123, "s": 29115, "text": "Node.js" }, { "code": null, "e": 29140, "s": 29123, "text": "Web Technologies" }, { "code": null, "e": 29238, "s": 29140, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29276, "s": 29238, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 29301, "s": 29276, "text": "MongoDB - limit() Method" }, { "code": null, "e": 29328, "s": 29301, "text": "MongoDB - FindOne() Method" }, { "code": null, "e": 29364, "s": 29328, "text": "Create user and add role in MongoDB" }, { "code": null, "e": 29388, "s": 29364, "text": "MongoDB - sort() Method" }, { "code": null, "e": 29421, "s": 29388, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29469, "s": 29421, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 29502, "s": 29469, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 29532, "s": 29502, "text": "Node.js fs.writeFile() Method" } ]
Object Equality in Scala - GeeksforGeeks
14 Aug, 2021 In programing language, Comparing two values for equality is ubiquitous. We define an equals method for a Scala class so we can compare object instances to each other. In Scala, equality method signifying object identity, however, it’s not used much. In scala, Three different equality methods available – The equals Method The == and != Methods The ne and eq Methods Note: eq behave same as the == operator behaves in Java, C++, and C#, but not == in Ruby. The ne method is the negation of eq, i.e., it is equivalent to !(x eq y). In Java, C++, and C# the == operator tests for reference, not value equality. In contrast, Ruby’s == operator tests for value equality. But in Scala, == is testing for value equality.Let’s understand with example.Example : Scala // Scala program of Equals // Creating a case class of// Subjectcase class Subject (LanguageName:String, TopicName:String) // Creating objectobject GFG{ // Main method def main(args: Array[String]) { // Creating objects var x = Subject("Scala", "Equality") var y = Subject("Scala", "Equality") var z = Subject("Java", "Array") // Displays true if instances // are equal else false println(x.equals(y)) println(x.equals(z)) println(y == z) }} Output: true false false equals Method: The equals method used to tests value equality. if x equals y is true if both x and y have the same value. They do not need to refer to the identical instance. Hence, the equals method in Java and equals method in Scala behaves same. The == and != Methods: While == is an operator in several languages, Scala reserved The == equality for the natural equality of every type. it’s a method in Scala, defined as final in Any. value equality will be tested by this. Here, x == y is true if both x and y have the same value. ne and eq Methods: Reference equality will be tested by eq method. Here, x eq y is true if both x and y point to the same location in memory or x and y reference the same object. These methods are only defined for AnyRef. If two object are equal according to the equals method, then calling the hash code method on each of the two objects must produce the same integer result. equals (and, ==) is by default the same as eq, but we can change its behavior by overriding the equals method in the classes we define. Scala treats == as if it were defined as follows in class Any: Below is the example of equals method and corresponding hashCode method:Example : Scala // Scala program to illustrate how// hashCode() and equals() methods work // Creating classclass Subject (name: String, article: Int){ // Defining canEqual method def canEqual(a: Any) = a.isInstanceOf[Subject] // Defining equals method with override keyword override def equals(that: Any): Boolean = that match { case that: Subject => that.canEqual(this) && this.hashCode == that.hashCode case _ => false } // Defining hashcode method override def hashCode: Int = { val prime = 31 var result = 1 result = prime * result + article; result = prime * result + (if (name == null) 0 else name.hashCode) return result }} // Driver codeobject GFG{ // Main method def main(args: Array[String]) { // Creating the Objects of Geek class. // Subject g1 = new Subject("aa", 1); val g1 = new Subject("Scala", 28) val g2 = new Subject("Scala", 28); // Comparing above created Objects. if(g1.hashCode() == g2.hashCode()) { if(g1.equals(g2)) println("Both Objects are equal. "); else println("Both Objects are not equal. "); } else println("Both Objects are not equal. "); }} Output: Both Objects are equal. In above example, a modified version of a hashCode method that Eclipse generated for a similar Java class. It also uses a canEqual method. With the equals method defined, we can compare instances of a Subject with == . ruhelaa48 Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Class and Object in Scala Scala Lists Scala Tutorial – Learn Scala with Step By Step Guide Operators in Scala Inheritance in Scala Scala Constructors Scala String substring() method with example Scala | Arrays How to get the first element of List in Scala Lambda Expression in Scala
[ { "code": null, "e": 25081, "s": 25053, "text": "\n14 Aug, 2021" }, { "code": null, "e": 25388, "s": 25081, "text": "In programing language, Comparing two values for equality is ubiquitous. We define an equals method for a Scala class so we can compare object instances to each other. In Scala, equality method signifying object identity, however, it’s not used much. In scala, Three different equality methods available – " }, { "code": null, "e": 25406, "s": 25388, "text": "The equals Method" }, { "code": null, "e": 25428, "s": 25406, "text": "The == and != Methods" }, { "code": null, "e": 25450, "s": 25428, "text": "The ne and eq Methods" }, { "code": null, "e": 25838, "s": 25450, "text": "Note: eq behave same as the == operator behaves in Java, C++, and C#, but not == in Ruby. The ne method is the negation of eq, i.e., it is equivalent to !(x eq y). In Java, C++, and C# the == operator tests for reference, not value equality. In contrast, Ruby’s == operator tests for value equality. But in Scala, == is testing for value equality.Let’s understand with example.Example : " }, { "code": null, "e": 25844, "s": 25838, "text": "Scala" }, { "code": "// Scala program of Equals // Creating a case class of// Subjectcase class Subject (LanguageName:String, TopicName:String) // Creating objectobject GFG{ // Main method def main(args: Array[String]) { // Creating objects var x = Subject(\"Scala\", \"Equality\") var y = Subject(\"Scala\", \"Equality\") var z = Subject(\"Java\", \"Array\") // Displays true if instances // are equal else false println(x.equals(y)) println(x.equals(z)) println(y == z) }}", "e": 26383, "s": 25844, "text": null }, { "code": null, "e": 26392, "s": 26383, "text": "Output: " }, { "code": null, "e": 26409, "s": 26392, "text": "true\nfalse\nfalse" }, { "code": null, "e": 26658, "s": 26409, "text": "equals Method: The equals method used to tests value equality. if x equals y is true if both x and y have the same value. They do not need to refer to the identical instance. Hence, the equals method in Java and equals method in Scala behaves same." }, { "code": null, "e": 26944, "s": 26658, "text": "The == and != Methods: While == is an operator in several languages, Scala reserved The == equality for the natural equality of every type. it’s a method in Scala, defined as final in Any. value equality will be tested by this. Here, x == y is true if both x and y have the same value." }, { "code": null, "e": 27166, "s": 26944, "text": "ne and eq Methods: Reference equality will be tested by eq method. Here, x eq y is true if both x and y point to the same location in memory or x and y reference the same object. These methods are only defined for AnyRef." }, { "code": null, "e": 27603, "s": 27166, "text": "If two object are equal according to the equals method, then calling the hash code method on each of the two objects must produce the same integer result. equals (and, ==) is by default the same as eq, but we can change its behavior by overriding the equals method in the classes we define. Scala treats == as if it were defined as follows in class Any: Below is the example of equals method and corresponding hashCode method:Example : " }, { "code": null, "e": 27609, "s": 27603, "text": "Scala" }, { "code": "// Scala program to illustrate how// hashCode() and equals() methods work // Creating classclass Subject (name: String, article: Int){ // Defining canEqual method def canEqual(a: Any) = a.isInstanceOf[Subject] // Defining equals method with override keyword override def equals(that: Any): Boolean = that match { case that: Subject => that.canEqual(this) && this.hashCode == that.hashCode case _ => false } // Defining hashcode method override def hashCode: Int = { val prime = 31 var result = 1 result = prime * result + article; result = prime * result + (if (name == null) 0 else name.hashCode) return result }} // Driver codeobject GFG{ // Main method def main(args: Array[String]) { // Creating the Objects of Geek class. // Subject g1 = new Subject(\"aa\", 1); val g1 = new Subject(\"Scala\", 28) val g2 = new Subject(\"Scala\", 28); // Comparing above created Objects. if(g1.hashCode() == g2.hashCode()) { if(g1.equals(g2)) println(\"Both Objects are equal. \"); else println(\"Both Objects are not equal. \"); } else println(\"Both Objects are not equal. \"); }}", "e": 28963, "s": 27609, "text": null }, { "code": null, "e": 28973, "s": 28963, "text": "Output: " }, { "code": null, "e": 28998, "s": 28973, "text": "Both Objects are equal. " }, { "code": null, "e": 29217, "s": 28998, "text": "In above example, a modified version of a hashCode method that Eclipse generated for a similar Java class. It also uses a canEqual method. With the equals method defined, we can compare instances of a Subject with == ." }, { "code": null, "e": 29227, "s": 29217, "text": "ruhelaa48" }, { "code": null, "e": 29233, "s": 29227, "text": "Scala" }, { "code": null, "e": 29331, "s": 29233, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29357, "s": 29331, "text": "Class and Object in Scala" }, { "code": null, "e": 29369, "s": 29357, "text": "Scala Lists" }, { "code": null, "e": 29422, "s": 29369, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 29441, "s": 29422, "text": "Operators in Scala" }, { "code": null, "e": 29462, "s": 29441, "text": "Inheritance in Scala" }, { "code": null, "e": 29481, "s": 29462, "text": "Scala Constructors" }, { "code": null, "e": 29526, "s": 29481, "text": "Scala String substring() method with example" }, { "code": null, "e": 29541, "s": 29526, "text": "Scala | Arrays" }, { "code": null, "e": 29587, "s": 29541, "text": "How to get the first element of List in Scala" } ]
How to perform a real time search and filter on a HTML table? - GeeksforGeeks
31 Oct, 2019 Here, we learn how to perform a real-time search and filter on an HTML table. When a word is entered, all rows of the table will be searched (except the table head) and the rows containing the matching word will be displayed. For this, we can use JQuery methods. filter(): This method is used to filter out all the elements that do not match the selected criteria and those matches will be returned. Reduce the set of matched elements to those that match the selector or pass the function’s test. toggle(): This method is used to check the visibility of selected elements to toggle between hide() and show() for the selected elements. Display or hide the matched elements. In the below example, the search value entered in the search box is stored in the variable named “value” and converted to lowercase since we are doing case insensitive search. After that, we search each row in the table using the filter() function and display the row where the string stored in variable “value” is found. The toggle() method is used to show the rows containing the search word and hide others. The indexOf(value) returns -1 if the word is not found in the row. Example: Below example illustrates the use of filter() and toggle() function to perform a realtime search and filter on HTML table. <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 50%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3> perform a real time search and filter on a HTML table </h3> <b>Search the table for Course, Fees or Type: <input id="gfg" type="text" placeholder="Search here"> </b> <br> <br> <table> <tr> <th>Course</th> <th>Duration</th> <th>Type</th> </tr> <tbody id="geeks"> <tr> <td>C++ STL</td> <td>1499</td> <td>Online Classes </td> </tr> <tr> <td>DSA Foundation</td> <td>7999</td> <td>Regular Classes</td> </tr> <tr> <td>Geeks Classes</td> <td>10799</td> <td>Weekend Classes</td> </tr> <tr> <td>Placement 100</td> <td>9999</td> <td>Online Classes</td> </tr> </tbody> </table> <script> $(document).ready(function() { $("#gfg").on("keyup", function() { var value = $(this).val().toLowerCase(); $("#geeks tr").filter(function() { $(this).toggle($(this).text() .toLowerCase().indexOf(value) > -1) }); }); }); </script> </center> </body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. jQuery-Misc Picked HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) How to Insert Form Data into Database using PHP ? Types of CSS (Cascading Style Sheet) HTML | <img> align Attribute Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26765, "s": 26737, "text": "\n31 Oct, 2019" }, { "code": null, "e": 27028, "s": 26765, "text": "Here, we learn how to perform a real-time search and filter on an HTML table. When a word is entered, all rows of the table will be searched (except the table head) and the rows containing the matching word will be displayed. For this, we can use JQuery methods." }, { "code": null, "e": 27262, "s": 27028, "text": "filter(): This method is used to filter out all the elements that do not match the selected criteria and those matches will be returned. Reduce the set of matched elements to those that match the selector or pass the function’s test." }, { "code": null, "e": 27438, "s": 27262, "text": "toggle(): This method is used to check the visibility of selected elements to toggle between hide() and show() for the selected elements. Display or hide the matched elements." }, { "code": null, "e": 27916, "s": 27438, "text": "In the below example, the search value entered in the search box is stored in the variable named “value” and converted to lowercase since we are doing case insensitive search. After that, we search each row in the table using the filter() function and display the row where the string stored in variable “value” is found. The toggle() method is used to show the rows containing the search word and hide others. The indexOf(value) returns -1 if the word is not found in the row." }, { "code": null, "e": 28048, "s": 27916, "text": "Example: Below example illustrates the use of filter() and toggle() function to perform a realtime search and filter on HTML table." }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 50%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3> perform a real time search and filter on a HTML table </h3> <b>Search the table for Course, Fees or Type: <input id=\"gfg\" type=\"text\" placeholder=\"Search here\"> </b> <br> <br> <table> <tr> <th>Course</th> <th>Duration</th> <th>Type</th> </tr> <tbody id=\"geeks\"> <tr> <td>C++ STL</td> <td>1499</td> <td>Online Classes </td> </tr> <tr> <td>DSA Foundation</td> <td>7999</td> <td>Regular Classes</td> </tr> <tr> <td>Geeks Classes</td> <td>10799</td> <td>Weekend Classes</td> </tr> <tr> <td>Placement 100</td> <td>9999</td> <td>Online Classes</td> </tr> </tbody> </table> <script> $(document).ready(function() { $(\"#gfg\").on(\"keyup\", function() { var value = $(this).val().toLowerCase(); $(\"#geeks tr\").filter(function() { $(this).toggle($(this).text() .toLowerCase().indexOf(value) > -1) }); }); }); </script> </center> </body> </html>", "e": 30143, "s": 28048, "text": null }, { "code": null, "e": 30151, "s": 30143, "text": "Output:" }, { "code": null, "e": 30288, "s": 30151, "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": 30300, "s": 30288, "text": "jQuery-Misc" }, { "code": null, "e": 30307, "s": 30300, "text": "Picked" }, { "code": null, "e": 30312, "s": 30307, "text": "HTML" }, { "code": null, "e": 30329, "s": 30312, "text": "Web Technologies" }, { "code": null, "e": 30356, "s": 30329, "text": "Web technologies Questions" }, { "code": null, "e": 30361, "s": 30356, "text": "HTML" }, { "code": null, "e": 30459, "s": 30361, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30507, "s": 30459, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 30531, "s": 30507, "text": "REST API (Introduction)" }, { "code": null, "e": 30581, "s": 30531, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 30618, "s": 30581, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 30647, "s": 30618, "text": "HTML | <img> align Attribute" }, { "code": null, "e": 30687, "s": 30647, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30720, "s": 30687, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30765, "s": 30720, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30808, "s": 30765, "text": "How to fetch data from an API in ReactJS ?" } ]
C | Arrays | Question 1 - GeeksforGeeks
10 Jan, 2013 Predict the output of below program: #include <stdio.h> int main(){ int arr[5]; // Assume that base address of arr is 2000 and size of integer // is 32 bit arr++; printf("%u", arr); return 0;} (A) 2002(B) 2004(C) 2020(D) lvalue requiredAnswer: (D)Explanation: Array name in C is implemented by a constant pointer. It is not possible to apply increment and decrement on constant types. Arrays C-Arrays C Language C Quiz Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. std::string class in C++ TCP Server-Client implementation in C Structures in C Exception Handling in C++ Memory Layout of C Programs Compiling a C program:- Behind the Scenes Operator Precedence and Associativity in C C | File Handling | Question 1 C | Misc | Question 7 Output of C programs | Set 64 (Pointers)
[ { "code": null, "e": 25277, "s": 25249, "text": "\n10 Jan, 2013" }, { "code": null, "e": 25314, "s": 25277, "text": "Predict the output of below program:" }, { "code": "#include <stdio.h> int main(){ int arr[5]; // Assume that base address of arr is 2000 and size of integer // is 32 bit arr++; printf(\"%u\", arr); return 0;}", "e": 25505, "s": 25314, "text": null }, { "code": null, "e": 25697, "s": 25505, "text": "(A) 2002(B) 2004(C) 2020(D) lvalue requiredAnswer: (D)Explanation: Array name in C is implemented by a constant pointer. It is not possible to apply increment and decrement on constant types." }, { "code": null, "e": 25704, "s": 25697, "text": "Arrays" }, { "code": null, "e": 25713, "s": 25704, "text": "C-Arrays" }, { "code": null, "e": 25724, "s": 25713, "text": "C Language" }, { "code": null, "e": 25731, "s": 25724, "text": "C Quiz" }, { "code": null, "e": 25738, "s": 25731, "text": "Arrays" }, { "code": null, "e": 25836, "s": 25738, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25861, "s": 25836, "text": "std::string class in C++" }, { "code": null, "e": 25899, "s": 25861, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 25915, "s": 25899, "text": "Structures in C" }, { "code": null, "e": 25941, "s": 25915, "text": "Exception Handling in C++" }, { "code": null, "e": 25969, "s": 25941, "text": "Memory Layout of C Programs" }, { "code": null, "e": 26011, "s": 25969, "text": "Compiling a C program:- Behind the Scenes" }, { "code": null, "e": 26054, "s": 26011, "text": "Operator Precedence and Associativity in C" }, { "code": null, "e": 26085, "s": 26054, "text": "C | File Handling | Question 1" }, { "code": null, "e": 26107, "s": 26085, "text": "C | Misc | Question 7" } ]
Find number of pairs (x, y) in an Array such that x^y > y^x | Set 2 - GeeksforGeeks
04 May, 2021 Given two arrays X[] and Y[] of positive integers, find the number of pairs such that x^y > y^x where x is an element from X[] and y is an element from Y[].Examples: Input: X[] = {2, 1, 6}, Y = {1, 5} Output: 3 Explanation: The 3 possible pairs are: (2, 1) => 21 > 12 (2, 5) => 25 (= 32) > 52 (= 25) (6, 1) => 61 > 16Input: X[] = {10, 19, 18}, Y[] = {11, 15, 9} Output: 2 Explanation: The possible pairs are (10, 11) and (10, 15). For Naive Approach [ O(M*N) ] and [ O(N logN + M logN) ] approach, please refer Set 1 of this article.Efficient Approach: The above two approaches can be further optimized in O(N) time complexity.This approach uses the concept of suffix sum to find the solution. We can observe that if y > x, then x^y > y^x. However, the following base cases and exceptions need to be considered: If x = 0, then count of possible y is 0. If x = 1, then count of possible y is the frequency of 0’s is the Y[] is the required answer. If x = 2, 23 < 32 and 24 = 42. Hence, for x = 2, we cannot have a valid pair with y = {2, 3, 4}. Hence, the sum of frequencies of 0, 1, and all numbers gt 4 in Y[] gives us the count of required valid pairs If x = 3, the sum of all frequencies except 3 in Y[] gives us the required count of possible pairs. Follow the steps below to solve the problem: Store the frequencies of every element of Y array. Store the suffix sum of the array containing the frequencies. For every element x in X[] which does not belong to any of the base cases, the possible number of y’s will be suffix[x+1] + count of 0’s in Y[] + count of 1’s in Y[]. For the base cases, compute the pairs accordingly as discussed above. Print the total count of pairs. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to finds the number of// pairs (x, y) from X[] and Y[]// such that x^y > y^x #include <bits/stdc++.h>using namespace std; // Function to return the count of pairsint countPairs(int X[], int Y[], int m, int n){ vector<int> suffix(1005); long long total_pairs = 0; for (int i = 0; i < n; i++) suffix[Y[i]]++; // Compute suffix sums till i = 3 for (int i = 1e3; i >= 3; i--) suffix[i] += suffix[i + 1]; for (int i = 0; i < m; i++) { // Base Case: x = 0 if (X[i] == 0) // No valid pairs continue; // Base Case: x = 1 else if (X[i] == 1) { // Store the count of 0's total_pairs += suffix[0]; continue; } // Base Case: x = 2 else if (X[i] == 2) // Store suffix sum upto 5 total_pairs += suffix[5]; // Base Case: x = 3 else if (X[i] == 3) // Store count of 2 and // suffix sum upto 4 total_pairs += suffix[2] + suffix[4]; // For all other values of x else total_pairs += suffix[X[i] + 1]; // For all x >=2, every y = 0 // and every y = 1 makes a valid pair total_pairs += suffix[0] + suffix[1]; } // Return the count of pairs return total_pairs;} // Driver Programint main(){ int X[] = { 10, 19, 18 }; int Y[] = { 11, 15, 9 }; int m = sizeof(X) / sizeof(X[0]); int n = sizeof(Y) / sizeof(Y[0]); cout << countPairs(X, Y, m, n); return 0;} // Java program to finds the number of// pairs (x, y) from X[] and Y[]// such that x^y > y^xclass GFG{ // Function to return the count of pairsstatic int countPairs(int X[], int Y[], int m, int n){ int []suffix = new int[1005]; long total_pairs = 0; for(int i = 0; i < n; i++) suffix[Y[i]]++; // Compute suffix sums till i = 3 for(int i = (int)1e3; i >= 3; i--) suffix[i] += suffix[i + 1]; for(int i = 0; i < m; i++) { // Base Case: x = 0 if (X[i] == 0) // No valid pairs continue; // Base Case: x = 1 else if (X[i] == 1) { // Store the count of 0's total_pairs += suffix[0]; continue; } // Base Case: x = 2 else if (X[i] == 2) // Store suffix sum upto 5 total_pairs += suffix[5]; // Base Case: x = 3 else if (X[i] == 3) // Store count of 2 and // suffix sum upto 4 total_pairs += suffix[2] + suffix[4]; // For all other values of x else total_pairs += suffix[X[i] + 1]; // For all x >=2, every y = 0 // and every y = 1 makes a valid pair total_pairs += suffix[0] + suffix[1]; } // Return the count of pairs return (int) total_pairs;} // Driver codepublic static void main(String[] args){ int X[] = { 10, 19, 18 }; int Y[] = { 11, 15, 9 }; int m = X.length; int n = Y.length; System.out.print(countPairs(X, Y, m, n));}} // This code is contributed by 29AjayKumar # Python3 program to finds the number of# pairs (x, y) from X[] and Y[]# such that x^y > y^x # Function to return the count of pairsdef countPairs(X, Y, m, n): suffix = [0] * 1005 total_pairs = 0 for i in range(n): suffix[Y[i]] += 1 # Compute suffix sums till i = 3 for i in range(int(1e3), 2, -1 ): suffix[i] += suffix[i + 1] for i in range(m): # Base Case: x = 0 if(X[i] == 0): # No valid pairs continue # Base Case: x = 1 elif(X[i] == 1): # Store the count of 0's total_pairs += suffix[0] continue # Base Case: x = 2 elif(X[i] == 2): # Store suffix sum upto 5 total_pairs += suffix[5] # Base Case: x = 3 elif(X[i] == 3): # Store count of 2 and # suffix sum upto 4 total_pairs += (suffix[2] + suffix[4]) # For all other values of x else: total_pairs += suffix[X[i] + 1] # For all x >=2, every y = 0 # and every y = 1 makes a valid pair total_pairs += suffix[0] + suffix[1] # Return the count of pairs return total_pairs # Driver codeif __name__ == '__main__': X = [ 10, 19, 18 ] Y = [ 11, 15, 9 ] m = len(X) n = len(Y) print(countPairs(X, Y, m, n)) # This code is contributed by Shivam Singh // C# program to finds the number of// pairs (x, y) from []X and []Y// such that x^y > y^xusing System;class GFG{ // Function to return the count of pairs static int countPairs(int[] X, int[] Y, int m, int n) { int[] suffix = new int[1005]; long total_pairs = 0; for (int i = 0; i < n; i++) suffix[Y[i]]++; // Compute suffix sums till i = 3 for (int i = (int)1e3; i >= 3; i--) suffix[i] += suffix[i + 1]; for (int i = 0; i < m; i++) { // Base Case: x = 0 if (X[i] == 0) // No valid pairs continue; // Base Case: x = 1 else if (X[i] == 1) { // Store the count of 0's total_pairs += suffix[0]; continue; } // Base Case: x = 2 else if (X[i] == 2) // Store suffix sum upto 5 total_pairs += suffix[5]; // Base Case: x = 3 else if (X[i] == 3) // Store count of 2 and // suffix sum upto 4 total_pairs += suffix[2] + suffix[4]; // For all other values of x else total_pairs += suffix[X[i] + 1]; // For all x >=2, every y = 0 // and every y = 1 makes a valid pair total_pairs += suffix[0] + suffix[1]; } // Return the count of pairs return (int)total_pairs; } // Driver code public static void Main(String[] args) { int[] X = {10, 19, 18}; int[] Y = {11, 15, 9}; int m = X.Length; int n = Y.Length; Console.Write(countPairs(X, Y, m, n)); }} // This code is contributed by Amit Katiyar <script> // JavaScript program to implement// the above approach // Function to return the count of pairsfunction countPairs(X, Y, m, n){ let suffix = Array.from({length: 1005}, (_, i) => 0); let total_pairs = 0; for(let i = 0; i < n; i++) suffix[Y[i]]++; // Compute suffix sums till i = 3 for(let i = 1e3; i >= 3; i--) suffix[i] += suffix[i + 1]; for(let i = 0; i < m; i++) { // Base Case: x = 0 if (X[i] == 0) // No valid pairs continue; // Base Case: x = 1 else if (X[i] == 1) { // Store the count of 0's total_pairs += suffix[0]; continue; } // Base Case: x = 2 else if (X[i] == 2) // Store suffix sum upto 5 total_pairs += suffix[5]; // Base Case: x = 3 else if (X[i] == 3) // Store count of 2 and // suffix sum upto 4 total_pairs += suffix[2] + suffix[4]; // For all other values of x else total_pairs += suffix[X[i] + 1]; // For all x >=2, every y = 0 // and every y = 1 makes a valid pair total_pairs += suffix[0] + suffix[1]; } // Return the count of pairs return total_pairs;} // Driver code let X = [ 10, 19, 18 ]; let Y = [ 11, 15, 9 ]; let m = X.length; let n = Y.length; document.write(countPairs(X, Y, m, n)); // This code is contributed by susmitakundugoaldanga.</script> 2 Time Complexity: O(N) Auxiliary Space: O(1) SHIVAMSINGH67 29AjayKumar amit143katiyar susmitakundugoaldanga frequency-counting maths-power Suffix Arrays Greedy Mathematical Searching Arrays Searching Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Write a program to print all permutations of a given string Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 26065, "s": 26037, "text": "\n04 May, 2021" }, { "code": null, "e": 26231, "s": 26065, "text": "Given two arrays X[] and Y[] of positive integers, find the number of pairs such that x^y > y^x where x is an element from X[] and y is an element from Y[].Examples:" }, { "code": null, "e": 26496, "s": 26231, "text": "Input: X[] = {2, 1, 6}, Y = {1, 5} Output: 3 Explanation: The 3 possible pairs are: (2, 1) => 21 > 12 (2, 5) => 25 (= 32) > 52 (= 25) (6, 1) => 61 > 16Input: X[] = {10, 19, 18}, Y[] = {11, 15, 9} Output: 2 Explanation: The possible pairs are (10, 11) and (10, 15)." }, { "code": null, "e": 26877, "s": 26496, "text": "For Naive Approach [ O(M*N) ] and [ O(N logN + M logN) ] approach, please refer Set 1 of this article.Efficient Approach: The above two approaches can be further optimized in O(N) time complexity.This approach uses the concept of suffix sum to find the solution. We can observe that if y > x, then x^y > y^x. However, the following base cases and exceptions need to be considered:" }, { "code": null, "e": 26918, "s": 26877, "text": "If x = 0, then count of possible y is 0." }, { "code": null, "e": 27012, "s": 26918, "text": "If x = 1, then count of possible y is the frequency of 0’s is the Y[] is the required answer." }, { "code": null, "e": 27219, "s": 27012, "text": "If x = 2, 23 < 32 and 24 = 42. Hence, for x = 2, we cannot have a valid pair with y = {2, 3, 4}. Hence, the sum of frequencies of 0, 1, and all numbers gt 4 in Y[] gives us the count of required valid pairs" }, { "code": null, "e": 27319, "s": 27219, "text": "If x = 3, the sum of all frequencies except 3 in Y[] gives us the required count of possible pairs." }, { "code": null, "e": 27364, "s": 27319, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 27415, "s": 27364, "text": "Store the frequencies of every element of Y array." }, { "code": null, "e": 27477, "s": 27415, "text": "Store the suffix sum of the array containing the frequencies." }, { "code": null, "e": 27714, "s": 27477, "text": "For every element x in X[] which does not belong to any of the base cases, the possible number of y’s will be suffix[x+1] + count of 0’s in Y[] + count of 1’s in Y[]. For the base cases, compute the pairs accordingly as discussed above." }, { "code": null, "e": 27746, "s": 27714, "text": "Print the total count of pairs." }, { "code": null, "e": 27797, "s": 27746, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27801, "s": 27797, "text": "C++" }, { "code": null, "e": 27806, "s": 27801, "text": "Java" }, { "code": null, "e": 27814, "s": 27806, "text": "Python3" }, { "code": null, "e": 27817, "s": 27814, "text": "C#" }, { "code": null, "e": 27828, "s": 27817, "text": "Javascript" }, { "code": "// C++ program to finds the number of// pairs (x, y) from X[] and Y[]// such that x^y > y^x #include <bits/stdc++.h>using namespace std; // Function to return the count of pairsint countPairs(int X[], int Y[], int m, int n){ vector<int> suffix(1005); long long total_pairs = 0; for (int i = 0; i < n; i++) suffix[Y[i]]++; // Compute suffix sums till i = 3 for (int i = 1e3; i >= 3; i--) suffix[i] += suffix[i + 1]; for (int i = 0; i < m; i++) { // Base Case: x = 0 if (X[i] == 0) // No valid pairs continue; // Base Case: x = 1 else if (X[i] == 1) { // Store the count of 0's total_pairs += suffix[0]; continue; } // Base Case: x = 2 else if (X[i] == 2) // Store suffix sum upto 5 total_pairs += suffix[5]; // Base Case: x = 3 else if (X[i] == 3) // Store count of 2 and // suffix sum upto 4 total_pairs += suffix[2] + suffix[4]; // For all other values of x else total_pairs += suffix[X[i] + 1]; // For all x >=2, every y = 0 // and every y = 1 makes a valid pair total_pairs += suffix[0] + suffix[1]; } // Return the count of pairs return total_pairs;} // Driver Programint main(){ int X[] = { 10, 19, 18 }; int Y[] = { 11, 15, 9 }; int m = sizeof(X) / sizeof(X[0]); int n = sizeof(Y) / sizeof(Y[0]); cout << countPairs(X, Y, m, n); return 0;}", "e": 29408, "s": 27828, "text": null }, { "code": "// Java program to finds the number of// pairs (x, y) from X[] and Y[]// such that x^y > y^xclass GFG{ // Function to return the count of pairsstatic int countPairs(int X[], int Y[], int m, int n){ int []suffix = new int[1005]; long total_pairs = 0; for(int i = 0; i < n; i++) suffix[Y[i]]++; // Compute suffix sums till i = 3 for(int i = (int)1e3; i >= 3; i--) suffix[i] += suffix[i + 1]; for(int i = 0; i < m; i++) { // Base Case: x = 0 if (X[i] == 0) // No valid pairs continue; // Base Case: x = 1 else if (X[i] == 1) { // Store the count of 0's total_pairs += suffix[0]; continue; } // Base Case: x = 2 else if (X[i] == 2) // Store suffix sum upto 5 total_pairs += suffix[5]; // Base Case: x = 3 else if (X[i] == 3) // Store count of 2 and // suffix sum upto 4 total_pairs += suffix[2] + suffix[4]; // For all other values of x else total_pairs += suffix[X[i] + 1]; // For all x >=2, every y = 0 // and every y = 1 makes a valid pair total_pairs += suffix[0] + suffix[1]; } // Return the count of pairs return (int) total_pairs;} // Driver codepublic static void main(String[] args){ int X[] = { 10, 19, 18 }; int Y[] = { 11, 15, 9 }; int m = X.length; int n = Y.length; System.out.print(countPairs(X, Y, m, n));}} // This code is contributed by 29AjayKumar", "e": 31095, "s": 29408, "text": null }, { "code": "# Python3 program to finds the number of# pairs (x, y) from X[] and Y[]# such that x^y > y^x # Function to return the count of pairsdef countPairs(X, Y, m, n): suffix = [0] * 1005 total_pairs = 0 for i in range(n): suffix[Y[i]] += 1 # Compute suffix sums till i = 3 for i in range(int(1e3), 2, -1 ): suffix[i] += suffix[i + 1] for i in range(m): # Base Case: x = 0 if(X[i] == 0): # No valid pairs continue # Base Case: x = 1 elif(X[i] == 1): # Store the count of 0's total_pairs += suffix[0] continue # Base Case: x = 2 elif(X[i] == 2): # Store suffix sum upto 5 total_pairs += suffix[5] # Base Case: x = 3 elif(X[i] == 3): # Store count of 2 and # suffix sum upto 4 total_pairs += (suffix[2] + suffix[4]) # For all other values of x else: total_pairs += suffix[X[i] + 1] # For all x >=2, every y = 0 # and every y = 1 makes a valid pair total_pairs += suffix[0] + suffix[1] # Return the count of pairs return total_pairs # Driver codeif __name__ == '__main__': X = [ 10, 19, 18 ] Y = [ 11, 15, 9 ] m = len(X) n = len(Y) print(countPairs(X, Y, m, n)) # This code is contributed by Shivam Singh", "e": 32511, "s": 31095, "text": null }, { "code": "// C# program to finds the number of// pairs (x, y) from []X and []Y// such that x^y > y^xusing System;class GFG{ // Function to return the count of pairs static int countPairs(int[] X, int[] Y, int m, int n) { int[] suffix = new int[1005]; long total_pairs = 0; for (int i = 0; i < n; i++) suffix[Y[i]]++; // Compute suffix sums till i = 3 for (int i = (int)1e3; i >= 3; i--) suffix[i] += suffix[i + 1]; for (int i = 0; i < m; i++) { // Base Case: x = 0 if (X[i] == 0) // No valid pairs continue; // Base Case: x = 1 else if (X[i] == 1) { // Store the count of 0's total_pairs += suffix[0]; continue; } // Base Case: x = 2 else if (X[i] == 2) // Store suffix sum upto 5 total_pairs += suffix[5]; // Base Case: x = 3 else if (X[i] == 3) // Store count of 2 and // suffix sum upto 4 total_pairs += suffix[2] + suffix[4]; // For all other values of x else total_pairs += suffix[X[i] + 1]; // For all x >=2, every y = 0 // and every y = 1 makes a valid pair total_pairs += suffix[0] + suffix[1]; } // Return the count of pairs return (int)total_pairs; } // Driver code public static void Main(String[] args) { int[] X = {10, 19, 18}; int[] Y = {11, 15, 9}; int m = X.Length; int n = Y.Length; Console.Write(countPairs(X, Y, m, n)); }} // This code is contributed by Amit Katiyar", "e": 34283, "s": 32511, "text": null }, { "code": "<script> // JavaScript program to implement// the above approach // Function to return the count of pairsfunction countPairs(X, Y, m, n){ let suffix = Array.from({length: 1005}, (_, i) => 0); let total_pairs = 0; for(let i = 0; i < n; i++) suffix[Y[i]]++; // Compute suffix sums till i = 3 for(let i = 1e3; i >= 3; i--) suffix[i] += suffix[i + 1]; for(let i = 0; i < m; i++) { // Base Case: x = 0 if (X[i] == 0) // No valid pairs continue; // Base Case: x = 1 else if (X[i] == 1) { // Store the count of 0's total_pairs += suffix[0]; continue; } // Base Case: x = 2 else if (X[i] == 2) // Store suffix sum upto 5 total_pairs += suffix[5]; // Base Case: x = 3 else if (X[i] == 3) // Store count of 2 and // suffix sum upto 4 total_pairs += suffix[2] + suffix[4]; // For all other values of x else total_pairs += suffix[X[i] + 1]; // For all x >=2, every y = 0 // and every y = 1 makes a valid pair total_pairs += suffix[0] + suffix[1]; } // Return the count of pairs return total_pairs;} // Driver code let X = [ 10, 19, 18 ]; let Y = [ 11, 15, 9 ]; let m = X.length; let n = Y.length; document.write(countPairs(X, Y, m, n)); // This code is contributed by susmitakundugoaldanga.</script>", "e": 35888, "s": 34283, "text": null }, { "code": null, "e": 35890, "s": 35888, "text": "2" }, { "code": null, "e": 35934, "s": 35890, "text": "Time Complexity: O(N) Auxiliary Space: O(1)" }, { "code": null, "e": 35948, "s": 35934, "text": "SHIVAMSINGH67" }, { "code": null, "e": 35960, "s": 35948, "text": "29AjayKumar" }, { "code": null, "e": 35975, "s": 35960, "text": "amit143katiyar" }, { "code": null, "e": 35997, "s": 35975, "text": "susmitakundugoaldanga" }, { "code": null, "e": 36016, "s": 35997, "text": "frequency-counting" }, { "code": null, "e": 36028, "s": 36016, "text": "maths-power" }, { "code": null, "e": 36035, "s": 36028, "text": "Suffix" }, { "code": null, "e": 36042, "s": 36035, "text": "Arrays" }, { "code": null, "e": 36049, "s": 36042, "text": "Greedy" }, { "code": null, "e": 36062, "s": 36049, "text": "Mathematical" }, { "code": null, "e": 36072, "s": 36062, "text": "Searching" }, { "code": null, "e": 36079, "s": 36072, "text": "Arrays" }, { "code": null, "e": 36089, "s": 36079, "text": "Searching" }, { "code": null, "e": 36096, "s": 36089, "text": "Greedy" }, { "code": null, "e": 36109, "s": 36096, "text": "Mathematical" }, { "code": null, "e": 36207, "s": 36109, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36234, "s": 36207, "text": "Count pairs with given sum" }, { "code": null, "e": 36265, "s": 36234, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 36290, "s": 36265, "text": "Window Sliding Technique" }, { "code": null, "e": 36328, "s": 36290, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 36349, "s": 36328, "text": "Next Greater Element" }, { "code": null, "e": 36400, "s": 36349, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 36458, "s": 36400, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 36509, "s": 36458, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 36569, "s": 36509, "text": "Write a program to print all permutations of a given string" } ]
SQL Query to Convert UTC to Local Time Zone - GeeksforGeeks
19 May, 2021 In this article, we will cover how to convert UTC to the local time zone for the different times of UTC in the database. Now, let’s execute a query that converts the UTC to local time zone using MSSQL as our database in detail step-by-step. Step 1: Creating a database time_converter by using the following SQL query as follows. CREATE DATABASE time_converter; Step 2: Using the database time_converter using the following SQL query as follows. USE time_converter; Step3: Creating table times with 2 columns using the following SQL query as follows. Let us create a table with index and DATETIME as a datatype. CREATE TABLE times (Sno INT, date_time DATETIME); Step 4: To view the description of the tables in the database using the following SQL query as follows. EXEC sp_columns times; Step 5: Inserting rows into times table using the following SQL query as follows. INSERT INTO times VALUES (1,'2021-03-01 12:00:00'), (2,'2021-04-01 09:30:00'), (3,'2021-02-05 10:50:00'), (4,'2021-04-18 08:50:00'); Step 6: Viewing the table times after inserting rows by using the following SQL query as follows. SELECT * FROM times; Query 1: Query to convert current time from UTC to local IST (Indian Standard Time) Note: India’s time zone is 5hours and 30 minutes ahead of UTC. Syntax: SELECT colum_name, CONVERT(datetime, SWITCHOFFSET(CONVERT(DATETIMEOFFSET, column_name), DATENAME(TZOFFSET, SYSDATETIMEOFFSET()))) AS general_name SELECT CONVERT(datetime, SWITCHOFFSET(CONVERT(DATETIMEOFFSET, GETUTCDATE()), DATENAME(TZOFFSET, SYSDATETIMEOFFSET()))) AS LOCAL_IST; Here, the GETUTCDATE() function can be used to get the current date and time UTC. Using this query the UTC gets converted to local IST. Query 2: Query to convert all the times in times table to local IST from UTC. Method 1: In this method, the UTC times in the table get converted to local Indian standard time. To get the UTC converted to IST, UTC must be added with “+05:30” the same gets added in the output. Syntax: SELECT colum_name, CONVERT(datetime, SWITCHOFFSET(CONVERT(DATETIMEOFFSET, column_name), DATENAME(TZOFFSET, SYSDATETIMEOFFSET()))) AS general_name FROM table_name; SELECT date_time, CONVERT(datetime, SWITCHOFFSET(CONVERT(DATETIMEOFFSET, date_time), DATENAME(TZOFFSET, SYSDATETIMEOFFSET()))) AS LOCAL_IST FROM times; Method 2: In this method, the difference between the present date-time(GETDATE()) and UTC (GETUTCDATE()) date time gets added to the dates in date_time column. Syntax: SELECT column_name, DATEADD(MI, DATEDIFF(MI, GETUTCDATE(), GETDATE()), date_time) AS LOCAL_IST FROM times; SELECT date_time, DATEADD(MI, DATEDIFF(MI, GETUTCDATE(), GETDATE()), date_time) AS LOCAL_IST FROM times; Picked SQL-Query SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL using Python How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n19 May, 2021" }, { "code": null, "e": 25754, "s": 25513, "text": "In this article, we will cover how to convert UTC to the local time zone for the different times of UTC in the database. Now, let’s execute a query that converts the UTC to local time zone using MSSQL as our database in detail step-by-step." }, { "code": null, "e": 25842, "s": 25754, "text": "Step 1: Creating a database time_converter by using the following SQL query as follows." }, { "code": null, "e": 25874, "s": 25842, "text": "CREATE DATABASE time_converter;" }, { "code": null, "e": 25958, "s": 25874, "text": "Step 2: Using the database time_converter using the following SQL query as follows." }, { "code": null, "e": 25978, "s": 25958, "text": "USE time_converter;" }, { "code": null, "e": 26063, "s": 25978, "text": "Step3: Creating table times with 2 columns using the following SQL query as follows." }, { "code": null, "e": 26124, "s": 26063, "text": "Let us create a table with index and DATETIME as a datatype." }, { "code": null, "e": 26175, "s": 26124, "text": "CREATE TABLE times\n(Sno INT,\n date_time DATETIME);" }, { "code": null, "e": 26279, "s": 26175, "text": "Step 4: To view the description of the tables in the database using the following SQL query as follows." }, { "code": null, "e": 26302, "s": 26279, "text": "EXEC sp_columns times;" }, { "code": null, "e": 26384, "s": 26302, "text": "Step 5: Inserting rows into times table using the following SQL query as follows." }, { "code": null, "e": 26517, "s": 26384, "text": "INSERT INTO times VALUES\n(1,'2021-03-01 12:00:00'),\n(2,'2021-04-01 09:30:00'),\n(3,'2021-02-05 10:50:00'),\n(4,'2021-04-18 08:50:00');" }, { "code": null, "e": 26615, "s": 26517, "text": "Step 6: Viewing the table times after inserting rows by using the following SQL query as follows." }, { "code": null, "e": 26636, "s": 26615, "text": "SELECT * FROM times;" }, { "code": null, "e": 26721, "s": 26636, "text": "Query 1: Query to convert current time from UTC to local IST (Indian Standard Time) " }, { "code": null, "e": 26784, "s": 26721, "text": "Note: India’s time zone is 5hours and 30 minutes ahead of UTC." }, { "code": null, "e": 26793, "s": 26784, "text": "Syntax: " }, { "code": null, "e": 26942, "s": 26793, "text": "SELECT colum_name,\nCONVERT(datetime, \nSWITCHOFFSET(CONVERT(DATETIMEOFFSET, column_name), \nDATENAME(TZOFFSET, SYSDATETIMEOFFSET()))) \nAS general_name" }, { "code": null, "e": 27079, "s": 26942, "text": "SELECT \nCONVERT(datetime, \nSWITCHOFFSET(CONVERT(DATETIMEOFFSET, GETUTCDATE()), \nDATENAME(TZOFFSET, SYSDATETIMEOFFSET()))) \nAS LOCAL_IST;" }, { "code": null, "e": 27215, "s": 27079, "text": "Here, the GETUTCDATE() function can be used to get the current date and time UTC. Using this query the UTC gets converted to local IST." }, { "code": null, "e": 27293, "s": 27215, "text": "Query 2: Query to convert all the times in times table to local IST from UTC." }, { "code": null, "e": 27303, "s": 27293, "text": "Method 1:" }, { "code": null, "e": 27491, "s": 27303, "text": "In this method, the UTC times in the table get converted to local Indian standard time. To get the UTC converted to IST, UTC must be added with “+05:30” the same gets added in the output." }, { "code": null, "e": 27500, "s": 27491, "text": "Syntax: " }, { "code": null, "e": 27666, "s": 27500, "text": "SELECT colum_name,\nCONVERT(datetime, \nSWITCHOFFSET(CONVERT(DATETIMEOFFSET, column_name), \nDATENAME(TZOFFSET, SYSDATETIMEOFFSET()))) \nAS general_name\nFROM table_name;" }, { "code": null, "e": 27821, "s": 27666, "text": "SELECT date_time,\nCONVERT(datetime, \nSWITCHOFFSET(CONVERT(DATETIMEOFFSET, date_time), \nDATENAME(TZOFFSET, SYSDATETIMEOFFSET()))) \nAS LOCAL_IST\nFROM times;" }, { "code": null, "e": 27831, "s": 27821, "text": "Method 2:" }, { "code": null, "e": 27982, "s": 27831, "text": "In this method, the difference between the present date-time(GETDATE()) and UTC (GETUTCDATE()) date time gets added to the dates in date_time column. " }, { "code": null, "e": 27990, "s": 27982, "text": "Syntax:" }, { "code": null, "e": 28099, "s": 27990, "text": "SELECT \ncolumn_name,\nDATEADD(MI, DATEDIFF(MI, GETUTCDATE(), GETDATE()), date_time) \nAS LOCAL_IST\nFROM times;" }, { "code": null, "e": 28206, "s": 28099, "text": "SELECT date_time,\nDATEADD(MI, DATEDIFF(MI, GETUTCDATE(), GETDATE()), date_time) \nAS LOCAL_IST \nFROM times;" }, { "code": null, "e": 28213, "s": 28206, "text": "Picked" }, { "code": null, "e": 28223, "s": 28213, "text": "SQL-Query" }, { "code": null, "e": 28227, "s": 28223, "text": "SQL" }, { "code": null, "e": 28231, "s": 28227, "text": "SQL" }, { "code": null, "e": 28329, "s": 28231, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28395, "s": 28329, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 28410, "s": 28395, "text": "SQL | Subquery" }, { "code": null, "e": 28467, "s": 28410, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 28499, "s": 28467, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 28577, "s": 28499, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 28613, "s": 28577, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 28630, "s": 28613, "text": "SQL using Python" }, { "code": null, "e": 28696, "s": 28630, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 28758, "s": 28696, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
Operations on Python Counter - GeeksforGeeks
18 Dec, 2021 The counter can be used to calculate the frequency in a list or in a string because as any list or string is passed as input, it returns output as a dictionary having keys are the unique elements of the list and values are the corresponding frequencies of the elements. In the code given below, Counter from Collection Python library is imported to find the frequency of every unique character occurring in this string, By using Counter on the list, the frequency of each unique elements present in the list can also be found. Python3 # Write Python3 code here# Counter used in string to find frequencies of all its unique Characters from collections import Counters1 ='aabbbcccdeff'c1 = Counter(s1)print("c1 :", c1) # Counter used in List to find frequencies of all its unique elements of listL1 =[1, 2, 1, 1, 4, 4, 4, 5, 6, 6, 3, 3, 0, 0]t1 = Counter(L1) print("t1 :", t1) c1 : Counter({'b': 3, 'c': 3, 'a': 2, 'f': 2, 'e': 1, 'd': 1}) t1 : Counter({1: 3, 4: 3, 0: 2, 3: 2, 6: 2, 2: 1, 5: 1}) Performing certain operations on returned output dictionary if d is output dictionary then like d.items(), d.keys(), d.values() Python3 from collections import Counterd ='aabbbcccdeff'd = Counter(d) # To print Counter valueprint("d :", d) # To access the values corresponds to each keys of the returned dictionaryprint("d.values() : ", d.values()) # To get the keys and values both of dictionaryprint("d.items() :", d.items()) # To get only the keysprint("d.keys() :", d.keys()) # To sort the values of dictionaryprint("sorted(d) :", sorted(d)) d : Counter({'b': 3, 'c': 3, 'a': 2, 'f': 2, 'e': 1, 'd': 1}) d.values() : dict_values([2, 3, 3, 2, 1, 1]) d.items() : dict_items([('a', 2), ('b', 3), ('c', 3), ('f', 2), ('e', 1), ('d', 1)]) d.keys() : dict_keys(['a', 'b', 'c', 'f', 'e', 'd']) sorted(d) : ['a', 'b', 'c', 'd', 'e', 'f'] Addition of two Counters Addition of two counter creates the additions of values corresponds to each keys, and if a key that is present in one counter and not in other, in that case this key value also get into final output. Python3 from collections import Countert1 = Counter('aabbddffggjik')t2 = Counter('aaabbbssshhhggdkkll') print("t1:", t1)print("t2:", t2)print("t1 + t2 :", t1 + t2) t1: Counter({'g': 2, 'a': 2, 'b': 2, 'f': 2, 'd': 2, 'k': 1, 'j': 1, 'i': 1}) t2: Counter({'a': 3, 'b': 3, 'h': 3, 's': 3, 'l': 2, 'g': 2, 'k': 2, 'd': 1}) t1+t2 : Counter({'a': 5, 'b': 5, 'g': 4, 'k': 3, 'h': 3, 'd': 3, 's': 3, 'l': 2, 'f': 2, 'j': 1, 'i': 1}) Subtraction of two Counters Counts of common elements are subtracted from each other and (keeps only positive counts) Python3 from collections import Countert1 = Counter('aabbddffggjik')t2 = Counter('aaabbbssshhhggdkkll') print("t1:", t1)print("t2:", t2)print("t1-t2 :", t1-t2)print("t2-t1 :", t2-t1) t1: Counter({'f': 2, 'd': 2, 'b': 2, 'a': 2, 'g': 2, 'k': 1, 'i': 1, 'j': 1}) t2: Counter({'h': 3, 'b': 3, 'a': 3, 's': 3, 'l': 2, 'k': 2, 'g': 2, 'd': 1}) t1-t2 : Counter({'f': 2, 'i': 1, 'j': 1, 'd': 1}) t2-t1 : Counter({'h': 3, 's': 3, 'l': 2, 'k': 1, 'b': 1, 'a': 1}) Intersections(&) of two Counters Intersection(&) will keep only the minimum of corresponding counts: min(t1[x], t2[x]): Python3 from collections import Countert1 = Counter('aaabbbbccdeeee')t2 = Counter('aabbccccdddee') print("t1 :", t1)print("t2 :", t2)print("t1&t2 :", t1&t2) t1 : Counter({'e': 4, 'b': 4, 'a': 3, 'c': 2, 'd': 1}) t2 : Counter({'c': 4, 'd': 3, 'a': 2, 'e': 2, 'b': 2}) t1&t2 : Counter({'c': 2, 'a': 2, 'e': 2, 'b': 2, 'd': 1}) Union(|) of two Counters Union(|) will keep only the maximum of corresponding counts: max(c[x], d[x]): Python3 from collections import Countert1 = Counter('aaabbbbccdeeee')t2 = Counter('aabbccccdddee') print("t1 :", t1)print("t2 :", t2)print("t1|t2 :", t1|t2) t1 : Counter({'b': 4, 'e': 4, 'a': 3, 'c': 2, 'd': 1}) t2 : Counter({'c': 4, 'd': 3, 'a': 2, 'b': 2, 'e': 2}) t1|t2 : Counter({'b': 4, 'e': 4, 'c': 4, 'a': 3, 'd': 3}) adnanirshad158 sweetyty varshagumber28 Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25563, "s": 25535, "text": "\n18 Dec, 2021" }, { "code": null, "e": 26090, "s": 25563, "text": "The counter can be used to calculate the frequency in a list or in a string because as any list or string is passed as input, it returns output as a dictionary having keys are the unique elements of the list and values are the corresponding frequencies of the elements. In the code given below, Counter from Collection Python library is imported to find the frequency of every unique character occurring in this string, By using Counter on the list, the frequency of each unique elements present in the list can also be found." }, { "code": null, "e": 26098, "s": 26090, "text": "Python3" }, { "code": "# Write Python3 code here# Counter used in string to find frequencies of all its unique Characters from collections import Counters1 ='aabbbcccdeff'c1 = Counter(s1)print(\"c1 :\", c1) # Counter used in List to find frequencies of all its unique elements of listL1 =[1, 2, 1, 1, 4, 4, 4, 5, 6, 6, 3, 3, 0, 0]t1 = Counter(L1) print(\"t1 :\", t1)", "e": 26438, "s": 26098, "text": null }, { "code": null, "e": 26558, "s": 26438, "text": "c1 : Counter({'b': 3, 'c': 3, 'a': 2, 'f': 2, 'e': 1, 'd': 1})\nt1 : Counter({1: 3, 4: 3, 0: 2, 3: 2, 6: 2, 2: 1, 5: 1})" }, { "code": null, "e": 26688, "s": 26560, "text": "Performing certain operations on returned output dictionary if d is output dictionary then like d.items(), d.keys(), d.values()" }, { "code": null, "e": 26696, "s": 26688, "text": "Python3" }, { "code": "from collections import Counterd ='aabbbcccdeff'd = Counter(d) # To print Counter valueprint(\"d :\", d) # To access the values corresponds to each keys of the returned dictionaryprint(\"d.values() : \", d.values()) # To get the keys and values both of dictionaryprint(\"d.items() :\", d.items()) # To get only the keysprint(\"d.keys() :\", d.keys()) # To sort the values of dictionaryprint(\"sorted(d) :\", sorted(d))", "e": 27106, "s": 26696, "text": null }, { "code": null, "e": 27395, "s": 27106, "text": "d : Counter({'b': 3, 'c': 3, 'a': 2, 'f': 2, 'e': 1, 'd': 1})\nd.values() : dict_values([2, 3, 3, 2, 1, 1])\nd.items() : dict_items([('a', 2), ('b', 3), ('c', 3), ('f', 2), ('e', 1), ('d', 1)])\nd.keys() : dict_keys(['a', 'b', 'c', 'f', 'e', 'd'])\nsorted(d) : ['a', 'b', 'c', 'd', 'e', 'f']" }, { "code": null, "e": 27623, "s": 27397, "text": "Addition of two Counters Addition of two counter creates the additions of values corresponds to each keys, and if a key that is present in one counter and not in other, in that case this key value also get into final output. " }, { "code": null, "e": 27631, "s": 27623, "text": "Python3" }, { "code": "from collections import Countert1 = Counter('aabbddffggjik')t2 = Counter('aaabbbssshhhggdkkll') print(\"t1:\", t1)print(\"t2:\", t2)print(\"t1 + t2 :\", t1 + t2)", "e": 27787, "s": 27631, "text": null }, { "code": null, "e": 28049, "s": 27787, "text": "t1: Counter({'g': 2, 'a': 2, 'b': 2, 'f': 2, 'd': 2, 'k': 1, 'j': 1, 'i': 1})\nt2: Counter({'a': 3, 'b': 3, 'h': 3, 's': 3, 'l': 2, 'g': 2, 'k': 2, 'd': 1})\nt1+t2 : Counter({'a': 5, 'b': 5, 'g': 4, 'k': 3, 'h': 3, 'd': 3, 's': 3, 'l': 2, 'f': 2, 'j': 1, 'i': 1})" }, { "code": null, "e": 28170, "s": 28051, "text": "Subtraction of two Counters Counts of common elements are subtracted from each other and (keeps only positive counts) " }, { "code": null, "e": 28178, "s": 28170, "text": "Python3" }, { "code": "from collections import Countert1 = Counter('aabbddffggjik')t2 = Counter('aaabbbssshhhggdkkll') print(\"t1:\", t1)print(\"t2:\", t2)print(\"t1-t2 :\", t1-t2)print(\"t2-t1 :\", t2-t1)", "e": 28353, "s": 28178, "text": null }, { "code": null, "e": 28625, "s": 28353, "text": "t1: Counter({'f': 2, 'd': 2, 'b': 2, 'a': 2, 'g': 2, 'k': 1, 'i': 1, 'j': 1})\nt2: Counter({'h': 3, 'b': 3, 'a': 3, 's': 3, 'l': 2, 'k': 2, 'g': 2, 'd': 1})\nt1-t2 : Counter({'f': 2, 'i': 1, 'j': 1, 'd': 1})\nt2-t1 : Counter({'h': 3, 's': 3, 'l': 2, 'k': 1, 'b': 1, 'a': 1})" }, { "code": null, "e": 28748, "s": 28627, "text": "Intersections(&) of two Counters Intersection(&) will keep only the minimum of corresponding counts: min(t1[x], t2[x]): " }, { "code": null, "e": 28756, "s": 28748, "text": "Python3" }, { "code": "from collections import Countert1 = Counter('aaabbbbccdeeee')t2 = Counter('aabbccccdddee') print(\"t1 :\", t1)print(\"t2 :\", t2)print(\"t1&t2 :\", t1&t2)", "e": 28905, "s": 28756, "text": null }, { "code": null, "e": 29073, "s": 28905, "text": "t1 : Counter({'e': 4, 'b': 4, 'a': 3, 'c': 2, 'd': 1})\nt2 : Counter({'c': 4, 'd': 3, 'a': 2, 'e': 2, 'b': 2})\nt1&t2 : Counter({'c': 2, 'a': 2, 'e': 2, 'b': 2, 'd': 1})" }, { "code": null, "e": 29179, "s": 29075, "text": "Union(|) of two Counters Union(|) will keep only the maximum of corresponding counts: max(c[x], d[x]): " }, { "code": null, "e": 29187, "s": 29179, "text": "Python3" }, { "code": "from collections import Countert1 = Counter('aaabbbbccdeeee')t2 = Counter('aabbccccdddee') print(\"t1 :\", t1)print(\"t2 :\", t2)print(\"t1|t2 :\", t1|t2)", "e": 29336, "s": 29187, "text": null }, { "code": null, "e": 29504, "s": 29336, "text": "t1 : Counter({'b': 4, 'e': 4, 'a': 3, 'c': 2, 'd': 1})\nt2 : Counter({'c': 4, 'd': 3, 'a': 2, 'b': 2, 'e': 2})\nt1|t2 : Counter({'b': 4, 'e': 4, 'c': 4, 'a': 3, 'd': 3})" }, { "code": null, "e": 29521, "s": 29506, "text": "adnanirshad158" }, { "code": null, "e": 29530, "s": 29521, "text": "sweetyty" }, { "code": null, "e": 29545, "s": 29530, "text": "varshagumber28" }, { "code": null, "e": 29552, "s": 29545, "text": "Python" }, { "code": null, "e": 29568, "s": 29552, "text": "Python Programs" }, { "code": null, "e": 29666, "s": 29568, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29698, "s": 29666, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29740, "s": 29698, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29782, "s": 29740, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29809, "s": 29782, "text": "Python Classes and Objects" }, { "code": null, "e": 29865, "s": 29809, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29887, "s": 29865, "text": "Defaultdict in Python" }, { "code": null, "e": 29926, "s": 29887, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29972, "s": 29926, "text": "Python | Split string into list of characters" }, { "code": null, "e": 30010, "s": 29972, "text": "Python | Convert a list to dictionary" } ]
Python - Matching Pairs of Brackets - GeeksforGeeks
22 Jun, 2020 Sometimes, while working with Python data, we can have a problem in which we need to pair all the elements with the suitable closing brackets, and can have data associated with pairing. This kind of problem is classic application of Stack Data Structure and can have usage across many domains. Let’s discuss a certain way in which this task can be done. Input : test_list = [(‘(‘, 1), (‘(‘, 2), (‘)’, 3), (‘)’, 4)]Output : [(2, 3), (1, 4)] Input : test_list = [(‘(‘, 1), (‘)’, 4)]Output : [(1, 4)] Method : Using stack DS + loopThe combination above functionalities can be used to solve this problem. In this, we make a new pair with each opening bracket and when the corresponding closing bracket comes using LIFO technique, we form a pair with that closing bracket. # Python3 code to demonstrate working of # Matching Pairs of Brackets# Using stack DS + loop # initializing listtest_list = [('(', 7), ('(', 9), (')', 10), (')', 11), ('(', 15), (')', 100)] # printing original listprint("The original list is : " + str(test_list)) # Matching Pairs of Brackets# Using stack DS + loopstck = []res = []for ele1, ele2 in test_list: if '(' in ele1: stck.append((ele1, ele2)) elif ')' in ele1: res.append((stck.pop()[1], ele2)) # printing result print("The paired elements : " + str(res)) The original list is : [('(', 7), ('(', 9), (')', 10), (')', 11), ('(', 15), (')', 100)] The paired elements : [(9, 10), (7, 11), (15, 100)] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n22 Jun, 2020" }, { "code": null, "e": 25891, "s": 25537, "text": "Sometimes, while working with Python data, we can have a problem in which we need to pair all the elements with the suitable closing brackets, and can have data associated with pairing. This kind of problem is classic application of Stack Data Structure and can have usage across many domains. Let’s discuss a certain way in which this task can be done." }, { "code": null, "e": 25977, "s": 25891, "text": "Input : test_list = [(‘(‘, 1), (‘(‘, 2), (‘)’, 3), (‘)’, 4)]Output : [(2, 3), (1, 4)]" }, { "code": null, "e": 26035, "s": 25977, "text": "Input : test_list = [(‘(‘, 1), (‘)’, 4)]Output : [(1, 4)]" }, { "code": null, "e": 26305, "s": 26035, "text": "Method : Using stack DS + loopThe combination above functionalities can be used to solve this problem. In this, we make a new pair with each opening bracket and when the corresponding closing bracket comes using LIFO technique, we form a pair with that closing bracket." }, { "code": "# Python3 code to demonstrate working of # Matching Pairs of Brackets# Using stack DS + loop # initializing listtest_list = [('(', 7), ('(', 9), (')', 10), (')', 11), ('(', 15), (')', 100)] # printing original listprint(\"The original list is : \" + str(test_list)) # Matching Pairs of Brackets# Using stack DS + loopstck = []res = []for ele1, ele2 in test_list: if '(' in ele1: stck.append((ele1, ele2)) elif ')' in ele1: res.append((stck.pop()[1], ele2)) # printing result print(\"The paired elements : \" + str(res)) ", "e": 26846, "s": 26305, "text": null }, { "code": null, "e": 26988, "s": 26846, "text": "The original list is : [('(', 7), ('(', 9), (')', 10), (')', 11), ('(', 15), (')', 100)]\nThe paired elements : [(9, 10), (7, 11), (15, 100)]\n" }, { "code": null, "e": 27009, "s": 26988, "text": "Python list-programs" }, { "code": null, "e": 27016, "s": 27009, "text": "Python" }, { "code": null, "e": 27032, "s": 27016, "text": "Python Programs" }, { "code": null, "e": 27130, "s": 27032, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27162, "s": 27130, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27204, "s": 27162, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27246, "s": 27204, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27302, "s": 27246, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27329, "s": 27302, "text": "Python Classes and Objects" }, { "code": null, "e": 27351, "s": 27329, "text": "Defaultdict in Python" }, { "code": null, "e": 27390, "s": 27351, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27436, "s": 27390, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27474, "s": 27436, "text": "Python | Convert a list to dictionary" } ]
How to Count Distinct Values of a Pandas Dataframe Column? - GeeksforGeeks
19 Aug, 2020 Let’s see How to Count Distinct Values of a Pandas Dataframe Column? Consider a tabular structure as given below which has to be created as Dataframe. The columns are height, weight and age. The records of 8 students form the rows. First step is to create the Dataframe for the above tabulation. Look at the code snippet below. Python3 # import libraryimport pandas as pd # create a Dataframedf = pd.DataFrame({ 'height' : [165, 165, 164, 158, 167, 160, 158, 165], 'weight' : [63.5, 64, 63.5, 54, 63.5, 62, 64, 64], 'age' : [20, 22, 22, 21, 23, 22, 20, 21]}, index = ['Steve', 'Ria', 'Nivi', 'Jane', 'Kate', 'Lucy', 'Ram', 'Niki']) # show the Dataframedf Output: Method 1: Using for loop. The Dataframe has been created and one can hard coded using for loop and count the number of unique values in a specific column. For example In the above table, if one wishes to count the number of unique values in the column height. The idea is to use a variable cnt for storing the count and a list visited that has the previously visited values. Then for loop that iterates through the ‘height’ column and for each value, it checks whether the same value has already been visited in the visited list. If the value was not visited previously, then the count is incremented by 1. Below is the implementation: Python3 # import libraryimport pandas as pd # create a Dataframedf = pd.DataFrame({ 'height' : [165, 165, 164, 158, 167, 160, 158, 165], 'weight' : [63.5, 64, 63.5, 54, 63.5, 62, 64, 64], 'age' : [20, 22, 22, 21, 23, 22, 20, 21]}, index = ['Steve', 'Ria', 'Nivi', 'Jane', 'Kate', 'Lucy', 'Ram', 'Niki']) # variable to hold the countcnt = 0 # list to hold visited valuesvisited = [] # loop for counting the unique# values in heightfor i in range(0, len(df['height'])): if df['height'][i] not in visited: visited.append(df['height'][i]) cnt += 1 print("No.of.unique values :", cnt) print("unique values :", visited) Output : No.of.unique values : 5 unique values : [165, 164, 158, 167, 160] But this method is not so efficient when the Dataframe grows in size and contains thousands of rows and columns. To give an efficient there are three methods available which are listed below: pandas.unique() Dataframe.nunique() Series.value_counts() Method 2: Using unique(). The unique method takes a 1-D array or Series as an input and returns a list of unique items in it. The return value is a NumPy array and the contents in it based on the input passed. If indices are supplied as input, then the return value will also be the indices of the unique value. Syntax: pandas.unique(Series) Example: Python3 # import libraryimport pandas as pd # create a Dataframedf = pd.DataFrame({ 'height' : [165, 165, 164, 158, 167, 160, 158, 165], 'weight' : [63.5, 64, 63.5, 54, 63.5, 62, 64, 64], 'age' : [20, 22, 22, 21, 23, 22, 20, 21]}, index = ['Steve', 'Ria', 'Nivi', 'Jane', 'Kate', 'Lucy', 'Ram', 'Niki']) # counting unique valuesn = len(pd.unique(df['height'])) print("No.of.unique values :", n) Output: No.of.unique values : 5 Method 3: Using Dataframe.nunique(). This method returns the count of unique values in the specified axis. The syntax is : Syntax: Dataframe.nunique (axis=0/1, dropna=True/False) Example: Python3 # import libraryimport pandas as pd # create a Dataframedf = pd.DataFrame({ 'height' : [165, 165, 164, 158, 167, 160, 158, 165], 'weight' : [63.5, 64, 63.5, 54, 63.5, 62, 64, 64], 'age' : [20, 22, 22, 21, 23, 22, 20, 21]}, index = ['Steve', 'Ria', 'Nivi', 'Jane', 'Kate', 'Lucy', 'Ram', 'Niki']) # check the values of # each row for each columnn = df.nunique(axis=0) print("No.of.unique values in each column :\n", n) Output: No.of.unique values in each column : height 5 weight 4 age 4 dtype: int64 To get the number of unique values in a specified column: Syntax: Dataframe.col_name.nunique() Example: Python3 # import libraryimport pandas as pd # create a Dataframedf = pd.DataFrame({ 'height' : [165, 165, 164, 158, 167, 160, 158, 165], 'weight' : [63.5, 64, 63.5, 54, 63.5, 62, 64, 64], 'age' : [20, 22, 22, 21, 23, 22, 20, 21]}, index = ['Steve', 'Ria', 'Nivi', 'Jane', 'Kate', 'Lucy', 'Ram', 'Niki']) # count no. of unique # values in height columnn = df.height.nunique() print("No.of.unique values in height column :", n) Output: No.of.unique values in height column : 5 Method 3: Using Series.value_counts(). This method returns the count of all unique values in the specified column. Syntax: Series.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True) Example: Python3 # import libraryimport pandas as pd # create a Dataframedf = pd.DataFrame({ 'height' : [165, 165, 164, 158, 167, 160, 158, 165], 'weight' : [63.5, 64, 63.5, 54, 63.5, 62, 64, 64], 'age' : [20, 22, 22, 21, 23, 22, 20, 21]}, index = ['Steve', 'Ria', 'Nivi', 'Jane', 'Kate', 'Lucy', 'Ram', 'Niki']) # getting the list of unique valuesli = list(df.height.value_counts()) # print the unique value countsprint("No.of.unique values :", len(li)) Output: No.of.unique values : 5 Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26307, "s": 26279, "text": "\n19 Aug, 2020" }, { "code": null, "e": 26376, "s": 26307, "text": "Let’s see How to Count Distinct Values of a Pandas Dataframe Column?" }, { "code": null, "e": 26540, "s": 26376, "text": "Consider a tabular structure as given below which has to be created as Dataframe. The columns are height, weight and age. The records of 8 students form the rows. " }, { "code": null, "e": 26636, "s": 26540, "text": "First step is to create the Dataframe for the above tabulation. Look at the code snippet below." }, { "code": null, "e": 26644, "s": 26636, "text": "Python3" }, { "code": "# import libraryimport pandas as pd # create a Dataframedf = pd.DataFrame({ 'height' : [165, 165, 164, 158, 167, 160, 158, 165], 'weight' : [63.5, 64, 63.5, 54, 63.5, 62, 64, 64], 'age' : [20, 22, 22, 21, 23, 22, 20, 21]}, index = ['Steve', 'Ria', 'Nivi', 'Jane', 'Kate', 'Lucy', 'Ram', 'Niki']) # show the Dataframedf", "e": 27080, "s": 26644, "text": null }, { "code": null, "e": 27088, "s": 27080, "text": "Output:" }, { "code": null, "e": 27114, "s": 27088, "text": "Method 1: Using for loop." }, { "code": null, "e": 27695, "s": 27114, "text": "The Dataframe has been created and one can hard coded using for loop and count the number of unique values in a specific column. For example In the above table, if one wishes to count the number of unique values in the column height. The idea is to use a variable cnt for storing the count and a list visited that has the previously visited values. Then for loop that iterates through the ‘height’ column and for each value, it checks whether the same value has already been visited in the visited list. If the value was not visited previously, then the count is incremented by 1." }, { "code": null, "e": 27724, "s": 27695, "text": "Below is the implementation:" }, { "code": null, "e": 27732, "s": 27724, "text": "Python3" }, { "code": "# import libraryimport pandas as pd # create a Dataframedf = pd.DataFrame({ 'height' : [165, 165, 164, 158, 167, 160, 158, 165], 'weight' : [63.5, 64, 63.5, 54, 63.5, 62, 64, 64], 'age' : [20, 22, 22, 21, 23, 22, 20, 21]}, index = ['Steve', 'Ria', 'Nivi', 'Jane', 'Kate', 'Lucy', 'Ram', 'Niki']) # variable to hold the countcnt = 0 # list to hold visited valuesvisited = [] # loop for counting the unique# values in heightfor i in range(0, len(df['height'])): if df['height'][i] not in visited: visited.append(df['height'][i]) cnt += 1 print(\"No.of.unique values :\", cnt) print(\"unique values :\", visited)", "e": 28509, "s": 27732, "text": null }, { "code": null, "e": 28518, "s": 28509, "text": "Output :" }, { "code": null, "e": 28585, "s": 28518, "text": "No.of.unique values : 5\nunique values : [165, 164, 158, 167, 160]\n" }, { "code": null, "e": 28777, "s": 28585, "text": "But this method is not so efficient when the Dataframe grows in size and contains thousands of rows and columns. To give an efficient there are three methods available which are listed below:" }, { "code": null, "e": 28793, "s": 28777, "text": "pandas.unique()" }, { "code": null, "e": 28813, "s": 28793, "text": "Dataframe.nunique()" }, { "code": null, "e": 28835, "s": 28813, "text": "Series.value_counts()" }, { "code": null, "e": 28861, "s": 28835, "text": "Method 2: Using unique()." }, { "code": null, "e": 29148, "s": 28861, "text": "The unique method takes a 1-D array or Series as an input and returns a list of unique items in it. The return value is a NumPy array and the contents in it based on the input passed. If indices are supplied as input, then the return value will also be the indices of the unique value. " }, { "code": null, "e": 29178, "s": 29148, "text": "Syntax: pandas.unique(Series)" }, { "code": null, "e": 29187, "s": 29178, "text": "Example:" }, { "code": null, "e": 29195, "s": 29187, "text": "Python3" }, { "code": "# import libraryimport pandas as pd # create a Dataframedf = pd.DataFrame({ 'height' : [165, 165, 164, 158, 167, 160, 158, 165], 'weight' : [63.5, 64, 63.5, 54, 63.5, 62, 64, 64], 'age' : [20, 22, 22, 21, 23, 22, 20, 21]}, index = ['Steve', 'Ria', 'Nivi', 'Jane', 'Kate', 'Lucy', 'Ram', 'Niki']) # counting unique valuesn = len(pd.unique(df['height'])) print(\"No.of.unique values :\", n)", "e": 29706, "s": 29195, "text": null }, { "code": null, "e": 29714, "s": 29706, "text": "Output:" }, { "code": null, "e": 29739, "s": 29714, "text": "No.of.unique values : 5\n" }, { "code": null, "e": 29776, "s": 29739, "text": "Method 3: Using Dataframe.nunique()." }, { "code": null, "e": 29862, "s": 29776, "text": "This method returns the count of unique values in the specified axis. The syntax is :" }, { "code": null, "e": 29918, "s": 29862, "text": "Syntax: Dataframe.nunique (axis=0/1, dropna=True/False)" }, { "code": null, "e": 29927, "s": 29918, "text": "Example:" }, { "code": null, "e": 29935, "s": 29927, "text": "Python3" }, { "code": "# import libraryimport pandas as pd # create a Dataframedf = pd.DataFrame({ 'height' : [165, 165, 164, 158, 167, 160, 158, 165], 'weight' : [63.5, 64, 63.5, 54, 63.5, 62, 64, 64], 'age' : [20, 22, 22, 21, 23, 22, 20, 21]}, index = ['Steve', 'Ria', 'Nivi', 'Jane', 'Kate', 'Lucy', 'Ram', 'Niki']) # check the values of # each row for each columnn = df.nunique(axis=0) print(\"No.of.unique values in each column :\\n\", n)", "e": 30476, "s": 29935, "text": null }, { "code": null, "e": 30484, "s": 30476, "text": "Output:" }, { "code": null, "e": 30572, "s": 30484, "text": "No.of.unique values in each column :\nheight 5\nweight 4\nage 4\ndtype: int64\n\n" }, { "code": null, "e": 30630, "s": 30572, "text": "To get the number of unique values in a specified column:" }, { "code": null, "e": 30668, "s": 30630, "text": " Syntax: Dataframe.col_name.nunique()" }, { "code": null, "e": 30677, "s": 30668, "text": "Example:" }, { "code": null, "e": 30685, "s": 30677, "text": "Python3" }, { "code": "# import libraryimport pandas as pd # create a Dataframedf = pd.DataFrame({ 'height' : [165, 165, 164, 158, 167, 160, 158, 165], 'weight' : [63.5, 64, 63.5, 54, 63.5, 62, 64, 64], 'age' : [20, 22, 22, 21, 23, 22, 20, 21]}, index = ['Steve', 'Ria', 'Nivi', 'Jane', 'Kate', 'Lucy', 'Ram', 'Niki']) # count no. of unique # values in height columnn = df.height.nunique() print(\"No.of.unique values in height column :\", n)", "e": 31226, "s": 30685, "text": null }, { "code": null, "e": 31234, "s": 31226, "text": "Output:" }, { "code": null, "e": 31276, "s": 31234, "text": "No.of.unique values in height column : 5\n" }, { "code": null, "e": 31315, "s": 31276, "text": "Method 3: Using Series.value_counts()." }, { "code": null, "e": 31392, "s": 31315, "text": "This method returns the count of all unique values in the specified column. " }, { "code": null, "e": 31489, "s": 31392, "text": "Syntax: Series.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True)" }, { "code": null, "e": 31498, "s": 31489, "text": "Example:" }, { "code": null, "e": 31506, "s": 31498, "text": "Python3" }, { "code": "# import libraryimport pandas as pd # create a Dataframedf = pd.DataFrame({ 'height' : [165, 165, 164, 158, 167, 160, 158, 165], 'weight' : [63.5, 64, 63.5, 54, 63.5, 62, 64, 64], 'age' : [20, 22, 22, 21, 23, 22, 20, 21]}, index = ['Steve', 'Ria', 'Nivi', 'Jane', 'Kate', 'Lucy', 'Ram', 'Niki']) # getting the list of unique valuesli = list(df.height.value_counts()) # print the unique value countsprint(\"No.of.unique values :\", len(li))", "e": 32069, "s": 31506, "text": null }, { "code": null, "e": 32077, "s": 32069, "text": "Output:" }, { "code": null, "e": 32102, "s": 32077, "text": "No.of.unique values : 5\n" }, { "code": null, "e": 32126, "s": 32102, "text": "Python pandas-dataFrame" }, { "code": null, "e": 32149, "s": 32126, "text": "Python Pandas-exercise" }, { "code": null, "e": 32163, "s": 32149, "text": "Python-pandas" }, { "code": null, "e": 32170, "s": 32163, "text": "Python" }, { "code": null, "e": 32268, "s": 32170, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32286, "s": 32268, "text": "Python Dictionary" }, { "code": null, "e": 32321, "s": 32286, "text": "Read a file line by line in Python" }, { "code": null, "e": 32353, "s": 32321, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32375, "s": 32353, "text": "Enumerate() in Python" }, { "code": null, "e": 32417, "s": 32375, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 32447, "s": 32417, "text": "Iterate over a list in Python" }, { "code": null, "e": 32473, "s": 32447, "text": "Python String | replace()" }, { "code": null, "e": 32502, "s": 32473, "text": "*args and **kwargs in Python" }, { "code": null, "e": 32546, "s": 32502, "text": "Reading and Writing to text files in Python" } ]
Flutter - Grouped List - GeeksforGeeks
14 May, 2021 The grouped_list package in Flutter as the name suggests is used to create list items in different groups. This package also provides 3 specific functions that are listed below: List Items can be separated into groups.An individual header can be given to each groupMost fields from the ListView.builder is available in this library List Items can be separated into groups. An individual header can be given to each group Most fields from the ListView.builder is available in this library A Grouped List can be created as follows using this package: Syntax: GroupedListView<dynamic, String>( elements: _elements, groupBy: (element) => element['group'], groupSeparatorBuilder: (String groupByValue) => Text(groupByValue), itemBuilder: (context, dynamic element) => Text(element['name']), itemComparator: (item1, item2) => item1['name'].compareTo(item2['name']), useStickyGroupSeparators: true, floatingHeader: true, order: GroupedListOrder.ASC, ), The below list holds all the parameters of the GroupedListView with their explanation: element: It comprises the content that is to be displayed in the list. It is a required field. groupBy: The content and the groups are mapped using this function. It is a required field. itemBuilder / indexedItemBuilder: This functions the widget that defines the content of the app. separator: This widget separates the content of one group from another. order: It sets the order in which the grouped list is displayed. Now let’s implement the same in the below example. Example: Add the grouped_list library in the dependencies section of the pubspec.yaml file as shown below: Now import the dependency to the code file using the below line of code: import 'package:grouped_list/grouped_list.dart'; Now, it’s time to define the List items. We in this example will add the following items : List _elements = [ {'name': 'Virat Kohli', 'group': 'RCB'}, {'name': 'Rohit Sharma', 'group': 'MI'}, {'name': 'AB de Villiers', 'group': 'RCB'}, {'name': 'Jasprit Bumrah', 'group': 'MI'}, {'name': 'KL Rahul', 'group': 'KXIP'}, {'name': 'Md. Shammi', 'group': 'KXIP'}, ]; Now structure the application by extending the StatelessWidget and call the GroupedListView method as shown below: Dart class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Example', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: GroupedListView<dynamic, String>( elements: _elements, groupBy: (element) => element['group'], groupComparator: (value1, value2) => value2.compareTo(value1), itemComparator: (item1, item2) => item1['name'].compareTo(item2['name']), order: GroupedListOrder.DESC, useStickyGroupSeparators: true, groupSeparatorBuilder: (String value) => Padding( ), ); }, ), ), ); }} Now design the UI for the list as you want. For the sake of simplicity we will be using the ItemBuilder as follows: Dart itemBuilder: (c, element) { return Card( elevation: 8.0, margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0), child: Container( child: ListTile( contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0), leading: ImageIcon( NetworkImage('http://www.pngall.com/wp-content/uploads/2017/04/IPL-Logo-2017-PNG.png') ), title: Text(element['name']), ), ), );}, Complete Source Code: Dart import 'package:flutter/material.dart';import 'package:grouped_list/grouped_list.dart'; void main() => runApp(MyApp()); List _elements = [ {'name': 'Virat Kohli', 'group': 'RCB'}, {'name': 'Rohit Sharma', 'group': 'MI'}, {'name': 'AB de Villiers', 'group': 'RCB'}, {'name': 'Jasprit Bumrah', 'group': 'MI'}, {'name': 'KL Rahul', 'group': 'KXIP'}, {'name': 'Md. Shammi', 'group': 'KXIP'},]; class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Example', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: GroupedListView<dynamic, String>( elements: _elements, groupBy: (element) => element['group'], groupComparator: (value1, value2) => value2.compareTo(value1), itemComparator: (item1, item2) => item1['name'].compareTo(item2['name']), order: GroupedListOrder.DESC, useStickyGroupSeparators: true, groupSeparatorBuilder: (String value) => Padding( padding: const EdgeInsets.all(8.0), child: Text( value, textAlign: TextAlign.center, style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), ), ), itemBuilder: (c, element) { return Card( elevation: 8.0, margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0), child: Container( child: ListTile( contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0), leading: ImageIcon( NetworkImage('http://www.pngall.com/wp-content/uploads/2017/04/IPL-Logo-2017-PNG.png') ), title: Text(element['name']), ), ), ); }, ), ), ); }} Output: sweetyty android Flutter Flutter UI-components Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs
[ { "code": null, "e": 25261, "s": 25233, "text": "\n14 May, 2021" }, { "code": null, "e": 25439, "s": 25261, "text": "The grouped_list package in Flutter as the name suggests is used to create list items in different groups. This package also provides 3 specific functions that are listed below:" }, { "code": null, "e": 25593, "s": 25439, "text": "List Items can be separated into groups.An individual header can be given to each groupMost fields from the ListView.builder is available in this library" }, { "code": null, "e": 25634, "s": 25593, "text": "List Items can be separated into groups." }, { "code": null, "e": 25682, "s": 25634, "text": "An individual header can be given to each group" }, { "code": null, "e": 25749, "s": 25682, "text": "Most fields from the ListView.builder is available in this library" }, { "code": null, "e": 25810, "s": 25749, "text": "A Grouped List can be created as follows using this package:" }, { "code": null, "e": 26244, "s": 25810, "text": "Syntax:\n GroupedListView<dynamic, String>(\n elements: _elements,\n groupBy: (element) => element['group'],\n groupSeparatorBuilder: (String groupByValue) => Text(groupByValue),\n itemBuilder: (context, dynamic element) => Text(element['name']),\n itemComparator: (item1, item2) => item1['name'].compareTo(item2['name']),\n useStickyGroupSeparators: true,\n floatingHeader: true,\n order: GroupedListOrder.ASC,\n )," }, { "code": null, "e": 26331, "s": 26244, "text": "The below list holds all the parameters of the GroupedListView with their explanation:" }, { "code": null, "e": 26426, "s": 26331, "text": "element: It comprises the content that is to be displayed in the list. It is a required field." }, { "code": null, "e": 26518, "s": 26426, "text": "groupBy: The content and the groups are mapped using this function. It is a required field." }, { "code": null, "e": 26616, "s": 26518, "text": "itemBuilder / indexedItemBuilder: This functions the widget that defines the content of the app." }, { "code": null, "e": 26688, "s": 26616, "text": "separator: This widget separates the content of one group from another." }, { "code": null, "e": 26753, "s": 26688, "text": "order: It sets the order in which the grouped list is displayed." }, { "code": null, "e": 26804, "s": 26753, "text": "Now let’s implement the same in the below example." }, { "code": null, "e": 26813, "s": 26804, "text": "Example:" }, { "code": null, "e": 26911, "s": 26813, "text": "Add the grouped_list library in the dependencies section of the pubspec.yaml file as shown below:" }, { "code": null, "e": 26984, "s": 26911, "text": "Now import the dependency to the code file using the below line of code:" }, { "code": null, "e": 27033, "s": 26984, "text": "import 'package:grouped_list/grouped_list.dart';" }, { "code": null, "e": 27124, "s": 27033, "text": "Now, it’s time to define the List items. We in this example will add the following items :" }, { "code": null, "e": 27407, "s": 27124, "text": "List _elements = [\n {'name': 'Virat Kohli', 'group': 'RCB'},\n {'name': 'Rohit Sharma', 'group': 'MI'},\n {'name': 'AB de Villiers', 'group': 'RCB'},\n {'name': 'Jasprit Bumrah', 'group': 'MI'},\n {'name': 'KL Rahul', 'group': 'KXIP'},\n {'name': 'Md. Shammi', 'group': 'KXIP'},\n];" }, { "code": null, "e": 27522, "s": 27407, "text": "Now structure the application by extending the StatelessWidget and call the GroupedListView method as shown below:" }, { "code": null, "e": 27527, "s": 27522, "text": "Dart" }, { "code": "class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Example', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: GroupedListView<dynamic, String>( elements: _elements, groupBy: (element) => element['group'], groupComparator: (value1, value2) => value2.compareTo(value1), itemComparator: (item1, item2) => item1['name'].compareTo(item2['name']), order: GroupedListOrder.DESC, useStickyGroupSeparators: true, groupSeparatorBuilder: (String value) => Padding( ), ); }, ), ), ); }}", "e": 28402, "s": 27527, "text": null }, { "code": null, "e": 28522, "s": 28406, "text": "Now design the UI for the list as you want. For the sake of simplicity we will be using the ItemBuilder as follows:" }, { "code": null, "e": 28529, "s": 28524, "text": "Dart" }, { "code": "itemBuilder: (c, element) { return Card( elevation: 8.0, margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0), child: Container( child: ListTile( contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0), leading: ImageIcon( NetworkImage('http://www.pngall.com/wp-content/uploads/2017/04/IPL-Logo-2017-PNG.png') ), title: Text(element['name']), ), ), );},", "e": 28979, "s": 28529, "text": null }, { "code": null, "e": 29005, "s": 28983, "text": "Complete Source Code:" }, { "code": null, "e": 29012, "s": 29007, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'package:grouped_list/grouped_list.dart'; void main() => runApp(MyApp()); List _elements = [ {'name': 'Virat Kohli', 'group': 'RCB'}, {'name': 'Rohit Sharma', 'group': 'MI'}, {'name': 'AB de Villiers', 'group': 'RCB'}, {'name': 'Jasprit Bumrah', 'group': 'MI'}, {'name': 'KL Rahul', 'group': 'KXIP'}, {'name': 'Md. Shammi', 'group': 'KXIP'},]; class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Example', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: GroupedListView<dynamic, String>( elements: _elements, groupBy: (element) => element['group'], groupComparator: (value1, value2) => value2.compareTo(value1), itemComparator: (item1, item2) => item1['name'].compareTo(item2['name']), order: GroupedListOrder.DESC, useStickyGroupSeparators: true, groupSeparatorBuilder: (String value) => Padding( padding: const EdgeInsets.all(8.0), child: Text( value, textAlign: TextAlign.center, style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), ), ), itemBuilder: (c, element) { return Card( elevation: 8.0, margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0), child: Container( child: ListTile( contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0), leading: ImageIcon( NetworkImage('http://www.pngall.com/wp-content/uploads/2017/04/IPL-Logo-2017-PNG.png') ), title: Text(element['name']), ), ), ); }, ), ), ); }}", "e": 31083, "s": 29012, "text": null }, { "code": null, "e": 31095, "s": 31087, "text": "Output:" }, { "code": null, "e": 31108, "s": 31099, "text": "sweetyty" }, { "code": null, "e": 31116, "s": 31108, "text": "android" }, { "code": null, "e": 31124, "s": 31116, "text": "Flutter" }, { "code": null, "e": 31146, "s": 31124, "text": "Flutter UI-components" }, { "code": null, "e": 31151, "s": 31146, "text": "Dart" }, { "code": null, "e": 31159, "s": 31151, "text": "Flutter" }, { "code": null, "e": 31257, "s": 31159, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31296, "s": 31257, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 31322, "s": 31296, "text": "ListView Class in Flutter" }, { "code": null, "e": 31348, "s": 31322, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 31371, "s": 31348, "text": "Flutter - Stack Widget" }, { "code": null, "e": 31389, "s": 31371, "text": "Flutter - Dialogs" }, { "code": null, "e": 31428, "s": 31389, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 31445, "s": 31428, "text": "Flutter Tutorial" }, { "code": null, "e": 31471, "s": 31445, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 31494, "s": 31471, "text": "Flutter - Stack Widget" } ]
Difference Between getPath() and getCanonicalPath() in Java - GeeksforGeeks
02 Dec, 2021 getPath() method is a part of File class. This function returns the path of the given file object. The function returns a string object which contains the path of the given file object whereas the getCanonicalPath() method is a part of Path class. This function returns the Canonical pathname of the given file object. If the pathname of the file object is Canonical then it simply returns the path of the current file object. The Canonical path is always absolute and unique, the function removes the ‘.’ ‘..’ from the path if present. Now, both methods getPath() and getCanonicalPath() both are part of the File class and both are File methods to get the File system path. First, we understand the difference between both paths from the following file structure. Illustration: Considering a random path in the windows directory |--D: \--Article \--Test \--Program \--Python \--JAVA \Program1.java If the path- “Python/../JAVA/Program1.java” is passed pass then the value of Path and the canonical path is like the following. Path: Python\..\JAVA\Program1.java Canonical Path: d:\Program\JAVA\Program1.java Now let’s understand the difference between both methods (A)Theoretical Differences This method throws the following exceptions. Security Exception: if the required property value cannot be accessed. I/O Exception: if I/O exception occurs. Example: File f = new File(“c:\\users\\..\\program\\.\\file1.txt”) Path :- c:\users\..\program\.\file1.txt Example: File f = new File(“c:\\users\\..\\program\\.\\file1.txt”) Canonical path :- c:\program\file1.txt Implementation: (B) Practical differences Example Java // Java program to demonstrate the difference// between getPath() and getCanonicalPath() function // Importing input output classesimport java.io.*; // Classpublic class GFG { // Main driver method public static void main(String args[]) { // Try block to check exceptions try { // Creating a file object File f = new File( "g:\\gfg\\A(7)PATH\\Test\\..\\file1.txt"); // Getting the Path of file object String path = f.getPath(); // Getting the Canonical path of the file object String canonical = f.getCanonicalPath(); // Display the file path of the file object // and also the Canonical path of file System.out.println("Path : " + path); System.out.println("Canonical path : " + canonical); } // Catch block to handle if exception/s occurs catch (Exception e) { // Exception message is printed where occurred System.err.println(e.getMessage()); } }} Output: Path (getPath()): g:\gfg\A(7)PATH\Test\..\file1.txt path (getCanonicalPath()) : G:\gfg\A(7)PATH\file1.txt sumitgumber28 varshagumber28 Java-File Class Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25225, "s": 25197, "text": "\n02 Dec, 2021" }, { "code": null, "e": 25990, "s": 25225, "text": "getPath() method is a part of File class. This function returns the path of the given file object. The function returns a string object which contains the path of the given file object whereas the getCanonicalPath() method is a part of Path class. This function returns the Canonical pathname of the given file object. If the pathname of the file object is Canonical then it simply returns the path of the current file object. The Canonical path is always absolute and unique, the function removes the ‘.’ ‘..’ from the path if present. Now, both methods getPath() and getCanonicalPath() both are part of the File class and both are File methods to get the File system path. First, we understand the difference between both paths from the following file structure." }, { "code": null, "e": 26055, "s": 25990, "text": "Illustration: Considering a random path in the windows directory" }, { "code": null, "e": 26164, "s": 26055, "text": "|--D:\n \\--Article \n \\--Test\n \\--Program\n \\--Python\n \\--JAVA\n \\Program1.java" }, { "code": null, "e": 26292, "s": 26164, "text": "If the path- “Python/../JAVA/Program1.java” is passed pass then the value of Path and the canonical path is like the following." }, { "code": null, "e": 26327, "s": 26292, "text": "Path: Python\\..\\JAVA\\Program1.java" }, { "code": null, "e": 26373, "s": 26327, "text": "Canonical Path: d:\\Program\\JAVA\\Program1.java" }, { "code": null, "e": 26430, "s": 26373, "text": "Now let’s understand the difference between both methods" }, { "code": null, "e": 26457, "s": 26430, "text": "(A)Theoretical Differences" }, { "code": null, "e": 26503, "s": 26457, "text": "This method throws the following exceptions. " }, { "code": null, "e": 26574, "s": 26503, "text": "Security Exception: if the required property value cannot be accessed." }, { "code": null, "e": 26614, "s": 26574, "text": "I/O Exception: if I/O exception occurs." }, { "code": null, "e": 26623, "s": 26614, "text": "Example:" }, { "code": null, "e": 26681, "s": 26623, "text": "File f = new File(“c:\\\\users\\\\..\\\\program\\\\.\\\\file1.txt”)" }, { "code": null, "e": 26721, "s": 26681, "text": "Path :- c:\\users\\..\\program\\.\\file1.txt" }, { "code": null, "e": 26730, "s": 26721, "text": "Example:" }, { "code": null, "e": 26788, "s": 26730, "text": "File f = new File(“c:\\\\users\\\\..\\\\program\\\\.\\\\file1.txt”)" }, { "code": null, "e": 26827, "s": 26788, "text": "Canonical path :- c:\\program\\file1.txt" }, { "code": null, "e": 26869, "s": 26827, "text": "Implementation: (B) Practical differences" }, { "code": null, "e": 26877, "s": 26869, "text": "Example" }, { "code": null, "e": 26882, "s": 26877, "text": "Java" }, { "code": "// Java program to demonstrate the difference// between getPath() and getCanonicalPath() function // Importing input output classesimport java.io.*; // Classpublic class GFG { // Main driver method public static void main(String args[]) { // Try block to check exceptions try { // Creating a file object File f = new File( \"g:\\\\gfg\\\\A(7)PATH\\\\Test\\\\..\\\\file1.txt\"); // Getting the Path of file object String path = f.getPath(); // Getting the Canonical path of the file object String canonical = f.getCanonicalPath(); // Display the file path of the file object // and also the Canonical path of file System.out.println(\"Path : \" + path); System.out.println(\"Canonical path : \" + canonical); } // Catch block to handle if exception/s occurs catch (Exception e) { // Exception message is printed where occurred System.err.println(e.getMessage()); } }}", "e": 27972, "s": 26882, "text": null }, { "code": null, "e": 27980, "s": 27972, "text": "Output:" }, { "code": null, "e": 28086, "s": 27980, "text": "Path (getPath()): g:\\gfg\\A(7)PATH\\Test\\..\\file1.txt\npath (getCanonicalPath()) : G:\\gfg\\A(7)PATH\\file1.txt" }, { "code": null, "e": 28100, "s": 28086, "text": "sumitgumber28" }, { "code": null, "e": 28115, "s": 28100, "text": "varshagumber28" }, { "code": null, "e": 28131, "s": 28115, "text": "Java-File Class" }, { "code": null, "e": 28138, "s": 28131, "text": "Picked" }, { "code": null, "e": 28143, "s": 28138, "text": "Java" }, { "code": null, "e": 28157, "s": 28143, "text": "Java Programs" }, { "code": null, "e": 28162, "s": 28157, "text": "Java" }, { "code": null, "e": 28260, "s": 28162, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28275, "s": 28260, "text": "Stream In Java" }, { "code": null, "e": 28296, "s": 28275, "text": "Constructors in Java" }, { "code": null, "e": 28315, "s": 28296, "text": "Exceptions in Java" }, { "code": null, "e": 28345, "s": 28315, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28391, "s": 28345, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28417, "s": 28391, "text": "Java Programming Examples" }, { "code": null, "e": 28451, "s": 28417, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 28498, "s": 28451, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 28530, "s": 28498, "text": "How to Iterate HashMap in Java?" } ]
time() function in C - GeeksforGeeks
15 Jul, 2021 The time() function is defined in time.h (ctime in C++) header file. This function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. If second is not a null pointer, the returned value is also stored in the object pointed to by second. Syntax: time_t time( time_t *second ) Parameter: This function accepts single parameter second. This parameter is used to set the time_t object which store the time.Return Value: This function returns current calendar time as a object of type time_t. Program 1: C // C program to demonstrate// example of time() function.#include <stdio.h>#include <time.h> int main (){ time_t seconds; seconds = time(NULL); printf("Seconds since January 1, 1970 = %ld\n", seconds); return(0);} Seconds since January 1, 1970 = 1538123990 Example 2: C // C program to demonstrate// example of time() function. #include <stdio.h>#include <time.h> int main(){ time_t seconds; // Stores time seconds time(&seconds); printf("Seconds since January 1, 1970 = %ld\n", seconds); return 0;} Seconds since January 1, 1970 = 1538123990 clintra C-Functions C-Library C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Function Pointer in C Substring in C++ fork() in C Strings in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File Header files in C/C++ and its uses Basics of File Handling in C
[ { "code": null, "e": 26160, "s": 26132, "text": "\n15 Jul, 2021" }, { "code": null, "e": 26428, "s": 26160, "text": "The time() function is defined in time.h (ctime in C++) header file. This function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. If second is not a null pointer, the returned value is also stored in the object pointed to by second." }, { "code": null, "e": 26438, "s": 26428, "text": "Syntax: " }, { "code": null, "e": 26468, "s": 26438, "text": "time_t time( time_t *second )" }, { "code": null, "e": 26681, "s": 26468, "text": "Parameter: This function accepts single parameter second. This parameter is used to set the time_t object which store the time.Return Value: This function returns current calendar time as a object of type time_t." }, { "code": null, "e": 26693, "s": 26681, "text": "Program 1: " }, { "code": null, "e": 26695, "s": 26693, "text": "C" }, { "code": "// C program to demonstrate// example of time() function.#include <stdio.h>#include <time.h> int main (){ time_t seconds; seconds = time(NULL); printf(\"Seconds since January 1, 1970 = %ld\\n\", seconds); return(0);}", "e": 26931, "s": 26695, "text": null }, { "code": null, "e": 26974, "s": 26931, "text": "Seconds since January 1, 1970 = 1538123990" }, { "code": null, "e": 26988, "s": 26976, "text": "Example 2: " }, { "code": null, "e": 26990, "s": 26988, "text": "C" }, { "code": "// C program to demonstrate// example of time() function. #include <stdio.h>#include <time.h> int main(){ time_t seconds; // Stores time seconds time(&seconds); printf(\"Seconds since January 1, 1970 = %ld\\n\", seconds); return 0;}", "e": 27242, "s": 26990, "text": null }, { "code": null, "e": 27285, "s": 27242, "text": "Seconds since January 1, 1970 = 1538123990" }, { "code": null, "e": 27295, "s": 27287, "text": "clintra" }, { "code": null, "e": 27307, "s": 27295, "text": "C-Functions" }, { "code": null, "e": 27317, "s": 27307, "text": "C-Library" }, { "code": null, "e": 27328, "s": 27317, "text": "C Language" }, { "code": null, "e": 27339, "s": 27328, "text": "C Programs" }, { "code": null, "e": 27437, "s": 27339, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27472, "s": 27437, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 27518, "s": 27472, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 27540, "s": 27518, "text": "Function Pointer in C" }, { "code": null, "e": 27557, "s": 27540, "text": "Substring in C++" }, { "code": null, "e": 27569, "s": 27557, "text": "fork() in C" }, { "code": null, "e": 27582, "s": 27569, "text": "Strings in C" }, { "code": null, "e": 27623, "s": 27582, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 27664, "s": 27623, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 27699, "s": 27664, "text": "Header files in C/C++ and its uses" } ]
Basic Quiz App In Flutter API - GeeksforGeeks
25 Nov, 2021 Flutter API is an open-source software development kit for building beautiful UI which is natively compiled. Currently, it is available is a stable version for IOS and Android OS. In this app we are going to have the features or modules mentioned below: Five multiple-choice questions ( more questions can be added ). Four selectable options for each question in the form of buttons except the last one. The score will be calculated based on the option selected for each question (Internally). And based on the final score a remark will be shown at the end of the quiz in addition to the score and restart button. There are two screens in the app home (where questions will be shown) and the result screen ( where score and remark will be shown). The whole app will be separated into five different modules namely main.dart, question.dart, answer.dart,quiz.dart and result.dart. Making this app will give you a good revision of flutter and dart basics. As we are covering a lot of concepts such as: Showing Widgets on the screen. Recycling Widgets. Changing Screens. Internal Logic and else. To start making the app we first have to create a flutter project which will give us many files and folders. In the Lib folder, there is a main.dart file already present. And now in the same folder rest, four files should be created:- question.dart answer.dart quiz.dart and result.dart Step 1: In step one we are going to Create MyApp class and make it stateful. Add questions for the home screen. Create a widget tree for the home screen. Starting with the main.dart file Dart import 'package:flutter/material.dart'; import './quiz.dart';import './result.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override State<StatefulWidget> createState() { return _MyAppState(); }} class _MyAppState extends State<MyApp> { final _questions = const [ { 'questionText': 'Q1. Who created Flutter?', 'answers': [ {'text': 'Facebook', 'score': -2}, {'text': 'Adobe', 'score': -2}, {'text': 'Google', 'score': 10}, {'text': 'Microsoft', 'score': -2}, ], }, { 'questionText': 'Q2. What is Flutter?', 'answers': [ {'text': 'Android Development Kit', 'score': -2}, {'text': 'IOS Development Kit', 'score': -2}, {'text': 'Web Development Kit', 'score': -2}, { 'text': 'SDK to build beautiful IOS, Android, Web & Desktop Native Apps', 'score': 10 }, ], }, { 'questionText': ' Q3. Which programing language is used by Flutter', 'answers': [ {'text': 'Ruby', 'score': -2}, {'text': 'Dart', 'score': 10}, {'text': 'C++', 'score': -2}, {'text': 'Kotlin', 'score': -2}, ], }, { 'questionText': 'Q4. Who created Dart programing language?', 'answers': [ {'text': 'Lars Bak and Kasper Lund', 'score': 10}, {'text': 'Brendan Eich', 'score': -2}, {'text': 'Bjarne Stroustrup', 'score': -2}, {'text': 'Jeremy Ashkenas', 'score': -2}, ], }, { 'questionText': 'Q5. Is Flutter for Web and Desktop available in stable version?', 'answers': [ { 'text': 'Yes', 'score': -2, }, {'text': 'No', 'score': 10}, ], }, ]; var _questionIndex = 0; var _totalScore = 0; void _resetQuiz() { setState(() { _questionIndex = 0; _totalScore = 0; }); } void _answerQuestion(int score) { _totalScore += score; setState(() { _questionIndex = _questionIndex + 1; }); print(_questionIndex); if (_questionIndex < _questions.length) { print('We have more questions!'); } else { print('No more questions!'); } } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Geeks for Geeks'), backgroundColor: Color(0xFF00E676), ), body: Padding( padding: const EdgeInsets.all(30.0), child: _questionIndex < _questions.length ? Quiz( answerQuestion: _answerQuestion, questionIndex: _questionIndex, questions: _questions, ) //Quiz : Result(_totalScore, _resetQuiz), ), //Padding ), //Scaffold debugShowCheckedModeBanner: false, ); //MaterialApp }} In Flutter main.dart file is the entry point from which the code starts executing. In the main.dart file firstly material design package has been imported in addition to quiz.dart and result.dart . Then a function runApp has been created with parameter as MyApp. After the declaration of class MyApp which is a stateful widget, the state of class MyApp has been laid out. Now that is followed by the four questions along with their respective answer options & score. And at the end, we have the widget tree for the home screen, which shows the appBar with title, body with the questions and options. At the last, the debug banner has been disabled. We have classes like Quiz or Result, that will be defined in the following pages. Step 2: In step two we will create Class Quiz (used in the home screen) Widget tree for class Quiz quiz.dart Dart import 'package:flutter/material.dart'; import './answer.dart';import './question.dart'; class Quiz extends StatelessWidget { final List<Map<String, Object>> questions; final int questionIndex; final Function answerQuestion; Quiz({ required this.questions, required this.answerQuestion, required this.questionIndex, }); @override Widget build(BuildContext context) { return Column( children: [ Question( questions[questionIndex]['questionText'], ), //Question ...(questions[questionIndex]['answers'] as List<Map<String, Object>>) .map((answer) { return Answer(() => answerQuestion(answer['score']), answer['text']); }).toList() ], ); //Column }} This is the quiz.dart which was already imported in the main.dart file. In this file the class Quiz is being defined which is used in the main.dart file. Class Quiz has been extended as stateless widget as it need not change any time in the run cycle of the app, which is followed by constructor Quiz. Then we have the widget tree that defines the structure of the class Quiz which is basically the questions and their options. Again we have the class Question which will be defined in the question.dart file. Step 3: In step three we will create Class Question (again used in the home screen) Widget tree for the class Question question.dart Dart import 'package:flutter/material.dart'; class Question extends StatelessWidget { final String questionText; Question(this.questionText); @override Widget build(BuildContext context) { return Container( width: double.infinity, margin: EdgeInsets.all(10), child: Text( questionText, style: TextStyle(fontSize: 28), textAlign: TextAlign.center, ), //Text ); //Container }} This question.dart file has already been imported into the quiz.dart file, which uses the class Question. The class Question would be a stateless one as similar to the Quiz it needs not change in the run cycle. Then we have the constructor Question which is followed by the widget tree that gives structure to the Question widget. Step 4: In step four we will create Class Answer (used in the home screen) Widget tree for class Answer answer.dart Dart import 'package:flutter/material.dart'; class Answer extends StatelessWidget { final Function selectHandler; final String answerText; Answer(this.selectHandler, this.answerText); @override Widget build(BuildContext context) { return Container( width: double.infinity, child: RaisedButton( color: Color(0xFF00E676), textColor: Colors.white, child: Text(answerText), onPressed: selectHandler, ), //RaisedButton ); //Container }} This answer.dart file was also imported in the quiz.dart file. This file contains the Answer class which was uses in the quiz.dart file. Again similar to Quiz and Question class Answer would also be stateless. In the class Answer function, selectHandelr and string answerText have been passed using the keyword final as they belong to stateful widget and hence need to specified immutable and not doing so will result in a dart analysis warning. That is followed by the constructor and the usual widget tree to give it a structure. Step 5: In the last step we will create Class Result for (result screen) Remark logic Class Result widget tree result.dart Dart import 'package:flutter/material.dart'; class Result extends StatelessWidget { final int resultScore; final Function resetHandler; Result(this.resultScore, this.resetHandler); //Remark Logic String get resultPhrase { String resultText; if (resultScore >= 41) { resultText = 'You are awesome!'; print(resultScore); } else if (resultScore >= 31) { resultText = 'Pretty likeable!'; print(resultScore); } else if (resultScore >= 21) { resultText = 'You need to work more!'; } else if (resultScore >= 1) { resultText = 'You need to work hard!'; } else { resultText = 'This is a poor score!'; print(resultScore); } return resultText; } @override Widget build(BuildContext context) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( resultPhrase, style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold), textAlign: TextAlign.center, ), //Text Text( 'Score ' '$resultScore', style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold), textAlign: TextAlign.center, ), //Text FlatButton( child: Text( 'Restart Quiz!', ), //Text textColor: Colors.blue, onPressed: resetHandler, ), //FlatButton ], //<Widget>[] ), //Column ); //Center }} This result.dart file had been imported in the main.dart file already as the class Result is defined in this file. Class result will not change in the app run cycle therefore it is a stateless widget. As subclasses or variables which are used in the stateful widget needs to be made immutable keyword final has been used, it is followed by the Result keyword. After that, we have the resulting logic which decided which remark would be shown after the quiz bases on the final score. And at last, we have the widget tree that defines the structure of the class Result. And now after completing the result.dart file our basic quiz app is completed now. We can preview the app in any physical device or emulator or even in the browser. It should look something like this. After the app has been finalized, apk for the app can be generated by giving the command ‘flutter build apk’ in the terminal. rajeev0719singh sadeanandkiran rkbhola5 Dart Flutter Project Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Listview.builder in Flutter Flutter - Asset Image Splash Screen in Flutter Flutter - Custom Bottom Navigation Bar Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget Flutter - Flexible Widget Flutter - BoxShadow Widget
[ { "code": null, "e": 27183, "s": 27155, "text": "\n25 Nov, 2021" }, { "code": null, "e": 27363, "s": 27183, "text": "Flutter API is an open-source software development kit for building beautiful UI which is natively compiled. Currently, it is available is a stable version for IOS and Android OS." }, { "code": null, "e": 27437, "s": 27363, "text": "In this app we are going to have the features or modules mentioned below:" }, { "code": null, "e": 27501, "s": 27437, "text": "Five multiple-choice questions ( more questions can be added )." }, { "code": null, "e": 27587, "s": 27501, "text": "Four selectable options for each question in the form of buttons except the last one." }, { "code": null, "e": 27677, "s": 27587, "text": "The score will be calculated based on the option selected for each question (Internally)." }, { "code": null, "e": 27797, "s": 27677, "text": "And based on the final score a remark will be shown at the end of the quiz in addition to the score and restart button." }, { "code": null, "e": 27930, "s": 27797, "text": "There are two screens in the app home (where questions will be shown) and the result screen ( where score and remark will be shown)." }, { "code": null, "e": 28062, "s": 27930, "text": "The whole app will be separated into five different modules namely main.dart, question.dart, answer.dart,quiz.dart and result.dart." }, { "code": null, "e": 28182, "s": 28062, "text": "Making this app will give you a good revision of flutter and dart basics. As we are covering a lot of concepts such as:" }, { "code": null, "e": 28213, "s": 28182, "text": "Showing Widgets on the screen." }, { "code": null, "e": 28232, "s": 28213, "text": "Recycling Widgets." }, { "code": null, "e": 28250, "s": 28232, "text": "Changing Screens." }, { "code": null, "e": 28265, "s": 28250, "text": "Internal Logic" }, { "code": null, "e": 28275, "s": 28265, "text": "and else." }, { "code": null, "e": 28511, "s": 28275, "text": "To start making the app we first have to create a flutter project which will give us many files and folders. In the Lib folder, there is a main.dart file already present. And now in the same folder rest, four files should be created:- " }, { "code": null, "e": 28525, "s": 28511, "text": "question.dart" }, { "code": null, "e": 28537, "s": 28525, "text": "answer.dart" }, { "code": null, "e": 28551, "s": 28537, "text": "quiz.dart and" }, { "code": null, "e": 28563, "s": 28551, "text": "result.dart" }, { "code": null, "e": 28599, "s": 28563, "text": "Step 1: In step one we are going to" }, { "code": null, "e": 28640, "s": 28599, "text": "Create MyApp class and make it stateful." }, { "code": null, "e": 28675, "s": 28640, "text": "Add questions for the home screen." }, { "code": null, "e": 28717, "s": 28675, "text": "Create a widget tree for the home screen." }, { "code": null, "e": 28750, "s": 28717, "text": "Starting with the main.dart file" }, { "code": null, "e": 28755, "s": 28750, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; import './quiz.dart';import './result.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override State<StatefulWidget> createState() { return _MyAppState(); }} class _MyAppState extends State<MyApp> { final _questions = const [ { 'questionText': 'Q1. Who created Flutter?', 'answers': [ {'text': 'Facebook', 'score': -2}, {'text': 'Adobe', 'score': -2}, {'text': 'Google', 'score': 10}, {'text': 'Microsoft', 'score': -2}, ], }, { 'questionText': 'Q2. What is Flutter?', 'answers': [ {'text': 'Android Development Kit', 'score': -2}, {'text': 'IOS Development Kit', 'score': -2}, {'text': 'Web Development Kit', 'score': -2}, { 'text': 'SDK to build beautiful IOS, Android, Web & Desktop Native Apps', 'score': 10 }, ], }, { 'questionText': ' Q3. Which programing language is used by Flutter', 'answers': [ {'text': 'Ruby', 'score': -2}, {'text': 'Dart', 'score': 10}, {'text': 'C++', 'score': -2}, {'text': 'Kotlin', 'score': -2}, ], }, { 'questionText': 'Q4. Who created Dart programing language?', 'answers': [ {'text': 'Lars Bak and Kasper Lund', 'score': 10}, {'text': 'Brendan Eich', 'score': -2}, {'text': 'Bjarne Stroustrup', 'score': -2}, {'text': 'Jeremy Ashkenas', 'score': -2}, ], }, { 'questionText': 'Q5. Is Flutter for Web and Desktop available in stable version?', 'answers': [ { 'text': 'Yes', 'score': -2, }, {'text': 'No', 'score': 10}, ], }, ]; var _questionIndex = 0; var _totalScore = 0; void _resetQuiz() { setState(() { _questionIndex = 0; _totalScore = 0; }); } void _answerQuestion(int score) { _totalScore += score; setState(() { _questionIndex = _questionIndex + 1; }); print(_questionIndex); if (_questionIndex < _questions.length) { print('We have more questions!'); } else { print('No more questions!'); } } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Geeks for Geeks'), backgroundColor: Color(0xFF00E676), ), body: Padding( padding: const EdgeInsets.all(30.0), child: _questionIndex < _questions.length ? Quiz( answerQuestion: _answerQuestion, questionIndex: _questionIndex, questions: _questions, ) //Quiz : Result(_totalScore, _resetQuiz), ), //Padding ), //Scaffold debugShowCheckedModeBanner: false, ); //MaterialApp }}", "e": 31600, "s": 28755, "text": null }, { "code": null, "e": 32331, "s": 31600, "text": "In Flutter main.dart file is the entry point from which the code starts executing. In the main.dart file firstly material design package has been imported in addition to quiz.dart and result.dart . Then a function runApp has been created with parameter as MyApp. After the declaration of class MyApp which is a stateful widget, the state of class MyApp has been laid out. Now that is followed by the four questions along with their respective answer options & score. And at the end, we have the widget tree for the home screen, which shows the appBar with title, body with the questions and options. At the last, the debug banner has been disabled. We have classes like Quiz or Result, that will be defined in the following pages." }, { "code": null, "e": 32366, "s": 32331, "text": "Step 2: In step two we will create" }, { "code": null, "e": 32403, "s": 32366, "text": "Class Quiz (used in the home screen)" }, { "code": null, "e": 32430, "s": 32403, "text": "Widget tree for class Quiz" }, { "code": null, "e": 32440, "s": 32430, "text": "quiz.dart" }, { "code": null, "e": 32445, "s": 32440, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; import './answer.dart';import './question.dart'; class Quiz extends StatelessWidget { final List<Map<String, Object>> questions; final int questionIndex; final Function answerQuestion; Quiz({ required this.questions, required this.answerQuestion, required this.questionIndex, }); @override Widget build(BuildContext context) { return Column( children: [ Question( questions[questionIndex]['questionText'], ), //Question ...(questions[questionIndex]['answers'] as List<Map<String, Object>>) .map((answer) { return Answer(() => answerQuestion(answer['score']), answer['text']); }).toList() ], ); //Column }}", "e": 33183, "s": 32445, "text": null }, { "code": null, "e": 33693, "s": 33183, "text": "This is the quiz.dart which was already imported in the main.dart file. In this file the class Quiz is being defined which is used in the main.dart file. Class Quiz has been extended as stateless widget as it need not change any time in the run cycle of the app, which is followed by constructor Quiz. Then we have the widget tree that defines the structure of the class Quiz which is basically the questions and their options. Again we have the class Question which will be defined in the question.dart file." }, { "code": null, "e": 33730, "s": 33693, "text": "Step 3: In step three we will create" }, { "code": null, "e": 33777, "s": 33730, "text": "Class Question (again used in the home screen)" }, { "code": null, "e": 33812, "s": 33777, "text": "Widget tree for the class Question" }, { "code": null, "e": 33826, "s": 33812, "text": "question.dart" }, { "code": null, "e": 33831, "s": 33826, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; class Question extends StatelessWidget { final String questionText; Question(this.questionText); @override Widget build(BuildContext context) { return Container( width: double.infinity, margin: EdgeInsets.all(10), child: Text( questionText, style: TextStyle(fontSize: 28), textAlign: TextAlign.center, ), //Text ); //Container }}", "e": 34255, "s": 33831, "text": null }, { "code": null, "e": 34586, "s": 34255, "text": "This question.dart file has already been imported into the quiz.dart file, which uses the class Question. The class Question would be a stateless one as similar to the Quiz it needs not change in the run cycle. Then we have the constructor Question which is followed by the widget tree that gives structure to the Question widget." }, { "code": null, "e": 34622, "s": 34586, "text": "Step 4: In step four we will create" }, { "code": null, "e": 34661, "s": 34622, "text": "Class Answer (used in the home screen)" }, { "code": null, "e": 34690, "s": 34661, "text": "Widget tree for class Answer" }, { "code": null, "e": 34702, "s": 34690, "text": "answer.dart" }, { "code": null, "e": 34707, "s": 34702, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; class Answer extends StatelessWidget { final Function selectHandler; final String answerText; Answer(this.selectHandler, this.answerText); @override Widget build(BuildContext context) { return Container( width: double.infinity, child: RaisedButton( color: Color(0xFF00E676), textColor: Colors.white, child: Text(answerText), onPressed: selectHandler, ), //RaisedButton ); //Container }}", "e": 35191, "s": 34707, "text": null }, { "code": null, "e": 35724, "s": 35191, "text": "This answer.dart file was also imported in the quiz.dart file. This file contains the Answer class which was uses in the quiz.dart file. Again similar to Quiz and Question class Answer would also be stateless. In the class Answer function, selectHandelr and string answerText have been passed using the keyword final as they belong to stateful widget and hence need to specified immutable and not doing so will result in a dart analysis warning. That is followed by the constructor and the usual widget tree to give it a structure." }, { "code": null, "e": 35764, "s": 35724, "text": "Step 5: In the last step we will create" }, { "code": null, "e": 35797, "s": 35764, "text": "Class Result for (result screen)" }, { "code": null, "e": 35810, "s": 35797, "text": "Remark logic" }, { "code": null, "e": 35835, "s": 35810, "text": "Class Result widget tree" }, { "code": null, "e": 35847, "s": 35835, "text": "result.dart" }, { "code": null, "e": 35852, "s": 35847, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; class Result extends StatelessWidget { final int resultScore; final Function resetHandler; Result(this.resultScore, this.resetHandler); //Remark Logic String get resultPhrase { String resultText; if (resultScore >= 41) { resultText = 'You are awesome!'; print(resultScore); } else if (resultScore >= 31) { resultText = 'Pretty likeable!'; print(resultScore); } else if (resultScore >= 21) { resultText = 'You need to work more!'; } else if (resultScore >= 1) { resultText = 'You need to work hard!'; } else { resultText = 'This is a poor score!'; print(resultScore); } return resultText; } @override Widget build(BuildContext context) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( resultPhrase, style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold), textAlign: TextAlign.center, ), //Text Text( 'Score ' '$resultScore', style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold), textAlign: TextAlign.center, ), //Text FlatButton( child: Text( 'Restart Quiz!', ), //Text textColor: Colors.blue, onPressed: resetHandler, ), //FlatButton ], //<Widget>[] ), //Column ); //Center }}", "e": 37325, "s": 35852, "text": null }, { "code": null, "e": 37893, "s": 37325, "text": "This result.dart file had been imported in the main.dart file already as the class Result is defined in this file. Class result will not change in the app run cycle therefore it is a stateless widget. As subclasses or variables which are used in the stateful widget needs to be made immutable keyword final has been used, it is followed by the Result keyword. After that, we have the resulting logic which decided which remark would be shown after the quiz bases on the final score. And at last, we have the widget tree that defines the structure of the class Result." }, { "code": null, "e": 38094, "s": 37893, "text": "And now after completing the result.dart file our basic quiz app is completed now. We can preview the app in any physical device or emulator or even in the browser. It should look something like this." }, { "code": null, "e": 38220, "s": 38094, "text": "After the app has been finalized, apk for the app can be generated by giving the command ‘flutter build apk’ in the terminal." }, { "code": null, "e": 38236, "s": 38220, "text": "rajeev0719singh" }, { "code": null, "e": 38251, "s": 38236, "text": "sadeanandkiran" }, { "code": null, "e": 38260, "s": 38251, "text": "rkbhola5" }, { "code": null, "e": 38265, "s": 38260, "text": "Dart" }, { "code": null, "e": 38273, "s": 38265, "text": "Flutter" }, { "code": null, "e": 38281, "s": 38273, "text": "Project" }, { "code": null, "e": 38379, "s": 38281, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38411, "s": 38379, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 38439, "s": 38411, "text": "Listview.builder in Flutter" }, { "code": null, "e": 38461, "s": 38439, "text": "Flutter - Asset Image" }, { "code": null, "e": 38486, "s": 38461, "text": "Splash Screen in Flutter" }, { "code": null, "e": 38525, "s": 38486, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 38557, "s": 38525, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 38596, "s": 38557, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 38622, "s": 38596, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 38648, "s": 38622, "text": "Flutter - Flexible Widget" } ]
How to Sort Pandas DataFrame? - GeeksforGeeks
28 Jul, 2020 In this article, we will discuss how to sort Pandas Dataframe. Let’s create a dataframe. Example : Python3 # importing pandas libraryimport pandas as pd # creating and initializing a nested listage_list = [['Afghanistan', 1952, 8425333, 'Asia'], ['Australia', 1957, 9712569, 'Oceania'], ['Brazil', 1962, 76039390, 'Americas'], ['China', 1957, 637408000, 'Asia'], ['France', 1957, 44310863, 'Europe'], ['India', 1952, 3.72e+08, 'Asia'], ['United States', 1957, 171984000, 'Americas']] # creating a pandas dataframedf = pd.DataFrame(age_list, columns=['Country', 'Year', 'Population', 'Continent']) df Output : In order to sort the data frame in pandas, function sort_values() is used. Pandas sort_values() can sort the data frame in Ascending or Descending order. Example 1: Sorting the Data frame in Ascending order Python3 # importing pandas libraryimport pandas as pd # creating and initializing a nested list age_list = [['Afghanistan',1952,8425333,'Asia'], ['Australia',1957,9712569,'Oceania'], ['Brazil',1962,76039390,'Americas'], ['China',1957,637408000,'Asia'], ['France',1957,44310863,'Europe'], ['India',1952,3.72e+08,'Asia'], ['United States',1957,171984000,'Americas']] # creating a pandas dataframedf = pd.DataFrame(age_list,columns=['Country','Year', 'Population','Continent']) # Sorting by column 'Country'df.sort_values(by=['Country']) Output : Example 2: Sorting the Data frame in Descending order Python3 # Sorting Pandas Dataframe in Descending Order # importing pandas libraryimport pandas as pd # Initializing the nested list with Data setage_list = [['Afghanistan', 1952, 8425333, 'Asia'], ['Australia', 1957, 9712569, 'Oceania'], ['Brazil', 1962, 76039390, 'Americas'], ['China', 1957, 637408000, 'Asia'], ['France', 1957, 44310863, 'Europe'], ['India', 1952, 3.72e+08, 'Asia'], ['United States', 1957, 171984000, 'Americas']] # creating a pandas dataframedf = pd.DataFrame(age_list, columns=['Country', 'Year', 'Population', 'Continent']) # Sorting by column "Population"df.sort_values(by=['Population'], ascending=False) Output : Example 3: Sorting Pandas Data frame by putting missing values first Python3 # Sorting Pandas Data frame by putting# missing values first # importing pandas libraryimport pandas as pd # Initializing the nested list with Data setage_list = [['Afghanistan', 1952, 8425333, 'Asia'], ['Australia', 1957, 9712569, 'Oceania'], ['Brazil', 1962, 76039390, 'Americas'], ['China', 1957, 637408000, 'Asia'], ['France', 1957, 44310863, 'Europe'], ['India', 1952, 3.72e+08, 'Asia'], ['United States', 1957, 0, 'Americas']] # creating a pandas dataframedf = pd.DataFrame(age_list, columns=['Country', 'Year', 'Population', 'Continent']) # Sorting by column "Population"# by putting missing values firstdf.sort_values(by=['Population'], na_position='first') Output : Example 4: Sorting Data frames by multiple columns Python3 # Sorting Pandas Dataframe based on# the Values of Multiple Columns # importing pandas libraryimport pandas as pd # Initializing the nested list with data setage_list = [['Afghanistan', 1952, 8425333, 'Asia'], ['Australia', 1957, 9712569, 'Oceania'], ['Brazil', 1962, 76039390, 'Americas'], ['China', 1957, 637408000, 'Asia'], ['France', 1957, 44310863, 'Europe'], ['India', 1952, 3.72e+08, 'Asia'], ['United States', 1957, 171984000, 'Americas']] # creating a pandas dataframedf = pd.DataFrame(age_list, columns=['Country', 'Year', 'Population', 'Continent']) # Sorting by columns "Country" and then "Continent"df.sort_values(by=['Country', 'Continent']) Output : 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 ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25555, "s": 25527, "text": "\n28 Jul, 2020" }, { "code": null, "e": 25644, "s": 25555, "text": "In this article, we will discuss how to sort Pandas Dataframe. Let’s create a dataframe." }, { "code": null, "e": 25654, "s": 25644, "text": "Example :" }, { "code": null, "e": 25662, "s": 25654, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # creating and initializing a nested listage_list = [['Afghanistan', 1952, 8425333, 'Asia'], ['Australia', 1957, 9712569, 'Oceania'], ['Brazil', 1962, 76039390, 'Americas'], ['China', 1957, 637408000, 'Asia'], ['France', 1957, 44310863, 'Europe'], ['India', 1952, 3.72e+08, 'Asia'], ['United States', 1957, 171984000, 'Americas']] # creating a pandas dataframedf = pd.DataFrame(age_list, columns=['Country', 'Year', 'Population', 'Continent']) df", "e": 26260, "s": 25662, "text": null }, { "code": null, "e": 26269, "s": 26260, "text": "Output :" }, { "code": null, "e": 26423, "s": 26269, "text": "In order to sort the data frame in pandas, function sort_values() is used. Pandas sort_values() can sort the data frame in Ascending or Descending order." }, { "code": null, "e": 26477, "s": 26423, "text": "Example 1: Sorting the Data frame in Ascending order " }, { "code": null, "e": 26485, "s": 26477, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # creating and initializing a nested list age_list = [['Afghanistan',1952,8425333,'Asia'], ['Australia',1957,9712569,'Oceania'], ['Brazil',1962,76039390,'Americas'], ['China',1957,637408000,'Asia'], ['France',1957,44310863,'Europe'], ['India',1952,3.72e+08,'Asia'], ['United States',1957,171984000,'Americas']] # creating a pandas dataframedf = pd.DataFrame(age_list,columns=['Country','Year', 'Population','Continent']) # Sorting by column 'Country'df.sort_values(by=['Country'])", "e": 27116, "s": 26485, "text": null }, { "code": null, "e": 27125, "s": 27116, "text": "Output :" }, { "code": null, "e": 27180, "s": 27125, "text": "Example 2: Sorting the Data frame in Descending order " }, { "code": null, "e": 27188, "s": 27180, "text": "Python3" }, { "code": "# Sorting Pandas Dataframe in Descending Order # importing pandas libraryimport pandas as pd # Initializing the nested list with Data setage_list = [['Afghanistan', 1952, 8425333, 'Asia'], ['Australia', 1957, 9712569, 'Oceania'], ['Brazil', 1962, 76039390, 'Americas'], ['China', 1957, 637408000, 'Asia'], ['France', 1957, 44310863, 'Europe'], ['India', 1952, 3.72e+08, 'Asia'], ['United States', 1957, 171984000, 'Americas']] # creating a pandas dataframedf = pd.DataFrame(age_list, columns=['Country', 'Year', 'Population', 'Continent']) # Sorting by column \"Population\"df.sort_values(by=['Population'], ascending=False)", "e": 27917, "s": 27188, "text": null }, { "code": null, "e": 27926, "s": 27917, "text": "Output :" }, { "code": null, "e": 27995, "s": 27926, "text": "Example 3: Sorting Pandas Data frame by putting missing values first" }, { "code": null, "e": 28003, "s": 27995, "text": "Python3" }, { "code": "# Sorting Pandas Data frame by putting# missing values first # importing pandas libraryimport pandas as pd # Initializing the nested list with Data setage_list = [['Afghanistan', 1952, 8425333, 'Asia'], ['Australia', 1957, 9712569, 'Oceania'], ['Brazil', 1962, 76039390, 'Americas'], ['China', 1957, 637408000, 'Asia'], ['France', 1957, 44310863, 'Europe'], ['India', 1952, 3.72e+08, 'Asia'], ['United States', 1957, 0, 'Americas']] # creating a pandas dataframedf = pd.DataFrame(age_list, columns=['Country', 'Year', 'Population', 'Continent']) # Sorting by column \"Population\"# by putting missing values firstdf.sort_values(by=['Population'], na_position='first')", "e": 28775, "s": 28003, "text": null }, { "code": null, "e": 28784, "s": 28775, "text": "Output :" }, { "code": null, "e": 28836, "s": 28784, "text": "Example 4: Sorting Data frames by multiple columns" }, { "code": null, "e": 28844, "s": 28836, "text": "Python3" }, { "code": "# Sorting Pandas Dataframe based on# the Values of Multiple Columns # importing pandas libraryimport pandas as pd # Initializing the nested list with data setage_list = [['Afghanistan', 1952, 8425333, 'Asia'], ['Australia', 1957, 9712569, 'Oceania'], ['Brazil', 1962, 76039390, 'Americas'], ['China', 1957, 637408000, 'Asia'], ['France', 1957, 44310863, 'Europe'], ['India', 1952, 3.72e+08, 'Asia'], ['United States', 1957, 171984000, 'Americas']] # creating a pandas dataframedf = pd.DataFrame(age_list, columns=['Country', 'Year', 'Population', 'Continent']) # Sorting by columns \"Country\" and then \"Continent\"df.sort_values(by=['Country', 'Continent'])", "e": 29609, "s": 28844, "text": null }, { "code": null, "e": 29618, "s": 29609, "text": "Output :" }, { "code": null, "e": 29642, "s": 29618, "text": "Python pandas-dataFrame" }, { "code": null, "e": 29656, "s": 29642, "text": "Python-pandas" }, { "code": null, "e": 29663, "s": 29656, "text": "Python" }, { "code": null, "e": 29761, "s": 29663, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29793, "s": 29761, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29835, "s": 29793, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29877, "s": 29835, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29933, "s": 29877, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29960, "s": 29933, "text": "Python Classes and Objects" }, { "code": null, "e": 29991, "s": 29960, "text": "Python | os.path.join() method" }, { "code": null, "e": 30030, "s": 29991, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30059, "s": 30030, "text": "Create a directory in Python" }, { "code": null, "e": 30081, "s": 30059, "text": "Defaultdict in Python" } ]
How To Test Your Software With Julia | by Emmett Boudreau | Towards Data Science
Testing is one of the most important aspects of iterative software development. This is because tests can reveal problems with software automatically without ever needing to actually use the software. Needless to say, it is probably a bad idea to push software that does not even work to a repository, and testing can avoid ever running into that issue. The implementation of testing into the Julia programming language is an implementation that I think is rather awesome and unique. I think it is great because it provides a very structured and easy way to test software using conditionals and macros. Today I wanted to walk through the basics of the Testing.jl package for Julia so that you can make sure your software works before making a huge mistake! In order to demonstrate Julia’s testing package, we are first going to need to set up a new project. In order to set up a new project, we can use Pkg.generate(), or the generate command in the Pkg REPL. Once in the Julia REPL, I will press ] and generate our new project named “ Sample.” julia> ](@v1.6) pkg> generate sample Next, I will backspace out of that REPL and then press ; to enter the Bash REPL. Afterwards, we will cd into our new Project folder. julia> ;shell> cd sample Now I will cd into the source folder and nano the sample.jl file, adding a new function that we can test. shell> cd src/home/emmett/dev/julia/sample/srcshell> nano sample.jl Inside of this file, I put a few functions that are used for model validation, along with the functions that are used to support them: mean(x) = sum(x) / length(x)function mae(actual,pred) l = length(actual) lp = length(pred) if l != lp throw(ArgumentError("The array shape does not match!")) end result = actual-pred maeunf = mean(result) if maeunf < 0 maeunf = (maeunf - maeunf) - maeunf end return(maeunf)endfunction mse(y,ŷ) diff = y .- ŷ diff = diff .^ 2 Σdiff = sum(diff) return(Σdiff)endfunction correlationcoeff(x,y) n = length(x) yl = length(y) @assert n == yl DimensionMismatch("These Arrays are not the same size.") xy = x .* y sx = sum(x) sy = sum(y) sxy = sum(xy) x2 = x .^ 2 y2 = y .^ 2 sx2 = sum(x2) sy2 = sum(y2) ((n*sxy) - (sx * sy)) / (sqrt((((n*sx2)-(sx^2)) * ((n*sy2)-(sy^2)))))endfunction r2(actual,pred) l = length(actual) lp = length(pred) if l != lp throw(ArgumentError("The array shape does not match!")) end r = correlationcoeff(actual,pred) rsq = r^2 rsq = rsq * 100 return(rsq)endexport r2, mae, mse Then I used ctrl+O to right that new buffer out, and now we can get started on actually testing these functions! Now that we actually have a package to test, we can go about setting up our test environment. With Julia packages, both the testing and the documentation are considered packages separate to the original package. That in mind, we are going to use the generate command once again in order to create both of these project directories. We will activate this new test environment, and then we will add the test dependency to its virtual environment. shell> cd ../home/emmett/dev/julia/sample(@v1.6) pkg> activate test Activating new environment at `~/dev/julia/sample/test/Project.toml`(test) pkg> add Test Updating registry at `~/.julia/registries/General` Resolving package versions... Updating `~/dev/julia/sample/test/Project.toml` [8dfed614] + Test Updating `~/dev/julia/sample/test/Manifest.toml` [2a0f44e3] + Base64 [b77e0a4c] + InteractiveUtils [56ddb016] + Logging [d6f4376e] + Markdown [9a3f8284] + Random [9e88b42a] + Serialization [8dfed614] + Test(test) pkg> Now we can write our testing algorithms. The first function inside of the package is MAE. In order to perform a test, we need to start a test set. This is done with the test set macro. After the macro, we provide a string as the first parameter, and then we provide an expression as the second parameter. The string is a title of for our test-set, and the expression is the code that will perform our test. We can create such an expression using a begin and end block. That all comes together to look something like this: using Testinclude("../src/sample.jl")using Main.sample@testset "MAE tests" beginend We will start these tests with a test where the two are equal, for this scenario, the MAE should be one. The test macro takes a single argument, and that argument is a boolean. Let’s use a bool-type bitwise operator on the MAE of two equal arrays, which should be equal to zero. x = [5, 10, 15]y = [5, 10, 15]@test mae(x, y) == 0 Our next test is going to be whether or not we are actually getting the mean of the difference of the dims. x, y = [4, 10, 15], [5, 10, 15] @test mae(x, y) == mean([1, 0, 0]) For a final test set that looks like this: using Main.sample: r2, mae, mse, mean@testset "MAE Tests" begin x = [5, 10, 15] y = [5, 10, 15] @test mae(x, y) == 0 x, y = [4, 10, 15], [5, 10, 15] @test mae(x, y) == mean([1, 0, 0])end Next, we will begin a new test set for the MSE function. We will be doing one assertion test, and one zero test just like we did before. @testset "MSE Tests" beginx = [5, 10, 15]y = [5, 10, 15]@test mse(x, y) == 0y = [4, 10, 15]y2 = [6, 10, 15]@test mse(x, y) == mse(x, y2)end Next, we will test our r2 function. Since our r2 function is meant to return a percentage, we will both check the type of the return as a Float64 and then check if it is less than 1. @testset "R2 Tests" beginx = randn(50)y = randn(50)@test r2(x, y) <= 1@test typeof(r2(x, y)) == Float64 Now we can run our tests by going back to the REPL and including this code. include("test/test.jl") No matter what kind of software you create, it is always going to be important to test it. Julia has a pretty cool method of testing software that utilizes macros and makes the tests very organized. I do happen to prefer this to a lot of other styles of testing, and I think that Julia makes testing a breeze using this methodology. Thank you very much for reading my article, and I hope the information provided is valuable towards making your software work better! Thank you for reading!
[ { "code": null, "e": 928, "s": 171, "text": "Testing is one of the most important aspects of iterative software development. This is because tests can reveal problems with software automatically without ever needing to actually use the software. Needless to say, it is probably a bad idea to push software that does not even work to a repository, and testing can avoid ever running into that issue. The implementation of testing into the Julia programming language is an implementation that I think is rather awesome and unique. I think it is great because it provides a very structured and easy way to test software using conditionals and macros. Today I wanted to walk through the basics of the Testing.jl package for Julia so that you can make sure your software works before making a huge mistake!" }, { "code": null, "e": 1216, "s": 928, "text": "In order to demonstrate Julia’s testing package, we are first going to need to set up a new project. In order to set up a new project, we can use Pkg.generate(), or the generate command in the Pkg REPL. Once in the Julia REPL, I will press ] and generate our new project named “ Sample.”" }, { "code": null, "e": 1253, "s": 1216, "text": "julia> ](@v1.6) pkg> generate sample" }, { "code": null, "e": 1386, "s": 1253, "text": "Next, I will backspace out of that REPL and then press ; to enter the Bash REPL. Afterwards, we will cd into our new Project folder." }, { "code": null, "e": 1411, "s": 1386, "text": "julia> ;shell> cd sample" }, { "code": null, "e": 1517, "s": 1411, "text": "Now I will cd into the source folder and nano the sample.jl file, adding a new function that we can test." }, { "code": null, "e": 1585, "s": 1517, "text": "shell> cd src/home/emmett/dev/julia/sample/srcshell> nano sample.jl" }, { "code": null, "e": 1720, "s": 1585, "text": "Inside of this file, I put a few functions that are used for model validation, along with the functions that are used to support them:" }, { "code": null, "e": 2735, "s": 1720, "text": "mean(x) = sum(x) / length(x)function mae(actual,pred) l = length(actual) lp = length(pred) if l != lp throw(ArgumentError(\"The array shape does not match!\")) end result = actual-pred maeunf = mean(result) if maeunf < 0 maeunf = (maeunf - maeunf) - maeunf end return(maeunf)endfunction mse(y,ŷ) diff = y .- ŷ diff = diff .^ 2 Σdiff = sum(diff) return(Σdiff)endfunction correlationcoeff(x,y) n = length(x) yl = length(y) @assert n == yl DimensionMismatch(\"These Arrays are not the same size.\") xy = x .* y sx = sum(x) sy = sum(y) sxy = sum(xy) x2 = x .^ 2 y2 = y .^ 2 sx2 = sum(x2) sy2 = sum(y2) ((n*sxy) - (sx * sy)) / (sqrt((((n*sx2)-(sx^2)) * ((n*sy2)-(sy^2)))))endfunction r2(actual,pred) l = length(actual) lp = length(pred) if l != lp throw(ArgumentError(\"The array shape does not match!\")) end r = correlationcoeff(actual,pred) rsq = r^2 rsq = rsq * 100 return(rsq)endexport r2, mae, mse" }, { "code": null, "e": 2848, "s": 2735, "text": "Then I used ctrl+O to right that new buffer out, and now we can get started on actually testing these functions!" }, { "code": null, "e": 3293, "s": 2848, "text": "Now that we actually have a package to test, we can go about setting up our test environment. With Julia packages, both the testing and the documentation are considered packages separate to the original package. That in mind, we are going to use the generate command once again in order to create both of these project directories. We will activate this new test environment, and then we will add the test dependency to its virtual environment." }, { "code": null, "e": 3835, "s": 3293, "text": "shell> cd ../home/emmett/dev/julia/sample(@v1.6) pkg> activate test Activating new environment at `~/dev/julia/sample/test/Project.toml`(test) pkg> add Test Updating registry at `~/.julia/registries/General` Resolving package versions... Updating `~/dev/julia/sample/test/Project.toml` [8dfed614] + Test Updating `~/dev/julia/sample/test/Manifest.toml` [2a0f44e3] + Base64 [b77e0a4c] + InteractiveUtils [56ddb016] + Logging [d6f4376e] + Markdown [9a3f8284] + Random [9e88b42a] + Serialization [8dfed614] + Test(test) pkg>" }, { "code": null, "e": 4357, "s": 3835, "text": "Now we can write our testing algorithms. The first function inside of the package is MAE. In order to perform a test, we need to start a test set. This is done with the test set macro. After the macro, we provide a string as the first parameter, and then we provide an expression as the second parameter. The string is a title of for our test-set, and the expression is the code that will perform our test. We can create such an expression using a begin and end block. That all comes together to look something like this:" }, { "code": null, "e": 4441, "s": 4357, "text": "using Testinclude(\"../src/sample.jl\")using Main.sample@testset \"MAE tests\" beginend" }, { "code": null, "e": 4720, "s": 4441, "text": "We will start these tests with a test where the two are equal, for this scenario, the MAE should be one. The test macro takes a single argument, and that argument is a boolean. Let’s use a bool-type bitwise operator on the MAE of two equal arrays, which should be equal to zero." }, { "code": null, "e": 4771, "s": 4720, "text": "x = [5, 10, 15]y = [5, 10, 15]@test mae(x, y) == 0" }, { "code": null, "e": 4879, "s": 4771, "text": "Our next test is going to be whether or not we are actually getting the mean of the difference of the dims." }, { "code": null, "e": 4949, "s": 4879, "text": "x, y = [4, 10, 15], [5, 10, 15] @test mae(x, y) == mean([1, 0, 0])" }, { "code": null, "e": 4992, "s": 4949, "text": "For a final test set that looks like this:" }, { "code": null, "e": 5194, "s": 4992, "text": "using Main.sample: r2, mae, mse, mean@testset \"MAE Tests\" begin x = [5, 10, 15] y = [5, 10, 15] @test mae(x, y) == 0 x, y = [4, 10, 15], [5, 10, 15] @test mae(x, y) == mean([1, 0, 0])end" }, { "code": null, "e": 5331, "s": 5194, "text": "Next, we will begin a new test set for the MSE function. We will be doing one assertion test, and one zero test just like we did before." }, { "code": null, "e": 5471, "s": 5331, "text": "@testset \"MSE Tests\" beginx = [5, 10, 15]y = [5, 10, 15]@test mse(x, y) == 0y = [4, 10, 15]y2 = [6, 10, 15]@test mse(x, y) == mse(x, y2)end" }, { "code": null, "e": 5654, "s": 5471, "text": "Next, we will test our r2 function. Since our r2 function is meant to return a percentage, we will both check the type of the return as a Float64 and then check if it is less than 1." }, { "code": null, "e": 5758, "s": 5654, "text": "@testset \"R2 Tests\" beginx = randn(50)y = randn(50)@test r2(x, y) <= 1@test typeof(r2(x, y)) == Float64" }, { "code": null, "e": 5834, "s": 5758, "text": "Now we can run our tests by going back to the REPL and including this code." }, { "code": null, "e": 5858, "s": 5834, "text": "include(\"test/test.jl\")" } ]
Compute Derivative of an Expression in R Programming - deriv() and D() Function - GeeksforGeeks
30 Jun, 2020 In R programming, derivative of a function can be computed using deriv() and D() function. It is used to compute derivatives of simple expressions. Syntax:deriv(expr, name)D(expr, name) Parameters:expr: represents an expression or a formula with no LHSname: represents character vector to which derivatives will be computed Example 1: # Expression or formulaf = expression(x^2 + 5*x + 1) # Derivativecat("Using deriv() function:\n")print(deriv(f, "x")) cat("\nUsing D() function:\n")print(D(f, 'x')) Output: Using deriv() function: expression({ .value <- x^2 + 5 * x + 1 .grad <- array(0, c(length(.value), 1L), list(NULL, c("x"))) .grad[, "x"] <- 2 * x + 5 attr(.value, "gradient") <- .grad .value }) Using D() function: 2 * x + 5 Example 2: # Little harder derivative # Using deriv() Functioncat("Using deriv() function:\n")print(deriv(quote(sinpi(x^2)), "x")) # Using D() Functioncat("\nUsing D() function:\n")print(D(quote(sinpi(x^2)), "x")) Output: Using deriv() function: expression({ .expr1 <- x^2 .value <- sinpi(.expr1) .grad <- array(0, c(length(.value), 1L), list(NULL, c("x"))) .grad[, "x"] <- cospi(.expr1) * (pi * (2 * x)) attr(.value, "gradient") <- .grad .value }) Using D() function: cospi(x^2) * (pi * (2 * x)) R Math-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to import an Excel File into R ? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Time Series Analysis in R R - if statement
[ { "code": null, "e": 25242, "s": 25214, "text": "\n30 Jun, 2020" }, { "code": null, "e": 25390, "s": 25242, "text": "In R programming, derivative of a function can be computed using deriv() and D() function. It is used to compute derivatives of simple expressions." }, { "code": null, "e": 25428, "s": 25390, "text": "Syntax:deriv(expr, name)D(expr, name)" }, { "code": null, "e": 25566, "s": 25428, "text": "Parameters:expr: represents an expression or a formula with no LHSname: represents character vector to which derivatives will be computed" }, { "code": null, "e": 25577, "s": 25566, "text": "Example 1:" }, { "code": "# Expression or formulaf = expression(x^2 + 5*x + 1) # Derivativecat(\"Using deriv() function:\\n\")print(deriv(f, \"x\")) cat(\"\\nUsing D() function:\\n\")print(D(f, 'x'))", "e": 25744, "s": 25577, "text": null }, { "code": null, "e": 25752, "s": 25744, "text": "Output:" }, { "code": null, "e": 25998, "s": 25752, "text": "Using deriv() function:\nexpression({\n .value <- x^2 + 5 * x + 1\n .grad <- array(0, c(length(.value), 1L), list(NULL, c(\"x\")))\n .grad[, \"x\"] <- 2 * x + 5\n attr(.value, \"gradient\") <- .grad\n .value\n})\n\nUsing D() function:\n2 * x + 5\n" }, { "code": null, "e": 26009, "s": 25998, "text": "Example 2:" }, { "code": "# Little harder derivative # Using deriv() Functioncat(\"Using deriv() function:\\n\")print(deriv(quote(sinpi(x^2)), \"x\")) # Using D() Functioncat(\"\\nUsing D() function:\\n\")print(D(quote(sinpi(x^2)), \"x\"))", "e": 26214, "s": 26009, "text": null }, { "code": null, "e": 26222, "s": 26214, "text": "Output:" }, { "code": null, "e": 26523, "s": 26222, "text": "Using deriv() function:\nexpression({\n .expr1 <- x^2\n .value <- sinpi(.expr1)\n .grad <- array(0, c(length(.value), 1L), list(NULL, c(\"x\")))\n .grad[, \"x\"] <- cospi(.expr1) * (pi * (2 * x))\n attr(.value, \"gradient\") <- .grad\n .value\n})\n\nUsing D() function:\ncospi(x^2) * (pi * (2 * x))\n" }, { "code": null, "e": 26539, "s": 26523, "text": "R Math-Function" }, { "code": null, "e": 26550, "s": 26539, "text": "R Language" }, { "code": null, "e": 26648, "s": 26550, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26700, "s": 26648, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26738, "s": 26700, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26773, "s": 26738, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26831, "s": 26773, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 26880, "s": 26831, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 26917, "s": 26880, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 26967, "s": 26917, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27010, "s": 26967, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 27036, "s": 27010, "text": "Time Series Analysis in R" } ]
How to Create a RAID 0 Storage Array with ‘mdadm’ on Ubuntu 16.04
In this article, we will learn how to create a RAID 0 Array configuration using the ‘mdadm’ utility. The ‘mdadm’ is a utility which is used to create and manage storage arrays on Linux with RAID capability where the administrators are having a great flexibility in managing the individual storage devices and creating the logical storage with a high performance and redundancy. RAID 0 array will work by dividing the data into small chunks and strips that data across the available storage disks, which means that each and every storage disk will contain a portion of data and when retrieving the data multiple disks are referred. There is no redundancy if any of the drives fails since all the data could be lost. The primary benefit of the RAID 0 is its high performance. Minimum of 2 storage disks are required. RAID 0 has no parity. A Ubuntu machine with a non-root user with Sudo permission. Minimum two storage devices for creating RAID 0 storage. To find the attached storages in the machine, we can use the below command. $ lsblk –o NAME,SIZE,FSTYPE,TYPE,MOUNTPOINT Output NAME SIZE FSTYPE TYPE MOUNTPOINT xda 20G disk xdb 20G disk vda 20G disk ├─vda1 20G ext4 part / └─vda15 1M part As we can see in the above output we have 2 disks without any filesystem with 20GB and the devices are named as /dev/xda, /dev/xdb for this machine or session. For creating the RAID 0 array, we will use the ‘mdadm’ – create command with the device name we want to create and the raid level with the no of devices attaching to the RAID. $ sudo mdadm --create --verbose /dev/md0 --level=0 --raid-devices=2 /dev/xda /dev/xdb The mdadm tool will start the creation of an array and it will take some time to complete the configuration. We can monitor the progress using the below command – $ cat /proc/mdstat Personalities : [raid1] [linear] [multipath] [raid0] [raid6] [raid5] [raid4] [raid10] md0 : active raid0 xdb[1] xda[0] 209584128 blocks super 1.2, 512k chunk, algorithm 2 [3/2] [UU_] ... unused devices: <none> In the above output, we can see the /dev/md0 device is being created with RAID 0 using the /dev/xda, /dev/xdb storage devices which will also show the progress on the raid device. Before we mount the Array disk, we needed to create a filesystem on the array disk which we have created using the above steps. We will be creating a filesystem on the array $ sudo mkfs.ext4 –F /dev/md0 We will now create a mount point and attaché the new RAID disk created in the above steps. $ sudo mkdir –p /mnt/raiddisk1 $ sudo mount /dev/md0 /mnt/raiddisk1 Verifying the new mount point or RAID disk $ df –h –x devtmpfs –x tmpfs Output Filesystem Size Used Avail Use% Mounted on /dev/vda1 20G 1.1G 18G 6% / /dev/md0 40G 120M 39G 3% /mnt/raiddisk1 As we can see the new filesystem is mounted and accessible. Now we can scan the active array and append the file with the below command $ sudo mdadm –details –scan | sudo tee –a /etc/mdadm/mdadm.conf We needed to update the ‘initramfs’ file so that the RADI array will be available when the machine get started with the boot process. $ sudo update-initramfs -u Adding the RAID array to mount automatically at the boot time. Add the below line to the /etc/fstab. /dev/md0 /mnt/raiddisk1 ext4 defaults,nofail,discard 0 0 In the above setup and configuration we have configured a RAID 0 level array using two disks we can combine two disks and make one single disk with a combined capacity with high and mounted the disk at the boot time, so that whenever we restart the server the raid disk will be loaded.
[ { "code": null, "e": 1163, "s": 1062, "text": "In this article, we will learn how to create a RAID 0 Array configuration using the ‘mdadm’ utility." }, { "code": null, "e": 1440, "s": 1163, "text": "The ‘mdadm’ is a utility which is used to create and manage storage arrays on Linux with RAID capability where the administrators are having a great flexibility in managing the individual storage devices and creating the logical storage with a high performance and redundancy." }, { "code": null, "e": 1777, "s": 1440, "text": "RAID 0 array will work by dividing the data into small chunks and strips that data across the available storage disks, which means that each and every storage disk will contain a portion of data and when retrieving the data multiple disks are referred. There is no redundancy if any of the drives fails since all the data could be lost." }, { "code": null, "e": 1836, "s": 1777, "text": "The primary benefit of the RAID 0 is its high performance." }, { "code": null, "e": 1877, "s": 1836, "text": "Minimum of 2 storage disks are required." }, { "code": null, "e": 1899, "s": 1877, "text": "RAID 0 has no parity." }, { "code": null, "e": 1959, "s": 1899, "text": "A Ubuntu machine with a non-root user with Sudo permission." }, { "code": null, "e": 2016, "s": 1959, "text": "Minimum two storage devices for creating RAID 0 storage." }, { "code": null, "e": 2092, "s": 2016, "text": "To find the attached storages in the machine, we can use the below command." }, { "code": null, "e": 2339, "s": 2092, "text": "$ lsblk –o NAME,SIZE,FSTYPE,TYPE,MOUNTPOINT\nOutput\nNAME SIZE FSTYPE TYPE MOUNTPOINT\nxda 20G disk\nxdb 20G disk\nvda 20G disk\n├─vda1 20G ext4 part /\n└─vda15 1M part" }, { "code": null, "e": 2499, "s": 2339, "text": "As we can see in the above output we have 2 disks without any filesystem with 20GB and the devices are named as /dev/xda, /dev/xdb for this machine or session." }, { "code": null, "e": 2675, "s": 2499, "text": "For creating the RAID 0 array, we will use the ‘mdadm’ – create command with the device name we want to create and the raid level with the no of devices attaching to the RAID." }, { "code": null, "e": 2761, "s": 2675, "text": "$ sudo mdadm --create --verbose /dev/md0 --level=0 --raid-devices=2 /dev/xda /dev/xdb" }, { "code": null, "e": 2924, "s": 2761, "text": "The mdadm tool will start the creation of an array and it will take some time to complete the configuration. We can monitor the progress using the below command –" }, { "code": null, "e": 3153, "s": 2924, "text": "$ cat /proc/mdstat\nPersonalities : [raid1] [linear] [multipath] [raid0] [raid6] [raid5] [raid4] [raid10]\nmd0 : active raid0 xdb[1] xda[0]\n209584128 blocks super 1.2, 512k chunk, algorithm 2 [3/2] [UU_]\n...\nunused devices: <none>" }, { "code": null, "e": 3333, "s": 3153, "text": "In the above output, we can see the /dev/md0 device is being created with RAID 0 using the /dev/xda, /dev/xdb storage devices which will also show the progress on the raid device." }, { "code": null, "e": 3461, "s": 3333, "text": "Before we mount the Array disk, we needed to create a filesystem on the array disk which we have created using the above steps." }, { "code": null, "e": 3507, "s": 3461, "text": "We will be creating a filesystem on the array" }, { "code": null, "e": 3536, "s": 3507, "text": "$ sudo mkfs.ext4 –F /dev/md0" }, { "code": null, "e": 3628, "s": 3536, "text": "We will now create a mount point and attaché the new RAID disk created in the above steps." }, { "code": null, "e": 3696, "s": 3628, "text": "$ sudo mkdir –p /mnt/raiddisk1\n$ sudo mount /dev/md0 /mnt/raiddisk1" }, { "code": null, "e": 3739, "s": 3696, "text": "Verifying the new mount point or RAID disk" }, { "code": null, "e": 3935, "s": 3739, "text": "$ df –h –x devtmpfs –x tmpfs\nOutput\nFilesystem Size Used Avail Use% Mounted on\n/dev/vda1 20G 1.1G 18G 6% /\n/dev/md0 40G 120M 39G 3% /mnt/raiddisk1" }, { "code": null, "e": 3995, "s": 3935, "text": "As we can see the new filesystem is mounted and accessible." }, { "code": null, "e": 4071, "s": 3995, "text": "Now we can scan the active array and append the file with the below command" }, { "code": null, "e": 4135, "s": 4071, "text": "$ sudo mdadm –details –scan | sudo tee –a /etc/mdadm/mdadm.conf" }, { "code": null, "e": 4269, "s": 4135, "text": "We needed to update the ‘initramfs’ file so that the RADI array will be available when the machine get started with the boot process." }, { "code": null, "e": 4296, "s": 4269, "text": "$ sudo update-initramfs -u" }, { "code": null, "e": 4359, "s": 4296, "text": "Adding the RAID array to mount automatically at the boot time." }, { "code": null, "e": 4397, "s": 4359, "text": "Add the below line to the /etc/fstab." }, { "code": null, "e": 4454, "s": 4397, "text": "/dev/md0 /mnt/raiddisk1 ext4 defaults,nofail,discard 0 0" }, { "code": null, "e": 4740, "s": 4454, "text": "In the above setup and configuration we have configured a RAID 0 level array using two disks we can combine two disks and make one single disk with a combined capacity with high and mounted the disk at the boot time, so that whenever we restart the server the raid disk will be loaded." } ]
How to Install Winamp on Ubuntu/Linux Mint
Are you looking for an alternative Linux music player? Winamp might be a good option to consider.Winamp supports a wide variety of contemporary and specialized music file formats, including MIDI, MOD, MPEG-1 audio layers 1 and 2, AAC, M4A, FLAC, WAV, OGG Vorbis, and Windows Media Audio. It supports gapless playback for MP3 and AAC, and Replay Gain for volume leveling across tracks. This article describes” How to install Winamp on Ubuntu/Linux Mint” To install Winamp, get access of Winamp PPA from repository, use the following command – $ sudo add-apt-repository ppa:forkotov02/ppa The sample output should be like this – Releases of Qt-based multimedia player (Qmmp) Installation: sudo add-apt-repository ppa:forkotov02/ppa sudo apt-get update sudo apt-get install qmmp qmmp-plugin-pack libtag1-vanilla Qt4-based version (for Ubuntu 16.04 or higher): sudo apt-get install qmmp-qt4 qmmp-plugin-pack-qt4 More info: https://launchpad.net/~forkotov02/+archive/ubuntu/ppa Press [ENTER] to continue or ctrl-c to cancel adding it gpg: keyring `/tmp/tmpr684g0lc/secring.gpg' created gpg: keyring `/tmp/tmpr684g0lc/pubring.gpg' created gpg: requesting key C4FBC3E6 from hkp server keyserver.ubuntu.com gpg: /tmp/tmpr684g0lc/trustdb.gpg: trustdb created gpg: key C4FBC3E6: public key "Launchpad PPA for Ilya Kotov" imported gpg: Total number processed: 1 gpg: imported: 1 (RSA: 1) OK Then update Linux package indexes by using the following command – $ sudo apt-get update The sample output should be like this – Ign http://dl.google.com stable InRelease Hit http://dl.google.com stable Release.gpg Hit http://dl.google.com stable Release Get:1 http://security.ubuntu.com trusty-security InRelease [65.9 kB] Hit http://dl.google.com stable/main amd64 Packages Ign http://in.archive.ubuntu.com trusty InRelease Hit http://ppa.launchpad.net trusty InRelease Ign http://extras.ubuntu.com trusty InRelease Get:2 http://in.archive.ubuntu.com trusty-updates InRelease [65.9 kB] Get:3 http://extras.ubuntu.com trusty Release.gpg [72 B] Get:4 http://ppa.launchpad.net trusty InRelease [15.4 kB] Hit http://extras.ubuntu.com trusty Release Hit http://extras.ubuntu.com trusty/main Sources Hit http://ppa.launchpad.net trusty InRelease Get:5 http://security.ubuntu.com trusty-security/main Sources [108 kB] Get:6 http://in.archive.ubuntu.com trusty-backports InRelease [65.9 kB] Hit http://extras.ubuntu.com trusty/main amd64 Packages ............................................................... To install winamp, use the following command – $ sudo apt-get install qmmp qmmp-plugin-pack The sample output should be like this – Reading package lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: linux-headers-4.2.0-27 linux-headers-4.2.0-27-generic linux-image-4.2.0-27-generic linux-image-extra-4.2.0-27-generic linux-signed-image-4.2.0-27-generic php7.0-opcache Use 'apt-get autoremove' to remove them. The following extra packages will be installed: libadplug-2.2.1-0 libbinio1ldbl libbs2b0 libopusfile0 libqmmp-misc libqmmp0 libqmmpui0 libsidplayfp libxmp4 milkytracker opencubicplayer opencubicplayer-doc schism unmo3 xmp Suggested packages: adplug-utils sidplay2fp goattracker qmmp-plugin-projectm The following NEW packages will be installed: libadplug-2.2.1-0 libbinio1ldbl libbs2b0 libopusfile0 libqmmp-misc libqmmp0 libqmmpui0 libsidplayfp libxmp4 milkytracker opencubicplayer opencubicplayer-doc qmmp qmmp-plugin-pack schism unmo3 xmp 0 upgraded, 17 newly installed, 0 to remove and 10 not upgraded. Need to get 5,614 kB of archives. After this operation, 21.7 MB of additional disk space will be used. Do you want to continue? [Y/n] y ...................................... To open Winamp, use the following command – $ qmmp The output should be like this – To remove winamp from Linux, it is essential to remove winamp ppa as shown below – $ sudo add-apt-repository --remove ppa:forkotov02/ppa The sample output should be like this – Releases of Qt-based multimedia player (Qmmp) Installation: sudo add-apt-repository ppa:forkotov02/ppa sudo apt-get update sudo apt-get install qmmp qmmp-plugin-pack libtag1-vanilla Qt4-based version (for Ubuntu 16.04 or higher): sudo apt-get install qmmp-qt4 qmmp-plugin-pack-qt4 More info: https://launchpad.net/~forkotov02/+archive/ubuntu/ppa Press [ENTER] to continue or ctrl-c to cancel removing it To remove Winamp, use the following command – $ sudo apt-get remove qmmp The sample output should be like this – Reading package lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: linux-headers-4.2.0-27 linux-headers-4.2.0-27-generic linux-image-4.2.0-27-generic linux-image-extra-4.2.0-27-generic linux-signed-image-4.2.0-27-generic php7.0-opcache Use 'apt-get autoremove' to remove them. The following packages will be REMOVED: qmmp 0 upgraded, 0 newly installed, 1 to remove and 8 not upgraded. After this operation, 340 kB disk space will be freed. Do you want to continue? [Y/n] y (Reading database ... 252174 files and directories currently installed.) Removing qmmp (0.9.7-1ubuntu1~trusty0) ... Processing triggers for gnome-menus (3.10.1-0ubuntu2) ... Processing triggers for desktop-file-utils (0.22-1ubuntu1) ... Processing triggers for bamfdaemon (0.5.1+14.04.20140409-0ubuntu1) ... Rebuilding /usr/share/applications/bamf-2.index... Processing triggers for mime-support (3.54ubuntu1.1) ... ........................................................ Congratulations! Now, you know “How to install Winamp on Ubuntu/Linux Mint”. We’ll learn more about these types of commands in our next Linux post. Keep reading!
[ { "code": null, "e": 1515, "s": 1062, "text": "Are you looking for an alternative Linux music player? Winamp might be a good option to consider.Winamp supports a wide variety of contemporary and specialized music file formats, including MIDI, MOD, MPEG-1 audio layers 1 and 2, AAC, M4A, FLAC, WAV, OGG Vorbis, and Windows Media Audio. It supports gapless playback for MP3 and AAC, and Replay Gain for volume leveling across tracks. This article describes” How to install Winamp on Ubuntu/Linux Mint”" }, { "code": null, "e": 1604, "s": 1515, "text": "To install Winamp, get access of Winamp PPA from repository, use the following command –" }, { "code": null, "e": 1649, "s": 1604, "text": "$ sudo add-apt-repository ppa:forkotov02/ppa" }, { "code": null, "e": 1689, "s": 1649, "text": "The sample output should be like this –" }, { "code": null, "e": 2464, "s": 1689, "text": "Releases of Qt-based multimedia player (Qmmp)\n\nInstallation:\nsudo add-apt-repository ppa:forkotov02/ppa\nsudo apt-get update\nsudo apt-get install qmmp qmmp-plugin-pack libtag1-vanilla\n\nQt4-based version (for Ubuntu 16.04 or higher):\nsudo apt-get install qmmp-qt4 qmmp-plugin-pack-qt4\n\n More info: https://launchpad.net/~forkotov02/+archive/ubuntu/ppa\nPress [ENTER] to continue or ctrl-c to cancel adding it\n\ngpg: keyring `/tmp/tmpr684g0lc/secring.gpg' created\ngpg: keyring `/tmp/tmpr684g0lc/pubring.gpg' created\ngpg: requesting key C4FBC3E6 from hkp server keyserver.ubuntu.com\ngpg: /tmp/tmpr684g0lc/trustdb.gpg: trustdb created\ngpg: key C4FBC3E6: public key \"Launchpad PPA for Ilya Kotov\" imported\ngpg: Total number processed: 1\ngpg: imported: 1 (RSA: 1)\nOK" }, { "code": null, "e": 2531, "s": 2464, "text": "Then update Linux package indexes by using the following command –" }, { "code": null, "e": 2553, "s": 2531, "text": "$ sudo apt-get update" }, { "code": null, "e": 2593, "s": 2553, "text": "The sample output should be like this –" }, { "code": null, "e": 3569, "s": 2593, "text": "Ign http://dl.google.com stable InRelease\nHit http://dl.google.com stable Release.gpg\nHit http://dl.google.com stable Release\nGet:1 http://security.ubuntu.com trusty-security InRelease [65.9 kB]\nHit http://dl.google.com stable/main amd64 Packages\nIgn http://in.archive.ubuntu.com trusty InRelease\nHit http://ppa.launchpad.net trusty InRelease\nIgn http://extras.ubuntu.com trusty InRelease\nGet:2 http://in.archive.ubuntu.com trusty-updates InRelease [65.9 kB]\nGet:3 http://extras.ubuntu.com trusty Release.gpg [72 B]\nGet:4 http://ppa.launchpad.net trusty InRelease [15.4 kB]\nHit http://extras.ubuntu.com trusty Release\nHit http://extras.ubuntu.com trusty/main Sources\nHit http://ppa.launchpad.net trusty InRelease\nGet:5 http://security.ubuntu.com trusty-security/main Sources [108 kB]\nGet:6 http://in.archive.ubuntu.com trusty-backports InRelease [65.9 kB]\nHit http://extras.ubuntu.com trusty/main amd64 Packages\n..............................................................." }, { "code": null, "e": 3616, "s": 3569, "text": "To install winamp, use the following command –" }, { "code": null, "e": 3661, "s": 3616, "text": "$ sudo apt-get install qmmp qmmp-plugin-pack" }, { "code": null, "e": 3701, "s": 3661, "text": "The sample output should be like this –" }, { "code": null, "e": 4891, "s": 3701, "text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nThe following packages were automatically installed and are no longer required:\n linux-headers-4.2.0-27 linux-headers-4.2.0-27-generic\n linux-image-4.2.0-27-generic linux-image-extra-4.2.0-27-generic\n linux-signed-image-4.2.0-27-generic php7.0-opcache\nUse 'apt-get autoremove' to remove them.\nThe following extra packages will be installed:\n libadplug-2.2.1-0 libbinio1ldbl libbs2b0 libopusfile0 libqmmp-misc libqmmp0\n libqmmpui0 libsidplayfp libxmp4 milkytracker opencubicplayer\n opencubicplayer-doc schism unmo3 xmp\nSuggested packages:\n adplug-utils sidplay2fp goattracker qmmp-plugin-projectm\nThe following NEW packages will be installed:\n libadplug-2.2.1-0 libbinio1ldbl libbs2b0 libopusfile0 libqmmp-misc libqmmp0\n libqmmpui0 libsidplayfp libxmp4 milkytracker opencubicplayer\n opencubicplayer-doc qmmp qmmp-plugin-pack schism unmo3 xmp\n0 upgraded, 17 newly installed, 0 to remove and 10 not upgraded.\nNeed to get 5,614 kB of archives.\nAfter this operation, 21.7 MB of additional disk space will be used.\nDo you want to continue? [Y/n] y\n......................................" }, { "code": null, "e": 4935, "s": 4891, "text": "To open Winamp, use the following command –" }, { "code": null, "e": 4942, "s": 4935, "text": "$ qmmp" }, { "code": null, "e": 4975, "s": 4942, "text": "The output should be like this –" }, { "code": null, "e": 5058, "s": 4975, "text": "To remove winamp from Linux, it is essential to remove winamp ppa as shown below –" }, { "code": null, "e": 5112, "s": 5058, "text": "$ sudo add-apt-repository --remove ppa:forkotov02/ppa" }, { "code": null, "e": 5152, "s": 5112, "text": "The sample output should be like this –" }, { "code": null, "e": 5562, "s": 5152, "text": "Releases of Qt-based multimedia player (Qmmp)\n\nInstallation:\nsudo add-apt-repository ppa:forkotov02/ppa\nsudo apt-get update\nsudo apt-get install qmmp qmmp-plugin-pack libtag1-vanilla\n\nQt4-based version (for Ubuntu 16.04 or higher):\nsudo apt-get install qmmp-qt4 qmmp-plugin-pack-qt4\n\n More info: https://launchpad.net/~forkotov02/+archive/ubuntu/ppa\nPress [ENTER] to continue or ctrl-c to cancel removing it" }, { "code": null, "e": 5608, "s": 5562, "text": "To remove Winamp, use the following command –" }, { "code": null, "e": 5635, "s": 5608, "text": "$ sudo apt-get remove qmmp" }, { "code": null, "e": 5675, "s": 5635, "text": "The sample output should be like this –" }, { "code": null, "e": 6735, "s": 5675, "text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nThe following packages were automatically installed and are no longer required:\n linux-headers-4.2.0-27 linux-headers-4.2.0-27-generic\n linux-image-4.2.0-27-generic linux-image-extra-4.2.0-27-generic\n linux-signed-image-4.2.0-27-generic php7.0-opcache\nUse 'apt-get autoremove' to remove them.\nThe following packages will be REMOVED:\n qmmp\n0 upgraded, 0 newly installed, 1 to remove and 8 not upgraded.\nAfter this operation, 340 kB disk space will be freed.\nDo you want to continue? [Y/n] y\n(Reading database ... 252174 files and directories currently installed.)\nRemoving qmmp (0.9.7-1ubuntu1~trusty0) ...\nProcessing triggers for gnome-menus (3.10.1-0ubuntu2) ...\nProcessing triggers for desktop-file-utils (0.22-1ubuntu1) ...\nProcessing triggers for bamfdaemon (0.5.1+14.04.20140409-0ubuntu1) ...\nRebuilding /usr/share/applications/bamf-2.index...\nProcessing triggers for mime-support (3.54ubuntu1.1) ...\n........................................................" }, { "code": null, "e": 6897, "s": 6735, "text": "Congratulations! Now, you know “How to install Winamp on Ubuntu/Linux Mint”. We’ll learn more about these types of commands in our next Linux post. Keep reading!" } ]
Function to check two strings and return common words in JavaScript
We are required to write a JavaScript function that takes in two strings as arguments. The function should then check the two strings for common characters and prepare a new string of those characters. Lastly, the function should return that string. The code for this will be − const str1 = "IloveLinux"; const str2 = "weloveNodejs"; const findCommon = (str1 = '', str2 = '') => { const common = Object.create(null); let i, j, part; for (i = 0; i < str1.length - 1; i++) { for (j = i + 1; j <= str1.length; j++) { part = str1.slice(i, j); if (str2.indexOf(part) !== −1) { common[part] = true; } } } const commonEl = Object.keys(common); return commonEl; }; console.log(findCommon(str1, str2)); And the output in the console will be − [ 'l', 'lo', 'lov', 'love', 'o', 'ov', 'ove', 'v', 've', 'e' ]
[ { "code": null, "e": 1264, "s": 1062, "text": "We are required to write a JavaScript function that takes in two strings as arguments. The function should then check the two strings for common characters and prepare a new string of those characters." }, { "code": null, "e": 1312, "s": 1264, "text": "Lastly, the function should return that string." }, { "code": null, "e": 1340, "s": 1312, "text": "The code for this will be −" }, { "code": null, "e": 1825, "s": 1340, "text": "const str1 = \"IloveLinux\";\nconst str2 = \"weloveNodejs\";\nconst findCommon = (str1 = '', str2 = '') => {\n const common = Object.create(null);\n let i, j, part;\n for (i = 0; i < str1.length - 1; i++) {\n for (j = i + 1; j <= str1.length; j++) {\n part = str1.slice(i, j);\n if (str2.indexOf(part) !== −1) {\n common[part] = true;\n }\n }\n }\n const commonEl = Object.keys(common);\n return commonEl;\n};\nconsole.log(findCommon(str1, str2));" }, { "code": null, "e": 1865, "s": 1825, "text": "And the output in the console will be −" }, { "code": null, "e": 1940, "s": 1865, "text": "[\n 'l', 'lo', 'lov',\n 'love', 'o', 'ov',\n 'ove', 'v', 've',\n 'e'\n]" } ]
Using PyTorchVideo for efficient video understanding | by Eric Hofesmann | Towards Data Science
The massive sea of computer vision models can be difficult to navigate if you are trying to find the best models or even just relevant baselines for your task. Model zoos like TensorFlow Hub and Facebook’s Detectron2 make it easy to access popular models. Further, libraries like PyTorch lightning make it easy to then modify these models to suit your needs. This is all well and good for images, but for videos, it’s another story. Video data is becoming increasingly more popular, but the additional complexity that comes with it often leaves video-related tasks on the backburner. PyTorchVideo is a new library that has set out to make video models just as easy to load, build, and train as image models. PyTorchVideo provides access to a video model zoo, video data processing functions, and a video-focused accelerator to deploy models all backed in PyTorch allowing for seamless integration into existing workflows. The only thing missing from PyTorchVideo to complete your video workflows is a way to visualize your datasets and interpret your model results. This is where FiftyOne comes in. FiftyOne is an open-source tool that I have been working on at Voxel51. It is designed to make it easy to visualize any image or video dataset and explore ground truth and predicted labels stored locally or in the cloud. The flexible representation of FiftyOne datasets and the FiftyOne App let you quickly get hands-on with your datasets and interpret your models to find failure modes, annotation mistakes, visualize complex labels, and more. This blog post is an extension of a recent PyTorchVideo tutorial and is written to teach you how to integrate PyTorchVideo with FiftyOne to close the loop on video-based ML workflows. Specifically, this post covers: Downloading a subset of the Kinetics dataset Loading a video dataset with FiftyOne Using PyTorchVideo to perform inference Visualizing and evaluating the PyTorchVideo model You can run the examples in this blog post directly in your browser in this Google Colab notebook! To follow along with this walkthrough, you will need to install FiftyOne, PyTorchVideo, PyTorch, and TorchVision: pip install fiftyone pytorch torchvision While PyTorchVideo is also installable through pip, the functionality in this post requires it to be installed through GitHub: git clone https://github.com/facebookresearch/pytorchvideo.gitcd pytorchvideopip install -e . This walkthrough uses a subset of the Kinetics-400 dataset which can be downloaded with the following code snippet: One of the many reasons that video datasets are more difficult to work with than image datasets is the fact that many popular video datasets are available only through YouTube. So instead of being able to download a zip containing everything you need, you instead need to run scripts like the one below to download individual videos from YouTube that may or may not have become unavailable since the dataset was curated. For image datasets, there are some rudimentary options available for visualizing batches of data like pillow and OpenCV. There are very few options available for visualizing video datasets. FiftyOne is a new open-source library that provides simple and powerful visualization for both image and video datasets. If your dataset follows a common format, like the COCO format for detections, then you can load it in a single line of code: Even if your dataset is in a custom format, it is still straightforward to load your dataset with FiftyOne. For example, if you are using an object detection video model, you can load your data as follows: In this example, we will be following the PyTorchVision tutorial on running a video classification model. Generally, video classification datasets will be stored on disk in a directory tree whose subfolders define dataset classes. This format can be loaded in one line of code: If you are following along yourself, hover over or click on the samples to play the videos: We also need to download and store a list of default class names that will be used when evaluating predictions: wget https://dl.fbaipublicfiles.com/pyslowfast/dataset/class_names/kinetics_classnames.json In this section, we use PyTorchVideo to download and run a video classification model on the data that we loaded in the previous section and store the results in our dataset. The code in this section is adapted from this PyTorchVideo tutorial. Torch Hub is a repository for pretrained PyTorch models that allow you to download models and run inference on your dataset. PyTorchVideo provides a number of video classification models through their Torch Hub-backed model zoo including SlowFast, I3D, C2D, R(2+1)D, and X3D. The following code snippet downloads the slow branch of SlowFast with a ResNet50 backbone and loads it into Python: Every model has a specific input structure that it expects. The standard workflow is to write custom scripts that perform the necessary loading and transformation functions to format data for every model. PyTorchVideo expedites this process by providing these functions for you in a flexible way that will work for most video processing needs. For example, the following code constructs the transforms to sample frames from the video, normalize, scale, and crop it, without needing to write any of those functions yourself: Since the dataset is being stored in FiftyOne, we can easily iterate through the samples, load and run our model on them with PyTorchVideo, and store the predictions back in FiftyOne for further visualization and analysis: Aside from being an open-source ecosystem for dataset curation, FiftyOne is also designed to visualize, evaluate, and interpret models by allowing you to quickly find and address model failure modes. To this end, we can start by visualizing the predictions generated in the last section: We can then use FiftyOne to evaluate the predictions with the ground truth to view aggregate metrics and plots showing things like confusion matrices and precision-recall curves. This evaluation adds per-sample correctness labels (“eval”) to the dataset, which make it easy to filter by correct/incorrect predictions, or more generally by TP/FP/FN for object detections. Evaluation can be performed in just a single line of code: precision recall f1-score support springboard diving 0.80 0.80 0.80 5 surfing water 1.00 0.60 0.75 5 swimming backstroke 1.00 0.80 0.89 5 swimming breast stroke 0.57 0.80 0.67 5swimming butterfly stroke 1.00 0.60 0.75 5 micro avg 0.82 0.72 0.77 25 macro avg 0.87 0.72 0.77 25 weighted avg 0.87 0.72 0.77 25 Let’s plot the confusion matrix for the classes we are interested in: We can attach this plot to a session object to make it interactive. So if you click one of the cells, the FiftyOne App session updates to show the samples in that cell. Note: Plots are currently only interactive in Jupyter Notebooks but additional environments will be supported soon! FiftyOne also provides a novel query language to create views into your dataset by searching and filtering any given labels and metadata. This makes it easy to explore your dataset and find samples related to any question you may have in mind. For example, we can quickly find samples where the model was least certain about its prediction based on similar confidences across multiple classes and use the per-sample correctness labels (“eval”) from the previous evaluation to only look at incorrectly predicted samples: Visualizing these samples lets us get an idea of the type of data that should be added to the training dataset. To mark these for future reference, we can use the tagging functionality in the FiftyOne App: The ease of this hands-on analysis will generally lead to significant improvements in dataset quality, and consequently improvements in model performance, faster than any analysis only using aggregate dataset statistics. While most large video datasets and research efforts revolve around classification problems like human activity recognition, applications of video-based ML often involve object detection. At the moment, PyTorchVideo primarily supports video classification problems, however, there are video object detection capabilities available in FiftyOne. FiftyOne allows you to either generate predictions from an image-based object detection model in the FiftyOne Model Zoo or add predictions from your own model to a video dataset. There are a host of models available in the zoo. For example, let’s use EfficientDet-D0. We first need to install TensorFlow and AutoML. We can use the eta package that comes with FiftyOne to easily install AutoML: pip install tensorflow==1.14eta install automl Now let’s apply the model to a video and visualize the results: This kind of visualization would require writing custom scripts to load the raw video, annotations, and predictions, then using software like OpenCV to draw boxes and export the visualizations to a new video on disk. Then if you want to change the labels you are looking at you would need to rewrite your script and regenerate the videos every time. Instead, all of this took us only a few lines of code and resulted in an easier-to-use and more flexible representation of our data. Video-based machine learning models are growing in popularity but have lacked the same level of ease-of-use code bases that allow for quick development and evaluation of image models. PyTorchVideo aims to make it easier to implement, train, and evaluate video models through their model zoo, video-focused components, and acceleration functions. On the flip side, where PyTorchVideo is making it easier to work with video models, FiftyOne is an open-source library that aims to make it easy and efficient to curate, evaluate, and improve video (and image) datasets. Together, FiftyOne and PyTorchVideo provide significant savings in the time and effort required to create high-quality video datasets and models. Disclosure: I work at Voxel51 and am a developer of FiftyOne Headquartered in Ann Arbor, Michigan, and founded in 2016 by University of Michigan professor Dr. Jason Corso and Dr. Brian Moore, Voxel51 is an AI software company that is democratizing access to software 2.0 by providing the open core software building blocks that enable computer vision and machine learning engineers to rapidly engineer data-powered workflows. Learn more at fiftyone.ai!
[ { "code": null, "e": 756, "s": 172, "text": "The massive sea of computer vision models can be difficult to navigate if you are trying to find the best models or even just relevant baselines for your task. Model zoos like TensorFlow Hub and Facebook’s Detectron2 make it easy to access popular models. Further, libraries like PyTorch lightning make it easy to then modify these models to suit your needs. This is all well and good for images, but for videos, it’s another story. Video data is becoming increasingly more popular, but the additional complexity that comes with it often leaves video-related tasks on the backburner." }, { "code": null, "e": 880, "s": 756, "text": "PyTorchVideo is a new library that has set out to make video models just as easy to load, build, and train as image models." }, { "code": null, "e": 1094, "s": 880, "text": "PyTorchVideo provides access to a video model zoo, video data processing functions, and a video-focused accelerator to deploy models all backed in PyTorch allowing for seamless integration into existing workflows." }, { "code": null, "e": 1716, "s": 1094, "text": "The only thing missing from PyTorchVideo to complete your video workflows is a way to visualize your datasets and interpret your model results. This is where FiftyOne comes in. FiftyOne is an open-source tool that I have been working on at Voxel51. It is designed to make it easy to visualize any image or video dataset and explore ground truth and predicted labels stored locally or in the cloud. The flexible representation of FiftyOne datasets and the FiftyOne App let you quickly get hands-on with your datasets and interpret your models to find failure modes, annotation mistakes, visualize complex labels, and more." }, { "code": null, "e": 1932, "s": 1716, "text": "This blog post is an extension of a recent PyTorchVideo tutorial and is written to teach you how to integrate PyTorchVideo with FiftyOne to close the loop on video-based ML workflows. Specifically, this post covers:" }, { "code": null, "e": 1977, "s": 1932, "text": "Downloading a subset of the Kinetics dataset" }, { "code": null, "e": 2015, "s": 1977, "text": "Loading a video dataset with FiftyOne" }, { "code": null, "e": 2055, "s": 2015, "text": "Using PyTorchVideo to perform inference" }, { "code": null, "e": 2105, "s": 2055, "text": "Visualizing and evaluating the PyTorchVideo model" }, { "code": null, "e": 2204, "s": 2105, "text": "You can run the examples in this blog post directly in your browser in this Google Colab notebook!" }, { "code": null, "e": 2318, "s": 2204, "text": "To follow along with this walkthrough, you will need to install FiftyOne, PyTorchVideo, PyTorch, and TorchVision:" }, { "code": null, "e": 2359, "s": 2318, "text": "pip install fiftyone pytorch torchvision" }, { "code": null, "e": 2486, "s": 2359, "text": "While PyTorchVideo is also installable through pip, the functionality in this post requires it to be installed through GitHub:" }, { "code": null, "e": 2580, "s": 2486, "text": "git clone https://github.com/facebookresearch/pytorchvideo.gitcd pytorchvideopip install -e ." }, { "code": null, "e": 2696, "s": 2580, "text": "This walkthrough uses a subset of the Kinetics-400 dataset which can be downloaded with the following code snippet:" }, { "code": null, "e": 3117, "s": 2696, "text": "One of the many reasons that video datasets are more difficult to work with than image datasets is the fact that many popular video datasets are available only through YouTube. So instead of being able to download a zip containing everything you need, you instead need to run scripts like the one below to download individual videos from YouTube that may or may not have become unavailable since the dataset was curated." }, { "code": null, "e": 3428, "s": 3117, "text": "For image datasets, there are some rudimentary options available for visualizing batches of data like pillow and OpenCV. There are very few options available for visualizing video datasets. FiftyOne is a new open-source library that provides simple and powerful visualization for both image and video datasets." }, { "code": null, "e": 3553, "s": 3428, "text": "If your dataset follows a common format, like the COCO format for detections, then you can load it in a single line of code:" }, { "code": null, "e": 3759, "s": 3553, "text": "Even if your dataset is in a custom format, it is still straightforward to load your dataset with FiftyOne. For example, if you are using an object detection video model, you can load your data as follows:" }, { "code": null, "e": 4037, "s": 3759, "text": "In this example, we will be following the PyTorchVision tutorial on running a video classification model. Generally, video classification datasets will be stored on disk in a directory tree whose subfolders define dataset classes. This format can be loaded in one line of code:" }, { "code": null, "e": 4129, "s": 4037, "text": "If you are following along yourself, hover over or click on the samples to play the videos:" }, { "code": null, "e": 4241, "s": 4129, "text": "We also need to download and store a list of default class names that will be used when evaluating predictions:" }, { "code": null, "e": 4333, "s": 4241, "text": "wget https://dl.fbaipublicfiles.com/pyslowfast/dataset/class_names/kinetics_classnames.json" }, { "code": null, "e": 4577, "s": 4333, "text": "In this section, we use PyTorchVideo to download and run a video classification model on the data that we loaded in the previous section and store the results in our dataset. The code in this section is adapted from this PyTorchVideo tutorial." }, { "code": null, "e": 4969, "s": 4577, "text": "Torch Hub is a repository for pretrained PyTorch models that allow you to download models and run inference on your dataset. PyTorchVideo provides a number of video classification models through their Torch Hub-backed model zoo including SlowFast, I3D, C2D, R(2+1)D, and X3D. The following code snippet downloads the slow branch of SlowFast with a ResNet50 backbone and loads it into Python:" }, { "code": null, "e": 5493, "s": 4969, "text": "Every model has a specific input structure that it expects. The standard workflow is to write custom scripts that perform the necessary loading and transformation functions to format data for every model. PyTorchVideo expedites this process by providing these functions for you in a flexible way that will work for most video processing needs. For example, the following code constructs the transforms to sample frames from the video, normalize, scale, and crop it, without needing to write any of those functions yourself:" }, { "code": null, "e": 5716, "s": 5493, "text": "Since the dataset is being stored in FiftyOne, we can easily iterate through the samples, load and run our model on them with PyTorchVideo, and store the predictions back in FiftyOne for further visualization and analysis:" }, { "code": null, "e": 5916, "s": 5716, "text": "Aside from being an open-source ecosystem for dataset curation, FiftyOne is also designed to visualize, evaluate, and interpret models by allowing you to quickly find and address model failure modes." }, { "code": null, "e": 6004, "s": 5916, "text": "To this end, we can start by visualizing the predictions generated in the last section:" }, { "code": null, "e": 6434, "s": 6004, "text": "We can then use FiftyOne to evaluate the predictions with the ground truth to view aggregate metrics and plots showing things like confusion matrices and precision-recall curves. This evaluation adds per-sample correctness labels (“eval”) to the dataset, which make it easy to filter by correct/incorrect predictions, or more generally by TP/FP/FN for object detections. Evaluation can be performed in just a single line of code:" }, { "code": null, "e": 7029, "s": 6434, "text": " precision recall f1-score support springboard diving 0.80 0.80 0.80 5 surfing water 1.00 0.60 0.75 5 swimming backstroke 1.00 0.80 0.89 5 swimming breast stroke 0.57 0.80 0.67 5swimming butterfly stroke 1.00 0.60 0.75 5 micro avg 0.82 0.72 0.77 25 macro avg 0.87 0.72 0.77 25 weighted avg 0.87 0.72 0.77 25" }, { "code": null, "e": 7099, "s": 7029, "text": "Let’s plot the confusion matrix for the classes we are interested in:" }, { "code": null, "e": 7268, "s": 7099, "text": "We can attach this plot to a session object to make it interactive. So if you click one of the cells, the FiftyOne App session updates to show the samples in that cell." }, { "code": null, "e": 7384, "s": 7268, "text": "Note: Plots are currently only interactive in Jupyter Notebooks but additional environments will be supported soon!" }, { "code": null, "e": 7904, "s": 7384, "text": "FiftyOne also provides a novel query language to create views into your dataset by searching and filtering any given labels and metadata. This makes it easy to explore your dataset and find samples related to any question you may have in mind. For example, we can quickly find samples where the model was least certain about its prediction based on similar confidences across multiple classes and use the per-sample correctness labels (“eval”) from the previous evaluation to only look at incorrectly predicted samples:" }, { "code": null, "e": 8110, "s": 7904, "text": "Visualizing these samples lets us get an idea of the type of data that should be added to the training dataset. To mark these for future reference, we can use the tagging functionality in the FiftyOne App:" }, { "code": null, "e": 8331, "s": 8110, "text": "The ease of this hands-on analysis will generally lead to significant improvements in dataset quality, and consequently improvements in model performance, faster than any analysis only using aggregate dataset statistics." }, { "code": null, "e": 8675, "s": 8331, "text": "While most large video datasets and research efforts revolve around classification problems like human activity recognition, applications of video-based ML often involve object detection. At the moment, PyTorchVideo primarily supports video classification problems, however, there are video object detection capabilities available in FiftyOne." }, { "code": null, "e": 9069, "s": 8675, "text": "FiftyOne allows you to either generate predictions from an image-based object detection model in the FiftyOne Model Zoo or add predictions from your own model to a video dataset. There are a host of models available in the zoo. For example, let’s use EfficientDet-D0. We first need to install TensorFlow and AutoML. We can use the eta package that comes with FiftyOne to easily install AutoML:" }, { "code": null, "e": 9116, "s": 9069, "text": "pip install tensorflow==1.14eta install automl" }, { "code": null, "e": 9180, "s": 9116, "text": "Now let’s apply the model to a video and visualize the results:" }, { "code": null, "e": 9663, "s": 9180, "text": "This kind of visualization would require writing custom scripts to load the raw video, annotations, and predictions, then using software like OpenCV to draw boxes and export the visualizations to a new video on disk. Then if you want to change the labels you are looking at you would need to rewrite your script and regenerate the videos every time. Instead, all of this took us only a few lines of code and resulted in an easier-to-use and more flexible representation of our data." }, { "code": null, "e": 10375, "s": 9663, "text": "Video-based machine learning models are growing in popularity but have lacked the same level of ease-of-use code bases that allow for quick development and evaluation of image models. PyTorchVideo aims to make it easier to implement, train, and evaluate video models through their model zoo, video-focused components, and acceleration functions. On the flip side, where PyTorchVideo is making it easier to work with video models, FiftyOne is an open-source library that aims to make it easy and efficient to curate, evaluate, and improve video (and image) datasets. Together, FiftyOne and PyTorchVideo provide significant savings in the time and effort required to create high-quality video datasets and models." }, { "code": null, "e": 10436, "s": 10375, "text": "Disclosure: I work at Voxel51 and am a developer of FiftyOne" }, { "code": null, "e": 10801, "s": 10436, "text": "Headquartered in Ann Arbor, Michigan, and founded in 2016 by University of Michigan professor Dr. Jason Corso and Dr. Brian Moore, Voxel51 is an AI software company that is democratizing access to software 2.0 by providing the open core software building blocks that enable computer vision and machine learning engineers to rapidly engineer data-powered workflows." } ]
How to find out port of MySQL Server?
To find the port of the MySQL server, the command show can be used. Its syntax is as follows − show variables where variable_name=’port’; The above syntax is used to get the port number of the MySQL server using the following query − mysql> show variables where variable_name = 'port'; After executing the above command, port of MySQL server is obtained as 3306. This can be seen in the following output − +---------------+-------+ | Variable_name | Value | +---------------+-------+ | port | 3306 | +---------------+-------+ 1 row in set (0.01 sec) Alternatively, the system variable @@port can also be used to find the MySQL server port. This is demonstrated by the following query − mysql> SELECT @@port; The output of the above query is as follows − +--------+ | @@port | +--------+ | 3306 | +--------+ 1 row in set (0.00 sec) The above output also gives the port of MySQL server as 3306.
[ { "code": null, "e": 1157, "s": 1062, "text": "To find the port of the MySQL server, the command show can be used. Its syntax is as follows −" }, { "code": null, "e": 1200, "s": 1157, "text": "show variables where variable_name=’port’;" }, { "code": null, "e": 1296, "s": 1200, "text": "The above syntax is used to get the port number of the MySQL server using the following query −" }, { "code": null, "e": 1348, "s": 1296, "text": "mysql> show variables where variable_name = 'port';" }, { "code": null, "e": 1468, "s": 1348, "text": "After executing the above command, port of MySQL server is obtained as 3306. This can be seen in the following output −" }, { "code": null, "e": 1622, "s": 1468, "text": "+---------------+-------+\n| Variable_name | Value |\n+---------------+-------+\n| port | 3306 |\n+---------------+-------+\n1 row in set (0.01 sec)" }, { "code": null, "e": 1758, "s": 1622, "text": "Alternatively, the system variable @@port can also be used to find the MySQL server port. This is demonstrated by the following query −" }, { "code": null, "e": 1780, "s": 1758, "text": "mysql> SELECT @@port;" }, { "code": null, "e": 1826, "s": 1780, "text": "The output of the above query is as follows −" }, { "code": null, "e": 1905, "s": 1826, "text": "+--------+\n| @@port |\n+--------+\n| 3306 |\n+--------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1967, "s": 1905, "text": "The above output also gives the port of MySQL server as 3306." } ]
Tryit Editor v3.7
HTML Input attributes Tryit: The placeholder attribute
[ { "code": null, "e": 32, "s": 10, "text": "HTML Input attributes" } ]
Print all n-digit numbers whose sum of digits equals to given sum in C++
In this problem, we are given two numbers n and sum. We have to print all n digit numbers whose sum is equal to the sum. In this problem, numbers with leading 0’s are not considered. Let’s take an example to understand the problem, Input: n = 2 , sum = 5 Output: 14 23 32 41 50 Explanation: The sum of digits of the number in all numbers in 5. To solve this problem, we will have to find all the n-digit numbers with sum with the given sum value. For this, we will fix a digit place with all values and based on its position to be even or odd, call for values at other places in the number such that the condition remains satisfied. Program to implement the above solution − Live Demo #include <iostream> using namespace std; void PrintNumberWithDigitSum(int n, int sum, char* out, int index) { if (index > n || sum < 0) return; if (index == n) { if(sum == 0) { out[index] = ' '; cout << out << " "; } return; } for (int i = 0; i <= 9; i++) { out[index] = i + '0'; PrintNumberWithDigitSum(n, sum - i, out, index + 1); } } void numberWithSum(int n, int sum) { char out[n + 1]; for (int i = 1; i <= 9; i++) { out[0] = i + '0'; PrintNumberWithDigitSum(n, sum - i, out, 1); } } int main() { int n = 3, sum = 6; cout<<"All "<<n<<" digit numbers with sum "<<sum<<" are :\n"; numberWithSum(n, sum); return 0; } All 3 digit numbers with sum 6 are − 105 114 123 132 141 150 204 213 222 231 240 303 312 321 330 402 411 420 501 510 600
[ { "code": null, "e": 1245, "s": 1062, "text": "In this problem, we are given two numbers n and sum. We have to print all n digit numbers whose sum is equal to the sum. In this problem, numbers with leading 0’s are not considered." }, { "code": null, "e": 1294, "s": 1245, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1406, "s": 1294, "text": "Input: n = 2 , sum = 5\nOutput: 14 23 32 41 50\nExplanation: The sum of digits of the number in all numbers in 5." }, { "code": null, "e": 1695, "s": 1406, "text": "To solve this problem, we will have to find all the n-digit numbers with sum with the given sum value. For this, we will fix a digit place with all values and based on its position to be even or odd, call for values at other places in the number such that the condition remains satisfied." }, { "code": null, "e": 1737, "s": 1695, "text": "Program to implement the above solution −" }, { "code": null, "e": 1748, "s": 1737, "text": " Live Demo" }, { "code": null, "e": 2469, "s": 1748, "text": "#include <iostream>\nusing namespace std;\nvoid PrintNumberWithDigitSum(int n, int sum, char* out, int index) {\n if (index > n || sum < 0)\n return;\n if (index == n) {\n if(sum == 0) {\n out[index] = ' ';\n cout << out << \" \";\n }\n return;\n }\n for (int i = 0; i <= 9; i++) {\n out[index] = i + '0';\n PrintNumberWithDigitSum(n, sum - i, out, index + 1);\n }\n}\nvoid numberWithSum(int n, int sum) {\n char out[n + 1];\n for (int i = 1; i <= 9; i++) {\n out[0] = i + '0';\n PrintNumberWithDigitSum(n, sum - i, out, 1);\n }\n}\nint main() {\n int n = 3, sum = 6;\n cout<<\"All \"<<n<<\" digit numbers with sum \"<<sum<<\" are :\\n\";\n numberWithSum(n, sum);\n return 0;\n}" }, { "code": null, "e": 2590, "s": 2469, "text": "All 3 digit numbers with sum 6 are −\n105 114 123 132 141 150 204 213 222 231 240 303 312 321 330 402 411 420 501 510 600" } ]
Build A MFCC-Based Music Recommendation Engine On Cloud | by Xiaoqian Wang | Towards Data Science
In the past decade, the evolution of mobile technology and cellular networks have unprecedentedly reshaped the world in ways that no one could have predicted. We are living in an era of information explosion and taking advantage of fancy mobile apps driven by ever more affordable cellular data. Walkmans and iPods have no longer been put in our pockets since the debut of smart phones equipped with music streaming apps like Spotify and Pandora. If you are using or have ever used one of them, you might be aware of the music recommendation list, aka “guess you like” feature while streaming a soundtrack. Music recommendation is a big topic and there are existing articles articulating and exploring the algorithms running behind — cluster analysis on genres, NLP modelling on lyrics, user based and content based collaborative filtering to name but a few. Well, is there an intrinsic way that recommendation can be made based on audio signal itself? The answer is yes and this article will run through some basic acoustic knowledge and explore the feasibility of a lightweight audio feature-based music recommendation system. By definition, sound is a kind of energy produced by vibrations that propagates a sinusoidal wave at a certain frequency and amplitude through a transmission medium like air. A piece of music is essentially a sequence of sound waves at different frequencies and amplitudes. The term “pitch” is widely used in the perception of audio characteristics of musical instruments. Although not completely equivalent, frequency is seen as a proxy of “pitch”. When people say “high-pitch instruments”, it in particular refers to those orchestra instruments always producing sound waves at higher frequency, e.g., trumpet, piccolo or violin. It is evident that there is a strong correlation between sound frequency and people’s mood, one of the fun facts is that at times people claim superiority of pianos tuned to A432 over those tuned to A440 because of the alleged “healing frequency” at 432Hz. The amplitude of a sound wave determines the loudness, when sound produced, the air compression resulting from vibrations creates pressure change that can be perceived by ears. The perceived pressure change, measured in dB, is also affected by the distance to the source. Generally speaking, the sound pressure level will decay at the rate of 6dB for point source while 3dB for line source at each time the distance is doubled. When talking about digital audio, there is a key concept we cannot steer clear of — sample rate. In digital recording, samples are taken along the sound waves at a regular interval, the frequency at which samples are taken is what we refer to as sample rate. If you love music, you might be aware of the “44.1kHz/16-bit” tag printed on the backside of your CD cover. 44.1kHz is the standard sample rate for consumer CDs, some can go up to 48kHz. Why this number? This is because 20kHz is generally considered the upper limit that human ear is capable to perceive, according to Nyquist–Shannon sampling theorem, sample rate must be at least twice the maximum frequency of the original audio signal to avoid unexpected distortion or alias. Is sample rate higher better? Sound quality wise yes, it is quite often to see Hi-Fi enthusiasts sniff at the “inferior” 44.1kHz/16-bit and pursue premium quality soundtracks recorded at 96kHz/24-bit or even 192kHz/24-bit sourced from analogue medium like vinyls in any linear PCM based lossless audio format, e.g., WAV, FLAC or APE. Ok, time for some audio analysis, let me plot the audio samples of the soundtrack “A lover in Berlin” performed by my favourite Norwegian singer Kari Bremnes. Normally we expect 2 channels for most soundtracks and in most cases they are similar. The amplitude is normalised to the range from 0 to 1. import matplotlib.pyplot as pltfrom scipy.io import wavfileimport numpy as npfile = r"(01) [Kari Bremnes] A Lover in Berlin.wav"sample_rate,data = wavfile.read(file)length = data.shape[0]/sample_ratefig,axes = plt.subplots(1,2,figsize=(20,7))time = np.linspace(.0,length,data.shape[0])for i,j,k in zip(range(axes.size),["Left Channel","Right Channel"],["b","y"]): axes[i].plot(time, data[:, i]/data[:, i].max(),color=k) axes[i].set_xlabel("Time [s]") axes[i].set_ylabel("Amplitude") axes[i].set_title(j)plt.show() As sound waves are time-domain signals, Fast Fourier Transformation needs to be performed for frequency-domain response. from scipy.fftpack import fft# Take the left channela = data.T[0]# Normalised fast fourier transformationc = fft(a)/len(a)freqs = np.arange(0, (len(a)), 1.0) * (sample_rate*1.0/len(a))plt.figure(figsize=(20,7))y=c[:int(len(c))]# Normalised the amplitude plt.plot(freqs/1000,abs(y)/max(abs(y)),'r') plt.xlabel("Frequency (kHz)")plt.ylabel("Amplitude")plt.show() Wait...Why is this FFT plot mirrored? Technically it is called conjugate symmetry as a result of the nature of Discrete Fourier Transformation. The DFT formula is written as: Xn here is the amplitude inputs which in this case are real numbers, k denotes the current frequency while the outputs Xk are complex numbers encapsulating both amplitude and phase information. According to Euler’s formula, the underlying equation can be written as: Xk has either positive or negative frequency term at a certain n. The magnitude of Xk is essentially the the amplitude we want to plot, which can be derived from its real part and imaginary part: As you can see, Xk at positive frequencies and negative frequencies have the same magnitude and thus responding the same way in terms of amplitude, in other words, Xk at positive frequency is conjugate of Xk at negative frequency. That is to say we only need to take the first half of the full plot to tell the story but given that most features distribute across low frequency band, I took the first 1/20th instead for easy showcase: As expected, the acoustic feature of this soundtrack is well presented in the sense that rich spikes spread across 200~600 Hz, which is in line with typical female vocal range. Having said that FFT response makes a lot of sense here, we cannot use it solely when it comes to modelling as FFT doesn’t address time feature. Music, to some extent, is just like language that carries information in a certain order. If you are familiar with NLP, you might know that algorithms like bidirectional LSTM and BERT generally perform better than TF-IDF simply because the input order plays a key role. Similarly, we want to capture that feature here. Spectrogram seems a good approach as it shows how frequency and amplitude change over time. plt.figure(figsize=(25,8))plt.title('Spectrogram - A Lover In Berlin',fontsize=18)spec, freqs, t, im = plt.specgram(data[:,0],Fs=sample_rate,NFFT=512)plt.xlabel('Time [s]',fontsize=18)plt.ylabel('Frequency',fontsize=18)plt.show() Well, a new concern would arise if we choose to model on spectrum — it seems unrealistic to take raw frequency as the input as it is way too granular. Is there any trick that generates a low-cardinality feature based on what we have? MFCC (Mel-Frequency Cepstral Coefficients) is one of the ways to go! MFCC is widely used in voice analytics. Although there are existing articles covering this topic, I still want to briefly go through the concept of cepstrum. cepsturm is spectrum with “spec” reversed, technically it is derived from the inverse Fourier Transformation against the logarithm of the original FFT signal. It describes the change rate in the different spectrum bands. The resulting cepstrum is a signal in “quefrency” domain. Mel-frequency cepstrum is derived from passing the initial FFT response to a set of band-pass filters known as Mel-filter bank prior to taking the logarithm, these filters are engineered to work the same way as human ear does given that human ear is naturally a low-pass filter, this is why most of us are not able to perceive high frequency sounds over 20kHz. Mel-frequency maps the original frequency input to Mel-scale through the following formula: In a nutshell, Mel-scale is optimised for human auditory system. The resulting MFC has 13 coefficients: from python_speech_features import mfccfrom matplotlib import cmplt.figure(figsize=(25,8))mfcc_feat = mfcc(a,sample_rate)mfcc_data= mfcc_feat.Tplt.imshow(mfcc_data, cmap=plt.cm.jet, aspect='auto',origin='lower')plt.title('MFC - A Lover In Berlin',fontsize=18)plt.xlabel('Time [s]',fontsize=18)plt.ylabel('MFCC',fontsize=18)plt.show() Given that our ultimate goal is to develop a music recommendation engine, recommendations can be made based on the similarities of these coefficients between songs. Well...How are the similarities calculated? As soundtrack length may vary from one to another, it is not quite possible to make apples to apples comparison, is it? Dynamic Time Wrapping (DTW) is designed for resolving this problem. By definition, DTW is a time series alignment algorithm that aims to align two sequences of feature vectors by warping the time axis iteratively until an optimal match. It means we can use it to calculate the similarity or distance between any two input vectors without worrying about input lengths. I created a mini music library containing 151 soundtracks in MP3 format at 190kbps covering a wide range of genres like pop, jazz, folk, metal, rock, R&B etc. Let’s take a look at the distribution of all 13 coefficients across my music lib. from python_speech_features import mfccimport seaborn as snsimport librosaimport ostracks = os.listdir(r"soundtracks")L=[]for i in tracks: data,sample_rate = librosa.load(r"soundtracks"+"\\"+i,sr=44100) # Cut off the first and the last 500 samples a = data.T[500:-500] a = a/a.max() plt.figure(figsize=(20,7)) mfcc_feat = mfcc(a,sample_rate) mfcc_data= mfcc_feat.T L.append(mfcc_data)L2 = np.array([i.mean(axis=1) for i in L])fig,axes = plt.subplots(5,3,figsize=(30,10))for i in range(L2.shape[1]): sns.distplot(L2.T[i],ax=axes.ravel()[i]) axes.ravel()[i].set_title("Coe "+str(i)) plt.tight_layout() It seems all the 13 coefficients are normally distributed across my music lib and thus I am going to sum the calculated DTW distance over all 13 coe vectors as a proxy of the overall similarity of any two soundtracks. Let’s take a look if this algorithm works: from fastdtw import fastdtwimport numpy as npc=[]for i in range(len(L)): group = [] for n in range(13): dis,path=fastdtw(L[2][n],L[i][n]) group.append(dis) total_dis = np.sum(group) c.append([total_dis,i])c.sort(key=lambda x:x[0])fig,axes = plt.subplots(1,2,figsize=(25,8))tracks = os.listdir("soundtracks")for i,j in enumerate([tracks[2],tracks[c[1][1]]]): title = "MFC-"+j.replace(".mp3","") data,sample_rate = librosa.load(r"soundtracks"+"\\"+j,sr=44100) a = data.T[500:-500] a = a/a.max() mfcc_feat = mfcc(a,sample_rate) mfcc_data= mfcc_feat.T axes[i].set_title(title,fontsize=18) axes[i].set_xlabel('Time [s]',fontsize=18) axes[i].set_ylabel('MFCC',fontsize=18) axes[i].imshow(mfcc_data, cmap=plt.cm.jet, aspect='auto',origin='lower')plt.tight_layout() Ok...The result indicates that the closest soundtrack to “A Lover In Berlin” is “Samba De Verao” performed by Ono Lisa (小野リサ). Folk pop vs. Bossa nova, both are stylish female vocal music. Not too bad! Now let’s develop a full solution on Microsoft Azure to host this service. A mini lambda architecture is adopted for this solution. The speed layer is to extract and load the meta data of the uploaded soundtrack that we want to make recommendations against to Azure CosmosDB. The batch layer is to perform recommendation logic and load the resulting recommendation list to SQL database. All service components are developed in Python and Spark. A flask app is developed and deployed to Azure App Service as the main UI for initial audio file upload and subsequent recommended music streaming.An Azure SQL database is built to store music lib meta data, e.g., title, artist, album, genre, release year, soundtrack path and artwork path.5 blob containers are created within the same Azure Storage Account.Container A catches the initial upload in blob and triggers an Azure function to collect the meta data via a 3rd party music recognition API service and load the results in json to CosmosDB to be queried by another Azure function serving as an API endpoint to be consumed by the web app.The initial upload is duplicated to container B in blob as it is landing at container A. The duplication is seen a blob change event to be captured by Azure Event Grid which consequently triggers an Azure Databricks Notebook placed within an Azure Data Factory pipeline. The Notebook is to perform the recommendation logic and to load the resulting recommendation list to another table in Azure SQL database to be joined in a view containing all the meta data to be queried by the web app.Container C is to store a parquet file containing the Mel-frequency cepstrum of the music lib. The parquet file is registered as a Hive table to be referenced by Azure Databricks as in step 5.Container D and E are built to store the music lib soundtracks and artworks to be streamed and displayed via the web app.All service credentials including CosmosDB connection string, SQL database connection string, Blob storage connection string and the 3rd party music recognition API token are stored in and secured by Azure Key Vault. A flask app is developed and deployed to Azure App Service as the main UI for initial audio file upload and subsequent recommended music streaming. An Azure SQL database is built to store music lib meta data, e.g., title, artist, album, genre, release year, soundtrack path and artwork path. 5 blob containers are created within the same Azure Storage Account. Container A catches the initial upload in blob and triggers an Azure function to collect the meta data via a 3rd party music recognition API service and load the results in json to CosmosDB to be queried by another Azure function serving as an API endpoint to be consumed by the web app. The initial upload is duplicated to container B in blob as it is landing at container A. The duplication is seen a blob change event to be captured by Azure Event Grid which consequently triggers an Azure Databricks Notebook placed within an Azure Data Factory pipeline. The Notebook is to perform the recommendation logic and to load the resulting recommendation list to another table in Azure SQL database to be joined in a view containing all the meta data to be queried by the web app. Container C is to store a parquet file containing the Mel-frequency cepstrum of the music lib. The parquet file is registered as a Hive table to be referenced by Azure Databricks as in step 5. Container D and E are built to store the music lib soundtracks and artworks to be streamed and displayed via the web app. All service credentials including CosmosDB connection string, SQL database connection string, Blob storage connection string and the 3rd party music recognition API token are stored in and secured by Azure Key Vault. Load soundtracks and artworks to the designated containers. Create a new table in SQL database to store music lib meta data. Extract meta data from audio files and load them into a data frame. The soundtrack paths and artwork paths are generated by shared access signatures (SAS) via blob client API. from mutagen.easyid3 import EasyID3import pandas as pdimport osfrom azure.storage.blob import generate_container_sasfrom datetime import datetime,timedeltasongs = os.listdir("soundtracks")l=[]for song in songs: audio = EasyID3("soundtracks"+"\\"+song) meta=[] for e in ["title","album","artist","genre","date"]: try: if e=="date": attr = audio[e][0][:4] elif e=="title": attr = song.replace(".mp3","") else: attr = audio[e][0] meta.append(attr) except: meta.append(None) l.append(meta)df = pd.DataFrame(l,columns=["TITLE","ALBUM","ARTIST","GENRE","RELEASE_YEAR"])key=my_keysas_sound=generate_container_sas('xwstorage', 'soundtracks',key,expiry=datetime.utcnow()+timedelta(days=30),permission='r')sas_art=generate_container_sas('xwstorage', 'artworks',key,expiry=datetime.utcnow()+timedelta(days=30),permission='r')df["SOUNDTRACK_PATH"] = "https://xwstorage.blob.core.windows.net/soundtracks/"+df["TITLE"]+".mp3"+"?"+sas_sounddf["ARTWORK_PATH"] = "https://xwstorage.blob.core.windows.net/artworks/"+df["TITLE"]+".jpeg"+"?"+sas_art Load the resulting data frame to the SQL table we created before. import sqlalchemyimport pyodbcfrom sqlalchemy.engine import URLcnxn = my_odbc_connection_stringconnection_url = URL.create("mssql+pyodbc", query={"odbc_connect": cnxn})engine = sqlalchemy.create_engine(connection_url)df.to_sql("SOUNDTRACKS", engine,if_exists="append",index=False) Dump the music lib Mel-frequency cepstrum into a parquet file and then upload the parquet file to the designated container. import pandas as pdfrom python_speech_features import mfccimport matplotlib.pyplot as pltimport librosaimport ostracks = os.listdir(r"soundtracks")L=[]for i in tracks: print(i) data,sample_rate = librosa.load(r"soundtracks"+"\\"+i,sr=44100) a = data.T[500:-500] a = a/a.max() plt.figure(figsize=(20,7)) mfcc_feat = mfcc(a,sample_rate) mfcc_data= mfcc_feat.T L.append(mfcc_data)columns = ["COE_"+str(i) for i in range(1,14)]L2 = [pd.DataFrame(i.T,columns=columns) for i in L]titles = [i.replace(".mp3","") for i in tracks]for i,j in zip(L2,titles): i["Title"]=jdf=pd.concat(L2)df.reset_index(drop=True).reset_index().to_parquet("soundtracks.parquet") As mentioned earlier, all service credentials are stored in and secured by Azure Key Vault. Create a CosmosDB instance to store the meta data of the uploaded audio file. Create a blob-trigger type Azure function as the starting point. The function is to cut a 200KB sample out of the input blob and POST it to a 3rd party music recognition service API for meta data collection. Have the function bind the output path to CosmosDB and another blob container as such that the original input blob will be duplicated to where it needs to be for batch layer processing and the resulting meta data in json will be loaded into CosmosDB at the same time. Create a http-trigger type Azure function with GET method only to query the latest record in CosmosDB. This function serves as an API endpoint to be consumed by the web app. Once we have both Azure functions deployed, we can simply drop a MP3 file to the target blob container to quickly test if the API endpoint works in the browser. Create a cluster instance for Azure Databricks. Load the cepstrum parquet file into a spark data frame and register it as a Hive table. Given that the cepstrum table has nearly 4 million rows while 14 columns (13 MFCC + Title) only, A columnstore format like parquet is more optimised over a rowstore format like CSV in this case. A secret scope needs to be created to interact with Azure Key Vault. Create a new notebook and rewrite the DTW based MFCC similarity computing logic from Python list iteration to Spark data frame manipulation and load the results to Azure SQL database via JDBC connector. Given the fact that similarity computing requires large table aggregations only and doesn’t involve any machine learning algorithm, a multi-node computing environment definitely takes advantage here, this is the fundamental reason why I chose Azure Databricks over Azure ML Service for this operation. A recommendation list will be loaded into a SQL table to be joined in a view if the operation succeeded. Place the notebook within a Azure Data Factory pipeline and make it triggerable by a blob change event taking place in the target container. In this fashion, the notebook will be activated as soon as the initial upload is duplicated from the speed layer container to the batch layer container. Develop and deploy a flask app to Azure App Service. The app is built to render 2 html pages. The first is for music file uploading, the second is for recommended music streaming. Finally... demo session. Uploaded an infoless soundtrack “Lunchbox” performed by Marilyn Manson. The song was recognised precisely along with the top 5 similar songs and one of which is performed by the same singer!
[ { "code": null, "e": 1176, "s": 47, "text": "In the past decade, the evolution of mobile technology and cellular networks have unprecedentedly reshaped the world in ways that no one could have predicted. We are living in an era of information explosion and taking advantage of fancy mobile apps driven by ever more affordable cellular data. Walkmans and iPods have no longer been put in our pockets since the debut of smart phones equipped with music streaming apps like Spotify and Pandora. If you are using or have ever used one of them, you might be aware of the music recommendation list, aka “guess you like” feature while streaming a soundtrack. Music recommendation is a big topic and there are existing articles articulating and exploring the algorithms running behind — cluster analysis on genres, NLP modelling on lyrics, user based and content based collaborative filtering to name but a few. Well, is there an intrinsic way that recommendation can be made based on audio signal itself? The answer is yes and this article will run through some basic acoustic knowledge and explore the feasibility of a lightweight audio feature-based music recommendation system." }, { "code": null, "e": 2064, "s": 1176, "text": "By definition, sound is a kind of energy produced by vibrations that propagates a sinusoidal wave at a certain frequency and amplitude through a transmission medium like air. A piece of music is essentially a sequence of sound waves at different frequencies and amplitudes. The term “pitch” is widely used in the perception of audio characteristics of musical instruments. Although not completely equivalent, frequency is seen as a proxy of “pitch”. When people say “high-pitch instruments”, it in particular refers to those orchestra instruments always producing sound waves at higher frequency, e.g., trumpet, piccolo or violin. It is evident that there is a strong correlation between sound frequency and people’s mood, one of the fun facts is that at times people claim superiority of pianos tuned to A432 over those tuned to A440 because of the alleged “healing frequency” at 432Hz." }, { "code": null, "e": 2492, "s": 2064, "text": "The amplitude of a sound wave determines the loudness, when sound produced, the air compression resulting from vibrations creates pressure change that can be perceived by ears. The perceived pressure change, measured in dB, is also affected by the distance to the source. Generally speaking, the sound pressure level will decay at the rate of 6dB for point source while 3dB for line source at each time the distance is doubled." }, { "code": null, "e": 3564, "s": 2492, "text": "When talking about digital audio, there is a key concept we cannot steer clear of — sample rate. In digital recording, samples are taken along the sound waves at a regular interval, the frequency at which samples are taken is what we refer to as sample rate. If you love music, you might be aware of the “44.1kHz/16-bit” tag printed on the backside of your CD cover. 44.1kHz is the standard sample rate for consumer CDs, some can go up to 48kHz. Why this number? This is because 20kHz is generally considered the upper limit that human ear is capable to perceive, according to Nyquist–Shannon sampling theorem, sample rate must be at least twice the maximum frequency of the original audio signal to avoid unexpected distortion or alias. Is sample rate higher better? Sound quality wise yes, it is quite often to see Hi-Fi enthusiasts sniff at the “inferior” 44.1kHz/16-bit and pursue premium quality soundtracks recorded at 96kHz/24-bit or even 192kHz/24-bit sourced from analogue medium like vinyls in any linear PCM based lossless audio format, e.g., WAV, FLAC or APE." }, { "code": null, "e": 3864, "s": 3564, "text": "Ok, time for some audio analysis, let me plot the audio samples of the soundtrack “A lover in Berlin” performed by my favourite Norwegian singer Kari Bremnes. Normally we expect 2 channels for most soundtracks and in most cases they are similar. The amplitude is normalised to the range from 0 to 1." }, { "code": null, "e": 4390, "s": 3864, "text": "import matplotlib.pyplot as pltfrom scipy.io import wavfileimport numpy as npfile = r\"(01) [Kari Bremnes] A Lover in Berlin.wav\"sample_rate,data = wavfile.read(file)length = data.shape[0]/sample_ratefig,axes = plt.subplots(1,2,figsize=(20,7))time = np.linspace(.0,length,data.shape[0])for i,j,k in zip(range(axes.size),[\"Left Channel\",\"Right Channel\"],[\"b\",\"y\"]): axes[i].plot(time, data[:, i]/data[:, i].max(),color=k) axes[i].set_xlabel(\"Time [s]\") axes[i].set_ylabel(\"Amplitude\") axes[i].set_title(j)plt.show()" }, { "code": null, "e": 4511, "s": 4390, "text": "As sound waves are time-domain signals, Fast Fourier Transformation needs to be performed for frequency-domain response." }, { "code": null, "e": 4872, "s": 4511, "text": "from scipy.fftpack import fft# Take the left channela = data.T[0]# Normalised fast fourier transformationc = fft(a)/len(a)freqs = np.arange(0, (len(a)), 1.0) * (sample_rate*1.0/len(a))plt.figure(figsize=(20,7))y=c[:int(len(c))]# Normalised the amplitude plt.plot(freqs/1000,abs(y)/max(abs(y)),'r') plt.xlabel(\"Frequency (kHz)\")plt.ylabel(\"Amplitude\")plt.show()" }, { "code": null, "e": 5047, "s": 4872, "text": "Wait...Why is this FFT plot mirrored? Technically it is called conjugate symmetry as a result of the nature of Discrete Fourier Transformation. The DFT formula is written as:" }, { "code": null, "e": 5314, "s": 5047, "text": "Xn here is the amplitude inputs which in this case are real numbers, k denotes the current frequency while the outputs Xk are complex numbers encapsulating both amplitude and phase information. According to Euler’s formula, the underlying equation can be written as:" }, { "code": null, "e": 5510, "s": 5314, "text": "Xk has either positive or negative frequency term at a certain n. The magnitude of Xk is essentially the the amplitude we want to plot, which can be derived from its real part and imaginary part:" }, { "code": null, "e": 5945, "s": 5510, "text": "As you can see, Xk at positive frequencies and negative frequencies have the same magnitude and thus responding the same way in terms of amplitude, in other words, Xk at positive frequency is conjugate of Xk at negative frequency. That is to say we only need to take the first half of the full plot to tell the story but given that most features distribute across low frequency band, I took the first 1/20th instead for easy showcase:" }, { "code": null, "e": 6678, "s": 5945, "text": "As expected, the acoustic feature of this soundtrack is well presented in the sense that rich spikes spread across 200~600 Hz, which is in line with typical female vocal range. Having said that FFT response makes a lot of sense here, we cannot use it solely when it comes to modelling as FFT doesn’t address time feature. Music, to some extent, is just like language that carries information in a certain order. If you are familiar with NLP, you might know that algorithms like bidirectional LSTM and BERT generally perform better than TF-IDF simply because the input order plays a key role. Similarly, we want to capture that feature here. Spectrogram seems a good approach as it shows how frequency and amplitude change over time." }, { "code": null, "e": 6908, "s": 6678, "text": "plt.figure(figsize=(25,8))plt.title('Spectrogram - A Lover In Berlin',fontsize=18)spec, freqs, t, im = plt.specgram(data[:,0],Fs=sample_rate,NFFT=512)plt.xlabel('Time [s]',fontsize=18)plt.ylabel('Frequency',fontsize=18)plt.show()" }, { "code": null, "e": 7648, "s": 6908, "text": "Well, a new concern would arise if we choose to model on spectrum — it seems unrealistic to take raw frequency as the input as it is way too granular. Is there any trick that generates a low-cardinality feature based on what we have? MFCC (Mel-Frequency Cepstral Coefficients) is one of the ways to go! MFCC is widely used in voice analytics. Although there are existing articles covering this topic, I still want to briefly go through the concept of cepstrum. cepsturm is spectrum with “spec” reversed, technically it is derived from the inverse Fourier Transformation against the logarithm of the original FFT signal. It describes the change rate in the different spectrum bands. The resulting cepstrum is a signal in “quefrency” domain." }, { "code": null, "e": 8101, "s": 7648, "text": "Mel-frequency cepstrum is derived from passing the initial FFT response to a set of band-pass filters known as Mel-filter bank prior to taking the logarithm, these filters are engineered to work the same way as human ear does given that human ear is naturally a low-pass filter, this is why most of us are not able to perceive high frequency sounds over 20kHz. Mel-frequency maps the original frequency input to Mel-scale through the following formula:" }, { "code": null, "e": 8205, "s": 8101, "text": "In a nutshell, Mel-scale is optimised for human auditory system. The resulting MFC has 13 coefficients:" }, { "code": null, "e": 8539, "s": 8205, "text": "from python_speech_features import mfccfrom matplotlib import cmplt.figure(figsize=(25,8))mfcc_feat = mfcc(a,sample_rate)mfcc_data= mfcc_feat.Tplt.imshow(mfcc_data, cmap=plt.cm.jet, aspect='auto',origin='lower')plt.title('MFC - A Lover In Berlin',fontsize=18)plt.xlabel('Time [s]',fontsize=18)plt.ylabel('MFCC',fontsize=18)plt.show()" }, { "code": null, "e": 9236, "s": 8539, "text": "Given that our ultimate goal is to develop a music recommendation engine, recommendations can be made based on the similarities of these coefficients between songs. Well...How are the similarities calculated? As soundtrack length may vary from one to another, it is not quite possible to make apples to apples comparison, is it? Dynamic Time Wrapping (DTW) is designed for resolving this problem. By definition, DTW is a time series alignment algorithm that aims to align two sequences of feature vectors by warping the time axis iteratively until an optimal match. It means we can use it to calculate the similarity or distance between any two input vectors without worrying about input lengths." }, { "code": null, "e": 9477, "s": 9236, "text": "I created a mini music library containing 151 soundtracks in MP3 format at 190kbps covering a wide range of genres like pop, jazz, folk, metal, rock, R&B etc. Let’s take a look at the distribution of all 13 coefficients across my music lib." }, { "code": null, "e": 10111, "s": 9477, "text": "from python_speech_features import mfccimport seaborn as snsimport librosaimport ostracks = os.listdir(r\"soundtracks\")L=[]for i in tracks: data,sample_rate = librosa.load(r\"soundtracks\"+\"\\\\\"+i,sr=44100) # Cut off the first and the last 500 samples a = data.T[500:-500] a = a/a.max() plt.figure(figsize=(20,7)) mfcc_feat = mfcc(a,sample_rate) mfcc_data= mfcc_feat.T L.append(mfcc_data)L2 = np.array([i.mean(axis=1) for i in L])fig,axes = plt.subplots(5,3,figsize=(30,10))for i in range(L2.shape[1]): sns.distplot(L2.T[i],ax=axes.ravel()[i]) axes.ravel()[i].set_title(\"Coe \"+str(i)) plt.tight_layout()" }, { "code": null, "e": 10372, "s": 10111, "text": "It seems all the 13 coefficients are normally distributed across my music lib and thus I am going to sum the calculated DTW distance over all 13 coe vectors as a proxy of the overall similarity of any two soundtracks. Let’s take a look if this algorithm works:" }, { "code": null, "e": 11186, "s": 10372, "text": "from fastdtw import fastdtwimport numpy as npc=[]for i in range(len(L)): group = [] for n in range(13): dis,path=fastdtw(L[2][n],L[i][n]) group.append(dis) total_dis = np.sum(group) c.append([total_dis,i])c.sort(key=lambda x:x[0])fig,axes = plt.subplots(1,2,figsize=(25,8))tracks = os.listdir(\"soundtracks\")for i,j in enumerate([tracks[2],tracks[c[1][1]]]): title = \"MFC-\"+j.replace(\".mp3\",\"\") data,sample_rate = librosa.load(r\"soundtracks\"+\"\\\\\"+j,sr=44100) a = data.T[500:-500] a = a/a.max() mfcc_feat = mfcc(a,sample_rate) mfcc_data= mfcc_feat.T axes[i].set_title(title,fontsize=18) axes[i].set_xlabel('Time [s]',fontsize=18) axes[i].set_ylabel('MFCC',fontsize=18) axes[i].imshow(mfcc_data, cmap=plt.cm.jet, aspect='auto',origin='lower')plt.tight_layout()" }, { "code": null, "e": 11388, "s": 11186, "text": "Ok...The result indicates that the closest soundtrack to “A Lover In Berlin” is “Samba De Verao” performed by Ono Lisa (小野リサ). Folk pop vs. Bossa nova, both are stylish female vocal music. Not too bad!" }, { "code": null, "e": 11833, "s": 11388, "text": "Now let’s develop a full solution on Microsoft Azure to host this service. A mini lambda architecture is adopted for this solution. The speed layer is to extract and load the meta data of the uploaded soundtrack that we want to make recommendations against to Azure CosmosDB. The batch layer is to perform recommendation logic and load the resulting recommendation list to SQL database. All service components are developed in Python and Spark." }, { "code": null, "e": 13497, "s": 11833, "text": "A flask app is developed and deployed to Azure App Service as the main UI for initial audio file upload and subsequent recommended music streaming.An Azure SQL database is built to store music lib meta data, e.g., title, artist, album, genre, release year, soundtrack path and artwork path.5 blob containers are created within the same Azure Storage Account.Container A catches the initial upload in blob and triggers an Azure function to collect the meta data via a 3rd party music recognition API service and load the results in json to CosmosDB to be queried by another Azure function serving as an API endpoint to be consumed by the web app.The initial upload is duplicated to container B in blob as it is landing at container A. The duplication is seen a blob change event to be captured by Azure Event Grid which consequently triggers an Azure Databricks Notebook placed within an Azure Data Factory pipeline. The Notebook is to perform the recommendation logic and to load the resulting recommendation list to another table in Azure SQL database to be joined in a view containing all the meta data to be queried by the web app.Container C is to store a parquet file containing the Mel-frequency cepstrum of the music lib. The parquet file is registered as a Hive table to be referenced by Azure Databricks as in step 5.Container D and E are built to store the music lib soundtracks and artworks to be streamed and displayed via the web app.All service credentials including CosmosDB connection string, SQL database connection string, Blob storage connection string and the 3rd party music recognition API token are stored in and secured by Azure Key Vault." }, { "code": null, "e": 13645, "s": 13497, "text": "A flask app is developed and deployed to Azure App Service as the main UI for initial audio file upload and subsequent recommended music streaming." }, { "code": null, "e": 13789, "s": 13645, "text": "An Azure SQL database is built to store music lib meta data, e.g., title, artist, album, genre, release year, soundtrack path and artwork path." }, { "code": null, "e": 13858, "s": 13789, "text": "5 blob containers are created within the same Azure Storage Account." }, { "code": null, "e": 14146, "s": 13858, "text": "Container A catches the initial upload in blob and triggers an Azure function to collect the meta data via a 3rd party music recognition API service and load the results in json to CosmosDB to be queried by another Azure function serving as an API endpoint to be consumed by the web app." }, { "code": null, "e": 14636, "s": 14146, "text": "The initial upload is duplicated to container B in blob as it is landing at container A. The duplication is seen a blob change event to be captured by Azure Event Grid which consequently triggers an Azure Databricks Notebook placed within an Azure Data Factory pipeline. The Notebook is to perform the recommendation logic and to load the resulting recommendation list to another table in Azure SQL database to be joined in a view containing all the meta data to be queried by the web app." }, { "code": null, "e": 14829, "s": 14636, "text": "Container C is to store a parquet file containing the Mel-frequency cepstrum of the music lib. The parquet file is registered as a Hive table to be referenced by Azure Databricks as in step 5." }, { "code": null, "e": 14951, "s": 14829, "text": "Container D and E are built to store the music lib soundtracks and artworks to be streamed and displayed via the web app." }, { "code": null, "e": 15168, "s": 14951, "text": "All service credentials including CosmosDB connection string, SQL database connection string, Blob storage connection string and the 3rd party music recognition API token are stored in and secured by Azure Key Vault." }, { "code": null, "e": 15228, "s": 15168, "text": "Load soundtracks and artworks to the designated containers." }, { "code": null, "e": 15293, "s": 15228, "text": "Create a new table in SQL database to store music lib meta data." }, { "code": null, "e": 15469, "s": 15293, "text": "Extract meta data from audio files and load them into a data frame. The soundtrack paths and artwork paths are generated by shared access signatures (SAS) via blob client API." }, { "code": null, "e": 16625, "s": 15469, "text": "from mutagen.easyid3 import EasyID3import pandas as pdimport osfrom azure.storage.blob import generate_container_sasfrom datetime import datetime,timedeltasongs = os.listdir(\"soundtracks\")l=[]for song in songs: audio = EasyID3(\"soundtracks\"+\"\\\\\"+song) meta=[] for e in [\"title\",\"album\",\"artist\",\"genre\",\"date\"]: try: if e==\"date\": attr = audio[e][0][:4] elif e==\"title\": attr = song.replace(\".mp3\",\"\") else: attr = audio[e][0] meta.append(attr) except: meta.append(None) l.append(meta)df = pd.DataFrame(l,columns=[\"TITLE\",\"ALBUM\",\"ARTIST\",\"GENRE\",\"RELEASE_YEAR\"])key=my_keysas_sound=generate_container_sas('xwstorage', 'soundtracks',key,expiry=datetime.utcnow()+timedelta(days=30),permission='r')sas_art=generate_container_sas('xwstorage', 'artworks',key,expiry=datetime.utcnow()+timedelta(days=30),permission='r')df[\"SOUNDTRACK_PATH\"] = \"https://xwstorage.blob.core.windows.net/soundtracks/\"+df[\"TITLE\"]+\".mp3\"+\"?\"+sas_sounddf[\"ARTWORK_PATH\"] = \"https://xwstorage.blob.core.windows.net/artworks/\"+df[\"TITLE\"]+\".jpeg\"+\"?\"+sas_art" }, { "code": null, "e": 16691, "s": 16625, "text": "Load the resulting data frame to the SQL table we created before." }, { "code": null, "e": 16972, "s": 16691, "text": "import sqlalchemyimport pyodbcfrom sqlalchemy.engine import URLcnxn = my_odbc_connection_stringconnection_url = URL.create(\"mssql+pyodbc\", query={\"odbc_connect\": cnxn})engine = sqlalchemy.create_engine(connection_url)df.to_sql(\"SOUNDTRACKS\", engine,if_exists=\"append\",index=False)" }, { "code": null, "e": 17096, "s": 16972, "text": "Dump the music lib Mel-frequency cepstrum into a parquet file and then upload the parquet file to the designated container." }, { "code": null, "e": 17774, "s": 17096, "text": "import pandas as pdfrom python_speech_features import mfccimport matplotlib.pyplot as pltimport librosaimport ostracks = os.listdir(r\"soundtracks\")L=[]for i in tracks: print(i) data,sample_rate = librosa.load(r\"soundtracks\"+\"\\\\\"+i,sr=44100) a = data.T[500:-500] a = a/a.max() plt.figure(figsize=(20,7)) mfcc_feat = mfcc(a,sample_rate) mfcc_data= mfcc_feat.T L.append(mfcc_data)columns = [\"COE_\"+str(i) for i in range(1,14)]L2 = [pd.DataFrame(i.T,columns=columns) for i in L]titles = [i.replace(\".mp3\",\"\") for i in tracks]for i,j in zip(L2,titles): i[\"Title\"]=jdf=pd.concat(L2)df.reset_index(drop=True).reset_index().to_parquet(\"soundtracks.parquet\")" }, { "code": null, "e": 17866, "s": 17774, "text": "As mentioned earlier, all service credentials are stored in and secured by Azure Key Vault." }, { "code": null, "e": 17944, "s": 17866, "text": "Create a CosmosDB instance to store the meta data of the uploaded audio file." }, { "code": null, "e": 18152, "s": 17944, "text": "Create a blob-trigger type Azure function as the starting point. The function is to cut a 200KB sample out of the input blob and POST it to a 3rd party music recognition service API for meta data collection." }, { "code": null, "e": 18420, "s": 18152, "text": "Have the function bind the output path to CosmosDB and another blob container as such that the original input blob will be duplicated to where it needs to be for batch layer processing and the resulting meta data in json will be loaded into CosmosDB at the same time." }, { "code": null, "e": 18594, "s": 18420, "text": "Create a http-trigger type Azure function with GET method only to query the latest record in CosmosDB. This function serves as an API endpoint to be consumed by the web app." }, { "code": null, "e": 18755, "s": 18594, "text": "Once we have both Azure functions deployed, we can simply drop a MP3 file to the target blob container to quickly test if the API endpoint works in the browser." }, { "code": null, "e": 19086, "s": 18755, "text": "Create a cluster instance for Azure Databricks. Load the cepstrum parquet file into a spark data frame and register it as a Hive table. Given that the cepstrum table has nearly 4 million rows while 14 columns (13 MFCC + Title) only, A columnstore format like parquet is more optimised over a rowstore format like CSV in this case." }, { "code": null, "e": 19155, "s": 19086, "text": "A secret scope needs to be created to interact with Azure Key Vault." }, { "code": null, "e": 19358, "s": 19155, "text": "Create a new notebook and rewrite the DTW based MFCC similarity computing logic from Python list iteration to Spark data frame manipulation and load the results to Azure SQL database via JDBC connector." }, { "code": null, "e": 19660, "s": 19358, "text": "Given the fact that similarity computing requires large table aggregations only and doesn’t involve any machine learning algorithm, a multi-node computing environment definitely takes advantage here, this is the fundamental reason why I chose Azure Databricks over Azure ML Service for this operation." }, { "code": null, "e": 19765, "s": 19660, "text": "A recommendation list will be loaded into a SQL table to be joined in a view if the operation succeeded." }, { "code": null, "e": 20059, "s": 19765, "text": "Place the notebook within a Azure Data Factory pipeline and make it triggerable by a blob change event taking place in the target container. In this fashion, the notebook will be activated as soon as the initial upload is duplicated from the speed layer container to the batch layer container." }, { "code": null, "e": 20239, "s": 20059, "text": "Develop and deploy a flask app to Azure App Service. The app is built to render 2 html pages. The first is for music file uploading, the second is for recommended music streaming." } ]