title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
What is Gradient Clipping?. A simple yet effective way to tackle... | by Wanshun Wong | Towards Data Science
Recurrent Neural Networks (RNN) work very well with sequential data by utilizing hidden states that stores information about past inputs: the values of hidden states at time t depend on their values at time t -1 and also the inputs at time t. This architecture, while powerful, causes two problems in training: exploding gradients and vanishing gradients. In this article, we will look into gradient clipping which deals with the exploding gradients problem. Exploding gradients refer to the problem that the gradients get too large in training, making the model unstable. Similarly, vanishing gradients refer to gradients getting too small in training. This prevents the network weights from changing their values. Both problems cause the model unable to learn from the training data. The following informal discussion is not that rigorous but is sufficient to give us an intuition about the source of exploding and vanishing gradients. When we train a RNN by Backpropagation Through Time, it means we first unroll the RNN in time by creating a copy of the network for each time step, viewing it as a multi-layer feedforward neural network, where the number of layers is equal to the number of time steps. Then we do backpropagation on the unrolled network, taking into account the weight sharing: where W is the recurrent weight matrix. It can be shown that the gradient of the loss function consists of a product of n copies of WT, where n is the number of layers going back in time. This product of matrices is the source of exploding and vanishing gradients. For a scaler a ≠ 1, an shrink or grow exponentially. For example, consider n = 30. Then, for instance, 1.1n ≈ 17.45 and 0.9n ≈ 0.042. We pick 30 because it is quite common for a sentence in a Natural Language Processing task to have 30 words, and it is also quite typical for time series analysis to process 30 days of data. The situation for products of matrices (WT)n is very similar. The easiest way to see this is to assume WT is diagonalizable. Then WT = QDQ−1 for some diagonal matrix D = diag(λ1, ..., λx), and (WT)n = QDnQ−1 with Dn = diag(λ1n, ..., λxn). We refer to [2] for a rigorous treatment of the exploding and vanishing gradients problems. Gradient clipping is a technique that tackles exploding gradients. The idea of gradient clipping is very simple: If the gradient gets too large, we rescale it to keep it small. More precisely, if ‖g‖ ≥ c, then g ↤ c · g/‖g‖ where c is a hyperparameter, g is the gradient, and ‖g‖ is the norm of g. Since g/‖g‖ is a unit vector, after rescaling the new g will have norm c. Note that if ‖g‖ < c, then we don’t need to do anything. Gradient clipping ensures the gradient vector g has norm at most c. This helps gradient descent to have a reasonable behaviour even if the loss landscape of the model is irregular. The following figure shows an example with an extremely steep cliff in the loss landscape. Without clipping, the parameters take a huge descent step and leave the “good” region. With clipping, the descent step size is restricted and the parameters stay in the “good” region. Tensorflow: tf.clip_by_global_norm. PyTorch: torch.nn.utils.clip_grad_norm_. Q: How do we choose the hyperparameter c? A: We can train our neural networks for some epochs and look at the statistics of the gradient norms. The average value of gradient norms is a good initial trial. Q: Can we use gradient clipping in training neural architectures other than RNN? A: Yes. We can use gradient clipping for any neural architectures whenever we have exploding gradients. Chapter 10.11 of [1] has a good overview of how gradient clipping works.[3] introduces a new smoothness condition to provide a theoretical explanation for the effectiveness of gradient clipping. Chapter 10.11 of [1] has a good overview of how gradient clipping works. [3] introduces a new smoothness condition to provide a theoretical explanation for the effectiveness of gradient clipping. I. Goodfellow, Y. Bengio, and A. Courville. Deep Learning (2016), MIT Press.R. Pascanu, T. Mikolov, and Y. Bengio. On the difficulty of training Recurrent Neural Networks (2013), ICML 2013.J. Zhang, T. He, S. Sra, and A. Jadbabaie. Why gradient clipping accelerates training: A theoretical justification for adaptivity (2020), ICLR 2020. I. Goodfellow, Y. Bengio, and A. Courville. Deep Learning (2016), MIT Press. R. Pascanu, T. Mikolov, and Y. Bengio. On the difficulty of training Recurrent Neural Networks (2013), ICML 2013. J. Zhang, T. He, S. Sra, and A. Jadbabaie. Why gradient clipping accelerates training: A theoretical justification for adaptivity (2020), ICLR 2020.
[ { "code": null, "e": 630, "s": 171, "text": "Recurrent Neural Networks (RNN) work very well with sequential data by utilizing hidden states that stores information about past inputs: the values of hidden states at time t depend on their values at time t -1 and also the inputs at time t. This architecture, while powerful, causes two problems in training: exploding gradients and vanishing gradients. In this article, we will look into gradient clipping which deals with the exploding gradients problem." }, { "code": null, "e": 1109, "s": 630, "text": "Exploding gradients refer to the problem that the gradients get too large in training, making the model unstable. Similarly, vanishing gradients refer to gradients getting too small in training. This prevents the network weights from changing their values. Both problems cause the model unable to learn from the training data. The following informal discussion is not that rigorous but is sufficient to give us an intuition about the source of exploding and vanishing gradients." }, { "code": null, "e": 1470, "s": 1109, "text": "When we train a RNN by Backpropagation Through Time, it means we first unroll the RNN in time by creating a copy of the network for each time step, viewing it as a multi-layer feedforward neural network, where the number of layers is equal to the number of time steps. Then we do backpropagation on the unrolled network, taking into account the weight sharing:" }, { "code": null, "e": 1735, "s": 1470, "text": "where W is the recurrent weight matrix. It can be shown that the gradient of the loss function consists of a product of n copies of WT, where n is the number of layers going back in time. This product of matrices is the source of exploding and vanishing gradients." }, { "code": null, "e": 2300, "s": 1735, "text": "For a scaler a ≠ 1, an shrink or grow exponentially. For example, consider n = 30. Then, for instance, 1.1n ≈ 17.45 and 0.9n ≈ 0.042. We pick 30 because it is quite common for a sentence in a Natural Language Processing task to have 30 words, and it is also quite typical for time series analysis to process 30 days of data. The situation for products of matrices (WT)n is very similar. The easiest way to see this is to assume WT is diagonalizable. Then WT = QDQ−1 for some diagonal matrix D = diag(λ1, ..., λx), and (WT)n = QDnQ−1 with Dn = diag(λ1n, ..., λxn)." }, { "code": null, "e": 2392, "s": 2300, "text": "We refer to [2] for a rigorous treatment of the exploding and vanishing gradients problems." }, { "code": null, "e": 2602, "s": 2392, "text": "Gradient clipping is a technique that tackles exploding gradients. The idea of gradient clipping is very simple: If the gradient gets too large, we rescale it to keep it small. More precisely, if ‖g‖ ≥ c, then" }, { "code": null, "e": 2616, "s": 2602, "text": "g ↤ c · g/‖g‖" }, { "code": null, "e": 2821, "s": 2616, "text": "where c is a hyperparameter, g is the gradient, and ‖g‖ is the norm of g. Since g/‖g‖ is a unit vector, after rescaling the new g will have norm c. Note that if ‖g‖ < c, then we don’t need to do anything." }, { "code": null, "e": 3277, "s": 2821, "text": "Gradient clipping ensures the gradient vector g has norm at most c. This helps gradient descent to have a reasonable behaviour even if the loss landscape of the model is irregular. The following figure shows an example with an extremely steep cliff in the loss landscape. Without clipping, the parameters take a huge descent step and leave the “good” region. With clipping, the descent step size is restricted and the parameters stay in the “good” region." }, { "code": null, "e": 3313, "s": 3277, "text": "Tensorflow: tf.clip_by_global_norm." }, { "code": null, "e": 3354, "s": 3313, "text": "PyTorch: torch.nn.utils.clip_grad_norm_." }, { "code": null, "e": 3396, "s": 3354, "text": "Q: How do we choose the hyperparameter c?" }, { "code": null, "e": 3559, "s": 3396, "text": "A: We can train our neural networks for some epochs and look at the statistics of the gradient norms. The average value of gradient norms is a good initial trial." }, { "code": null, "e": 3640, "s": 3559, "text": "Q: Can we use gradient clipping in training neural architectures other than RNN?" }, { "code": null, "e": 3744, "s": 3640, "text": "A: Yes. We can use gradient clipping for any neural architectures whenever we have exploding gradients." }, { "code": null, "e": 3939, "s": 3744, "text": "Chapter 10.11 of [1] has a good overview of how gradient clipping works.[3] introduces a new smoothness condition to provide a theoretical explanation for the effectiveness of gradient clipping." }, { "code": null, "e": 4012, "s": 3939, "text": "Chapter 10.11 of [1] has a good overview of how gradient clipping works." }, { "code": null, "e": 4135, "s": 4012, "text": "[3] introduces a new smoothness condition to provide a theoretical explanation for the effectiveness of gradient clipping." }, { "code": null, "e": 4473, "s": 4135, "text": "I. Goodfellow, Y. Bengio, and A. Courville. Deep Learning (2016), MIT Press.R. Pascanu, T. Mikolov, and Y. Bengio. On the difficulty of training Recurrent Neural Networks (2013), ICML 2013.J. Zhang, T. He, S. Sra, and A. Jadbabaie. Why gradient clipping accelerates training: A theoretical justification for adaptivity (2020), ICLR 2020." }, { "code": null, "e": 4550, "s": 4473, "text": "I. Goodfellow, Y. Bengio, and A. Courville. Deep Learning (2016), MIT Press." }, { "code": null, "e": 4664, "s": 4550, "text": "R. Pascanu, T. Mikolov, and Y. Bengio. On the difficulty of training Recurrent Neural Networks (2013), ICML 2013." } ]
What is the role of Browser Object Model (BOM) in JavaScript?
The Browser Object Model (BOM) in JavaScript includes the properties and methods for JavaScript to interact with the web browser. BOM provides you with a window objects, for example, to show the width and height of the window. It also includes the window.screen object to show the width and height of the screen. You can try to run the following code to learn how to get screen height and width − Live Demo <!DOCTYPE html> <html> <body> <script> document.write("Screen width: " + screen.width); document.write("<br>Screen width: " + screen.width); </script> </body> </html>
[ { "code": null, "e": 1192, "s": 1062, "text": "The Browser Object Model (BOM) in JavaScript includes the properties and methods for JavaScript to interact with the web browser." }, { "code": null, "e": 1375, "s": 1192, "text": "BOM provides you with a window objects, for example, to show the width and height of the window. It also includes the window.screen object to show the width and height of the screen." }, { "code": null, "e": 1459, "s": 1375, "text": "You can try to run the following code to learn how to get screen height and width −" }, { "code": null, "e": 1469, "s": 1459, "text": "Live Demo" }, { "code": null, "e": 1672, "s": 1469, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n document.write(\"Screen width: \" + screen.width);\n document.write(\"<br>Screen width: \" + screen.width);\n </script>\n </body>\n</html>" } ]
SQL Tryit Editor v1.6
SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID GROUP BY ShipperName; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, Opera, and Edge(79). If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 80, "s": 0, "text": "SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders" }, { "code": null, "e": 140, "s": 80, "text": "LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID" }, { "code": null, "e": 162, "s": 140, "text": "GROUP BY ShipperName;" }, { "code": null, "e": 164, "s": 162, "text": "​" }, { "code": null, "e": 227, "s": 164, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 287, "s": 227, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 355, "s": 287, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 393, "s": 355, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 478, "s": 393, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 652, "s": 478, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 703, "s": 652, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 771, "s": 703, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 942, "s": 771, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 1042, "s": 942, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 1102, "s": 1042, "text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)." } ]
Object Detection- Tensorflow. Using the tensorflow Object Detection... | by Sahil Gupta | Towards Data Science
The model is trained using the Tensorflow Object Detection API for training the model for 20 classes on the Pascal VOC 2012 dataset. There has been a buzz all around, about Machine Learning and Deep Neural Networks since, their popularity has revived after they were shelved for quite a few years. Lately, the communities around the world have started to contribute to the field of Machine Learning. Since its advancement, Object detection and Object Recognition have gained immense popularity and researchers around the world have contributed with various state-of-the-art architectures. Tensorflow, by Google, has contributed with a dedicated API ( Object Detection API ) which provides with a bunch of models that have been trained on a large corpus. These models are freely available and also allow user contribution. Further in this post, I am going to train a model using the pre-trained model for detecting the objects in the PASCAL VOC dataset. The dataset used in this blog is available freely here (2012 version). However, the server is mostly down so you may find the dataset here. The dataset that we are using represent the data in the XML files and the corresponding images. Each XML file in the data contains the information of all the bounding boxes. The Object Detection API consumes these XML files and converts them into the csv format which can further be converted into the tf record format that is required to train the model. In our case, we are using the PASCAL VOC dataset, for which tensorflow has already provided various utilities to make our life easier. We will get into the details as we move ahead. The API abstracts the whole load of tricky stuff for us. However, there are a few requirements that are to be satisfied by the user before using the API. The API uses the dataset in the tf record format. It is a binary format for representing the data. The API uses this format to speed up the training process. Tf record internally represents the data in a format that allows for parallel processing. Let’s begin by cloning the tensorflow models which is a collection of models that are under research and the officially released models. Now we need to install the protocol buffer files inside of the object detection folder in models/research. Also, we need to install the all the models in the research folder. Let’s do that... After installing all the models in the research folder we are good to go for converting the data in the tf record format. Now, in our case as we are using the PASCAL VOC dataset, for that tensorflow provides us with a script which we can use to convert the data in the tf record format. We also require the labels data that contains the number of classes for which the model is to be trained. The label file looks something like this... item { id: 0 name: 'businesscard'} Here each id maps to a unique number starting from and the name is the class name. In our case we have 20 classes and will have 20 unique item JSON objects in the same file. For our purpose, tensorflow provides us with a label file for our dataset which can be found at the following path in your colab notebook /content/models/research/object_detection/data/pascal_label_map.pbtxt Similarly, you need to run the create_pascal_tf_record_test.py to convert the test data in the required format. While dealing with the API, there are various compatibility issues that one has to deal with. This is due to the initial releases of the API. I spent around 3 days solving a major issue which most of us face, which is the slim module. Even after providing correct paths and after reading a whole lot of blogs and comments, I was not able to solve this initially. But, I will guide you the steps to help you with it as per the current version. The Slim module is a requirement when you run the training process. To import the slim module you firstly need to make a new notebook and import and download all the libraries and clone the models in there. At the beginning of the colab notebook you must first convert the tensorflow version to 1.x using the following command %tensorflow_version 1.x For our training purposes we will be using the ssd_mobilenet_v1_coco model. I tried to use other models also but somehow, I couldn’t get rid of errors in there eve after following the same process. But everything worked just fine for ssd_mobilenet_v1 model. It is a model trained on the COCO dataset and hence can detect 90 classes. But for out purpose we need to train it for only 20 classes in the VOC dataset. Firstly, download the model from the official website of tensorflow (here). Now, we will extract the model tar file. Now, I am providing with you some of the commands that you can run to get rid of the slim issue. Copy and paste the following commands in your notebook to install the slim library, once inside the research/slim folder and second, copy all the slim files in object_detection folder and install them there also. Sometimes, directly installing tf-slim package using pip install tf-slim also works(mostly in the case of kaggle notebooks) Next, you need to download the config file for the model from the models/research/object_detection/samples/configs/ folder and change the path of the input tf-record file, label map file, test tf record file and a directory to save the model in. Now, run the command to start the training process. Note: In colab notebooks, even after modifying the fine_tune_checkpoint path the checkpoints were getting saved inside of the tmp folder in root of colab notebooks. Do consider the case if it still persists. Also, if there are errors in training then switch to tensorflow 2.x by restarting the session. This way slim error will not come now. After getting the model trained for 20 classes, we need to convert the checkpoint file in a reusable format. For converting the model in the required format, tensorflow provides with a script that can be used. Note: If export_inference_graph.py script throws an error which says that the path must be provided using output_file then you need to replace this script with another script which can downloaded found here and then run the above command For getting the predictions we will user the tensorflow utilities to get the probabilities and the bounding box values and then display the bounding box on the pictures. Whole code for the predictions is quite simple and folows the same structure. you can find the code below... You can find the complete working notebooks on my github repo: github.com I hope this tutorial helps you with every aspect of the training and testing. If you have any doubts you can ask them in the comments section.
[ { "code": null, "e": 305, "s": 172, "text": "The model is trained using the Tensorflow Object Detection API for training the model for 20 classes on the Pascal VOC 2012 dataset." }, { "code": null, "e": 761, "s": 305, "text": "There has been a buzz all around, about Machine Learning and Deep Neural Networks since, their popularity has revived after they were shelved for quite a few years. Lately, the communities around the world have started to contribute to the field of Machine Learning. Since its advancement, Object detection and Object Recognition have gained immense popularity and researchers around the world have contributed with various state-of-the-art architectures." }, { "code": null, "e": 1125, "s": 761, "text": "Tensorflow, by Google, has contributed with a dedicated API ( Object Detection API ) which provides with a bunch of models that have been trained on a large corpus. These models are freely available and also allow user contribution. Further in this post, I am going to train a model using the pre-trained model for detecting the objects in the PASCAL VOC dataset." }, { "code": null, "e": 1265, "s": 1125, "text": "The dataset used in this blog is available freely here (2012 version). However, the server is mostly down so you may find the dataset here." }, { "code": null, "e": 1803, "s": 1265, "text": "The dataset that we are using represent the data in the XML files and the corresponding images. Each XML file in the data contains the information of all the bounding boxes. The Object Detection API consumes these XML files and converts them into the csv format which can further be converted into the tf record format that is required to train the model. In our case, we are using the PASCAL VOC dataset, for which tensorflow has already provided various utilities to make our life easier. We will get into the details as we move ahead." }, { "code": null, "e": 1957, "s": 1803, "text": "The API abstracts the whole load of tricky stuff for us. However, there are a few requirements that are to be satisfied by the user before using the API." }, { "code": null, "e": 2205, "s": 1957, "text": "The API uses the dataset in the tf record format. It is a binary format for representing the data. The API uses this format to speed up the training process. Tf record internally represents the data in a format that allows for parallel processing." }, { "code": null, "e": 2342, "s": 2205, "text": "Let’s begin by cloning the tensorflow models which is a collection of models that are under research and the officially released models." }, { "code": null, "e": 2534, "s": 2342, "text": "Now we need to install the protocol buffer files inside of the object detection folder in models/research. Also, we need to install the all the models in the research folder. Let’s do that..." }, { "code": null, "e": 2971, "s": 2534, "text": "After installing all the models in the research folder we are good to go for converting the data in the tf record format. Now, in our case as we are using the PASCAL VOC dataset, for that tensorflow provides us with a script which we can use to convert the data in the tf record format. We also require the labels data that contains the number of classes for which the model is to be trained. The label file looks something like this..." }, { "code": null, "e": 3009, "s": 2971, "text": "item { id: 0 name: 'businesscard'} " }, { "code": null, "e": 3391, "s": 3009, "text": "Here each id maps to a unique number starting from and the name is the class name. In our case we have 20 classes and will have 20 unique item JSON objects in the same file. For our purpose, tensorflow provides us with a label file for our dataset which can be found at the following path in your colab notebook /content/models/research/object_detection/data/pascal_label_map.pbtxt" }, { "code": null, "e": 3503, "s": 3391, "text": "Similarly, you need to run the create_pascal_tf_record_test.py to convert the test data in the required format." }, { "code": null, "e": 4153, "s": 3503, "text": "While dealing with the API, there are various compatibility issues that one has to deal with. This is due to the initial releases of the API. I spent around 3 days solving a major issue which most of us face, which is the slim module. Even after providing correct paths and after reading a whole lot of blogs and comments, I was not able to solve this initially. But, I will guide you the steps to help you with it as per the current version. The Slim module is a requirement when you run the training process. To import the slim module you firstly need to make a new notebook and import and download all the libraries and clone the models in there." }, { "code": null, "e": 4297, "s": 4153, "text": "At the beginning of the colab notebook you must first convert the tensorflow version to 1.x using the following command %tensorflow_version 1.x" }, { "code": null, "e": 4710, "s": 4297, "text": "For our training purposes we will be using the ssd_mobilenet_v1_coco model. I tried to use other models also but somehow, I couldn’t get rid of errors in there eve after following the same process. But everything worked just fine for ssd_mobilenet_v1 model. It is a model trained on the COCO dataset and hence can detect 90 classes. But for out purpose we need to train it for only 20 classes in the VOC dataset." }, { "code": null, "e": 4827, "s": 4710, "text": "Firstly, download the model from the official website of tensorflow (here). Now, we will extract the model tar file." }, { "code": null, "e": 5137, "s": 4827, "text": "Now, I am providing with you some of the commands that you can run to get rid of the slim issue. Copy and paste the following commands in your notebook to install the slim library, once inside the research/slim folder and second, copy all the slim files in object_detection folder and install them there also." }, { "code": null, "e": 5261, "s": 5137, "text": "Sometimes, directly installing tf-slim package using pip install tf-slim also works(mostly in the case of kaggle notebooks)" }, { "code": null, "e": 5559, "s": 5261, "text": "Next, you need to download the config file for the model from the models/research/object_detection/samples/configs/ folder and change the path of the input tf-record file, label map file, test tf record file and a directory to save the model in. Now, run the command to start the training process." }, { "code": null, "e": 5901, "s": 5559, "text": "Note: In colab notebooks, even after modifying the fine_tune_checkpoint path the checkpoints were getting saved inside of the tmp folder in root of colab notebooks. Do consider the case if it still persists. Also, if there are errors in training then switch to tensorflow 2.x by restarting the session. This way slim error will not come now." }, { "code": null, "e": 6111, "s": 5901, "text": "After getting the model trained for 20 classes, we need to convert the checkpoint file in a reusable format. For converting the model in the required format, tensorflow provides with a script that can be used." }, { "code": null, "e": 6349, "s": 6111, "text": "Note: If export_inference_graph.py script throws an error which says that the path must be provided using output_file then you need to replace this script with another script which can downloaded found here and then run the above command" }, { "code": null, "e": 6628, "s": 6349, "text": "For getting the predictions we will user the tensorflow utilities to get the probabilities and the bounding box values and then display the bounding box on the pictures. Whole code for the predictions is quite simple and folows the same structure. you can find the code below..." }, { "code": null, "e": 6691, "s": 6628, "text": "You can find the complete working notebooks on my github repo:" }, { "code": null, "e": 6702, "s": 6691, "text": "github.com" } ]
MaterialApp class in Flutter - GeeksforGeeks
24 Nov, 2020 MaterialApp Class: MaterialApp is a predefined class in a flutter. It is likely the main or core component of flutter. We can access all the other components and widgets provided by Flutter SDK. Text widget, Dropdownbutton widget, AppBar widget, Scaffold widget, ListView widget, StatelessWidget, StatefulWidget, IconButton widget, TextField widget, Padding widget, ThemeData widget, etc. are the widgets that can be accessed using MaterialApp class. There are many more widgets that are accessed using MaterialApp class. Using this widget, we can make an attractive app. Here is a very simple code in dart language to make a screen that has an appBar title as GeeksforGeeks. const MaterialApp( {Key key, GlobalKey<NavigatorState> navigatorKey, Widget home, Map<String, WidgetBuilder> routes: const <String, WidgetBuilder>{}, String initialRoute, RouteFactory onGenerateRoute, InitialRouteListFactory onGenerateInitialRoutes, RouteFactory onUnknownRoute, List<NavigatorObserver> navigatorObservers: const <NavigatorObserver>[], TransitionBuilder builder, String title: '', GenerateAppTitle onGenerateTitle, Color color, ThemeData theme, ThemeData darkTheme, ThemeData highContrastTheme, ThemeData highContrastDarkTheme, ThemeMode themeMode: ThemeMode.system, Locale locale, Iterable<LocalizationsDelegate> localizationsDelegates, LocaleListResolutionCallback localeListResolutionCallback, LocaleResolutionCallback localeResolutionCallback, Iterable<Locale> supportedLocales: const <Locale>[Locale('en', 'US')], bool debugShowMaterialGrid: false, bool showPerformanceOverlay: false, bool checkerboardRasterCacheImages: false, bool checkerboardOffscreenLayers: false, bool showSemanticsDebugger: false, bool debugShowCheckedModeBanner: true, Map<LogicalKeySet, Intent> shortcuts, Map<Type, Action<Intent>> actions} ) action: This property takes in Map<Type, Action<Intent>> as the object. It controls intent keys. backButtonDispatcher: It decided how to handle the back button. checkerboardRasterCacheImage: This property takes in a boolean as the object. If set to true it turns on the checkerboarding of raster cache images. color: It controls the primary color used in the application. darkTheme: It provided theme data for the dark theme for the application. debugShowCheckedModeBanner: This property takes in a boolean as the object to decide whether to show the debug banner or not. debugShowMaterialGird: This property takes a boolean as the object. If set to true it paints a baseline grid material app. highContrastDarkTheme: It provided the theme data to use for the high contrast theme. home: This property takes in widget as the object to show on the default route of the app. initialRoute: This property takes in a string as the object to give the name of the first route in which the navigator is built. locale: It provides a locale for the MaterialApp. localizationsDelegate: This provides a delegate for the locales. navigatorObserver: It takes in GlobalKey<NavigatorState> as the object to generate a key when building a navigator. navigatorObserver: This property holds List<NavigatorObserver> as the object to create a list of observers for the navigator. onGenerateInitialRoutes: This property takes in InitialRouteListFactory typedef as the object to generate initial routes. onGeneratRoute: The onGenerateRoute takes in a RouteFactory as the object. It is used when the app is navigated to a named route. OnGenerateTitle: This property takes in RouteFactory typedef as the object to generate a title string for the application if provided. onUnknownRoute: The onUnknownRoute takes in RouteFactory typedef as the object to provide a route in case of failure in other metheod. routeInformationParse: This property holds RouteInformationParser<T> as the object to the routing information from the routeInformationProvider into a generic data type. routeInformationProvider: This property takes in RouteInformationProvider class as the object. It is responsible for providing routing information. routeDelegate: This property takes in RouterDelegate<T> as the object to configure a given widget. routes: The routes property takes in LogicalKeySet class as the object to control the app’s topmost level routing. shortcuts: This property takes in LogicalKeySet class as the object to decide the keyboard shortcut for the application. showPerformanceOverlay: The showPerformanceOverlay takes in a boolean value as the object to turn on or off performance overlay. showSemantisDebugger: This property takes in a boolean as the object. If set to true, it shows some accessible information. supportedLocales: The supportedLocales property keeps hold of the locals used in the app by taking in Iterable<E> class as the object. theme: This property takes in ThemeData class as the object to describe the theme for the MaterialApp. themeMode: This property holds ThemeMode enum as the object to decide the theme for the material app. title: The title property takes in a string as the object to decide the one-line description of the app for the device. Dart import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( title: 'GeeksforGeeks', theme: ThemeData( primarySwatch: Colors.green ), home: Scaffold( appBar: AppBar( title:Text( 'GeeksforGeeks' ) ), ), ));} import statement: The import statement is used to import the libraries that are provided by the flutter SDK. Here we have imported the ‘material.dart’ file. We can use all the flutter widgets that implement the material design by importing this file. main() function: Like many other programming languages, we also have main function in which we have to write the statements those are to be executed when the app starts. The return type of main function is ‘void’. runApp(Widget widget) function: The void runApp(Widget widget) takes a widget as an argument and sets it on a screen. It gives the constraints to the widget to fit into the screen. It makes the given widget the root widget of the app and other widgets as the child of it. Here we have used the MaterialApp as a root widget in which we have defined the other widgets. MaterialApp() widget: I have discussed MaterialApp in the beginning. Let us have a look at the different properties of the MaterialApp widget. title: This property is used to provide a short description of the application to the user. When the user press the recent apps button on mobile the text proceeded in title is displayed. theme: This property is used to provide the default theme to the application like the theme-color of the application.For this, we use the inbuilt class/widget named ThemeData(). In Themedata() widget we have to write the different properties related to the theme. Here we have used the primarySwatch which is used to define the default themecolor of the application. To choose the color we have used Colors class from the material library. In ThemeData() we can also define some other properties like TextTheme, Brightness(Can enable dark theme by this), AppBarTheme, and many more. home: It is used for the default route of the app means the widget defined in it is displayed when the application starts normally. Here we have defined the Scaffold widget inside the home property. Inside the Scaffold we define various properties like appBar, body, floatingActionButton, backgroundColor, etc. For example in the appBar property we have used the AppBar() widget in which as a title we have passed ‘GeeksforGeeks’ which will be displayed at the top of the application in appbar. The other properties in MaterialApp() are debugShowCheckedModeBanner (used to remove the debug tag at top corner), darkTheme (To request dark mode in application), color (For the primary color of application), routes (For routing table of application), ThemeMode (To determine which theme to be used), etc. Output: Here we can see that the text defined in the title of the appbar is displayed at the top. The default theme-color is green as we defined. runApp() has fitted the widget on the whole screen. ankit_kumar_ Flutter Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page? How to set the default value for an HTML <select> element ?
[ { "code": null, "e": 25551, "s": 25523, "text": "\n24 Nov, 2020" }, { "code": null, "e": 26227, "s": 25551, "text": "MaterialApp Class: MaterialApp is a predefined class in a flutter. It is likely the main or core component of flutter. We can access all the other components and widgets provided by Flutter SDK. Text widget, Dropdownbutton widget, AppBar widget, Scaffold widget, ListView widget, StatelessWidget, StatefulWidget, IconButton widget, TextField widget, Padding widget, ThemeData widget, etc. are the widgets that can be accessed using MaterialApp class. There are many more widgets that are accessed using MaterialApp class. Using this widget, we can make an attractive app. Here is a very simple code in dart language to make a screen that has an appBar title as GeeksforGeeks." }, { "code": null, "e": 27367, "s": 26227, "text": "const MaterialApp(\n{Key key,\nGlobalKey<NavigatorState> navigatorKey,\nWidget home,\nMap<String, WidgetBuilder> routes: const <String, WidgetBuilder>{},\nString initialRoute,\nRouteFactory onGenerateRoute,\nInitialRouteListFactory onGenerateInitialRoutes,\nRouteFactory onUnknownRoute,\nList<NavigatorObserver> navigatorObservers: const <NavigatorObserver>[],\nTransitionBuilder builder,\nString title: '',\nGenerateAppTitle onGenerateTitle,\nColor color,\nThemeData theme,\nThemeData darkTheme,\nThemeData highContrastTheme,\nThemeData highContrastDarkTheme,\nThemeMode themeMode: ThemeMode.system,\nLocale locale,\nIterable<LocalizationsDelegate> localizationsDelegates,\nLocaleListResolutionCallback localeListResolutionCallback,\nLocaleResolutionCallback localeResolutionCallback,\nIterable<Locale> supportedLocales: const <Locale>[Locale('en', 'US')],\nbool debugShowMaterialGrid: false,\nbool showPerformanceOverlay: false,\nbool checkerboardRasterCacheImages: false,\nbool checkerboardOffscreenLayers: false,\nbool showSemanticsDebugger: false,\nbool debugShowCheckedModeBanner: true,\nMap<LogicalKeySet, Intent> shortcuts,\nMap<Type, Action<Intent>> actions}\n)\n" }, { "code": null, "e": 27465, "s": 27367, "text": "action: This property takes in Map<Type, Action<Intent>> as the object. It controls intent keys." }, { "code": null, "e": 27529, "s": 27465, "text": "backButtonDispatcher: It decided how to handle the back button." }, { "code": null, "e": 27679, "s": 27529, "text": "checkerboardRasterCacheImage: This property takes in a boolean as the object. If set to true it turns on the checkerboarding of raster cache images." }, { "code": null, "e": 27741, "s": 27679, "text": "color: It controls the primary color used in the application." }, { "code": null, "e": 27815, "s": 27741, "text": "darkTheme: It provided theme data for the dark theme for the application." }, { "code": null, "e": 27941, "s": 27815, "text": "debugShowCheckedModeBanner: This property takes in a boolean as the object to decide whether to show the debug banner or not." }, { "code": null, "e": 28064, "s": 27941, "text": "debugShowMaterialGird: This property takes a boolean as the object. If set to true it paints a baseline grid material app." }, { "code": null, "e": 28150, "s": 28064, "text": "highContrastDarkTheme: It provided the theme data to use for the high contrast theme." }, { "code": null, "e": 28241, "s": 28150, "text": "home: This property takes in widget as the object to show on the default route of the app." }, { "code": null, "e": 28370, "s": 28241, "text": "initialRoute: This property takes in a string as the object to give the name of the first route in which the navigator is built." }, { "code": null, "e": 28420, "s": 28370, "text": "locale: It provides a locale for the MaterialApp." }, { "code": null, "e": 28485, "s": 28420, "text": "localizationsDelegate: This provides a delegate for the locales." }, { "code": null, "e": 28601, "s": 28485, "text": "navigatorObserver: It takes in GlobalKey<NavigatorState> as the object to generate a key when building a navigator." }, { "code": null, "e": 28727, "s": 28601, "text": "navigatorObserver: This property holds List<NavigatorObserver> as the object to create a list of observers for the navigator." }, { "code": null, "e": 28849, "s": 28727, "text": "onGenerateInitialRoutes: This property takes in InitialRouteListFactory typedef as the object to generate initial routes." }, { "code": null, "e": 28979, "s": 28849, "text": "onGeneratRoute: The onGenerateRoute takes in a RouteFactory as the object. It is used when the app is navigated to a named route." }, { "code": null, "e": 29114, "s": 28979, "text": "OnGenerateTitle: This property takes in RouteFactory typedef as the object to generate a title string for the application if provided." }, { "code": null, "e": 29249, "s": 29114, "text": "onUnknownRoute: The onUnknownRoute takes in RouteFactory typedef as the object to provide a route in case of failure in other metheod." }, { "code": null, "e": 29419, "s": 29249, "text": "routeInformationParse: This property holds RouteInformationParser<T> as the object to the routing information from the routeInformationProvider into a generic data type." }, { "code": null, "e": 29567, "s": 29419, "text": "routeInformationProvider: This property takes in RouteInformationProvider class as the object. It is responsible for providing routing information." }, { "code": null, "e": 29667, "s": 29567, "text": "routeDelegate: This property takes in RouterDelegate<T> as the object to configure a given widget." }, { "code": null, "e": 29782, "s": 29667, "text": "routes: The routes property takes in LogicalKeySet class as the object to control the app’s topmost level routing." }, { "code": null, "e": 29903, "s": 29782, "text": "shortcuts: This property takes in LogicalKeySet class as the object to decide the keyboard shortcut for the application." }, { "code": null, "e": 30032, "s": 29903, "text": "showPerformanceOverlay: The showPerformanceOverlay takes in a boolean value as the object to turn on or off performance overlay." }, { "code": null, "e": 30156, "s": 30032, "text": "showSemantisDebugger: This property takes in a boolean as the object. If set to true, it shows some accessible information." }, { "code": null, "e": 30291, "s": 30156, "text": "supportedLocales: The supportedLocales property keeps hold of the locals used in the app by taking in Iterable<E> class as the object." }, { "code": null, "e": 30394, "s": 30291, "text": "theme: This property takes in ThemeData class as the object to describe the theme for the MaterialApp." }, { "code": null, "e": 30497, "s": 30394, "text": "themeMode: This property holds ThemeMode enum as the object to decide the theme for the material app." }, { "code": null, "e": 30617, "s": 30497, "text": "title: The title property takes in a string as the object to decide the one-line description of the app for the device." }, { "code": null, "e": 30622, "s": 30617, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( title: 'GeeksforGeeks', theme: ThemeData( primarySwatch: Colors.green ), home: Scaffold( appBar: AppBar( title:Text( 'GeeksforGeeks' ) ), ), ));}", "e": 30897, "s": 30622, "text": null }, { "code": null, "e": 31148, "s": 30897, "text": "import statement: The import statement is used to import the libraries that are provided by the flutter SDK. Here we have imported the ‘material.dart’ file. We can use all the flutter widgets that implement the material design by importing this file." }, { "code": null, "e": 31362, "s": 31148, "text": "main() function: Like many other programming languages, we also have main function in which we have to write the statements those are to be executed when the app starts. The return type of main function is ‘void’." }, { "code": null, "e": 31729, "s": 31362, "text": "runApp(Widget widget) function: The void runApp(Widget widget) takes a widget as an argument and sets it on a screen. It gives the constraints to the widget to fit into the screen. It makes the given widget the root widget of the app and other widgets as the child of it. Here we have used the MaterialApp as a root widget in which we have defined the other widgets." }, { "code": null, "e": 31873, "s": 31729, "text": "MaterialApp() widget: I have discussed MaterialApp in the beginning. Let us have a look at the different properties of the MaterialApp widget. " }, { "code": null, "e": 32061, "s": 31873, "text": "title: This property is used to provide a short description of the application to the user. When the user press the recent apps button on mobile the text proceeded in title is displayed. " }, { "code": null, "e": 32644, "s": 32061, "text": "theme: This property is used to provide the default theme to the application like the theme-color of the application.For this, we use the inbuilt class/widget named ThemeData(). In Themedata() widget we have to write the different properties related to the theme. Here we have used the primarySwatch which is used to define the default themecolor of the application. To choose the color we have used Colors class from the material library. In ThemeData() we can also define some other properties like TextTheme, Brightness(Can enable dark theme by this), AppBarTheme, and many more." }, { "code": null, "e": 33139, "s": 32644, "text": "home: It is used for the default route of the app means the widget defined in it is displayed when the application starts normally. Here we have defined the Scaffold widget inside the home property. Inside the Scaffold we define various properties like appBar, body, floatingActionButton, backgroundColor, etc. For example in the appBar property we have used the AppBar() widget in which as a title we have passed ‘GeeksforGeeks’ which will be displayed at the top of the application in appbar." }, { "code": null, "e": 33447, "s": 33139, "text": "The other properties in MaterialApp() are debugShowCheckedModeBanner (used to remove the debug tag at top corner), darkTheme (To request dark mode in application), color (For the primary color of application), routes (For routing table of application), ThemeMode (To determine which theme to be used), etc. " }, { "code": null, "e": 33456, "s": 33447, "text": "Output: " }, { "code": null, "e": 33548, "s": 33458, "text": "Here we can see that the text defined in the title of the appbar is displayed at the top." }, { "code": null, "e": 33596, "s": 33548, "text": "The default theme-color is green as we defined." }, { "code": null, "e": 33648, "s": 33596, "text": "runApp() has fitted the widget on the whole screen." }, { "code": null, "e": 33663, "s": 33650, "text": "ankit_kumar_" }, { "code": null, "e": 33671, "s": 33663, "text": "Flutter" }, { "code": null, "e": 33690, "s": 33671, "text": "Technical Scripter" }, { "code": null, "e": 33707, "s": 33690, "text": "Web Technologies" }, { "code": null, "e": 33805, "s": 33707, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33814, "s": 33805, "text": "Comments" }, { "code": null, "e": 33827, "s": 33814, "text": "Old Comments" }, { "code": null, "e": 33883, "s": 33827, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 33916, "s": 33883, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33978, "s": 33916, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 34021, "s": 33978, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 34071, "s": 34021, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 34132, "s": 34071, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 34177, "s": 34132, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34249, "s": 34177, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 34307, "s": 34249, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Fractals in C/C++ - GeeksforGeeks
03 Oct, 2018 A Fractal is a never-ending pattern. Fractals are infinitely complex patterns that are self-similar across different scales. They are created by repeating a simple process over and over in an ongoing feedback loop. Mathematically fractals can be explained as follows. The location of a point on a screen is fed into an equation as its initial solution and the equation is iterated a large number of times. If that equation tends to zero (i.e. the value at the end of the iterations is smaller than the initial value), the point is coloured black. If the equation tends to infinity (i.e. the final value is larger than the initial value) then depending on the rate of increase (i.e. the rate at which the value tends to infinity), the pixel is painted with an appropriate colour. Mandelbrot Set :The Mandelbrot set is the set of complex numbers c for which the function fc(z) = z2 + c does not diverge when iterated from z = 0, i.e, for which the sequence fc(0), fc(fc(0)) etc, remains bounded in absolute value. The Mandelbrot set is the set of values of c in the complex plane for which the orbit of 0 under iteration of the quadratic map Zn+1 = Zn2 + c remains bounded. That is, a complex number c is part of the Mandelbrot set if, when starting with Z0 = 0 and applying the iteration repeatedly, the absolute value of Zn remains bounded however large n gets. Below given is the initial image of a Mandelbrot set zoom sequence. Black points correspond to numbers that are outside the set. Properties of Mandelbrot Set : The Mandelbrot set is a connected set since it always have a path from one point of the set to another point of the set so that all the points in the path are also in the set. The Mandelbrot Set has a finite area but infinite length of border. The Mandelbrot set is symmetric with respect to the real axis. This means if a complex number belongs to the set then its conjugate will also belong to that set. The Mandelbrot set is bounded. The Mandelbrot set is itself similar in a non exact sense. The border of the Mandelbrot set is a fractal structure with not yet known fractal dimension. Implementation : Since the concept of Fractals involves the mathematical properties of equations, the algorithm and the programs that create fractals are difficult to write and optimize. One can find many commercial software that create fractals. These programs represent some of the most optimized and probably the best fractal algorithms and implementations that have been created. Below given is the approach : For drawing Mandelbrot set, set the pixel that is a complex number. Colour the pixel if it belongs to the set. Iterate through every pixel and calculate the corresponding complex numbers whose result is saved in c_real for real part and c_imaginary for imaginary part. Calculate the Mandelbrot function which is defined as z = z*z + c where z is a complex number. Since complex multiplication is difficult, break the equation and calculate the sub parts i.e. the real and the imaginary part separately. As square of a complex number (a + ib)2 = a2 – b2 + 2abi, where a2 -b2 is the real part and 2abi is imaginary part. While calculating z, calculate them separately, i.e,Z_real = z_real*z_real – z_imaginary*z_imaginary + c_realZ_imaginary = 2*z_real*z_imaginary + c_imaginary Z_real = z_real*z_real – z_imaginary*z_imaginary + c_realZ_imaginary = 2*z_real*z_imaginary + c_imaginary Continue to calculate these values for each pixel until we reach the maximum iterations and the absolute value of z is not less than 2. Finally, we colour the pixel. // C++ implementation for mandelbrot set fractals#include <graphics.h>#include <stdio.h>#define MAXCOUNT 30 // Function to draw mandelbrot setvoid fractal(float left, float top, float xside, float yside){ float xscale, yscale, zx, zy, cx, tempx, cy; int x, y, i, j; int maxx, maxy, count; // getting maximum value of x-axis of screen maxx = getmaxx(); // getting maximum value of y-axis of screen maxy = getmaxy(); // setting up the xscale and yscale xscale = xside / maxx; yscale = yside / maxy; // calling rectangle function // where required image will be seen rectangle(0, 0, maxx, maxy); // scanning every point in that rectangular area. // Each point represents a Complex number (x + yi). // Iterate that complex number for (y = 1; y <= maxy - 1; y++) { for (x = 1; x <= maxx - 1; x++) { // c_real cx = x * xscale + left; // c_imaginary cy = y * yscale + top; // z_real zx = 0; // z_imaginary zy = 0; count = 0; // Calculate whether c(c_real + c_imaginary) belongs // to the Mandelbrot set or not and draw a pixel // at coordinates (x, y) accordingly // If you reach the Maximum number of iterations // and If the distance from the origin is // greater than 2 exit the loop while ((zx * zx + zy * zy < 4) && (count < MAXCOUNT)) { // Calculate Mandelbrot function // z = z*z + c where z is a complex number // tempx = z_real*_real - z_imaginary*z_imaginary + c_real tempx = zx * zx - zy * zy + cx; // 2*z_real*z_imaginary + c_imaginary zy = 2 * zx * zy + cy; // Updating z_real = tempx zx = tempx; // Increment count count = count + 1; } // To display the created fractal putpixel(x, y, count); } }} // Driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm, errorcode; float left, top, xside, yside; // setting the left, top, xside and yside // for the screen and image to be displayed left = -1.75; top = -0.25; xside = 0.25; yside = 0.45; char driver[] = ""; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, driver); // Function calling fractal(left, top, xside, yside); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system closegraph(); return 0;} Output : Applications of Fractals : The basic idea of Fractals is to find regularities in the existing irregularities. Below given are some applications of Fractals : Fractal image compression is used in computer science, based on the facts of fractal geometry. By using this technique image is much more compressed as compared to JPEG, GIF, etc. Also, there is no pixelization when the picture is enlarged. To ease the study of turbulent flows, fractal representation is used. Also, fractals are used to represent porous media which is used in petroleum science. Fractal shaped antenna have been recently used which help in reducing the size and the weight of antennas and providing high performance. computer-graphics Fractal C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Multidimensional Arrays in C / C++ rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ fork() in C Core Dump (Segmentation fault) in C/C++ Command line arguments in C/C++ Substring in C++ Function Pointer in C Different methods to reverse a string in C/C++ TCP Server-Client implementation in C
[ { "code": null, "e": 24057, "s": 24029, "text": "\n03 Oct, 2018" }, { "code": null, "e": 24325, "s": 24057, "text": "A Fractal is a never-ending pattern. Fractals are infinitely complex patterns that are self-similar across different scales. They are created by repeating a simple process over and over in an ongoing feedback loop. Mathematically fractals can be explained as follows." }, { "code": null, "e": 24463, "s": 24325, "text": "The location of a point on a screen is fed into an equation as its initial solution and the equation is iterated a large number of times." }, { "code": null, "e": 24604, "s": 24463, "text": "If that equation tends to zero (i.e. the value at the end of the iterations is smaller than the initial value), the point is coloured black." }, { "code": null, "e": 24836, "s": 24604, "text": "If the equation tends to infinity (i.e. the final value is larger than the initial value) then depending on the rate of increase (i.e. the rate at which the value tends to infinity), the pixel is painted with an appropriate colour." }, { "code": null, "e": 25069, "s": 24836, "text": "Mandelbrot Set :The Mandelbrot set is the set of complex numbers c for which the function fc(z) = z2 + c does not diverge when iterated from z = 0, i.e, for which the sequence fc(0), fc(fc(0)) etc, remains bounded in absolute value." }, { "code": null, "e": 25548, "s": 25069, "text": "The Mandelbrot set is the set of values of c in the complex plane for which the orbit of 0 under iteration of the quadratic map Zn+1 = Zn2 + c remains bounded. That is, a complex number c is part of the Mandelbrot set if, when starting with Z0 = 0 and applying the iteration repeatedly, the absolute value of Zn remains bounded however large n gets. Below given is the initial image of a Mandelbrot set zoom sequence. Black points correspond to numbers that are outside the set." }, { "code": null, "e": 25579, "s": 25548, "text": "Properties of Mandelbrot Set :" }, { "code": null, "e": 25755, "s": 25579, "text": "The Mandelbrot set is a connected set since it always have a path from one point of the set to another point of the set so that all the points in the path are also in the set." }, { "code": null, "e": 25823, "s": 25755, "text": "The Mandelbrot Set has a finite area but infinite length of border." }, { "code": null, "e": 25985, "s": 25823, "text": "The Mandelbrot set is symmetric with respect to the real axis. This means if a complex number belongs to the set then its conjugate will also belong to that set." }, { "code": null, "e": 26016, "s": 25985, "text": "The Mandelbrot set is bounded." }, { "code": null, "e": 26075, "s": 26016, "text": "The Mandelbrot set is itself similar in a non exact sense." }, { "code": null, "e": 26169, "s": 26075, "text": "The border of the Mandelbrot set is a fractal structure with not yet known fractal dimension." }, { "code": null, "e": 26583, "s": 26169, "text": "Implementation : Since the concept of Fractals involves the mathematical properties of equations, the algorithm and the programs that create fractals are difficult to write and optimize. One can find many commercial software that create fractals. These programs represent some of the most optimized and probably the best fractal algorithms and implementations that have been created. Below given is the approach :" }, { "code": null, "e": 26651, "s": 26583, "text": "For drawing Mandelbrot set, set the pixel that is a complex number." }, { "code": null, "e": 26694, "s": 26651, "text": "Colour the pixel if it belongs to the set." }, { "code": null, "e": 26852, "s": 26694, "text": "Iterate through every pixel and calculate the corresponding complex numbers whose result is saved in c_real for real part and c_imaginary for imaginary part." }, { "code": null, "e": 26947, "s": 26852, "text": "Calculate the Mandelbrot function which is defined as z = z*z + c where z is a complex number." }, { "code": null, "e": 27086, "s": 26947, "text": "Since complex multiplication is difficult, break the equation and calculate the sub parts i.e. the real and the imaginary part separately." }, { "code": null, "e": 27202, "s": 27086, "text": "As square of a complex number (a + ib)2 = a2 – b2 + 2abi, where a2 -b2 is the real part and 2abi is imaginary part." }, { "code": null, "e": 27360, "s": 27202, "text": "While calculating z, calculate them separately, i.e,Z_real = z_real*z_real – z_imaginary*z_imaginary + c_realZ_imaginary = 2*z_real*z_imaginary + c_imaginary" }, { "code": null, "e": 27466, "s": 27360, "text": "Z_real = z_real*z_real – z_imaginary*z_imaginary + c_realZ_imaginary = 2*z_real*z_imaginary + c_imaginary" }, { "code": null, "e": 27632, "s": 27466, "text": "Continue to calculate these values for each pixel until we reach the maximum iterations and the absolute value of z is not less than 2. Finally, we colour the pixel." }, { "code": "// C++ implementation for mandelbrot set fractals#include <graphics.h>#include <stdio.h>#define MAXCOUNT 30 // Function to draw mandelbrot setvoid fractal(float left, float top, float xside, float yside){ float xscale, yscale, zx, zy, cx, tempx, cy; int x, y, i, j; int maxx, maxy, count; // getting maximum value of x-axis of screen maxx = getmaxx(); // getting maximum value of y-axis of screen maxy = getmaxy(); // setting up the xscale and yscale xscale = xside / maxx; yscale = yside / maxy; // calling rectangle function // where required image will be seen rectangle(0, 0, maxx, maxy); // scanning every point in that rectangular area. // Each point represents a Complex number (x + yi). // Iterate that complex number for (y = 1; y <= maxy - 1; y++) { for (x = 1; x <= maxx - 1; x++) { // c_real cx = x * xscale + left; // c_imaginary cy = y * yscale + top; // z_real zx = 0; // z_imaginary zy = 0; count = 0; // Calculate whether c(c_real + c_imaginary) belongs // to the Mandelbrot set or not and draw a pixel // at coordinates (x, y) accordingly // If you reach the Maximum number of iterations // and If the distance from the origin is // greater than 2 exit the loop while ((zx * zx + zy * zy < 4) && (count < MAXCOUNT)) { // Calculate Mandelbrot function // z = z*z + c where z is a complex number // tempx = z_real*_real - z_imaginary*z_imaginary + c_real tempx = zx * zx - zy * zy + cx; // 2*z_real*z_imaginary + c_imaginary zy = 2 * zx * zy + cy; // Updating z_real = tempx zx = tempx; // Increment count count = count + 1; } // To display the created fractal putpixel(x, y, count); } }} // Driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // \"graphics.h\" header file int gd = DETECT, gm, errorcode; float left, top, xside, yside; // setting the left, top, xside and yside // for the screen and image to be displayed left = -1.75; top = -0.25; xside = 0.25; yside = 0.45; char driver[] = \"\"; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, driver); // Function calling fractal(left, top, xside, yside); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system closegraph(); return 0;}", "e": 30534, "s": 27632, "text": null }, { "code": null, "e": 30543, "s": 30534, "text": "Output :" }, { "code": null, "e": 30701, "s": 30543, "text": "Applications of Fractals : The basic idea of Fractals is to find regularities in the existing irregularities. Below given are some applications of Fractals :" }, { "code": null, "e": 30942, "s": 30701, "text": "Fractal image compression is used in computer science, based on the facts of fractal geometry. By using this technique image is much more compressed as compared to JPEG, GIF, etc. Also, there is no pixelization when the picture is enlarged." }, { "code": null, "e": 31098, "s": 30942, "text": "To ease the study of turbulent flows, fractal representation is used. Also, fractals are used to represent porous media which is used in petroleum science." }, { "code": null, "e": 31236, "s": 31098, "text": "Fractal shaped antenna have been recently used which help in reducing the size and the weight of antennas and providing high performance." }, { "code": null, "e": 31254, "s": 31236, "text": "computer-graphics" }, { "code": null, "e": 31262, "s": 31254, "text": "Fractal" }, { "code": null, "e": 31273, "s": 31262, "text": "C Language" }, { "code": null, "e": 31371, "s": 31273, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31380, "s": 31371, "text": "Comments" }, { "code": null, "e": 31393, "s": 31380, "text": "Old Comments" }, { "code": null, "e": 31428, "s": 31393, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 31456, "s": 31428, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 31502, "s": 31456, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 31514, "s": 31502, "text": "fork() in C" }, { "code": null, "e": 31554, "s": 31514, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 31586, "s": 31554, "text": "Command line arguments in C/C++" }, { "code": null, "e": 31603, "s": 31586, "text": "Substring in C++" }, { "code": null, "e": 31625, "s": 31603, "text": "Function Pointer in C" }, { "code": null, "e": 31672, "s": 31625, "text": "Different methods to reverse a string in C/C++" } ]
Naming Conventions in C#
A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of curly braces. The following are the conventions for class names. The coding conventions for a class name is the the name of the class names, for example, it should being PascalCasing. public class EmployeeDetails {} Above, the class name EmployeeDetails is in PascalCasing. Prefer adding class names as noun or noun phrases − public class Employee {} Identifier is a name used to identify a class, variable, function, or any other user-defined item.The following are the naming convetions for Identifiers − A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit. A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit. It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used. It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used. It should not be a C# keyword. It should not be a C# keyword.
[ { "code": null, "e": 1245, "s": 1062, "text": "A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of curly braces. The following are the conventions for class names." }, { "code": null, "e": 1364, "s": 1245, "text": "The coding conventions for a class name is the the name of the class names, for example, it should being PascalCasing." }, { "code": null, "e": 1396, "s": 1364, "text": "public class EmployeeDetails {}" }, { "code": null, "e": 1454, "s": 1396, "text": "Above, the class name EmployeeDetails is in PascalCasing." }, { "code": null, "e": 1506, "s": 1454, "text": "Prefer adding class names as noun or noun phrases −" }, { "code": null, "e": 1532, "s": 1506, "text": "public class Employee {}\n" }, { "code": null, "e": 1688, "s": 1532, "text": "Identifier is a name used to identify a class, variable, function, or any other user-defined item.The following are the naming convetions for Identifiers −" }, { "code": null, "e": 1855, "s": 1688, "text": "A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit." }, { "code": null, "e": 2022, "s": 1855, "text": "A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit." }, { "code": null, "e": 2171, "s": 2022, "text": "It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : \" ' / and \\. However, an underscore ( _ ) can be used." }, { "code": null, "e": 2320, "s": 2171, "text": "It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : \" ' / and \\. However, an underscore ( _ ) can be used." }, { "code": null, "e": 2351, "s": 2320, "text": "It should not be a C# keyword." }, { "code": null, "e": 2382, "s": 2351, "text": "It should not be a C# keyword." } ]
Check if Tree is Isomorphic | Practice | GeeksforGeeks
Given two Binary Trees. Check whether they are Isomorphic or not. Note: Two trees are called isomorphic if one can be obtained from another by a series of flips, i.e. by swapping left and right children of several nodes. Any number of nodes at any level can have their children swapped. Two empty trees are isomorphic. For example, the following two trees are isomorphic with the following sub-trees flipped: 2 and 3, NULL and 6, 7 and 8. Example 1: Input: T1 1 T2: 1 / \ / \ 2 3 3 2 / / 4 4 Output: No Example 2: Input: T1 1 T2: 1 / \ / \ 2 3 3 2 / \ 4 4 Output: Yes Your Task: You don't need to read input or print anything. Your task is to complete the function isomorphic() that takes the root nodes of both the Binary Trees as its input and returns True if the two trees are isomorphic. Else, it returns False. (The driver code will print Yes if the returned values are true, otherwise false.) Expected Time Complexity: O(min(M, N)) where M and N are the sizes of the two trees. Expected Auxiliary Space: O(min(H1, H2)) where H1 and H2 are the heights of the two trees. Constraints: 1<=Number of nodes<=105 0 ishajaiswal445563 days ago bool isIsomorphic(Node *root1,Node *root2) { if(root1==NULL && root2==NULL) { return true; } if(root1==NULL || root2==NULL) { return false; } bool check1=isIsomorphic(root1->left,root2->right) && isIsomorphic(root1->right , root2->left); bool check2=isIsomorphic(root1->left,root2->left) && isIsomorphic(root1->right , root2->right); bool check3 = (root1->data==root2->data); return (check1 || check2) && check3; //add code here. } +1 tanashah1 week ago if(root1==NULL && root2==NULL) return true; if(root1==NULL || root2==NULL) return false; if(root1->data!=root2->data) return false; //mirror tree ke liye int a=isIsomorphic(root1->left,root2->right) && isIsomorphic(root1->right,root2->left); //abhi same tree keliey int b=isIsomorphic(root1->left,root2->left) && isIsomorphic(root1->right,root2->right); return a||b; 0 amarrajsmart1972 weeks ago C++ Solution. bool isIsomorphic(Node *root1,Node *root2) { //add code here. bool a,b; if(!root1&&!root2) { return true; } else if(!root1||!root2) { return false; } else { if(root1->data!=root2->data) { return false; } a=isIsomorphic(root1->left,root2->left)&&isIsomorphic(root1->right,root2->right); b=isIsomorphic(root1->left,root2->right)&&isIsomorphic(root1->right,root2->left); return a||b; } } 0 1ashishchauhan20022 weeks ago if(root1==NULL && root2==NULL) return true; if(root1==NULL || root2==NULL) return false; if(root1->data!=root2->data) return false; int a=isIsomorphic(root1->left,root2->right) &&isIsomorphic(root1->right, root2->left); int b=isIsomorphic(root1->left, root2->left)&&isIsomorphic(root1->right,root2->right); return a||b; 0 harrypotter01 month ago Why TLE in Python? def isIsomorphic(self, root1, root2): if not root1 and not root2: return True if not root1 or not root2: return False if root1.data!= root2.data: return False return (self.isIsomorphic(root1.left, root2.left) \ and self.isIsomorphic(root1.right, root2.right)) \ or (self.isIsomorphic(root1.right, root2.left) \ and self.isIsomorphic(root1.left, root2.right)) +1 gdh14031 month ago //simple c++ solution //if you find it helpfull then upvote it. bool isIsomorphic(Node *root1,Node *root2) { if(!root1 || !root2) {//if both root null then it is valid case if(!root1 && !root2) return true; return false; } //both root value must be same for valid isomorphic if(root1->data != root2->data) return false; /*checking weather left and right part is isomorphic or not incase if not isomorphic then we will check by swapping its left and right child to check is isomorphic or not*/ bool f=(isIsomorphic(root1->left,root2->left)&&isIsomorphic(root1->right,root2->right)); if(!f) { return isIsomorphic(root1->left,root2->right); } return true; } +1 puranjanprithu1 month ago My python solution gives TLE ,while my C++ solution with same logic worked: WHY????? # My python answer: Why is it giving TLE def isIsomorphic(self, root1, root2): #code here. if root1 is None and root2 is None: return True if root1 is None or root2 is None : return False if root1.data!=root2.data: return False l=self.isIsomorphic(root1.left,root2.left) and self.isIsomorphic(root1.right,root2.right) r=self.isIsomorphic(root1.left,root2.right) and self.isIsomorphic(root1.right,root2.left) return l or r While my C++ solution with same logic worked: class Solution{ public: // Return True if the given trees are isomotphic. Else return False. bool isIsomorphic(Node *root1,Node *root2) { //add code here. if (!root1 and !root2) return true; if (!root1 or !root2) return false; if (root1->data!=root2->data) return false; bool l= isIsomorphic(root1->left,root2->left) and isIsomorphic(root1->right,root2->right); bool r= isIsomorphic(root1->left,root2->right) and isIsomorphic(root1->right,root2->left); return l or r; } }; +2 badgujarsachin831 month ago bool isIsomorphic(Node *root1,Node *root2) { //add code here. if(root1==NULL && root2==NULL){ return true; } if(root1==NULL || root2==NULL || root1->data!=root2->data){ return false; } return (isIsomorphic(root1->left,root2->left) && isIsomorphic(root1->right,root2->right)) || (isIsomorphic(root1->left,root2->right) && isIsomorphic(root1->right,root2->left)); } +1 sanketbhagat2 months ago SIMPLE JAVA SOLUTION class Solution { boolean isIsomorphic(Node root1, Node root2) { // code here. if(root1==null && root2==null) return true; if(root1==null || root2==null || root1.data!=root2.data) return false; return (isIsomorphic(root1.left,root2.left)&&isIsomorphic(root1.right,root2.right)) || (isIsomorphic(root1.left,root2.right)&&isIsomorphic(root1.right,root2.left)); } } 0 hamidnourashraf2 months ago def rec_isomorph(self, root1, root2): if root1 is None and root2 is None: return True elif root1 is None or root2 is None: return False elif root1.data != root2.data: return False else: return self.rec_isomorph(root1.left, root2.left) or self.rec_isomorph(root1.left, root2.right) def isIsomorphic(self, root1, root2): return self.rec_isomorph(root1, root2) We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 304, "s": 238, "text": "Given two Binary Trees. Check whether they are Isomorphic or not." }, { "code": null, "e": 679, "s": 304, "text": "Note: \nTwo trees are called isomorphic if one can be obtained from another by a series of flips, i.e. by swapping left and right children of several nodes. Any number of nodes at any level can have their children swapped. Two empty trees are isomorphic.\nFor example, the following two trees are isomorphic with the following sub-trees flipped: 2 and 3, NULL and 6, 7 and 8.\n" }, { "code": null, "e": 690, "s": 679, "text": "Example 1:" }, { "code": null, "e": 813, "s": 690, "text": "Input:\n T1 1 T2: 1\n / \\ / \\\n 2 3 3 2\n / /\n 4 4\nOutput: No\n\n" }, { "code": null, "e": 824, "s": 813, "text": "Example 2:" }, { "code": null, "e": 963, "s": 824, "text": "Input:\nT1 1 T2: 1\n / \\ / \\\n 2 3 3 2\n / \\\n 4 4\nOutput: Yes\n" }, { "code": null, "e": 1294, "s": 963, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function isomorphic() that takes the root nodes of both the Binary Trees as its input and returns True if the two trees are isomorphic. Else, it returns False. (The driver code will print Yes if the returned values are true, otherwise false.)" }, { "code": null, "e": 1472, "s": 1296, "text": "Expected Time Complexity: O(min(M, N)) where M and N are the sizes of the two trees.\nExpected Auxiliary Space: O(min(H1, H2)) where H1 and H2 are the heights of the two trees." }, { "code": null, "e": 1509, "s": 1472, "text": "Constraints:\n1<=Number of nodes<=105" }, { "code": null, "e": 1511, "s": 1509, "text": "0" }, { "code": null, "e": 1538, "s": 1511, "text": "ishajaiswal445563 days ago" }, { "code": null, "e": 2077, "s": 1540, "text": " bool isIsomorphic(Node *root1,Node *root2)\n {\n if(root1==NULL && root2==NULL)\n {\n return true;\n }\n if(root1==NULL || root2==NULL)\n {\n return false;\n }\n bool check1=isIsomorphic(root1->left,root2->right) && isIsomorphic(root1->right , root2->left);\n bool check2=isIsomorphic(root1->left,root2->left) && isIsomorphic(root1->right , root2->right);\n bool check3 = (root1->data==root2->data);\n return (check1 || check2) && check3;\n //add code here.\n }" }, { "code": null, "e": 2080, "s": 2077, "text": "+1" }, { "code": null, "e": 2099, "s": 2080, "text": "tanashah1 week ago" }, { "code": null, "e": 2523, "s": 2099, "text": " if(root1==NULL && root2==NULL) return true;\n if(root1==NULL || root2==NULL) return false;\n if(root1->data!=root2->data) return false;\n //mirror tree ke liye\n int a=isIsomorphic(root1->left,root2->right) && isIsomorphic(root1->right,root2->left);\n //abhi same tree keliey \n int b=isIsomorphic(root1->left,root2->left) && isIsomorphic(root1->right,root2->right);\n return a||b;" }, { "code": null, "e": 2525, "s": 2523, "text": "0" }, { "code": null, "e": 2552, "s": 2525, "text": "amarrajsmart1972 weeks ago" }, { "code": null, "e": 2566, "s": 2552, "text": "C++ Solution." }, { "code": null, "e": 3018, "s": 2566, "text": " bool isIsomorphic(Node *root1,Node *root2) { //add code here. bool a,b; if(!root1&&!root2) { return true; } else if(!root1||!root2) { return false; } else { if(root1->data!=root2->data) { return false; } a=isIsomorphic(root1->left,root2->left)&&isIsomorphic(root1->right,root2->right); b=isIsomorphic(root1->left,root2->right)&&isIsomorphic(root1->right,root2->left); return a||b; } }" }, { "code": null, "e": 3020, "s": 3018, "text": "0" }, { "code": null, "e": 3050, "s": 3020, "text": "1ashishchauhan20022 weeks ago" }, { "code": null, "e": 3401, "s": 3050, "text": " if(root1==NULL && root2==NULL) return true; if(root1==NULL || root2==NULL) return false; if(root1->data!=root2->data) return false; int a=isIsomorphic(root1->left,root2->right) &&isIsomorphic(root1->right, root2->left); int b=isIsomorphic(root1->left, root2->left)&&isIsomorphic(root1->right,root2->right); return a||b;" }, { "code": null, "e": 3405, "s": 3403, "text": "0" }, { "code": null, "e": 3429, "s": 3405, "text": "harrypotter01 month ago" }, { "code": null, "e": 3448, "s": 3429, "text": "Why TLE in Python?" }, { "code": null, "e": 3899, "s": 3450, "text": "\n def isIsomorphic(self, root1, root2): \n if not root1 and not root2:\n return True\n if not root1 or not root2:\n return False\n if root1.data!= root2.data:\n return False\n\n return (self.isIsomorphic(root1.left, root2.left) \\\n and self.isIsomorphic(root1.right, root2.right)) \\\n or (self.isIsomorphic(root1.right, root2.left) \\\n and self.isIsomorphic(root1.left, root2.right))\n" }, { "code": null, "e": 3902, "s": 3899, "text": "+1" }, { "code": null, "e": 3921, "s": 3902, "text": "gdh14031 month ago" }, { "code": null, "e": 4728, "s": 3921, "text": "//simple c++ solution\n//if you find it helpfull then upvote it.\nbool isIsomorphic(Node *root1,Node *root2)\n {\n if(!root1 || !root2)\n {//if both root null then it is valid case\n if(!root1 && !root2) return true;\n return false;\n }\n //both root value must be same for valid isomorphic\n if(root1->data != root2->data) return false;\n \t\t/*checking weather left and right part is isomorphic or not incase if not isomorphic then we will check by swapping its left and right child to check is isomorphic or not*/ \n bool f=(isIsomorphic(root1->left,root2->left)&&isIsomorphic(root1->right,root2->right)); \n if(!f)\n {\n return isIsomorphic(root1->left,root2->right);\n }\n return true;\n \n }\n " }, { "code": null, "e": 4731, "s": 4728, "text": "+1" }, { "code": null, "e": 4757, "s": 4731, "text": "puranjanprithu1 month ago" }, { "code": null, "e": 4842, "s": 4757, "text": "My python solution gives TLE ,while my C++ solution with same logic worked: WHY?????" }, { "code": null, "e": 4885, "s": 4844, "text": "# My python answer: Why is it giving TLE" }, { "code": null, "e": 5323, "s": 4885, "text": "def isIsomorphic(self, root1, root2): \n #code here.\n if root1 is None and root2 is None: return True\n if root1 is None or root2 is None : return False\n if root1.data!=root2.data: return False\n l=self.isIsomorphic(root1.left,root2.left) and self.isIsomorphic(root1.right,root2.right)\n r=self.isIsomorphic(root1.left,root2.right) and self.isIsomorphic(root1.right,root2.left)\n return l or r" }, { "code": null, "e": 5369, "s": 5323, "text": "While my C++ solution with same logic worked:" }, { "code": null, "e": 5893, "s": 5369, "text": "class Solution{\n public:\n // Return True if the given trees are isomotphic. Else return False.\n bool isIsomorphic(Node *root1,Node *root2)\n {\n //add code here.\n if (!root1 and !root2) return true;\n if (!root1 or !root2) return false;\n if (root1->data!=root2->data) return false;\n bool l= isIsomorphic(root1->left,root2->left) and isIsomorphic(root1->right,root2->right);\n bool r= isIsomorphic(root1->left,root2->right) and isIsomorphic(root1->right,root2->left);\n \n return l or r;\n }\n};" }, { "code": null, "e": 5896, "s": 5893, "text": "+2" }, { "code": null, "e": 5924, "s": 5896, "text": "badgujarsachin831 month ago" }, { "code": null, "e": 6337, "s": 5924, "text": " bool isIsomorphic(Node *root1,Node *root2)\n {\n //add code here.\n if(root1==NULL && root2==NULL){\n return true;\n }\n if(root1==NULL || root2==NULL || root1->data!=root2->data){\n return false;\n }\n return (isIsomorphic(root1->left,root2->left) && isIsomorphic(root1->right,root2->right)) || (isIsomorphic(root1->left,root2->right) && isIsomorphic(root1->right,root2->left));\n }" }, { "code": null, "e": 6340, "s": 6337, "text": "+1" }, { "code": null, "e": 6365, "s": 6340, "text": "sanketbhagat2 months ago" }, { "code": null, "e": 6386, "s": 6365, "text": "SIMPLE JAVA SOLUTION" }, { "code": null, "e": 6797, "s": 6386, "text": "class Solution { \n boolean isIsomorphic(Node root1, Node root2) { \n // code here.\n if(root1==null && root2==null) return true;\n if(root1==null || root2==null || root1.data!=root2.data) return false;\n return (isIsomorphic(root1.left,root2.left)&&isIsomorphic(root1.right,root2.right)) || (isIsomorphic(root1.left,root2.right)&&isIsomorphic(root1.right,root2.left));\n }\n} " }, { "code": null, "e": 6799, "s": 6797, "text": "0" }, { "code": null, "e": 6827, "s": 6799, "text": "hamidnourashraf2 months ago" }, { "code": null, "e": 7284, "s": 6827, "text": " def rec_isomorph(self, root1, root2):\n if root1 is None and root2 is None:\n return True\n elif root1 is None or root2 is None:\n return False\n elif root1.data != root2.data:\n return False\n else: \n return self.rec_isomorph(root1.left, root2.left) or self.rec_isomorph(root1.left, root2.right)\n def isIsomorphic(self, root1, root2): \n return self.rec_isomorph(root1, root2)\n" }, { "code": null, "e": 7430, "s": 7284, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 7466, "s": 7430, "text": " Login to access your submissions. " }, { "code": null, "e": 7476, "s": 7466, "text": "\nProblem\n" }, { "code": null, "e": 7486, "s": 7476, "text": "\nContest\n" }, { "code": null, "e": 7549, "s": 7486, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7697, "s": 7549, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7905, "s": 7697, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 8011, "s": 7905, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
The 80/20 Split Intuition and an Alternative Split Method | by The Data Detective | Towards Data Science
I am an inquisitive person. It’s my nature. It’s why I deconstructed many of my Christmas presents as a child, I wanted to know “why”. So when I ask the question, “Why are we using an 80/20 training/test split on this dataset?” and don’t get a specific answer, it drives me crazy. I dove into the ‘why’ of train/test splits. There is probably way more out there than what I can find, but I am going to cover a couple of train/test splitting practices that are out there in the “interverse” and see how they measure up or if it even matters. Pareto Principle The Pareto Principle is also called the 80/20 rule. The general point is that, in most cases, 80% of effects come from 20% of causes. For those that want to travel down this rabbit hole, feel free to check out the Wikipedia. While the preface of the principle was based on wealth distribution, it statistically does come close to explaining many human, machine, and environmental phenomena. For this reason, and typically without knowledge of the source, many use the 80/20 split for training and testing. Scaling Law In 1997, a new method was discussed in a paper called A scaling law for the validation-set training-set size ratio (Guyon). Here, they reference “ the best training/validation split for a specific problem: preventing overtraining of neural networks. They find that the fraction of patterns reserved for the validation set should be inversely proportional to the square root of the number of free adjustable parameters. Our result generalizes and confirms their result.” (Guyon, 1997). In essence, the split is determined by how many unique features are in the dataset (not including the target) and not the number of observations, which is contrary to most opinions on the subject. Let’s find out if the scaling law outperforms an assumed Pareto split using our trusty Titanic data. This dataset has already been imputed to fill nulls from a previous post Preprocessing: Encode and KNN Impute All Categorical Features Fast. First, we’ll load the data, make sure all of the columns are visible and run a .head() method to verify the data. import pandas as pdimport numpy as npfrom sklearn.model_selection import train_test_splitsplit_data = pd.read_csv('titanic_encoded_scaled-Copy1.csv')pd.options.display.max_columns = Nonesplit_data.head() Next, we will get rid of the unnamed column and split the data into X and y variables. Since we are testing model improvement, it was best to use a multi-class target, so the deck1 column was used (7 classes). split_data = split_data.drop('Unnamed: 0', axis=1)X = split_data.iloc[:,:-2]y = split_data.iloc[:,-2] From another previous post, we found that this data scaled best with the PowerTransform scaler set to the ‘yeo-johnson’ method. If you want to take a peek at that, just take a look: Preprocessing: Differences in Standardization Methods from sklearn.preprocessing import PowerTransformeryj = PowerTransformer(method = 'yeo-johnson')yj_data = yj.fit_transform(X) Now, we will split our data into train and test using the sklearn library. First, the Pareto Principle (80/20): #Pareto Principle SplitX_train, X_test, y_train, y_test = train_test_split(yj_data, y, test_size= 0.2, random_state= 123) Next, we will run the function to apply the scaling law and split that data into different variables: #discover scaling law splitcolumns = 14test = 1/np.sqrt(columns)train = 1 - testprint(test)print(train)#Scaling Law SplitA_train, A_test, b_train, b_test = train_test_split(yj_data, y, test_size= test, random_state= 123)0.2672612419124244 #test0.7327387580875756 #train Almost 7% difference between the Pareto and Scaling Law splits. Now to run a standard logistic regression model for both datasets: #perform logistic regression using pareto splitfrom sklearn.linear_model import LogisticRegressionbn1 = LogisticRegression(max_iter=1000)bn1.fit(X_train, y_train)pp_preds = bn1.predict(X_test)# use logistic regression using scaling law splitbn2 = LogisticRegression(max_iter=1000)bn2.fit(A_train, b_train)sl_preds = bn2.predict(A_test) Here is the classification report for the Pareto Principle: #classification report from pareto splitfrom sklearn.metrics import classification_reportprint(classification_report(y_test, pp_preds)) precision recall f1-score support 0.0 0.00 0.00 0.00 5 1.0 0.38 0.33 0.36 15 2.0 0.37 0.59 0.45 17 3.0 0.38 0.16 0.22 19 4.0 0.52 0.34 0.41 38 5.0 0.67 0.87 0.76 69 6.0 0.82 0.88 0.85 16 accuracy 0.59 179 macro avg 0.45 0.45 0.44 179weighted avg 0.55 0.59 0.55 179 A decent 59% accuracy. Now, the Scaling Law report: #classification report from scaling lawprint(classification_report(b_test, sl_preds)) precision recall f1-score support 0.0 0.50 0.20 0.29 5 1.0 0.31 0.26 0.29 19 2.0 0.35 0.52 0.42 21 3.0 0.30 0.12 0.17 26 4.0 0.61 0.47 0.53 53 5.0 0.71 0.88 0.78 97 6.0 0.84 0.89 0.86 18 accuracy 0.61 239 macro avg 0.52 0.48 0.48 239weighted avg 0.59 0.61 0.59 239 An increase of 2% accuracy and improvement in precision, recall and f1-score! Wrapping it up In the grand scheme of things, 2% is a pretty significant increase, in my opinion. Of course, this is a simple multi-class Logistic Regression model, but as I try to encourage, test both split methods on whatever dataset you have. It really is a simple algorithm that can make that extra difference. As always, you can find my work on Github. This particular repo is here. Have a great one!
[ { "code": null, "e": 713, "s": 172, "text": "I am an inquisitive person. It’s my nature. It’s why I deconstructed many of my Christmas presents as a child, I wanted to know “why”. So when I ask the question, “Why are we using an 80/20 training/test split on this dataset?” and don’t get a specific answer, it drives me crazy. I dove into the ‘why’ of train/test splits. There is probably way more out there than what I can find, but I am going to cover a couple of train/test splitting practices that are out there in the “interverse” and see how they measure up or if it even matters." }, { "code": null, "e": 730, "s": 713, "text": "Pareto Principle" }, { "code": null, "e": 1236, "s": 730, "text": "The Pareto Principle is also called the 80/20 rule. The general point is that, in most cases, 80% of effects come from 20% of causes. For those that want to travel down this rabbit hole, feel free to check out the Wikipedia. While the preface of the principle was based on wealth distribution, it statistically does come close to explaining many human, machine, and environmental phenomena. For this reason, and typically without knowledge of the source, many use the 80/20 split for training and testing." }, { "code": null, "e": 1248, "s": 1236, "text": "Scaling Law" }, { "code": null, "e": 1930, "s": 1248, "text": "In 1997, a new method was discussed in a paper called A scaling law for the validation-set training-set size ratio (Guyon). Here, they reference “ the best training/validation split for a specific problem: preventing overtraining of neural networks. They find that the fraction of patterns reserved for the validation set should be inversely proportional to the square root of the number of free adjustable parameters. Our result generalizes and confirms their result.” (Guyon, 1997). In essence, the split is determined by how many unique features are in the dataset (not including the target) and not the number of observations, which is contrary to most opinions on the subject." }, { "code": null, "e": 2172, "s": 1930, "text": "Let’s find out if the scaling law outperforms an assumed Pareto split using our trusty Titanic data. This dataset has already been imputed to fill nulls from a previous post Preprocessing: Encode and KNN Impute All Categorical Features Fast." }, { "code": null, "e": 2286, "s": 2172, "text": "First, we’ll load the data, make sure all of the columns are visible and run a .head() method to verify the data." }, { "code": null, "e": 2490, "s": 2286, "text": "import pandas as pdimport numpy as npfrom sklearn.model_selection import train_test_splitsplit_data = pd.read_csv('titanic_encoded_scaled-Copy1.csv')pd.options.display.max_columns = Nonesplit_data.head()" }, { "code": null, "e": 2700, "s": 2490, "text": "Next, we will get rid of the unnamed column and split the data into X and y variables. Since we are testing model improvement, it was best to use a multi-class target, so the deck1 column was used (7 classes)." }, { "code": null, "e": 2802, "s": 2700, "text": "split_data = split_data.drop('Unnamed: 0', axis=1)X = split_data.iloc[:,:-2]y = split_data.iloc[:,-2]" }, { "code": null, "e": 3038, "s": 2802, "text": "From another previous post, we found that this data scaled best with the PowerTransform scaler set to the ‘yeo-johnson’ method. If you want to take a peek at that, just take a look: Preprocessing: Differences in Standardization Methods" }, { "code": null, "e": 3163, "s": 3038, "text": "from sklearn.preprocessing import PowerTransformeryj = PowerTransformer(method = 'yeo-johnson')yj_data = yj.fit_transform(X)" }, { "code": null, "e": 3275, "s": 3163, "text": "Now, we will split our data into train and test using the sklearn library. First, the Pareto Principle (80/20):" }, { "code": null, "e": 3397, "s": 3275, "text": "#Pareto Principle SplitX_train, X_test, y_train, y_test = train_test_split(yj_data, y, test_size= 0.2, random_state= 123)" }, { "code": null, "e": 3499, "s": 3397, "text": "Next, we will run the function to apply the scaling law and split that data into different variables:" }, { "code": null, "e": 3769, "s": 3499, "text": "#discover scaling law splitcolumns = 14test = 1/np.sqrt(columns)train = 1 - testprint(test)print(train)#Scaling Law SplitA_train, A_test, b_train, b_test = train_test_split(yj_data, y, test_size= test, random_state= 123)0.2672612419124244 #test0.7327387580875756 #train" }, { "code": null, "e": 3900, "s": 3769, "text": "Almost 7% difference between the Pareto and Scaling Law splits. Now to run a standard logistic regression model for both datasets:" }, { "code": null, "e": 4236, "s": 3900, "text": "#perform logistic regression using pareto splitfrom sklearn.linear_model import LogisticRegressionbn1 = LogisticRegression(max_iter=1000)bn1.fit(X_train, y_train)pp_preds = bn1.predict(X_test)# use logistic regression using scaling law splitbn2 = LogisticRegression(max_iter=1000)bn2.fit(A_train, b_train)sl_preds = bn2.predict(A_test)" }, { "code": null, "e": 4296, "s": 4236, "text": "Here is the classification report for the Pareto Principle:" }, { "code": null, "e": 5018, "s": 4296, "text": "#classification report from pareto splitfrom sklearn.metrics import classification_reportprint(classification_report(y_test, pp_preds)) precision recall f1-score support 0.0 0.00 0.00 0.00 5 1.0 0.38 0.33 0.36 15 2.0 0.37 0.59 0.45 17 3.0 0.38 0.16 0.22 19 4.0 0.52 0.34 0.41 38 5.0 0.67 0.87 0.76 69 6.0 0.82 0.88 0.85 16 accuracy 0.59 179 macro avg 0.45 0.45 0.44 179weighted avg 0.55 0.59 0.55 179" }, { "code": null, "e": 5070, "s": 5018, "text": "A decent 59% accuracy. Now, the Scaling Law report:" }, { "code": null, "e": 5741, "s": 5070, "text": "#classification report from scaling lawprint(classification_report(b_test, sl_preds)) precision recall f1-score support 0.0 0.50 0.20 0.29 5 1.0 0.31 0.26 0.29 19 2.0 0.35 0.52 0.42 21 3.0 0.30 0.12 0.17 26 4.0 0.61 0.47 0.53 53 5.0 0.71 0.88 0.78 97 6.0 0.84 0.89 0.86 18 accuracy 0.61 239 macro avg 0.52 0.48 0.48 239weighted avg 0.59 0.61 0.59 239" }, { "code": null, "e": 5819, "s": 5741, "text": "An increase of 2% accuracy and improvement in precision, recall and f1-score!" }, { "code": null, "e": 5834, "s": 5819, "text": "Wrapping it up" }, { "code": null, "e": 6134, "s": 5834, "text": "In the grand scheme of things, 2% is a pretty significant increase, in my opinion. Of course, this is a simple multi-class Logistic Regression model, but as I try to encourage, test both split methods on whatever dataset you have. It really is a simple algorithm that can make that extra difference." } ]
C# Program to get the absolute value of the time
To get the absolute value of time, use the TimesSpan Duration() method. Let’s say the following is our TimeSpan. TimeSpan ts = new TimeSpan(-7, -50, -25); Now to get the absolute value. TimeSpan duration = ts.Duration(); Let us see the complete code. Live Demo using System; using System.Linq; public class Demo { public static void Main() { TimeSpan ts = new TimeSpan(-7, -50, -25); TimeSpan duration = ts.Duration(); Console.WriteLine(duration); } } 07:50:25
[ { "code": null, "e": 1134, "s": 1062, "text": "To get the absolute value of time, use the TimesSpan Duration() method." }, { "code": null, "e": 1175, "s": 1134, "text": "Let’s say the following is our TimeSpan." }, { "code": null, "e": 1217, "s": 1175, "text": "TimeSpan ts = new TimeSpan(-7, -50, -25);" }, { "code": null, "e": 1248, "s": 1217, "text": "Now to get the absolute value." }, { "code": null, "e": 1283, "s": 1248, "text": "TimeSpan duration = ts.Duration();" }, { "code": null, "e": 1313, "s": 1283, "text": "Let us see the complete code." }, { "code": null, "e": 1324, "s": 1313, "text": " Live Demo" }, { "code": null, "e": 1539, "s": 1324, "text": "using System;\nusing System.Linq;\npublic class Demo {\n public static void Main() {\n TimeSpan ts = new TimeSpan(-7, -50, -25);\n TimeSpan duration = ts.Duration();\n Console.WriteLine(duration);\n }\n}" }, { "code": null, "e": 1548, "s": 1539, "text": "07:50:25" } ]
Econometric Approach to Time Series Analysis — Seasonal ARIMA in Python | by Jahangir Mammadov | Towards Data Science
At this post, we will talk about the analysis of time series data with Trend and Seasonal components. An econometric approach will be followed to model the statistical properties of the data. The business objective here is forecasting. We attempted to explain various concepts involved in time series modelling, such as time series components, serial correlation, model fitting, metrics, etc. We will use SARIMAX model provided by statsmodels library to model both, seasonality and trend in the data. SARIMA (Seasonal ARIMA) is capable of modelling seasonality and trend together, unlike ARIMA which can only model trend. Contents: Definition of time series dataIntroduction to the project and dataSeasonal decomposition and Time series components: Trend, Seasonality, Cycles, ResidualsStationarity in time series data and why it is importantAutocorrelation and partial autocorrelationData transformation: Log transformation and differencingModel Selection and FittingConclusion Definition of time series data Introduction to the project and data Seasonal decomposition and Time series components: Trend, Seasonality, Cycles, Residuals Stationarity in time series data and why it is important Autocorrelation and partial autocorrelation Data transformation: Log transformation and differencing Model Selection and Fitting Conclusion Access full Python code from the GitHub repository: https://github.com/jahangirmammadov/sarima/blob/master/Seasonal%20Time%20Series%20Analysis.ipynb Time series data is a sequence of data points measured over time intervals. In other words, data is a function of time f(t) = y.Data points can be measured hourly, daily, weekly, monthly, quarterly, yearly and also with smaller or larger time scales such as seconds or decades. The data we are using in this article is a monthly home sales index for 20 major US cities between the years 2000 and 2019. (https://fred.stlouisfed.org/series/SPCS20RPSNSA). You can freely download many different economic time series data representing the US economy from this source. You may see 2 different versions of the same data, seasonally-adjusted and non-seasonally-adjusted. The version used at this post is not seasonally adjusted as we want to model the seasonality as well as trend. You may ask why people want to use seasonally adjusted data in the industry. Well, sometimes businesses may want to know the true effect of economic events on a particular data, which may overlap with a season. In that case, seasonality may hide or underestimate/overestimate the effect of an economic event. For instance: Heating oil producers may want to study the impact of the declining petrol prices on heating oil prices. However, heating oil prices are increasing in winter, despite the fact that heating oil is a petrol substance. The decrease in petrol prices should be reflected in the decrease in heating oil prices. However, in winter there is a big demand for heating, which causes a slight increase in prices. By removing the seasonal effect from the time series data, you may see that heating oil price actually follows a decreasing trend. The slight increase in the price was the seasonal effect. In Section 3, we will talk about seasonal decomposition in more detail. If we look at the time series plot of the data we can observe an increasing trend in 2000–2006, a decreasing trend in home sales starting from 2007 till 2012 due to big financial crisis and increasing trend again till 2018. We can also observe seasonality in the data as usually the housing market is not active at the beginning of a year and sales usually go high in mid-year and again sales getting lower by the end of the year. Seems like warmer seasons, especially summer is the good season for the American housing market. Time series data Y is composed of a combination of Trend, Cycles, Seasonality and Residuals. Obviously, you may come across with time series where it doesn’t have a Trend, Cycles or Seasonality. So, it is your task to identify the components of time series data. Definition of the terms are given below: Trend — long-term upward or downward movement. Cycle — periodic variation due to economic movements. It is different from seasonal variation. The cycle is the variation of autoregressive component of time series data. Cycles occur within longer time intervals such as every 6–10 years, whereas seasonal variation occurs in shorter time intervals. Seasonality — variation in data caused by seasonal effects. Ice cream sales are high in summer, heating oil sales are high in winter but low in summer.Residuals — a component that is left after other components have been calculated and removed from time series data. It is randomly, identiclly and independently distributed (i.i.d). Residuals, R~ N(0,1). Statsmodels library has a function called seasonal_decompose, which decomposes time series Y into Trend, Seasonality and Residuals. Although, it is a naive decomposition algorithm, in practice it is very intuitive and works well for time series data where T, S and R are obvious. Before explaining the below graphs I would like to talk about the interaction among these components. Time series data Y can take either an additive or a multiplicative form. In additive form, time series Y is formed by the sum of time series components, namely, T, S, C, R: Y = T + C + S + R In multiplicative form time series Y is formed by the product of time series components:Y = T * C * S * R So, is home sales index is multiplicative or additive? If you carefully look at the time series plot of Housing index you may notice that the seasonal variation (seasonality) gets smaller when the trend decreases (years 2008–2013) and gets bigger when the trend increases (years 2014–2019). This happens in multiplicative time series, where small value for trend T results in small S because we multiply S by T. You don’t experience this phenomenon in additive time series. We decompose time series data into Trend, Seasonal component and Residuals using seasonal_decompose(original_data, ‘multiplicative’) function from statsmodels. Don’t be surprised if the function returns all 3 components even though you assume that they do not exist for a particular time series data. In reality, these components are generated by a simple algorithm, that’s why the decomposition function cannot say a component doesn’t exist, despite the calculated value is not significant. So, you will see these three components for any time series data. You have to know how to read the results and decide which model (ARIMA or SARIMA) to fit the data. We will try to decompose the data into components ourselves to better understand their derivation and usage. The trend can be calculated taking moving average with window size= 12. The below plot is very similar to the Trend generated by stats model library. Remember the multiplicative model, Y = T *C* S* R ? Dividing Y by T may give you Y/T=C*S*R and we assume that Residuals are too small for this data as the time series plot looks smooth. We have a very small data, thus we cannot detect an economic cycle. We get a seasonal component when we divide time series by trend, S=Y/T. Graph of seasonality is a little bit harder to understand, however, the explanation given here is sufficient. y=1.2(red marker) means there were 20% more sales in July-2000. In other words, June has a seasonal effect of +20% or 1.2 *T. On the other hand, y=0.8(green marker) in Feb-2003 shows a 20% decrease in sales. So, for some time series data not at this particular case, you may see the seasonal effect is very small i.e y=0.0001. It shows a very small seasonal effect, which shouldn’t even be considered significant. Residuals can be computed as R = Y/(S*T) There are some other ways to detect seasonality. In the below graph, monthly home sales for each year is plotted and as you can see every year follows pretty much the same pattern with a slight difference. House sales are high in summer, lower in winter months. When we have trend and/or seasonality in a time series data we call it non-staionary. Stationarity means the statistical properties of data, such as mean, variance and standard deviation remain constant over time. Why do we want the statistical properties to remain the same over time? Well, because we make statistical assumptions (a good example could be OLS assumptions) about the sample data in due course of model building and the model will only be capable of performing under those assumptions. When the statistical properties of the data changes, the model is no longer capable of representing the true nature of the data. That’s why our forecasting/prediction results will no longer be valid. Changing mean/variance will require us to fit another model and this model may be valid for a short period of time and we have to abandon it again and fit a new model. See, how inefficient and unreliable this process looks like. We have to make time series data stationary before fitting a model. We can make time series stationary by transforming the data. Usually, differencing is used to make the data stationary. We will talk about it in Section 6, below. So, how can we test whether a time series data is stationary or not? The first is just eyeballing the time series plot and identify trend or seasonality. If at least one of them exists, then the time series data is not stationary. Secondly, you may divide the data into 3 different sets and calculate mean and variance for each set and confirm whether mean and variance for each set is substantially different or not. The third option is to use one of the statistical tests provided in statsmodels library. Augmented Dickey-Fuller test is the most popular amongst others, where the null hypothesis, H_0 = data is not stationary. ADF test result provides test statistic and P value. P value >= 0.05 means the data is not stationary, otherwise, we reject the null hypothesis and say data is stationary. We assume you know what hypothesis testing is and what P value means. If you are not quite familiar with these terms, then look at the p-value and if it is smaller than 0.05 (p-value < 0.05) then data is stationary if p-value >= 0.05 data is not stationary. ADF test confirms that the original time series data is not stationary with p-value ~ 0.08 Time series data is not stationary. Adfuller test pvalue=0.0803366374517756 We have to take a look at ACF and PACF plots, before model building as we will use these plots a lot from now on. Autocorrelation plot shows the correlation of time series data with its own lagged values. For example, autocorrelation at lag=1 shows the correlation between y_t and y_t-1. At lag=2, corr(y_t, y_t-2). At lag=12 corr(y_t, y_t-12). Every data point at time t having a high correlation with a data point at time t-12, t-24, etc denotes seasonality at this particular example. The below code snippet and scatter plots may help you to better understand the correlation between lagged values, namely, autocorrelation. Back to ACF plot, blue shaded area at the autocorrelation plot shows significance level. So, correlation coefficients within the shaded area show weak correlation at those lags and we don’t consider them significant in the analysis.The partial autocorrelation function (PACF) gives the partial correlation of a stationary time series with its own lagged values. PACF removes the correlation contribution of other lags and gives the pure correlation between two lags without the effect of others. We use ACF and PACF to choose a correct order for AR(p) and MA(q) components/features of an ARIMA model. For AR order p, look at PACF plot and choose a lag value which has a significant correlation factor before correlations get insignificant. For MA order q look at ACF plot and do the same. Don’t forget you should only get these values from the ACF and PACF plots of stationary time series, not the above plots. The ACF and PACF plot given above are the plots of original data, which is non-stationary. So, let’s transform the data to make it stationary, so we can start the model building phase. We split the original data into training and test data. Training data will contain US home sales data from 2000 to 2018 and test data will contain data from 2018 to 2019. Don’t forget, you cannot do random sampling like you are doing for cross-sectional data. We have to keep the temporal behaviour (dependence on time) of time series data. Home sales index data can be formulated as a multiplicative model where Y= T*S*R. I am ignoring Cycles, as it is not actually present in this data. (S)ARIMA models are linear models, like Linear Regression. We can not fit a linear model SARIMA to data generated by a process Y = T*S*R. We have to make Y linear before fitting a linear model. As you are aware of from math Log(a*b) = log(a) + log(b). We have to log-transform the data to make it linear. log(Y) = log(T) + log(S) + log(R). Log transformation makes data linear and smoother. log_transformed_data = np.log(training_data)plot_data_properties(log_transformed_data, ‘Log tranformed training data’) Sometimes, log transformation on itself can make data stationary, but it is not the case here. test_stationarity(log_transformed_data)Time series data is not stationary. Adfuller test pvalue=0.22522944188413385 Differencing is a basic operation or data transformation. It is the difference between y at time=t and y at time=t-x. diff_1 = y_t — y_t-1 Differencing makes the data stationary as it removes time series components from the data and you are left with changes between time periods. Notice, first order differencing took away only Trend, not Seasonality. Data is still not stationary as it contains seasonal effects. logged_diffed_data = log_transformed_data.diff()[1:]plot_data_properties(logged_diffed_data, 'Log transformed and differenced data') test_stationarity(logged_diffed_data)Time series data is not stationary. Adfuller test pvalue=0.20261733702504936 We have to take 12th order difference to remove seasonality. You may ask how we decided to take 12th order difference not 6th or 8th or other order. Usually, monthly data has seasonality at lag=12, weekly data has at lag=4 and daily has at lag=30. Or you can derive it from the ACF plot. The12th, 24th, 36th lags are highly correlated for this particular data. Data is stationary now. If you look at the histogram at the below graph, it looks like Normal bell curve. Stationary data is randomly i.i.d distributed and the plot looks like white noise. White noise is just an example of stationary time series data. seasonally_diffed_data = logged_diffed_data.diff(12)[12:]plot_data_properties(seasonally_diffed_data, 'Log transofrmed, diff=1 and seasonally differenced data') test_stationarity(seasonally_diffed_data)Time series data is stationary. Adfuller test pvalue=0.0006264163287311492 As transformed data is stationary now we can proceed to model fitting phase. We had a brief chat about SARIMA before. I want to elaborate on this particular model. SARIMA, Seasonal ARIMA is a special member of ARIMA family which can model seasonal component of time series data. Just to recap what ARIMA means: AR — Auto-Regressive model means time series data is regressed on its lagged values. Lagged values become independent variables, whereas time series itself becomes the dependent variable. y = a_0 + a_1*y_t-1 + a_2*y_t-2, ....., a_k*y_t-k. The main task here is to choose how many time steps to be used as independent variables. Do not let the word time series or lagged values to confuse you, they are just independent variables. In linear Regression, you could look at the correlation between independent and dependent variables and choose highly correlated variables as your features. Here you should do the same. But, you don’t have to calculate the correlation between lagged values and target variable, because you can use PACF to determine how many lags to use. PACF of stationary data has significant autocorrelation at lag=1 and the next autocorrelation at Lag=2 becomes insignificant. Ideally, AR order p should be 1. Since AR(p) and MA(q) terms interact, the initial p and q values observed from autocorrelation plots are no longer reliable and should be used as a starting point. We have to do parameter search on p to find the optimal value. An initial guess will help to define which values to use for a grid search. In this case, p = [0–2] would be sufficient. I — order of integration: Basically, how many times you have differenced the data. We had it once d=1. Do not forget to fit the model to not differenced data when you set parameter d=1, as the algorithm will differentiate it. If you fit model to stationary data, thenyou don't need differencing anymore. You can leave d=0. We need differencing just to make the data stationary. MA — Moving Average model: Time series y is regressed on residuals w. y = a_0 + a_1*w1 + a_2*w2 + .... + a_k*wk Look at ACF plot to determine MA order (q) of the ARIMA model. ACF suggests order q=1 for MA part of the ARIMA model. However, we should do a grid search to find an optimal model. I suggest looking at values q=[0–2] Seasonal model — Seasonal features have to be added to the model together with AR and MA and it has 4 parameters (P, D, Q, s). Think of P, D and Q parameters being similar to AR, I and MA parameters, but only for a seasonal component of the series. Choose P by looking at PACF and Q by looking at ACF. The number of seasonal differences has been taken is D. Frequency of seasonal effect is defined by s. P = 1 — because we have significant correlation at lag=12, however, they are not strong enough and we may not need to have an AR variable in the model. That’s why we should grid search on P = [0–2] D=1 — we differenced for seasonality once Q=1 — as we have strong correlation at lag=12 according to ACF plot. Let’s perform grid search on parameter Q=[0–2], too. s=12 — seasonality frequency, every 12 months best_sarima_model function below performs grid search on (p,d,q) and (P,D,Q,s) parameters and finds the best model taking statistical metrics AIC, BIC, HQIC as evaluation criteria. Lower AIC, BIC, HQIC means better model. These metrics reward goodness-of-fit (log-likelihood) and penalises overfitting. In our case having many lagged features leads to overfitting. AIC, BIC and HQIC balance the tradeoff between likelihood and degrees of freedom. You can see this property in their formula. I will not get into the details of other metrics, but will give an example below for supporting my point of using AIC: -k is number of estimated parameters in the model, in other words, number of features (lag terms). -L is the maximum of the likelihood function.AIC = 2k — 2ln(L) I have seen many examples in the industry, using only one of those metrics as a model selection criteria, but you may come across the cases where AIC of a model can be lower than another, while BIC is higher. That’s why try to choose a model over the other if 2 of the 3 metrics are lower. Note, we are fitting a model to log-transformed data and because of that. we have set d=1 and D=1 parameters so that the model to do differencing itself. If you are fitting a model to stationary data instead, you have to set order of integration (d, D) to 0. We evaluated SARIMA models with the parameters we have identified above. The summary below shows the best model or in other words lowest AIC, BIC, HQIC. The best model suggests that we don’t need to have AR features, but only MA and seasonal MA features. best_model, models = best_sarima_model(train_data=log_transformed_data,p=range(3),q=range(3),P=range(3),Q=range(3)) ARIMA or SARIMA models are estimated by using MLE and OLS assumptions are applicable to this family of models. I don't want to elaborate on these assumptions here. It is a topic of another article. However, we have to confirm that our model aligns with those assumptions. P values of coefficients are <= 0.05. Residuals are stationary and homoscedastic. There is no serial correlation among residuals. We will predict home sales from 2018–01–01 to 2019–01–01. I will use MAPE — mean absolute percentage error to evaluate the model performance. Best model we have got is SARIMA(order=(0,1,2),seasonal_order=(0,1,1,12). I prefer MAPE error metric in time series analysis as it is more intuitive. Sklearn doesn’t provide MAPE metric, that’s why we have to code it ourselves. Formula: When you use predict function, there are some nuances to be careful about its parameters: type = ‘levels’ means predicted values will be at the same level with endog/training values, in our case they were log transformed and not diffed at all. Then, if you notice we take np.exp() to scale the predicted values to original data. Remember, np.exp(np.log(a)) = a. So, np.exp(np.log(original data)) = original datadynamics = True, then use the predicted value for time = t as a predictor for time = t+1. type = ‘levels’ means predicted values will be at the same level with endog/training values, in our case they were log transformed and not diffed at all. Then, if you notice we take np.exp() to scale the predicted values to original data. Remember, np.exp(np.log(a)) = a. So, np.exp(np.log(original data)) = original data dynamics = True, then use the predicted value for time = t as a predictor for time = t+1. preds_best=np.exp(best_model.predict(start=test_start_date,end='2019-01-01', dynamic=True, typ='levels'))print("MAPE{}%".format(np.round(mean_abs_pct_error(test_data,preds_best),2)))MAPE:6.05% We make approx. 6% error in our prediction. It doesn’t mean the model will underperform at 6% of the time. Rather it translates as the predicted value will be offset from the real value 6% on average. Plot the predicted values with original data and see the results. What can we infer from the below plot? Well, a lot! The model can successfully capture the seasonal effect, however, cannot do the same with the trend. Home sales go downward trend, however, the model cannot capture it well. It knows that sales go down but due to seasonal effect, however, there is a downward trend after 2018 which it struggles to predict. This is due to small training data we have got. If we had a larger data set, we could identify an economic cycle, and model it. Possibly, every 6–7 years of housing sales follow a reduction. Or if this downward trend continues in 2019 our 2020 prediction would definitely capture the trend. Another option to capture trend quicker is to add an AR term to the model. If we add 1 or 2 AR terms to the model it could react to the trend quicker and have less MAPE. The below plot displays MAPE for each model. Models performing better than the best model in terms of test MAPE are in green. We have added AR terms to the model and we have got improvement in test metrics. agile_model = SARIMAX(endog=log_transformed_data,order=(1,1,2), seasonal_order=(1,1,2,12),enforce_invertibility=False).fit()agile_model.summary() Test MAPE now is 5.67%, improved from 6.05%, which is the test MAPE of the optimal model. agile_model_pred = np.exp(agile_model.predict(start=test_start_date,end=’2019–01–01', dynamic=True, typ=’levels’))print(“MAPE{}%”.format(np.round(mean_abs_pct_error(test_data,agile_model_pred),2)))MAPE:5.67% However, if you look at AIC, BIC and HQIC we get higher values, which means we traded off the model generality. We know that we have few data points roughly 300 and having 6 features in a linear model may lead to overfitting. If you take a look at the model summary above, P values of feature coefficients ar.L1, ma.L2, ar.S.L12, ma.S.L12 and ma.S.L24 are higher than 0.05%. We have talked about many different concepts above, which are used during the analysis and model building phase. The below steps summarize the approach we have taken and can be used as a guidance or a framework for a similar project: Identify if the model is multiplicative or additiveIdentify time series components: Trend, Cycle, Seasonality, ResidualsTransform data to make it linearMake data stationary if it is notBased on step 2, choose ARIMA or SARIMA modelDefine order parameters for each model variable/featureDo grid search and choose an optimal model based on AIC, BIC, HQICCheck if model residuals comply with OLS assumptionsForecast and calculate forecasting error: MAPE, MAE, etc. Identify if the model is multiplicative or additive Identify time series components: Trend, Cycle, Seasonality, Residuals Transform data to make it linear Make data stationary if it is not Based on step 2, choose ARIMA or SARIMA model Define order parameters for each model variable/feature Do grid search and choose an optimal model based on AIC, BIC, HQIC Check if model residuals comply with OLS assumptions Forecast and calculate forecasting error: MAPE, MAE, etc.
[ { "code": null, "e": 794, "s": 172, "text": "At this post, we will talk about the analysis of time series data with Trend and Seasonal components. An econometric approach will be followed to model the statistical properties of the data. The business objective here is forecasting. We attempted to explain various concepts involved in time series modelling, such as time series components, serial correlation, model fitting, metrics, etc. We will use SARIMAX model provided by statsmodels library to model both, seasonality and trend in the data. SARIMA (Seasonal ARIMA) is capable of modelling seasonality and trend together, unlike ARIMA which can only model trend." }, { "code": null, "e": 804, "s": 794, "text": "Contents:" }, { "code": null, "e": 1151, "s": 804, "text": "Definition of time series dataIntroduction to the project and dataSeasonal decomposition and Time series components: Trend, Seasonality, Cycles, ResidualsStationarity in time series data and why it is importantAutocorrelation and partial autocorrelationData transformation: Log transformation and differencingModel Selection and FittingConclusion" }, { "code": null, "e": 1182, "s": 1151, "text": "Definition of time series data" }, { "code": null, "e": 1219, "s": 1182, "text": "Introduction to the project and data" }, { "code": null, "e": 1308, "s": 1219, "text": "Seasonal decomposition and Time series components: Trend, Seasonality, Cycles, Residuals" }, { "code": null, "e": 1365, "s": 1308, "text": "Stationarity in time series data and why it is important" }, { "code": null, "e": 1409, "s": 1365, "text": "Autocorrelation and partial autocorrelation" }, { "code": null, "e": 1466, "s": 1409, "text": "Data transformation: Log transformation and differencing" }, { "code": null, "e": 1494, "s": 1466, "text": "Model Selection and Fitting" }, { "code": null, "e": 1505, "s": 1494, "text": "Conclusion" }, { "code": null, "e": 1654, "s": 1505, "text": "Access full Python code from the GitHub repository: https://github.com/jahangirmammadov/sarima/blob/master/Seasonal%20Time%20Series%20Analysis.ipynb" }, { "code": null, "e": 1932, "s": 1654, "text": "Time series data is a sequence of data points measured over time intervals. In other words, data is a function of time f(t) = y.Data points can be measured hourly, daily, weekly, monthly, quarterly, yearly and also with smaller or larger time scales such as seconds or decades." }, { "code": null, "e": 3414, "s": 1932, "text": "The data we are using in this article is a monthly home sales index for 20 major US cities between the years 2000 and 2019. (https://fred.stlouisfed.org/series/SPCS20RPSNSA). You can freely download many different economic time series data representing the US economy from this source. You may see 2 different versions of the same data, seasonally-adjusted and non-seasonally-adjusted. The version used at this post is not seasonally adjusted as we want to model the seasonality as well as trend. You may ask why people want to use seasonally adjusted data in the industry. Well, sometimes businesses may want to know the true effect of economic events on a particular data, which may overlap with a season. In that case, seasonality may hide or underestimate/overestimate the effect of an economic event. For instance: Heating oil producers may want to study the impact of the declining petrol prices on heating oil prices. However, heating oil prices are increasing in winter, despite the fact that heating oil is a petrol substance. The decrease in petrol prices should be reflected in the decrease in heating oil prices. However, in winter there is a big demand for heating, which causes a slight increase in prices. By removing the seasonal effect from the time series data, you may see that heating oil price actually follows a decreasing trend. The slight increase in the price was the seasonal effect. In Section 3, we will talk about seasonal decomposition in more detail." }, { "code": null, "e": 3942, "s": 3414, "text": "If we look at the time series plot of the data we can observe an increasing trend in 2000–2006, a decreasing trend in home sales starting from 2007 till 2012 due to big financial crisis and increasing trend again till 2018. We can also observe seasonality in the data as usually the housing market is not active at the beginning of a year and sales usually go high in mid-year and again sales getting lower by the end of the year. Seems like warmer seasons, especially summer is the good season for the American housing market." }, { "code": null, "e": 4246, "s": 3942, "text": "Time series data Y is composed of a combination of Trend, Cycles, Seasonality and Residuals. Obviously, you may come across with time series where it doesn’t have a Trend, Cycles or Seasonality. So, it is your task to identify the components of time series data. Definition of the terms are given below:" }, { "code": null, "e": 4948, "s": 4246, "text": "Trend — long-term upward or downward movement. Cycle — periodic variation due to economic movements. It is different from seasonal variation. The cycle is the variation of autoregressive component of time series data. Cycles occur within longer time intervals such as every 6–10 years, whereas seasonal variation occurs in shorter time intervals. Seasonality — variation in data caused by seasonal effects. Ice cream sales are high in summer, heating oil sales are high in winter but low in summer.Residuals — a component that is left after other components have been calculated and removed from time series data. It is randomly, identiclly and independently distributed (i.i.d). Residuals, R~ N(0,1)." }, { "code": null, "e": 5521, "s": 4948, "text": "Statsmodels library has a function called seasonal_decompose, which decomposes time series Y into Trend, Seasonality and Residuals. Although, it is a naive decomposition algorithm, in practice it is very intuitive and works well for time series data where T, S and R are obvious. Before explaining the below graphs I would like to talk about the interaction among these components. Time series data Y can take either an additive or a multiplicative form. In additive form, time series Y is formed by the sum of time series components, namely, T, S, C, R: Y = T + C + S + R" }, { "code": null, "e": 5627, "s": 5521, "text": "In multiplicative form time series Y is formed by the product of time series components:Y = T * C * S * R" }, { "code": null, "e": 6101, "s": 5627, "text": "So, is home sales index is multiplicative or additive? If you carefully look at the time series plot of Housing index you may notice that the seasonal variation (seasonality) gets smaller when the trend decreases (years 2008–2013) and gets bigger when the trend increases (years 2014–2019). This happens in multiplicative time series, where small value for trend T results in small S because we multiply S by T. You don’t experience this phenomenon in additive time series." }, { "code": null, "e": 6758, "s": 6101, "text": "We decompose time series data into Trend, Seasonal component and Residuals using seasonal_decompose(original_data, ‘multiplicative’) function from statsmodels. Don’t be surprised if the function returns all 3 components even though you assume that they do not exist for a particular time series data. In reality, these components are generated by a simple algorithm, that’s why the decomposition function cannot say a component doesn’t exist, despite the calculated value is not significant. So, you will see these three components for any time series data. You have to know how to read the results and decide which model (ARIMA or SARIMA) to fit the data." }, { "code": null, "e": 7017, "s": 6758, "text": "We will try to decompose the data into components ourselves to better understand their derivation and usage. The trend can be calculated taking moving average with window size= 12. The below plot is very similar to the Trend generated by stats model library." }, { "code": null, "e": 7343, "s": 7017, "text": "Remember the multiplicative model, Y = T *C* S* R ? Dividing Y by T may give you Y/T=C*S*R and we assume that Residuals are too small for this data as the time series plot looks smooth. We have a very small data, thus we cannot detect an economic cycle. We get a seasonal component when we divide time series by trend, S=Y/T." }, { "code": null, "e": 7867, "s": 7343, "text": "Graph of seasonality is a little bit harder to understand, however, the explanation given here is sufficient. y=1.2(red marker) means there were 20% more sales in July-2000. In other words, June has a seasonal effect of +20% or 1.2 *T. On the other hand, y=0.8(green marker) in Feb-2003 shows a 20% decrease in sales. So, for some time series data not at this particular case, you may see the seasonal effect is very small i.e y=0.0001. It shows a very small seasonal effect, which shouldn’t even be considered significant." }, { "code": null, "e": 7908, "s": 7867, "text": "Residuals can be computed as R = Y/(S*T)" }, { "code": null, "e": 8170, "s": 7908, "text": "There are some other ways to detect seasonality. In the below graph, monthly home sales for each year is plotted and as you can see every year follows pretty much the same pattern with a slight difference. House sales are high in summer, lower in winter months." }, { "code": null, "e": 8256, "s": 8170, "text": "When we have trend and/or seasonality in a time series data we call it non-staionary." }, { "code": null, "e": 8384, "s": 8256, "text": "Stationarity means the statistical properties of data, such as mean, variance and standard deviation remain constant over time." }, { "code": null, "e": 8801, "s": 8384, "text": "Why do we want the statistical properties to remain the same over time? Well, because we make statistical assumptions (a good example could be OLS assumptions) about the sample data in due course of model building and the model will only be capable of performing under those assumptions. When the statistical properties of the data changes, the model is no longer capable of representing the true nature of the data." }, { "code": null, "e": 9332, "s": 8801, "text": "That’s why our forecasting/prediction results will no longer be valid. Changing mean/variance will require us to fit another model and this model may be valid for a short period of time and we have to abandon it again and fit a new model. See, how inefficient and unreliable this process looks like. We have to make time series data stationary before fitting a model. We can make time series stationary by transforming the data. Usually, differencing is used to make the data stationary. We will talk about it in Section 6, below." }, { "code": null, "e": 9839, "s": 9332, "text": "So, how can we test whether a time series data is stationary or not? The first is just eyeballing the time series plot and identify trend or seasonality. If at least one of them exists, then the time series data is not stationary. Secondly, you may divide the data into 3 different sets and calculate mean and variance for each set and confirm whether mean and variance for each set is substantially different or not. The third option is to use one of the statistical tests provided in statsmodels library." }, { "code": null, "e": 10133, "s": 9839, "text": "Augmented Dickey-Fuller test is the most popular amongst others, where the null hypothesis, H_0 = data is not stationary. ADF test result provides test statistic and P value. P value >= 0.05 means the data is not stationary, otherwise, we reject the null hypothesis and say data is stationary." }, { "code": null, "e": 10482, "s": 10133, "text": "We assume you know what hypothesis testing is and what P value means. If you are not quite familiar with these terms, then look at the p-value and if it is smaller than 0.05 (p-value < 0.05) then data is stationary if p-value >= 0.05 data is not stationary. ADF test confirms that the original time series data is not stationary with p-value ~ 0.08" }, { "code": null, "e": 10558, "s": 10482, "text": "Time series data is not stationary. Adfuller test pvalue=0.0803366374517756" }, { "code": null, "e": 10672, "s": 10558, "text": "We have to take a look at ACF and PACF plots, before model building as we will use these plots a lot from now on." }, { "code": null, "e": 11046, "s": 10672, "text": "Autocorrelation plot shows the correlation of time series data with its own lagged values. For example, autocorrelation at lag=1 shows the correlation between y_t and y_t-1. At lag=2, corr(y_t, y_t-2). At lag=12 corr(y_t, y_t-12). Every data point at time t having a high correlation with a data point at time t-12, t-24, etc denotes seasonality at this particular example." }, { "code": null, "e": 11185, "s": 11046, "text": "The below code snippet and scatter plots may help you to better understand the correlation between lagged values, namely, autocorrelation." }, { "code": null, "e": 11547, "s": 11185, "text": "Back to ACF plot, blue shaded area at the autocorrelation plot shows significance level. So, correlation coefficients within the shaded area show weak correlation at those lags and we don’t consider them significant in the analysis.The partial autocorrelation function (PACF) gives the partial correlation of a stationary time series with its own lagged values." }, { "code": null, "e": 11681, "s": 11547, "text": "PACF removes the correlation contribution of other lags and gives the pure correlation between two lags without the effect of others." }, { "code": null, "e": 12187, "s": 11681, "text": "We use ACF and PACF to choose a correct order for AR(p) and MA(q) components/features of an ARIMA model. For AR order p, look at PACF plot and choose a lag value which has a significant correlation factor before correlations get insignificant. For MA order q look at ACF plot and do the same. Don’t forget you should only get these values from the ACF and PACF plots of stationary time series, not the above plots. The ACF and PACF plot given above are the plots of original data, which is non-stationary." }, { "code": null, "e": 12622, "s": 12187, "text": "So, let’s transform the data to make it stationary, so we can start the model building phase. We split the original data into training and test data. Training data will contain US home sales data from 2000 to 2018 and test data will contain data from 2018 to 2019. Don’t forget, you cannot do random sampling like you are doing for cross-sectional data. We have to keep the temporal behaviour (dependence on time) of time series data." }, { "code": null, "e": 13161, "s": 12622, "text": "Home sales index data can be formulated as a multiplicative model where Y= T*S*R. I am ignoring Cycles, as it is not actually present in this data. (S)ARIMA models are linear models, like Linear Regression. We can not fit a linear model SARIMA to data generated by a process Y = T*S*R. We have to make Y linear before fitting a linear model. As you are aware of from math Log(a*b) = log(a) + log(b). We have to log-transform the data to make it linear. log(Y) = log(T) + log(S) + log(R). Log transformation makes data linear and smoother." }, { "code": null, "e": 13280, "s": 13161, "text": "log_transformed_data = np.log(training_data)plot_data_properties(log_transformed_data, ‘Log tranformed training data’)" }, { "code": null, "e": 13375, "s": 13280, "text": "Sometimes, log transformation on itself can make data stationary, but it is not the case here." }, { "code": null, "e": 13491, "s": 13375, "text": "test_stationarity(log_transformed_data)Time series data is not stationary. Adfuller test pvalue=0.22522944188413385" }, { "code": null, "e": 13630, "s": 13491, "text": "Differencing is a basic operation or data transformation. It is the difference between y at time=t and y at time=t-x. diff_1 = y_t — y_t-1" }, { "code": null, "e": 13906, "s": 13630, "text": "Differencing makes the data stationary as it removes time series components from the data and you are left with changes between time periods. Notice, first order differencing took away only Trend, not Seasonality. Data is still not stationary as it contains seasonal effects." }, { "code": null, "e": 14039, "s": 13906, "text": "logged_diffed_data = log_transformed_data.diff()[1:]plot_data_properties(logged_diffed_data, 'Log transformed and differenced data')" }, { "code": null, "e": 14153, "s": 14039, "text": "test_stationarity(logged_diffed_data)Time series data is not stationary. Adfuller test pvalue=0.20261733702504936" }, { "code": null, "e": 14514, "s": 14153, "text": "We have to take 12th order difference to remove seasonality. You may ask how we decided to take 12th order difference not 6th or 8th or other order. Usually, monthly data has seasonality at lag=12, weekly data has at lag=4 and daily has at lag=30. Or you can derive it from the ACF plot. The12th, 24th, 36th lags are highly correlated for this particular data." }, { "code": null, "e": 14766, "s": 14514, "text": "Data is stationary now. If you look at the histogram at the below graph, it looks like Normal bell curve. Stationary data is randomly i.i.d distributed and the plot looks like white noise. White noise is just an example of stationary time series data." }, { "code": null, "e": 14927, "s": 14766, "text": "seasonally_diffed_data = logged_diffed_data.diff(12)[12:]plot_data_properties(seasonally_diffed_data, 'Log transofrmed, diff=1 and seasonally differenced data')" }, { "code": null, "e": 15043, "s": 14927, "text": "test_stationarity(seasonally_diffed_data)Time series data is stationary. Adfuller test pvalue=0.0006264163287311492" }, { "code": null, "e": 15354, "s": 15043, "text": "As transformed data is stationary now we can proceed to model fitting phase. We had a brief chat about SARIMA before. I want to elaborate on this particular model. SARIMA, Seasonal ARIMA is a special member of ARIMA family which can model seasonal component of time series data. Just to recap what ARIMA means:" }, { "code": null, "e": 15542, "s": 15354, "text": "AR — Auto-Regressive model means time series data is regressed on its lagged values. Lagged values become independent variables, whereas time series itself becomes the dependent variable." }, { "code": null, "e": 15593, "s": 15542, "text": "y = a_0 + a_1*y_t-1 + a_2*y_t-2, ....., a_k*y_t-k." }, { "code": null, "e": 16629, "s": 15593, "text": "The main task here is to choose how many time steps to be used as independent variables. Do not let the word time series or lagged values to confuse you, they are just independent variables. In linear Regression, you could look at the correlation between independent and dependent variables and choose highly correlated variables as your features. Here you should do the same. But, you don’t have to calculate the correlation between lagged values and target variable, because you can use PACF to determine how many lags to use. PACF of stationary data has significant autocorrelation at lag=1 and the next autocorrelation at Lag=2 becomes insignificant. Ideally, AR order p should be 1. Since AR(p) and MA(q) terms interact, the initial p and q values observed from autocorrelation plots are no longer reliable and should be used as a starting point. We have to do parameter search on p to find the optimal value. An initial guess will help to define which values to use for a grid search. In this case, p = [0–2] would be sufficient." }, { "code": null, "e": 17007, "s": 16629, "text": "I — order of integration: Basically, how many times you have differenced the data. We had it once d=1. Do not forget to fit the model to not differenced data when you set parameter d=1, as the algorithm will differentiate it. If you fit model to stationary data, thenyou don't need differencing anymore. You can leave d=0. We need differencing just to make the data stationary." }, { "code": null, "e": 17077, "s": 17007, "text": "MA — Moving Average model: Time series y is regressed on residuals w." }, { "code": null, "e": 17119, "s": 17077, "text": "y = a_0 + a_1*w1 + a_2*w2 + .... + a_k*wk" }, { "code": null, "e": 17335, "s": 17119, "text": "Look at ACF plot to determine MA order (q) of the ARIMA model. ACF suggests order q=1 for MA part of the ARIMA model. However, we should do a grid search to find an optimal model. I suggest looking at values q=[0–2]" }, { "code": null, "e": 17584, "s": 17335, "text": "Seasonal model — Seasonal features have to be added to the model together with AR and MA and it has 4 parameters (P, D, Q, s). Think of P, D and Q parameters being similar to AR, I and MA parameters, but only for a seasonal component of the series." }, { "code": null, "e": 17739, "s": 17584, "text": "Choose P by looking at PACF and Q by looking at ACF. The number of seasonal differences has been taken is D. Frequency of seasonal effect is defined by s." }, { "code": null, "e": 17937, "s": 17739, "text": "P = 1 — because we have significant correlation at lag=12, however, they are not strong enough and we may not need to have an AR variable in the model. That’s why we should grid search on P = [0–2]" }, { "code": null, "e": 17979, "s": 17937, "text": "D=1 — we differenced for seasonality once" }, { "code": null, "e": 18101, "s": 17979, "text": "Q=1 — as we have strong correlation at lag=12 according to ACF plot. Let’s perform grid search on parameter Q=[0–2], too." }, { "code": null, "e": 18147, "s": 18101, "text": "s=12 — seasonality frequency, every 12 months" }, { "code": null, "e": 18757, "s": 18147, "text": "best_sarima_model function below performs grid search on (p,d,q) and (P,D,Q,s) parameters and finds the best model taking statistical metrics AIC, BIC, HQIC as evaluation criteria. Lower AIC, BIC, HQIC means better model. These metrics reward goodness-of-fit (log-likelihood) and penalises overfitting. In our case having many lagged features leads to overfitting. AIC, BIC and HQIC balance the tradeoff between likelihood and degrees of freedom. You can see this property in their formula. I will not get into the details of other metrics, but will give an example below for supporting my point of using AIC:" }, { "code": null, "e": 18919, "s": 18757, "text": "-k is number of estimated parameters in the model, in other words, number of features (lag terms). -L is the maximum of the likelihood function.AIC = 2k — 2ln(L)" }, { "code": null, "e": 19209, "s": 18919, "text": "I have seen many examples in the industry, using only one of those metrics as a model selection criteria, but you may come across the cases where AIC of a model can be lower than another, while BIC is higher. That’s why try to choose a model over the other if 2 of the 3 metrics are lower." }, { "code": null, "e": 19723, "s": 19209, "text": "Note, we are fitting a model to log-transformed data and because of that. we have set d=1 and D=1 parameters so that the model to do differencing itself. If you are fitting a model to stationary data instead, you have to set order of integration (d, D) to 0. We evaluated SARIMA models with the parameters we have identified above. The summary below shows the best model or in other words lowest AIC, BIC, HQIC. The best model suggests that we don’t need to have AR features, but only MA and seasonal MA features." }, { "code": null, "e": 19839, "s": 19723, "text": "best_model, models = best_sarima_model(train_data=log_transformed_data,p=range(3),q=range(3),P=range(3),Q=range(3))" }, { "code": null, "e": 20241, "s": 19839, "text": "ARIMA or SARIMA models are estimated by using MLE and OLS assumptions are applicable to this family of models. I don't want to elaborate on these assumptions here. It is a topic of another article. However, we have to confirm that our model aligns with those assumptions. P values of coefficients are <= 0.05. Residuals are stationary and homoscedastic. There is no serial correlation among residuals." }, { "code": null, "e": 20620, "s": 20241, "text": "We will predict home sales from 2018–01–01 to 2019–01–01. I will use MAPE — mean absolute percentage error to evaluate the model performance. Best model we have got is SARIMA(order=(0,1,2),seasonal_order=(0,1,1,12). I prefer MAPE error metric in time series analysis as it is more intuitive. Sklearn doesn’t provide MAPE metric, that’s why we have to code it ourselves. Formula:" }, { "code": null, "e": 20710, "s": 20620, "text": "When you use predict function, there are some nuances to be careful about its parameters:" }, { "code": null, "e": 21121, "s": 20710, "text": "type = ‘levels’ means predicted values will be at the same level with endog/training values, in our case they were log transformed and not diffed at all. Then, if you notice we take np.exp() to scale the predicted values to original data. Remember, np.exp(np.log(a)) = a. So, np.exp(np.log(original data)) = original datadynamics = True, then use the predicted value for time = t as a predictor for time = t+1." }, { "code": null, "e": 21443, "s": 21121, "text": "type = ‘levels’ means predicted values will be at the same level with endog/training values, in our case they were log transformed and not diffed at all. Then, if you notice we take np.exp() to scale the predicted values to original data. Remember, np.exp(np.log(a)) = a. So, np.exp(np.log(original data)) = original data" }, { "code": null, "e": 21533, "s": 21443, "text": "dynamics = True, then use the predicted value for time = t as a predictor for time = t+1." }, { "code": null, "e": 21726, "s": 21533, "text": "preds_best=np.exp(best_model.predict(start=test_start_date,end='2019-01-01', dynamic=True, typ='levels'))print(\"MAPE{}%\".format(np.round(mean_abs_pct_error(test_data,preds_best),2)))MAPE:6.05%" }, { "code": null, "e": 21927, "s": 21726, "text": "We make approx. 6% error in our prediction. It doesn’t mean the model will underperform at 6% of the time. Rather it translates as the predicted value will be offset from the real value 6% on average." }, { "code": null, "e": 22399, "s": 21927, "text": "Plot the predicted values with original data and see the results. What can we infer from the below plot? Well, a lot! The model can successfully capture the seasonal effect, however, cannot do the same with the trend. Home sales go downward trend, however, the model cannot capture it well. It knows that sales go down but due to seasonal effect, however, there is a downward trend after 2018 which it struggles to predict. This is due to small training data we have got." }, { "code": null, "e": 22642, "s": 22399, "text": "If we had a larger data set, we could identify an economic cycle, and model it. Possibly, every 6–7 years of housing sales follow a reduction. Or if this downward trend continues in 2019 our 2020 prediction would definitely capture the trend." }, { "code": null, "e": 22938, "s": 22642, "text": "Another option to capture trend quicker is to add an AR term to the model. If we add 1 or 2 AR terms to the model it could react to the trend quicker and have less MAPE. The below plot displays MAPE for each model. Models performing better than the best model in terms of test MAPE are in green." }, { "code": null, "e": 23019, "s": 22938, "text": "We have added AR terms to the model and we have got improvement in test metrics." }, { "code": null, "e": 23165, "s": 23019, "text": "agile_model = SARIMAX(endog=log_transformed_data,order=(1,1,2), seasonal_order=(1,1,2,12),enforce_invertibility=False).fit()agile_model.summary()" }, { "code": null, "e": 23255, "s": 23165, "text": "Test MAPE now is 5.67%, improved from 6.05%, which is the test MAPE of the optimal model." }, { "code": null, "e": 23463, "s": 23255, "text": "agile_model_pred = np.exp(agile_model.predict(start=test_start_date,end=’2019–01–01', dynamic=True, typ=’levels’))print(“MAPE{}%”.format(np.round(mean_abs_pct_error(test_data,agile_model_pred),2)))MAPE:5.67%" }, { "code": null, "e": 23838, "s": 23463, "text": "However, if you look at AIC, BIC and HQIC we get higher values, which means we traded off the model generality. We know that we have few data points roughly 300 and having 6 features in a linear model may lead to overfitting. If you take a look at the model summary above, P values of feature coefficients ar.L1, ma.L2, ar.S.L12, ma.S.L12 and ma.S.L24 are higher than 0.05%." }, { "code": null, "e": 24072, "s": 23838, "text": "We have talked about many different concepts above, which are used during the analysis and model building phase. The below steps summarize the approach we have taken and can be used as a guidance or a framework for a similar project:" }, { "code": null, "e": 24533, "s": 24072, "text": "Identify if the model is multiplicative or additiveIdentify time series components: Trend, Cycle, Seasonality, ResidualsTransform data to make it linearMake data stationary if it is notBased on step 2, choose ARIMA or SARIMA modelDefine order parameters for each model variable/featureDo grid search and choose an optimal model based on AIC, BIC, HQICCheck if model residuals comply with OLS assumptionsForecast and calculate forecasting error: MAPE, MAE, etc." }, { "code": null, "e": 24585, "s": 24533, "text": "Identify if the model is multiplicative or additive" }, { "code": null, "e": 24655, "s": 24585, "text": "Identify time series components: Trend, Cycle, Seasonality, Residuals" }, { "code": null, "e": 24688, "s": 24655, "text": "Transform data to make it linear" }, { "code": null, "e": 24722, "s": 24688, "text": "Make data stationary if it is not" }, { "code": null, "e": 24768, "s": 24722, "text": "Based on step 2, choose ARIMA or SARIMA model" }, { "code": null, "e": 24824, "s": 24768, "text": "Define order parameters for each model variable/feature" }, { "code": null, "e": 24891, "s": 24824, "text": "Do grid search and choose an optimal model based on AIC, BIC, HQIC" }, { "code": null, "e": 24944, "s": 24891, "text": "Check if model residuals comply with OLS assumptions" } ]
Grav - Modular Pages
Modular pages are difficult to understand at first but once you get to know about it, it would be very easy to work with. It enables to create a single page from its child pages. It has the ability to build complex one page layouts from modular content pages. Modular pages are set as non-routable because they cannot be reached directly through an URL. They are identified by _ (underscore) before the folder name. It is a collection of pages that are displayed one above each to get a single page. For example, user/pages/home/_header.. In case of one-page skeleton, you can find this page in the 01.home folder. In this, you get a single modular .md file that tells which pages must be included and the order of the pages to display. modular.html.twig can be found in your present theme folder. In the image below, you can see a folder structure that has been created for modular pages. Every sub-folder must contain a .md file that describes a markdown file. Firstly, you must create sub folders in /users/pages/01.home folder. Next, each folder must contain a .md file and a modular.md file. When you create the sub folder, the image and file both must be in the same folder. To create modular pages, you must follow the given steps. Step 1 − Create a few pages in /user/pages/01.home/. folder. In the image below, you can see we have created two folders along with a modular.md file. Step 2 − To create a modular page, you must create a file in each folder and name it as text.md. Step 3 − Next, add your code in text.md file, save it and run the same. Example Save all the four pages as .md file. Here we have created 4 pages and named as text.md, text1.md, text2.md and text3.md. --- title: Bio-diversity --- ## Bio-diversity Biodiversity refers to the variety of life. It is seen in the number of species in an [ecosystem](https://simple.wikipedia.org/wiki/Ecosystem) or on the entire [Earth] (https://simple.wikipedia.org/wiki/Earth). Biodiversity gets used as a measure of the health of biological systems, and to see if there is a danger that too many species become[extinct](https://simple.wikipedia.org/wiki/Extinct). Now, create 4 pages, add them to the \templates\modular folder as shown below. Next, go to home page and refresh, you can see the changes. In the new navigation bar, you can see the four file links. 19 Lectures 3 hours Mr. Pradeep Kshetrapal 30 Lectures 4 hours Priyanka Choudhary 55 Lectures 4.5 hours University Code 24 Lectures 1 hours Mike Clayton Print Add Notes Bookmark this page
[ { "code": null, "e": 2762, "s": 2502, "text": "Modular pages are difficult to understand at first but once you get to know about it, it would be very easy to work with. It enables to create a single page from its child pages. It has the ability to build complex one page layouts from modular content pages." }, { "code": null, "e": 3041, "s": 2762, "text": "Modular pages are set as non-routable because they cannot be reached directly through an URL. They are identified by _ (underscore) before the folder name. It is a collection of pages that are displayed one above each to get a single page. For example, user/pages/home/_header.." }, { "code": null, "e": 3300, "s": 3041, "text": "In case of one-page skeleton, you can find this page in the 01.home folder. In this, you get a single modular .md file that tells which pages must be included and the order of the pages to display. modular.html.twig can be found in your present theme folder." }, { "code": null, "e": 3392, "s": 3300, "text": "In the image below, you can see a folder structure that has been created for modular pages." }, { "code": null, "e": 3465, "s": 3392, "text": "Every sub-folder must contain a .md file that describes a markdown file." }, { "code": null, "e": 3599, "s": 3465, "text": "Firstly, you must create sub folders in /users/pages/01.home folder. Next, each folder must contain a .md file and a modular.md file." }, { "code": null, "e": 3683, "s": 3599, "text": "When you create the sub folder, the image and file both must be in the same folder." }, { "code": null, "e": 3741, "s": 3683, "text": "To create modular pages, you must follow the given steps." }, { "code": null, "e": 3892, "s": 3741, "text": "Step 1 − Create a few pages in /user/pages/01.home/. folder. In the image below, you can see we have created two folders along with a modular.md file." }, { "code": null, "e": 3989, "s": 3892, "text": "Step 2 − To create a modular page, you must create a file in each folder and name it as text.md." }, { "code": null, "e": 4061, "s": 3989, "text": "Step 3 − Next, add your code in text.md file, save it and run the same." }, { "code": null, "e": 4069, "s": 4061, "text": "Example" }, { "code": null, "e": 4190, "s": 4069, "text": "Save all the four pages as .md file. Here we have created 4 pages and named as text.md, text1.md, text2.md and text3.md." }, { "code": null, "e": 4638, "s": 4190, "text": "---\ntitle: Bio-diversity\n---\n\n## Bio-diversity\n\nBiodiversity refers to the variety of life. It is seen in the number of species in an \n[ecosystem](https://simple.wikipedia.org/wiki/Ecosystem) or on the entire [Earth]\n(https://simple.wikipedia.org/wiki/Earth). Biodiversity gets used as a measure of the\nhealth of biological systems, and to see if there is a danger that too many species\nbecome[extinct](https://simple.wikipedia.org/wiki/Extinct).\n" }, { "code": null, "e": 4717, "s": 4638, "text": "Now, create 4 pages, add them to the \\templates\\modular folder as shown below." }, { "code": null, "e": 4777, "s": 4717, "text": "Next, go to home page and refresh, you can see the changes." }, { "code": null, "e": 4837, "s": 4777, "text": "In the new navigation bar, you can see the four file links." }, { "code": null, "e": 4870, "s": 4837, "text": "\n 19 Lectures \n 3 hours \n" }, { "code": null, "e": 4894, "s": 4870, "text": " Mr. Pradeep Kshetrapal" }, { "code": null, "e": 4927, "s": 4894, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 4947, "s": 4927, "text": " Priyanka Choudhary" }, { "code": null, "e": 4982, "s": 4947, "text": "\n 55 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4999, "s": 4982, "text": " University Code" }, { "code": null, "e": 5032, "s": 4999, "text": "\n 24 Lectures \n 1 hours \n" }, { "code": null, "e": 5046, "s": 5032, "text": " Mike Clayton" }, { "code": null, "e": 5053, "s": 5046, "text": " Print" }, { "code": null, "e": 5064, "s": 5053, "text": " Add Notes" } ]
How to get Resource name using Resource id in Android?
This example demonstrates how do I get resource name using Resource id in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:text="" android:textSize="16sp" android:textStyle="bold" android:layout_centerInParent="true" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); int text = textView.getId(); String string = getResources().getResourceName(text); textView.setText("Resource ID: " + string); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1145, "s": 1062, "text": "This example demonstrates how do I get resource name using Resource id in android." }, { "code": null, "e": 1274, "s": 1145, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1339, "s": 1274, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1893, "s": 1339, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:text=\"\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\"\n android:layout_centerInParent=\"true\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"/>\n</RelativeLayout>" }, { "code": null, "e": 1950, "s": 1893, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2488, "s": 1950, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n int text = textView.getId();\n String string = getResources().getResourceName(text);\n textView.setText(\"Resource ID: \" + string);\n }\n}" }, { "code": null, "e": 2543, "s": 2488, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3213, "s": 2543, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3560, "s": 3213, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 3601, "s": 3560, "text": "Click here to download the project code." } ]
What is the use of ALLOW_INVALID_DATES SQL mode?
As the name suggests, enabling ALLOW_INVALID_DATES SQL mode will allow us to store invalid dates in the table. The example is given below to understand it − mysql> SET sql_mode = ALLOW_INVALID_DATES; Query OK, 0 rows affected, 1 warning (0.00 sec) mysql> Insert Into detail_bday(Name, Birth_Date) values('Sonia','1993-11-31'); Query OK, 1 row affected (0.09 sec) mysql> Insert Into detail_bday(Name, Birth_Date) values('Ram','0000-00-00'); Query OK, 1 row affected (0.10 sec) mysql> Select * from detail_bday; +----+---------+------------+ | Sr | Name | Birth_Date | +----+---------+------------+ | 1 | Saurabh | 1990-05-12 | | 2 | Raman | 1993-06-11 | | 3 | Gaurav | 1984-01-17 | | 4 | Rahul | 1993-06-11 | | 5 | Sonia | 1993-11-31 | | 6 | Ram | 0000-00-00 | +----+---------+------------+ 6 rows in set (0.00 sec) Above result set shows that MySQL allows us to store invalid date like ‘1993-11-31’ and ‘0000-00-00’ after enabling the ALOOW_INVALID_DATES SQL mode.
[ { "code": null, "e": 1219, "s": 1062, "text": "As the name suggests, enabling ALLOW_INVALID_DATES SQL mode will allow us to store invalid dates in the table. The example is given below to understand it −" }, { "code": null, "e": 1900, "s": 1219, "text": "mysql> SET sql_mode = ALLOW_INVALID_DATES;\nQuery OK, 0 rows affected, 1 warning (0.00 sec)\n\nmysql> Insert Into detail_bday(Name, Birth_Date) values('Sonia','1993-11-31');\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> Insert Into detail_bday(Name, Birth_Date) values('Ram','0000-00-00');\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> Select * from detail_bday;\n+----+---------+------------+\n| Sr | Name | Birth_Date |\n+----+---------+------------+\n| 1 | Saurabh | 1990-05-12 |\n| 2 | Raman | 1993-06-11 |\n| 3 | Gaurav | 1984-01-17 |\n| 4 | Rahul | 1993-06-11 |\n| 5 | Sonia | 1993-11-31 |\n| 6 | Ram | 0000-00-00 |\n+----+---------+------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2050, "s": 1900, "text": "Above result set shows that MySQL allows us to store invalid date like ‘1993-11-31’ and ‘0000-00-00’ after enabling the ALOOW_INVALID_DATES SQL mode." } ]
How to include groups of table columns in HTML?
Use the <colgroup> tag to include groups of table columns.The HTML <colgroup> tag is used for specifying properties for a group of columns within a table. If you need to apply different properties to a column within a colgroup, you can use the HTML col tag within the colgroup tag. The following are the attributes − You can try to run the following code to implement <colgroup> tag in HTML − <!DOCTYPE html> <html> <head> <title>HTML col Tag</title> </head> <body> <p>This example shows a colgroup that has three columns of different widths:</p> <table border = "1"> <colgroup span = "4"> <col width = "40"></col> <col width = "70"></col> <col width = "100"></col> <col width = "130"></col> <col width = "160"></col> </colgroup> <tr> <td>One</td> <td>Two</td> <td>Three</td> <td>Four</td> <td>Five</td> </tr> </table> </body> </html>
[ { "code": null, "e": 1344, "s": 1062, "text": "Use the <colgroup> tag to include groups of table columns.The HTML <colgroup> tag is used for specifying properties for a group of columns within a table. If you need to apply different properties to a column within a colgroup, you can use the HTML col tag within the colgroup tag." }, { "code": null, "e": 1379, "s": 1344, "text": "The following are the attributes −" }, { "code": null, "e": 1455, "s": 1379, "text": "You can try to run the following code to implement <colgroup> tag in HTML −" }, { "code": null, "e": 2092, "s": 1455, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML col Tag</title>\n </head>\n <body>\n <p>This example shows a colgroup that has three columns of different widths:</p>\n <table border = \"1\">\n <colgroup span = \"4\">\n <col width = \"40\"></col>\n <col width = \"70\"></col>\n <col width = \"100\"></col>\n <col width = \"130\"></col>\n <col width = \"160\"></col>\n </colgroup>\n <tr>\n <td>One</td>\n <td>Two</td>\n <td>Three</td>\n <td>Four</td>\n <td>Five</td>\n </tr>\n </table>\n </body>\n</html>" } ]
How to Create a Custom Intro Slider of an Android App? - GeeksforGeeks
10 Aug, 2021 Intro Slider in many apps is mostly used to educate the users about the app, the features of the app, and the services that our app will provide to us. In this article, we will take a look at the implementation of Custom Intro Slider in our app. We will be building a simple application in which we will be displaying an intro slider in which we will show slider in our app. This slider contains a simple image and two TextView. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Adding the dependency for Picasso in your build.gradle file As we will be loading all our images from online sources so we will be using Picasso for loading images from URLs inside our application. So for using the images from the URL we have to add the below dependency in our build.gradle file. implementation ‘com.squareup.picasso:picasso:2.71828’ Step 3: Adding permissions for the Internet As we will be loading images from the URL, so we have to add permissions for the internet in your AndroidManifest.xml file. For adding permissions. Navigate to the app > AndroidManifest.xml file and add the below permissions. <uses-permission android:name=”android.permission.INTERNET”/> Step 4: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:weightSum="5" tools:context=".MainActivity"> <!--view pager for displaying our slides--> <androidx.viewpager.widget.ViewPager android:id="@+id/idViewPager" android:layout_width="match_parent" android:layout_height="match_parent" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:background="@android:color/transparent" android:orientation="horizontal" android:weightSum="5"> <View android:layout_width="0dp" android:layout_height="0dp" android:layout_weight="2" /> <!--adding linear layout for creating dots view--> <LinearLayout android:id="@+id/idLLDots" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_weight="1" android:gravity="center_horizontal" android:orientation="horizontal" /> <!--button for skipping our intro slider--> <Button android:id="@+id/idBtnSkip" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="10dp" android:layout_weight="2" android:background="@color/purple_500" android:backgroundTint="@color/purple_500" android:text="Skip" android:textAllCaps="false" android:textColor="@color/white" /> </LinearLayout> </RelativeLayout> Step 5: Creating a layout file for our slider item Now we will create an item that we will be displaying in our slider. So for creating a new layout navigate to the app > res > layout > Right-click on it > Click on New > layout resource file and name it as slider_layout and add below code to it. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/idRLSlider" android:layout_width="match_parent" android:layout_height="match_parent"> <!--text view for displaying our heading--> <TextView android:id="@+id/idTVtitle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:padding="10dp" android:text="Slide 1" android:textAlignment="center" android:textColor="@color/white" android:textSize="20sp" android:textStyle="bold" /> <!--Image view for displaying our slider image--> <ImageView android:id="@+id/idIV" android:layout_width="200dp" android:layout_height="200dp" android:layout_below="@id/idTVtitle" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:padding="10dp" android:src="@mipmap/ic_launcher" /> <!--text view for displaying our slider description--> <TextView android:id="@+id/idTVheading" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idIV" android:layout_marginStart="20dp" android:layout_marginTop="90dp" android:layout_marginEnd="20dp" android:padding="10dp" android:text="C++ data structure and ALgorithm Course" android:textAlignment="center" android:textColor="@color/white" android:textSize="15sp" /> </RelativeLayout> Step 6: Creating a Modal class for storing all the data for Slider items For creating a new Modal class navigate to the app > java > your app’s package name > Right-click on it and click on New > Java class and name it as SliderModal. After creating this class add the below code to it. Java public class SliderModal { // string variable for storing // title, image url and description. private String title; private String heading; private String imgUrl; private int backgroundDrawable; public SliderModal() { // empty constructor is required // when using firebase } // creating getter methods. public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getHeading() { return heading; } // creating setter methods public void setHeading(String heading) { this.heading = heading; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } // constructor for our modal class public SliderModal(String title, String heading, String imgUrl, int backgroundDrawable) { this.title = title; this.heading = heading; this.imgUrl = imgUrl; this.backgroundDrawable = backgroundDrawable; } public int getBackgroundDrawable() { return backgroundDrawable; } public void setBackgroundDrawable(int backgroundDrawable) { this.backgroundDrawable = backgroundDrawable; }} Step 7: Create an Adapter class for setting data to each view For creating a new Adapter class navigate to the app > java > your app’s package name > Right-click on it > New Java class and name it as SliderAdapter and add the below code to it. Comments are added inside the code to understand the code in more detail. Java import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.RelativeLayout;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.viewpager.widget.PagerAdapter; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class SliderAdapter extends PagerAdapter { // creating variables for layout // inflater, context and array list. LayoutInflater layoutInflater; Context context; ArrayList<SliderModal> sliderModalArrayList; // creating constructor. public SliderAdapter(Context context, ArrayList<SliderModal> sliderModalArrayList) { this.context = context; this.sliderModalArrayList = sliderModalArrayList; } @Override public int getCount() { // inside get count method returning // the size of our array list. return sliderModalArrayList.size(); } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { // inside isViewFrombject method we are // returning our Relative layout object. return view == (RelativeLayout) object; } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { // in this method we will initialize all our layout // items and inflate our layout file as well. layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); // below line is use to inflate the // layout file which we created. View view = layoutInflater.inflate(R.layout.slider_layout, container, false); // initializing our views. ImageView imageView = view.findViewById(R.id.idIV); TextView titleTV = view.findViewById(R.id.idTVtitle); TextView headingTV = view.findViewById(R.id.idTVheading); RelativeLayout sliderRL = view.findViewById(R.id.idRLSlider); // setting data to our views. SliderModal modal = sliderModalArrayList.get(position); titleTV.setText(modal.getTitle()); headingTV.setText(modal.getHeading()); Picasso.get().load(modal.getImgUrl()).into(imageView); // below line is to set background // drawable to our each item sliderRL.setBackground(context.getResources().getDrawable(modal.getBackgroundDrawable())); // after setting the data to our views we // are adding the view to our container. container.addView(view); // at last we are // returning the view. return view; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { // this is a destroy view method // which is use to remove a view. container.removeView((RelativeLayout) object); }} Step 8: Creating custom gradient drawable for our background of each slide Navigate to the app > res > drawable > Right-click on it > New > drawable resource file and name the file as gradient_one and add the below code to it. gradient_one.xml XML <?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient android:angle="90" android:endColor="@color/purple_500" android:startColor="#4B6CD6" /></shape> gradient_two.xml XML <?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient android:angle="90" android:endColor="#FF9800" android:startColor="#F4C22B" /></shape> gradient_three.xml XML <?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient android:angle="90" android:endColor="#F44336" android:startColor="#FD7B52" /></shape> Step 9: Working with the MainActivity.java file 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.os.Bundle;import android.text.Html;import android.widget.LinearLayout;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity;import androidx.viewpager.widget.ViewPager; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating variables for view pager, // liner layout, adapter and our array list. private ViewPager viewPager; private LinearLayout dotsLL; SliderAdapter adapter; private ArrayList<SliderModal> sliderModalArrayList; private TextView[] dots; int size; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing all our views. viewPager = findViewById(R.id.idViewPager); dotsLL = findViewById(R.id.idLLDots); // in below line we are creating a new array list. sliderModalArrayList = new ArrayList<>(); // on below 3 lines we are adding data to our array list. sliderModalArrayList.add(new SliderModal("Slide 1 ", "Slide 1 heading", "https://images.unsplash.com/photo-1610842546881-b282c580b51d?ixid=MXwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw5fHx8ZW58MHx8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60", R.drawable.gradient_one)); sliderModalArrayList.add(new SliderModal("Slide 2 ", "Slide 2 heading", "https://images.unsplash.com/photo-1610783131813-475d08664ef6?ixid=MXwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxMnx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60", R.drawable.gradient_two)); sliderModalArrayList.add(new SliderModal("Slide 3 ", "Slide 3 heading", "https://images.unsplash.com/photo-1610832958506-aa56368176cf?ixid=MXwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxN3x8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60", R.drawable.gradient_three)); // below line is use to add our array list to adapter class. adapter = new SliderAdapter(MainActivity.this, sliderModalArrayList); // below line is use to set our // adapter to our view pager. viewPager.setAdapter(adapter); // we are storing the size of our // array list in a variable. size = sliderModalArrayList.size(); // calling method to add dots indicator addDots(size, 0); // below line is use to call on // page change listener method. viewPager.addOnPageChangeListener(viewListner); } private void addDots(int size, int pos) { // inside this method we are // creating a new text view. dots = new TextView[size]; // below line is use to remove all // the views from the linear layout. dotsLL.removeAllViews(); // running a for loop to add // number of dots to our slider. for (int i = 0; i < size; i++) { // below line is use to add the // dots and modify its color. dots[i] = new TextView(this); dots[i].setText(Html.fromHtml("•")); dots[i].setTextSize(35); // below line is called when the dots are not selected. dots[i].setTextColor(getResources().getColor(R.color.black)); dotsLL.addView(dots[i]); } if (dots.length > 0) { // this line is called when the dots // inside linear layout are selected dots[pos].setTextColor(getResources().getColor(R.color.purple_200)); } } // creating a method for view pager for on page change listener. ViewPager.OnPageChangeListener viewListner = new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { // we are calling our dots method to // change the position of selected dots. addDots(size, position); } @Override public void onPageScrollStateChanged(int state) { } };} Now run your app and see the output of the app. Make sure to keep your Internet On. anikaseth98 android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Android Listview in Java with Example Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 24725, "s": 24697, "text": "\n10 Aug, 2021" }, { "code": null, "e": 24972, "s": 24725, "text": "Intro Slider in many apps is mostly used to educate the users about the app, the features of the app, and the services that our app will provide to us. In this article, we will take a look at the implementation of Custom Intro Slider in our app. " }, { "code": null, "e": 25320, "s": 24972, "text": "We will be building a simple application in which we will be displaying an intro slider in which we will show slider in our app. This slider contains a simple image and two TextView. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 25349, "s": 25320, "text": "Step 1: Create a New Project" }, { "code": null, "e": 25511, "s": 25349, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 25579, "s": 25511, "text": "Step 2: Adding the dependency for Picasso in your build.gradle file" }, { "code": null, "e": 25817, "s": 25579, "text": "As we will be loading all our images from online sources so we will be using Picasso for loading images from URLs inside our application. So for using the images from the URL we have to add the below dependency in our build.gradle file. " }, { "code": null, "e": 25871, "s": 25817, "text": "implementation ‘com.squareup.picasso:picasso:2.71828’" }, { "code": null, "e": 25916, "s": 25871, "text": "Step 3: Adding permissions for the Internet " }, { "code": null, "e": 26143, "s": 25916, "text": "As we will be loading images from the URL, so we have to add permissions for the internet in your AndroidManifest.xml file. For adding permissions. Navigate to the app > AndroidManifest.xml file and add the below permissions. " }, { "code": null, "e": 26205, "s": 26143, "text": "<uses-permission android:name=”android.permission.INTERNET”/>" }, { "code": null, "e": 26253, "s": 26205, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 26396, "s": 26253, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 26400, "s": 26396, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:weightSum=\"5\" tools:context=\".MainActivity\"> <!--view pager for displaying our slides--> <androidx.viewpager.widget.ViewPager android:id=\"@+id/idViewPager\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_alignParentBottom=\"true\" android:background=\"@android:color/transparent\" android:orientation=\"horizontal\" android:weightSum=\"5\"> <View android:layout_width=\"0dp\" android:layout_height=\"0dp\" android:layout_weight=\"2\" /> <!--adding linear layout for creating dots view--> <LinearLayout android:id=\"@+id/idLLDots\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:layout_weight=\"1\" android:gravity=\"center_horizontal\" android:orientation=\"horizontal\" /> <!--button for skipping our intro slider--> <Button android:id=\"@+id/idBtnSkip\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:layout_weight=\"2\" android:background=\"@color/purple_500\" android:backgroundTint=\"@color/purple_500\" android:text=\"Skip\" android:textAllCaps=\"false\" android:textColor=\"@color/white\" /> </LinearLayout> </RelativeLayout>", "e": 28293, "s": 26400, "text": null }, { "code": null, "e": 28348, "s": 28296, "text": "Step 5: Creating a layout file for our slider item " }, { "code": null, "e": 28597, "s": 28350, "text": "Now we will create an item that we will be displaying in our slider. So for creating a new layout navigate to the app > res > layout > Right-click on it > Click on New > layout resource file and name it as slider_layout and add below code to it. " }, { "code": null, "e": 28601, "s": 28597, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:id=\"@+id/idRLSlider\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <!--text view for displaying our heading--> <TextView android:id=\"@+id/idTVtitle\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:padding=\"10dp\" android:text=\"Slide 1\" android:textAlignment=\"center\" android:textColor=\"@color/white\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> <!--Image view for displaying our slider image--> <ImageView android:id=\"@+id/idIV\" android:layout_width=\"200dp\" android:layout_height=\"200dp\" android:layout_below=\"@id/idTVtitle\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"50dp\" android:padding=\"10dp\" android:src=\"@mipmap/ic_launcher\" /> <!--text view for displaying our slider description--> <TextView android:id=\"@+id/idTVheading\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idIV\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"90dp\" android:layout_marginEnd=\"20dp\" android:padding=\"10dp\" android:text=\"C++ data structure and ALgorithm Course\" android:textAlignment=\"center\" android:textColor=\"@color/white\" android:textSize=\"15sp\" /> </RelativeLayout>", "e": 30223, "s": 28601, "text": null }, { "code": null, "e": 30299, "s": 30226, "text": "Step 6: Creating a Modal class for storing all the data for Slider items" }, { "code": null, "e": 30516, "s": 30301, "text": "For creating a new Modal class navigate to the app > java > your app’s package name > Right-click on it and click on New > Java class and name it as SliderModal. After creating this class add the below code to it. " }, { "code": null, "e": 30521, "s": 30516, "text": "Java" }, { "code": "public class SliderModal { // string variable for storing // title, image url and description. private String title; private String heading; private String imgUrl; private int backgroundDrawable; public SliderModal() { // empty constructor is required // when using firebase } // creating getter methods. public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getHeading() { return heading; } // creating setter methods public void setHeading(String heading) { this.heading = heading; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } // constructor for our modal class public SliderModal(String title, String heading, String imgUrl, int backgroundDrawable) { this.title = title; this.heading = heading; this.imgUrl = imgUrl; this.backgroundDrawable = backgroundDrawable; } public int getBackgroundDrawable() { return backgroundDrawable; } public void setBackgroundDrawable(int backgroundDrawable) { this.backgroundDrawable = backgroundDrawable; }}", "e": 31791, "s": 30521, "text": null }, { "code": null, "e": 31856, "s": 31794, "text": "Step 7: Create an Adapter class for setting data to each view" }, { "code": null, "e": 32114, "s": 31858, "text": "For creating a new Adapter class navigate to the app > java > your app’s package name > Right-click on it > New Java class and name it as SliderAdapter and add the below code to it. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 32121, "s": 32116, "text": "Java" }, { "code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.RelativeLayout;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.viewpager.widget.PagerAdapter; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class SliderAdapter extends PagerAdapter { // creating variables for layout // inflater, context and array list. LayoutInflater layoutInflater; Context context; ArrayList<SliderModal> sliderModalArrayList; // creating constructor. public SliderAdapter(Context context, ArrayList<SliderModal> sliderModalArrayList) { this.context = context; this.sliderModalArrayList = sliderModalArrayList; } @Override public int getCount() { // inside get count method returning // the size of our array list. return sliderModalArrayList.size(); } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { // inside isViewFrombject method we are // returning our Relative layout object. return view == (RelativeLayout) object; } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { // in this method we will initialize all our layout // items and inflate our layout file as well. layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); // below line is use to inflate the // layout file which we created. View view = layoutInflater.inflate(R.layout.slider_layout, container, false); // initializing our views. ImageView imageView = view.findViewById(R.id.idIV); TextView titleTV = view.findViewById(R.id.idTVtitle); TextView headingTV = view.findViewById(R.id.idTVheading); RelativeLayout sliderRL = view.findViewById(R.id.idRLSlider); // setting data to our views. SliderModal modal = sliderModalArrayList.get(position); titleTV.setText(modal.getTitle()); headingTV.setText(modal.getHeading()); Picasso.get().load(modal.getImgUrl()).into(imageView); // below line is to set background // drawable to our each item sliderRL.setBackground(context.getResources().getDrawable(modal.getBackgroundDrawable())); // after setting the data to our views we // are adding the view to our container. container.addView(view); // at last we are // returning the view. return view; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { // this is a destroy view method // which is use to remove a view. container.removeView((RelativeLayout) object); }}", "e": 35053, "s": 32121, "text": null }, { "code": null, "e": 35131, "s": 35056, "text": "Step 8: Creating custom gradient drawable for our background of each slide" }, { "code": null, "e": 35287, "s": 35133, "text": "Navigate to the app > res > drawable > Right-click on it > New > drawable resource file and name the file as gradient_one and add the below code to it. " }, { "code": null, "e": 35306, "s": 35287, "text": "gradient_one.xml " }, { "code": null, "e": 35310, "s": 35306, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\"> <gradient android:angle=\"90\" android:endColor=\"@color/purple_500\" android:startColor=\"#4B6CD6\" /></shape>", "e": 35574, "s": 35310, "text": null }, { "code": null, "e": 35591, "s": 35574, "text": "gradient_two.xml" }, { "code": null, "e": 35595, "s": 35591, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\"> <gradient android:angle=\"90\" android:endColor=\"#FF9800\" android:startColor=\"#F4C22B\" /></shape>", "e": 35849, "s": 35595, "text": null }, { "code": null, "e": 35868, "s": 35849, "text": "gradient_three.xml" }, { "code": null, "e": 35872, "s": 35868, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\"> <gradient android:angle=\"90\" android:endColor=\"#F44336\" android:startColor=\"#FD7B52\" /></shape>", "e": 36126, "s": 35872, "text": null }, { "code": null, "e": 36174, "s": 36126, "text": "Step 9: Working with the MainActivity.java file" }, { "code": null, "e": 36364, "s": 36174, "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": 36369, "s": 36364, "text": "Java" }, { "code": "import android.os.Bundle;import android.text.Html;import android.widget.LinearLayout;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity;import androidx.viewpager.widget.ViewPager; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating variables for view pager, // liner layout, adapter and our array list. private ViewPager viewPager; private LinearLayout dotsLL; SliderAdapter adapter; private ArrayList<SliderModal> sliderModalArrayList; private TextView[] dots; int size; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing all our views. viewPager = findViewById(R.id.idViewPager); dotsLL = findViewById(R.id.idLLDots); // in below line we are creating a new array list. sliderModalArrayList = new ArrayList<>(); // on below 3 lines we are adding data to our array list. sliderModalArrayList.add(new SliderModal(\"Slide 1 \", \"Slide 1 heading\", \"https://images.unsplash.com/photo-1610842546881-b282c580b51d?ixid=MXwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw5fHx8ZW58MHx8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60\", R.drawable.gradient_one)); sliderModalArrayList.add(new SliderModal(\"Slide 2 \", \"Slide 2 heading\", \"https://images.unsplash.com/photo-1610783131813-475d08664ef6?ixid=MXwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxMnx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60\", R.drawable.gradient_two)); sliderModalArrayList.add(new SliderModal(\"Slide 3 \", \"Slide 3 heading\", \"https://images.unsplash.com/photo-1610832958506-aa56368176cf?ixid=MXwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxN3x8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60\", R.drawable.gradient_three)); // below line is use to add our array list to adapter class. adapter = new SliderAdapter(MainActivity.this, sliderModalArrayList); // below line is use to set our // adapter to our view pager. viewPager.setAdapter(adapter); // we are storing the size of our // array list in a variable. size = sliderModalArrayList.size(); // calling method to add dots indicator addDots(size, 0); // below line is use to call on // page change listener method. viewPager.addOnPageChangeListener(viewListner); } private void addDots(int size, int pos) { // inside this method we are // creating a new text view. dots = new TextView[size]; // below line is use to remove all // the views from the linear layout. dotsLL.removeAllViews(); // running a for loop to add // number of dots to our slider. for (int i = 0; i < size; i++) { // below line is use to add the // dots and modify its color. dots[i] = new TextView(this); dots[i].setText(Html.fromHtml(\"•\")); dots[i].setTextSize(35); // below line is called when the dots are not selected. dots[i].setTextColor(getResources().getColor(R.color.black)); dotsLL.addView(dots[i]); } if (dots.length > 0) { // this line is called when the dots // inside linear layout are selected dots[pos].setTextColor(getResources().getColor(R.color.purple_200)); } } // creating a method for view pager for on page change listener. ViewPager.OnPageChangeListener viewListner = new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { // we are calling our dots method to // change the position of selected dots. addDots(size, position); } @Override public void onPageScrollStateChanged(int state) { } };}", "e": 40507, "s": 36369, "text": null }, { "code": null, "e": 40595, "s": 40510, "text": "Now run your app and see the output of the app. Make sure to keep your Internet On. " }, { "code": null, "e": 40611, "s": 40599, "text": "anikaseth98" }, { "code": null, "e": 40619, "s": 40611, "text": "android" }, { "code": null, "e": 40643, "s": 40619, "text": "Technical Scripter 2020" }, { "code": null, "e": 40651, "s": 40643, "text": "Android" }, { "code": null, "e": 40656, "s": 40651, "text": "Java" }, { "code": null, "e": 40675, "s": 40656, "text": "Technical Scripter" }, { "code": null, "e": 40680, "s": 40675, "text": "Java" }, { "code": null, "e": 40688, "s": 40680, "text": "Android" }, { "code": null, "e": 40786, "s": 40688, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40795, "s": 40786, "text": "Comments" }, { "code": null, "e": 40808, "s": 40795, "text": "Old Comments" }, { "code": null, "e": 40847, "s": 40808, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 40897, "s": 40847, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 40948, "s": 40897, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 40986, "s": 40948, "text": "Android Listview in Java with Example" }, { "code": null, "e": 41028, "s": 40986, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 41043, "s": 41028, "text": "Arrays in Java" }, { "code": null, "e": 41087, "s": 41043, "text": "Split() String method in Java with examples" }, { "code": null, "e": 41109, "s": 41087, "text": "For-each loop in Java" }, { "code": null, "e": 41134, "s": 41109, "text": "Reverse a string in Java" } ]
Iterator vs Collection in Java - GeeksforGeeks
16 Sep, 2021 Iterator and Collection, both has helped and comforted the programmers at many a times. But there usage and application has a very wide difference. 1. Iterator Declaration public interface Iterator Type Parameters: E - the type of elements returned by this iterator Iterators are used in Collection framework in Java to retrieve elements one by one. Method Summary 2. Collection Declaration: public interface Collection<E> extends Iterable<E> Type Parameters: E - the type of elements returned by this iterator A Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit. Method Summary Iterator Vs. Collection Iterator can only move to next() element or remove() an element. However Collection can add(), iterate, remove() or clear() the elements of the collection. Iterator provides a better speed than Collections, as the Iterator interface has limited number of operations. java.sql.SQLException extends Iterable. Hence it allows the caller to safely iterate over causes of SQLException. Using a collection, in this case, would be expensive because, in a chain of n exceptions, use of a collection in the SQLException interface would potentially require the construction of O(n^2) elements. However, use of Iterable provides O(n) access to the exception chain. chhabradhanvi Java - util package Java-Collections Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25249, "s": 25221, "text": "\n16 Sep, 2021" }, { "code": null, "e": 25398, "s": 25249, "text": "Iterator and Collection, both has helped and comforted the programmers at many a times. But there usage and application has a very wide difference. " }, { "code": null, "e": 25411, "s": 25398, "text": "1. Iterator " }, { "code": null, "e": 25424, "s": 25411, "text": "Declaration " }, { "code": null, "e": 25519, "s": 25424, "text": "public interface Iterator\n\nType Parameters:\nE - the type of elements returned by this iterator" }, { "code": null, "e": 25604, "s": 25519, "text": "Iterators are used in Collection framework in Java to retrieve elements one by one. " }, { "code": null, "e": 25620, "s": 25604, "text": "Method Summary " }, { "code": null, "e": 25635, "s": 25620, "text": "2. Collection " }, { "code": null, "e": 25649, "s": 25635, "text": "Declaration: " }, { "code": null, "e": 25769, "s": 25649, "text": "public interface Collection<E> extends Iterable<E>\n\nType Parameters:\nE - the type of elements returned by this iterator" }, { "code": null, "e": 25976, "s": 25769, "text": "A Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit. " }, { "code": null, "e": 25992, "s": 25976, "text": "Method Summary " }, { "code": null, "e": 26018, "s": 25992, "text": "Iterator Vs. Collection " }, { "code": null, "e": 26175, "s": 26018, "text": "Iterator can only move to next() element or remove() an element. However Collection can add(), iterate, remove() or clear() the elements of the collection. " }, { "code": null, "e": 26287, "s": 26175, "text": "Iterator provides a better speed than Collections, as the Iterator interface has limited number of operations. " }, { "code": null, "e": 26676, "s": 26287, "text": "java.sql.SQLException extends Iterable. Hence it allows the caller to safely iterate over causes of SQLException. Using a collection, in this case, would be expensive because, in a chain of n exceptions, use of a collection in the SQLException interface would potentially require the construction of O(n^2) elements. However, use of Iterable provides O(n) access to the exception chain. " }, { "code": null, "e": 26692, "s": 26678, "text": "chhabradhanvi" }, { "code": null, "e": 26712, "s": 26692, "text": "Java - util package" }, { "code": null, "e": 26729, "s": 26712, "text": "Java-Collections" }, { "code": null, "e": 26734, "s": 26729, "text": "Java" }, { "code": null, "e": 26739, "s": 26734, "text": "Java" }, { "code": null, "e": 26756, "s": 26739, "text": "Java-Collections" }, { "code": null, "e": 26854, "s": 26756, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26869, "s": 26854, "text": "Stream In Java" }, { "code": null, "e": 26890, "s": 26869, "text": "Constructors in Java" }, { "code": null, "e": 26909, "s": 26890, "text": "Exceptions in Java" }, { "code": null, "e": 26939, "s": 26909, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26985, "s": 26939, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27002, "s": 26985, "text": "Generics in Java" }, { "code": null, "e": 27023, "s": 27002, "text": "Introduction to Java" }, { "code": null, "e": 27066, "s": 27023, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27102, "s": 27066, "text": "Internal Working of HashMap in Java" } ]
How to use margin, border and padding to fit together in the box model ? - GeeksforGeeks
16 Nov, 2021 In this article, we will learn how the different parts of the box i.e., margin, border, padding & content fits together to create the box. The box model specifies how the HTML elements are organized & modeled in the browser engine along with deriving the CSS properties that define the dimension for the HTML elements. The box model can be described as a rectangular box that is generated for the HTML elements which forms a document tree. The box model has 4 main properties – margin, border, padding & content, which help to create the design and determine the layout of web pages. These properties can be given as: content: This is one of the main part of the box model that contains text, images, videos, links, etc, which can be resized using the height and width property. padding: It is the property used to create space around the content inside the bordered region. border: It covers the area under content, including the padding around the content. margin: This property refers to creating space around the element ie., around the border area. A simple box model contains a content, border, and the external space outside the border the box requires. This external space is given by margin, which separates the box from other boxes. When we create a box container, we can specify the distance between the border and inside content, which is given by padding. The width and color of the border can be given by the border attribute. Example: This example describes the basics of the Box model in CSS. HTML <!DOCTYPE html><html> <head> <title>Box</title> <style> .box { background-color: rgb(233, 141, 20); margin-top: 80px; margin-left: 5rem; width: 20rem; color: blueviolet; text-align: center; font-size: 50px; border: 7px solid red; padding: 6rem; } body { background-color: yellow; } </style></head> <body> <div class="box"> Welcome to GeeksforGeeks </div></body> </html> Output: CSS Box model Consider the below code example for setting the width & height property of an element: .box { margin: 100px 20px 50px 370px; width: 350px; height: 50px; font-size: 50px; border: 10px solid red; padding: 160px; } The total height and width of the box can be found after adding the following properties as: Box width = width + (left padding + right padding) + (left border + right border) + (left margin + right margin) Box height = height + (top padding + bottom padding) + (top border + bottom border) + (top margin + bottom margin) Thus, Total width = 350+(160+160)+(10+10)+(370+20) = 1080px and Total height = 50+(160+160)+(10+10)+(100+50) = 540px Padding property: CSS paddings are used to create space around the element, inside any defined border. We can set different paddings for individual sides(top, right, bottom, left). It is important to add border properties to implement padding properties. Syntax: padding: "padding-top|padding-right|padding-bottom|padding-left"; It consists of 4 components: padding-top: Specifies padding width in the box above the content padding-right: Specifies padding width in the box at the right of the content padding-bottom: Specifies padding width in the box below the content padding-left: Specifies padding width in the box at the left of the content Example: padding: 20px 30px 50px 70px; We can also write padding: 40px; This sets default padding of 40px on all four directions inside the box. Border property: It is a combination of three properties. Syntax: border : "width style color | initial | inherit"; Property values: width: This specifies the thickness of the border style: This specifies the outlook of the border, be it solid, dashed, dotted, double, groove, inset, etc. color: This specifies the color of the border The default value is initial. Example: border: 10px solid red; Margin property: It has four individual margin properties: Syntax: margin: "top-margin right-margin bottom-margin left-margin"; top-margin: Specifies margin width at the top of the box right-margin: Specifies margin width at the right of the box bottom-margin: Specifies margin width at bottom of the box left-margin: Specifies margin width at the left of the box We can write individually or in a single line. Example: margin: 100px 20px 50px 370px; If we write margin: 20px; It sets a default margin of 20px on all 4 sides of the reference object We can understand the box model from the following examples: Example 1: This example describes the Padding and Border properties. HTML <!DOCTYPE html> <head> <title>Padding</title> <style> .main { font-size: 38px; font-weight: bold; Text-align: center; } .box { margin-left: 500px; border: 50px solid #059900; width: 300px; height: 200px; text-align: center; padding: 50px; } .box1 { font-size: 42px; font-weight: bold; color: #000000; margin-top: 60px; background-color: #d9c5db; } </style></head> <body> <div class="main">CSS Padding and Border</div> <div class="box"> <div class="box1">GeeksforGeeks</div> </div></body> </html> Output: Green Border and white padding around the content area Example 2: The following code illustrates the Margin property of the box model. HTML <!DOCTYPE html> <head> <title>Padding</title> <style> .main { font-size: 38px; font-weight: bold; Text-align: center; } .box { margin-left: 500px; border: 50px solid #059900; width: 300px; height: 200px; text-align: center; padding: 50px; margin-top: 180px; } .box1 { font-size: 42px; font-weight: bold; color: #000000; margin-top: 60px; } </style></head> <body> <div class="main">CSS Margin Property</div> <div class="box"> <div class="box1">GeeksforGeeks</div> </div></body> </html> Output: Margin applied at top of the box model CSS-Properties CSS-Questions HTML-Questions Picked CSS Web Technologies 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 style a checkbox using CSS? 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": 26621, "s": 26593, "text": "\n16 Nov, 2021" }, { "code": null, "e": 27239, "s": 26621, "text": "In this article, we will learn how the different parts of the box i.e., margin, border, padding & content fits together to create the box. The box model specifies how the HTML elements are organized & modeled in the browser engine along with deriving the CSS properties that define the dimension for the HTML elements. The box model can be described as a rectangular box that is generated for the HTML elements which forms a document tree. The box model has 4 main properties – margin, border, padding & content, which help to create the design and determine the layout of web pages. These properties can be given as:" }, { "code": null, "e": 27400, "s": 27239, "text": "content: This is one of the main part of the box model that contains text, images, videos, links, etc, which can be resized using the height and width property." }, { "code": null, "e": 27496, "s": 27400, "text": "padding: It is the property used to create space around the content inside the bordered region." }, { "code": null, "e": 27580, "s": 27496, "text": "border: It covers the area under content, including the padding around the content." }, { "code": null, "e": 27675, "s": 27580, "text": "margin: This property refers to creating space around the element ie., around the border area." }, { "code": null, "e": 28063, "s": 27675, "text": "A simple box model contains a content, border, and the external space outside the border the box requires. This external space is given by margin, which separates the box from other boxes. When we create a box container, we can specify the distance between the border and inside content, which is given by padding. The width and color of the border can be given by the border attribute. " }, { "code": null, "e": 28131, "s": 28063, "text": "Example: This example describes the basics of the Box model in CSS." }, { "code": null, "e": 28136, "s": 28131, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Box</title> <style> .box { background-color: rgb(233, 141, 20); margin-top: 80px; margin-left: 5rem; width: 20rem; color: blueviolet; text-align: center; font-size: 50px; border: 7px solid red; padding: 6rem; } body { background-color: yellow; } </style></head> <body> <div class=\"box\"> Welcome to GeeksforGeeks </div></body> </html>", "e": 28671, "s": 28136, "text": null }, { "code": null, "e": 28679, "s": 28671, "text": "Output:" }, { "code": null, "e": 28693, "s": 28679, "text": "CSS Box model" }, { "code": null, "e": 28780, "s": 28693, "text": "Consider the below code example for setting the width & height property of an element:" }, { "code": null, "e": 28917, "s": 28780, "text": ".box {\n margin: 100px 20px 50px 370px;\n width: 350px;\n height: 50px;\n font-size: 50px;\n border: 10px solid red;\n padding: 160px;\n}" }, { "code": null, "e": 29010, "s": 28917, "text": "The total height and width of the box can be found after adding the following properties as:" }, { "code": null, "e": 29123, "s": 29010, "text": "Box width = width + (left padding + right padding) + (left border + right border) + (left margin + right margin)" }, { "code": null, "e": 29238, "s": 29123, "text": "Box height = height + (top padding + bottom padding) + (top border + bottom border) + (top margin + bottom margin)" }, { "code": null, "e": 29298, "s": 29238, "text": "Thus, Total width = 350+(160+160)+(10+10)+(370+20) = 1080px" }, { "code": null, "e": 29355, "s": 29298, "text": "and Total height = 50+(160+160)+(10+10)+(100+50) = 540px" }, { "code": null, "e": 29610, "s": 29355, "text": "Padding property: CSS paddings are used to create space around the element, inside any defined border. We can set different paddings for individual sides(top, right, bottom, left). It is important to add border properties to implement padding properties." }, { "code": null, "e": 29618, "s": 29610, "text": "Syntax:" }, { "code": null, "e": 29684, "s": 29618, "text": "padding: \"padding-top|padding-right|padding-bottom|padding-left\";" }, { "code": null, "e": 29713, "s": 29684, "text": "It consists of 4 components:" }, { "code": null, "e": 29779, "s": 29713, "text": "padding-top: Specifies padding width in the box above the content" }, { "code": null, "e": 29857, "s": 29779, "text": "padding-right: Specifies padding width in the box at the right of the content" }, { "code": null, "e": 29926, "s": 29857, "text": "padding-bottom: Specifies padding width in the box below the content" }, { "code": null, "e": 30002, "s": 29926, "text": "padding-left: Specifies padding width in the box at the left of the content" }, { "code": null, "e": 30011, "s": 30002, "text": "Example:" }, { "code": null, "e": 30041, "s": 30011, "text": "padding: 20px 30px 50px 70px;" }, { "code": null, "e": 30059, "s": 30041, "text": "We can also write" }, { "code": null, "e": 30074, "s": 30059, "text": "padding: 40px;" }, { "code": null, "e": 30147, "s": 30074, "text": "This sets default padding of 40px on all four directions inside the box." }, { "code": null, "e": 30205, "s": 30147, "text": "Border property: It is a combination of three properties." }, { "code": null, "e": 30213, "s": 30205, "text": "Syntax:" }, { "code": null, "e": 30263, "s": 30213, "text": "border : \"width style color | initial | inherit\";" }, { "code": null, "e": 30280, "s": 30263, "text": "Property values:" }, { "code": null, "e": 30330, "s": 30280, "text": "width: This specifies the thickness of the border" }, { "code": null, "e": 30436, "s": 30330, "text": "style: This specifies the outlook of the border, be it solid, dashed, dotted, double, groove, inset, etc." }, { "code": null, "e": 30482, "s": 30436, "text": "color: This specifies the color of the border" }, { "code": null, "e": 30512, "s": 30482, "text": "The default value is initial." }, { "code": null, "e": 30522, "s": 30512, "text": "Example: " }, { "code": null, "e": 30546, "s": 30522, "text": "border: 10px solid red;" }, { "code": null, "e": 30605, "s": 30546, "text": "Margin property: It has four individual margin properties:" }, { "code": null, "e": 30613, "s": 30605, "text": "Syntax:" }, { "code": null, "e": 30674, "s": 30613, "text": "margin: \"top-margin right-margin bottom-margin left-margin\";" }, { "code": null, "e": 30731, "s": 30674, "text": "top-margin: Specifies margin width at the top of the box" }, { "code": null, "e": 30792, "s": 30731, "text": "right-margin: Specifies margin width at the right of the box" }, { "code": null, "e": 30851, "s": 30792, "text": "bottom-margin: Specifies margin width at bottom of the box" }, { "code": null, "e": 30910, "s": 30851, "text": "left-margin: Specifies margin width at the left of the box" }, { "code": null, "e": 30957, "s": 30910, "text": "We can write individually or in a single line." }, { "code": null, "e": 30966, "s": 30957, "text": "Example:" }, { "code": null, "e": 30997, "s": 30966, "text": "margin: 100px 20px 50px 370px;" }, { "code": null, "e": 31010, "s": 30997, "text": "If we write " }, { "code": null, "e": 31024, "s": 31010, "text": "margin: 20px;" }, { "code": null, "e": 31096, "s": 31024, "text": "It sets a default margin of 20px on all 4 sides of the reference object" }, { "code": null, "e": 31157, "s": 31096, "text": "We can understand the box model from the following examples:" }, { "code": null, "e": 31226, "s": 31157, "text": "Example 1: This example describes the Padding and Border properties." }, { "code": null, "e": 31231, "s": 31226, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <title>Padding</title> <style> .main { font-size: 38px; font-weight: bold; Text-align: center; } .box { margin-left: 500px; border: 50px solid #059900; width: 300px; height: 200px; text-align: center; padding: 50px; } .box1 { font-size: 42px; font-weight: bold; color: #000000; margin-top: 60px; background-color: #d9c5db; } </style></head> <body> <div class=\"main\">CSS Padding and Border</div> <div class=\"box\"> <div class=\"box1\">GeeksforGeeks</div> </div></body> </html>", "e": 31889, "s": 31231, "text": null }, { "code": null, "e": 31897, "s": 31889, "text": "Output:" }, { "code": null, "e": 31952, "s": 31897, "text": "Green Border and white padding around the content area" }, { "code": null, "e": 32032, "s": 31952, "text": "Example 2: The following code illustrates the Margin property of the box model." }, { "code": null, "e": 32037, "s": 32032, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <title>Padding</title> <style> .main { font-size: 38px; font-weight: bold; Text-align: center; } .box { margin-left: 500px; border: 50px solid #059900; width: 300px; height: 200px; text-align: center; padding: 50px; margin-top: 180px; } .box1 { font-size: 42px; font-weight: bold; color: #000000; margin-top: 60px; } </style></head> <body> <div class=\"main\">CSS Margin Property</div> <div class=\"box\"> <div class=\"box1\">GeeksforGeeks</div> </div></body> </html>", "e": 32682, "s": 32037, "text": null }, { "code": null, "e": 32690, "s": 32682, "text": "Output:" }, { "code": null, "e": 32729, "s": 32690, "text": "Margin applied at top of the box model" }, { "code": null, "e": 32744, "s": 32729, "text": "CSS-Properties" }, { "code": null, "e": 32758, "s": 32744, "text": "CSS-Questions" }, { "code": null, "e": 32773, "s": 32758, "text": "HTML-Questions" }, { "code": null, "e": 32780, "s": 32773, "text": "Picked" }, { "code": null, "e": 32784, "s": 32780, "text": "CSS" }, { "code": null, "e": 32801, "s": 32784, "text": "Web Technologies" }, { "code": null, "e": 32899, "s": 32801, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32936, "s": 32899, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 32975, "s": 32936, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 33004, "s": 32975, "text": "Form validation using jQuery" }, { "code": null, "e": 33046, "s": 33004, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 33081, "s": 33046, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 33121, "s": 33081, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33154, "s": 33121, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33199, "s": 33154, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33242, "s": 33199, "text": "How to fetch data from an API in ReactJS ?" } ]
Efficiency of CSMA/CD - GeeksforGeeks
06 Apr, 2022 Prerequisite – Introduction to Ethernet, Basics of CSMA/ CD Carrier sense multiple access with collision detection (CSMA/CD) – The CSMA method does not tell us what to do in case there is a collision. Carrier sense multiple access with collision detection (CSMA/CD) adds to the CSMA algorithm to deal with the collision. In CSMA/CD, the size of a frame must be large enough so that collision can be detected by the sender while sending the frame. So, the frame transmission delay must be at least two times the maximum propagation delay. Assume some station transmitted data packet and successfully get to the destination but it is just the Best Case, so we have to take the Worst Case scenario in which there will be contention slots. Contention slots are those slots that are not able to transmit their journey due to the collision. Suppose A station transmitted data but collide and the worst-case time wasted is 2Tp and then some station B found out a way to transmit the data so it took (As shown in Figure) Tp ( propagation delay) + Tt(transmission time) Now we don’t know how many contention slots, so we consider the worst-case to be of n contention slots. Efficiency = Tt / ( C*2*Tp + Tt + Tp) Tt ? transmission time Tp ? propagation time C ? number of collision In CSMA/CD, for success, only 1 station should transmit while others shouldn’t. Let p be the probability to transmit data successfully. P(success) = nC1 * p * (1-p)n-1 (by using Binomial distribution) For max P(success), differentiate with respect to p and equate to zero (to get maxima and minima). We get P(max) = 1/e Number of times we need to try before getting 1st success 1/P(MAX) = 1/(1/e) = e Here number of times we need to try (C) = e. Put a = Tt/Tp and divide by T in Efficiency = Tt / (C* 2 * Tp + Tt + Tp) We get, Efficiency = 1/(e*2a + 1 + a) a = Tp/Tt e = 2.72 Now Efficiency = 1/( 1 + 6.44a) Further Analysis of Efficiency : Efficiency = 1/ (1 + 6.44a) = 1/ {1 + 6.44(Tp/Tt)} = 1/ {1 + 6.44((distance/speed)/(packet length/Bandwidth))} = 1/ {1+ 6.44 ((distance * bandwidth)/ (speed*packet length))} From this derivation, we can conclude many relations : If distance increases, the efficiency of CSMA decreases. CSMA is not suitable for long-distance networks like WAN but works optimally for LAN. If the length of the packet is bigger, the efficiency of CSMA also increases; but the maximum limit for length is 1500 Bytes. Transmission Time >= 2*Propagation Time GATE CS Corner Questions Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them. GATE CS 2003, Question 90GATE CS 2015 (Set 3), Question 65GATE IT 2005, Question 27GATE IT 2005, Question 71GATE CS 2016 (Set 2), Question 63GATE IT 2008, Question 63 GATE CS 2003, Question 90 GATE CS 2015 (Set 3), Question 65 GATE IT 2005, Question 27 GATE IT 2005, Question 71 GATE CS 2016 (Set 2), Question 63 GATE IT 2008, Question 63 Reference – https://www.youtube.com/watch?v=74zlRH-bj2c This article is contributed by Akash Sharan. 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. Akanksha_Rai gokutn raja11sep Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between IPv4 and IPv6 Socket Programming in Python Caesar Cipher in Cryptography UDP Server-Client implementation in C Socket Programming in Java ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS Page Replacement Algorithms in Operating Systems Cache Memory in Computer Organization
[ { "code": null, "e": 37839, "s": 37811, "text": "\n06 Apr, 2022" }, { "code": null, "e": 38852, "s": 37839, "text": "Prerequisite – Introduction to Ethernet, Basics of CSMA/ CD Carrier sense multiple access with collision detection (CSMA/CD) – The CSMA method does not tell us what to do in case there is a collision. Carrier sense multiple access with collision detection (CSMA/CD) adds to the CSMA algorithm to deal with the collision. In CSMA/CD, the size of a frame must be large enough so that collision can be detected by the sender while sending the frame. So, the frame transmission delay must be at least two times the maximum propagation delay. Assume some station transmitted data packet and successfully get to the destination but it is just the Best Case, so we have to take the Worst Case scenario in which there will be contention slots. Contention slots are those slots that are not able to transmit their journey due to the collision. Suppose A station transmitted data but collide and the worst-case time wasted is 2Tp and then some station B found out a way to transmit the data so it took (As shown in Figure)" }, { "code": null, "e": 38900, "s": 38852, "text": "Tp ( propagation delay) + Tt(transmission time)" }, { "code": null, "e": 39004, "s": 38900, "text": "Now we don’t know how many contention slots, so we consider the worst-case to be of n contention slots." }, { "code": null, "e": 39114, "s": 39004, "text": "Efficiency = Tt / ( C*2*Tp + Tt + Tp) \nTt ? transmission time\nTp ? propagation time\nC ? number of collision" }, { "code": null, "e": 39251, "s": 39114, "text": " In CSMA/CD, for success, only 1 station should transmit while others shouldn’t. Let p be the probability to transmit data successfully." }, { "code": null, "e": 39316, "s": 39251, "text": "P(success) = nC1 * p * (1-p)n-1 (by using Binomial distribution)" }, { "code": null, "e": 39415, "s": 39316, "text": "For max P(success), differentiate with respect to p and equate to zero (to get maxima and minima)." }, { "code": null, "e": 39436, "s": 39415, "text": "We get P(max) = 1/e " }, { "code": null, "e": 39494, "s": 39436, "text": "Number of times we need to try before getting 1st success" }, { "code": null, "e": 39517, "s": 39494, "text": "1/P(MAX) = 1/(1/e) = e" }, { "code": null, "e": 39643, "s": 39517, "text": "Here number of times we need to try (C) = e. Put a = Tt/Tp and divide by T in Efficiency = Tt / (C* 2 * Tp + Tt + Tp) We get," }, { "code": null, "e": 39726, "s": 39643, "text": "Efficiency = 1/(e*2a + 1 + a)\na = Tp/Tt\ne = 2.72\n\nNow \nEfficiency = 1/( 1 + 6.44a)" }, { "code": null, "e": 39760, "s": 39726, "text": "Further Analysis of Efficiency : " }, { "code": null, "e": 39981, "s": 39760, "text": "Efficiency = 1/ (1 + 6.44a)\n\n = 1/ {1 + 6.44(Tp/Tt)}\n\n = 1/ {1 + 6.44((distance/speed)/(packet length/Bandwidth))}\n \n = 1/ {1+ 6.44 ((distance * bandwidth)/ (speed*packet length))}" }, { "code": null, "e": 40036, "s": 39981, "text": "From this derivation, we can conclude many relations :" }, { "code": null, "e": 40093, "s": 40036, "text": "If distance increases, the efficiency of CSMA decreases." }, { "code": null, "e": 40179, "s": 40093, "text": "CSMA is not suitable for long-distance networks like WAN but works optimally for LAN." }, { "code": null, "e": 40305, "s": 40179, "text": "If the length of the packet is bigger, the efficiency of CSMA also increases; but the maximum limit for length is 1500 Bytes." }, { "code": null, "e": 40345, "s": 40305, "text": "Transmission Time >= 2*Propagation Time" }, { "code": null, "e": 40568, "s": 40345, "text": "GATE CS Corner Questions Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them." }, { "code": null, "e": 40735, "s": 40568, "text": "GATE CS 2003, Question 90GATE CS 2015 (Set 3), Question 65GATE IT 2005, Question 27GATE IT 2005, Question 71GATE CS 2016 (Set 2), Question 63GATE IT 2008, Question 63" }, { "code": null, "e": 40761, "s": 40735, "text": "GATE CS 2003, Question 90" }, { "code": null, "e": 40795, "s": 40761, "text": "GATE CS 2015 (Set 3), Question 65" }, { "code": null, "e": 40821, "s": 40795, "text": "GATE IT 2005, Question 27" }, { "code": null, "e": 40847, "s": 40821, "text": "GATE IT 2005, Question 71" }, { "code": null, "e": 40881, "s": 40847, "text": "GATE CS 2016 (Set 2), Question 63" }, { "code": null, "e": 40907, "s": 40881, "text": "GATE IT 2008, Question 63" }, { "code": null, "e": 41384, "s": 40907, "text": "Reference – https://www.youtube.com/watch?v=74zlRH-bj2c This article is contributed by Akash Sharan. 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": 41397, "s": 41384, "text": "Akanksha_Rai" }, { "code": null, "e": 41404, "s": 41397, "text": "gokutn" }, { "code": null, "e": 41414, "s": 41404, "text": "raja11sep" }, { "code": null, "e": 41432, "s": 41414, "text": "Computer Networks" }, { "code": null, "e": 41440, "s": 41432, "text": "GATE CS" }, { "code": null, "e": 41458, "s": 41440, "text": "Computer Networks" }, { "code": null, "e": 41556, "s": 41458, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41590, "s": 41556, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 41619, "s": 41590, "text": "Socket Programming in Python" }, { "code": null, "e": 41649, "s": 41619, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 41687, "s": 41649, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 41714, "s": 41687, "text": "Socket Programming in Java" }, { "code": null, "e": 41738, "s": 41714, "text": "ACID Properties in DBMS" }, { "code": null, "e": 41765, "s": 41738, "text": "Types of Operating Systems" }, { "code": null, "e": 41786, "s": 41765, "text": "Normal Forms in DBMS" }, { "code": null, "e": 41835, "s": 41786, "text": "Page Replacement Algorithms in Operating Systems" } ]
React JS useRef Hook - GeeksforGeeks
19 Oct, 2021 The useRef hook is the new addition in React 16.8. Before proceeding to this article there is a prerequisite to know about the ref in react.The useRef is a hook that allows to directly create a reference to the DOM element in the functional component. Syntax: const refContainer = useRef(initialValue); The useRef returns a mutable ref object. This object has a property called .current. The value is persisted in the refContainer.current property. These values are accessed from the current property of the returned object. The .current property could be initialised to the passed argument initialValue e.g. useRef(initialValue). The object can persist a value for a full lifetime of the component. Example: How to access the DOM using useRef hook. Javascript import React, {Fragment, useRef} from 'react'; function App() { // Creating a ref object using useRef hook const focusPoint = useRef(null); const onClickHandler = () => { focusPoint.current.value = "The quick brown fox jumps over the lazy dog"; focusPoint.current.focus(); }; return ( <Fragment> <div> <button onClick={onClickHandler}> ACTION </button> </div> <label> Click on the action button to focus and populate the text. </label><br/> <textarea ref={focusPoint} /> </Fragment> );}; export default App; Output: In this example, we have a button called ACTION, whenever we click on the button the onClickHandler is getting triggered and it’s focusing the textarea with help of useRef hook. The focusPoint is the useRef object which is initialised to null and the value is changing to onClick event. Let’s see the output of the above code. surindertarika1234 mikkey react-js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page? Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ? File uploading in React.js How to apply style to parent if it has child with CSS?
[ { "code": null, "e": 25361, "s": 25333, "text": "\n19 Oct, 2021" }, { "code": null, "e": 25614, "s": 25361, "text": "The useRef hook is the new addition in React 16.8. Before proceeding to this article there is a prerequisite to know about the ref in react.The useRef is a hook that allows to directly create a reference to the DOM element in the functional component. " }, { "code": null, "e": 25622, "s": 25614, "text": "Syntax:" }, { "code": null, "e": 25665, "s": 25622, "text": "const refContainer = useRef(initialValue);" }, { "code": null, "e": 26063, "s": 25665, "text": "The useRef returns a mutable ref object. This object has a property called .current. The value is persisted in the refContainer.current property. These values are accessed from the current property of the returned object. The .current property could be initialised to the passed argument initialValue e.g. useRef(initialValue). The object can persist a value for a full lifetime of the component. " }, { "code": null, "e": 26113, "s": 26063, "text": "Example: How to access the DOM using useRef hook." }, { "code": null, "e": 26124, "s": 26113, "text": "Javascript" }, { "code": "import React, {Fragment, useRef} from 'react'; function App() { // Creating a ref object using useRef hook const focusPoint = useRef(null); const onClickHandler = () => { focusPoint.current.value = \"The quick brown fox jumps over the lazy dog\"; focusPoint.current.focus(); }; return ( <Fragment> <div> <button onClick={onClickHandler}> ACTION </button> </div> <label> Click on the action button to focus and populate the text. </label><br/> <textarea ref={focusPoint} /> </Fragment> );}; export default App;", "e": 26717, "s": 26124, "text": null }, { "code": null, "e": 27055, "s": 26720, "text": "Output: In this example, we have a button called ACTION, whenever we click on the button the onClickHandler is getting triggered and it’s focusing the textarea with help of useRef hook. The focusPoint is the useRef object which is initialised to null and the value is changing to onClick event. Let’s see the output of the above code." }, { "code": null, "e": 27078, "s": 27059, "text": "surindertarika1234" }, { "code": null, "e": 27085, "s": 27078, "text": "mikkey" }, { "code": null, "e": 27094, "s": 27085, "text": "react-js" }, { "code": null, "e": 27111, "s": 27094, "text": "Web Technologies" }, { "code": null, "e": 27209, "s": 27111, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27249, "s": 27209, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27294, "s": 27249, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27337, "s": 27294, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27398, "s": 27337, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27470, "s": 27398, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27528, "s": 27470, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 27561, "s": 27528, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 27621, "s": 27561, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27648, "s": 27621, "text": "File uploading in React.js" } ]
Concatenate two given factor in a single factor in R - GeeksforGeeks
23 May, 2021 The factor variables in R programming can be combined to form vectors and lists. Concatenation of factor type objects is not possible like the primitive concatenation operations, since they do not preserve the “factor” class of variables, which may lead to data ambiguity. The class of any storage object in R programming can be fetched using sapply() method, which returns the data type or mode to which an object belongs. Syntax: sapply(X, FUN) Parameters:X: A vector or an objectFUN: Function applied to each element of x as.factor() method is used to specify a column vector in factor format rather than being numeric. The two input factors can be declared using the vector explicitly mapped to factors using this method. unlist() method in R language is used to provide conversion from a list object to vector. It simplifies to produce a vector by preserving all components, that is the class of the elements is preserved. Syntax: unlist( x ) where x is a list or vector This approach preserves the data and its corresponding levels. The data is concatenated in the order in with it is specified in the list() method. Example: R fac1 <- as.factor(c(1:5))print ("Factor1 : ")print (fac1)sapply(fac1,class) fac2 <- as.factor(c(8:10))print ("Factor2 : ")print (fac2)sapply(fac2,class) # combine into one factorcombined <- unlist(list(fac1,fac2))print ("Combined Factor : ")print (combined) sapply(combined,class) Output [1] “Factor1 : “ [1] 1 2 3 4 5 Levels: 1 2 3 4 5 [1] “factor” “factor” “factor” “factor” “factor” [1] “Factor2 : “ [1] 8 9 10 Levels: 8 9 10 [1] “factor” “factor” “factor” [1] “Combined Factor : “ [1] 1 2 3 4 5 8 9 10 Levels: 1 2 3 4 5 8 9 10 [1] “factor” “factor” “factor” “factor” “factor” “factor” “factor” “factor” Factor type objects belonging to different data types can also be merged together in a singular list of the factor type elements. The levels are preserved in this merge. Example: R fac1 <- as.factor(letters[1:3])print ("Factor1 : ")print (fac1)sapply(fac1,class) fac2 <- as.factor(c(1:4))print ("Factor2 : ")print (fac2)sapply(fac2,class) # combine into one factorcombined <- unlist(list(fac1,fac2))print ("Combined Factor : ")print (combined) sapply(combined,class) Output [1] “Factor1 : “ [1] a b c Levels: a b c [1] “factor” “factor” “factor” [1] “Factor2 : “ [1] 1 2 3 4 Levels: 1 2 3 4 [1] “factor” “factor” “factor” “factor” [1] “Combined Factor : “ [1] a b c 1 2 3 4 Levels: a b c 1 2 3 4 [1] “factor” “factor” “factor” “factor” “factor” “factor” “factor” The levels() method of the specific factor vector can be used to extract the individual levels in the form of independent strings. It returns the number of elements equivalent to the length of the vector. Syntax: levels (fac-vec)[fac-vec] Since, these levels are each returned as strings, therefore they belong to the same data type. Hence, they are combined now to form an atomic vector using the c() method. Syntax: c (vec1 , vec2) where vec1 and vec2 are vectors belonging to same data type Example: R fac1 <- factor(letters[1:3])print ("Factor1 : ")print (fac1)sapply(fac1,class) fac2 <- factor(c(1:4))print ("Factor2 : ")print (fac2)sapply(fac2,class) # extracting levels of factor1level1 <- levels(fac1)[fac1] # extracting levels of factor2level2 <- levels(fac2)[fac2] # combine into one factorcombined <- factor(c( level1,level2 ))print ("Combined Factor : ")print (combined) sapply(combined,class) Output [1] “Factor1 : “ [1] a b c Levels: a b c [1] “factor” “factor” “factor” [1] “Factor2 : “ [1] 1 2 3 4 Levels: 1 2 3 4 [1] “factor” “factor” “factor” “factor” [1] “Combined Factor : “ [1] a b c 1 2 3 4 Levels: 1 2 3 4 a b c [1] “factor” “factor” “factor” “factor” “factor” “factor” “factor” Picked R Factor-Programs R-Factors R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 26487, "s": 26459, "text": "\n23 May, 2021" }, { "code": null, "e": 26761, "s": 26487, "text": "The factor variables in R programming can be combined to form vectors and lists. Concatenation of factor type objects is not possible like the primitive concatenation operations, since they do not preserve the “factor” class of variables, which may lead to data ambiguity. " }, { "code": null, "e": 26912, "s": 26761, "text": "The class of any storage object in R programming can be fetched using sapply() method, which returns the data type or mode to which an object belongs." }, { "code": null, "e": 26935, "s": 26912, "text": "Syntax: sapply(X, FUN)" }, { "code": null, "e": 27013, "s": 26935, "text": "Parameters:X: A vector or an objectFUN: Function applied to each element of x" }, { "code": null, "e": 27215, "s": 27013, "text": "as.factor() method is used to specify a column vector in factor format rather than being numeric. The two input factors can be declared using the vector explicitly mapped to factors using this method. " }, { "code": null, "e": 27418, "s": 27215, "text": "unlist() method in R language is used to provide conversion from a list object to vector. It simplifies to produce a vector by preserving all components, that is the class of the elements is preserved. " }, { "code": null, "e": 27426, "s": 27418, "text": "Syntax:" }, { "code": null, "e": 27438, "s": 27426, "text": "unlist( x )" }, { "code": null, "e": 27466, "s": 27438, "text": "where x is a list or vector" }, { "code": null, "e": 27614, "s": 27466, "text": "This approach preserves the data and its corresponding levels. The data is concatenated in the order in with it is specified in the list() method. " }, { "code": null, "e": 27623, "s": 27614, "text": "Example:" }, { "code": null, "e": 27625, "s": 27623, "text": "R" }, { "code": "fac1 <- as.factor(c(1:5))print (\"Factor1 : \")print (fac1)sapply(fac1,class) fac2 <- as.factor(c(8:10))print (\"Factor2 : \")print (fac2)sapply(fac2,class) # combine into one factorcombined <- unlist(list(fac1,fac2))print (\"Combined Factor : \")print (combined) sapply(combined,class)", "e": 27909, "s": 27625, "text": null }, { "code": null, "e": 27916, "s": 27909, "text": "Output" }, { "code": null, "e": 27933, "s": 27916, "text": "[1] “Factor1 : “" }, { "code": null, "e": 27947, "s": 27933, "text": "[1] 1 2 3 4 5" }, { "code": null, "e": 27965, "s": 27947, "text": "Levels: 1 2 3 4 5" }, { "code": null, "e": 28014, "s": 27965, "text": "[1] “factor” “factor” “factor” “factor” “factor”" }, { "code": null, "e": 28031, "s": 28014, "text": "[1] “Factor2 : “" }, { "code": null, "e": 28044, "s": 28031, "text": "[1] 8 9 10" }, { "code": null, "e": 28059, "s": 28044, "text": "Levels: 8 9 10" }, { "code": null, "e": 28090, "s": 28059, "text": "[1] “factor” “factor” “factor”" }, { "code": null, "e": 28115, "s": 28090, "text": "[1] “Combined Factor : “" }, { "code": null, "e": 28143, "s": 28115, "text": "[1] 1 2 3 4 5 8 9 10" }, { "code": null, "e": 28168, "s": 28143, "text": "Levels: 1 2 3 4 5 8 9 10" }, { "code": null, "e": 28244, "s": 28168, "text": "[1] “factor” “factor” “factor” “factor” “factor” “factor” “factor” “factor”" }, { "code": null, "e": 28415, "s": 28244, "text": "Factor type objects belonging to different data types can also be merged together in a singular list of the factor type elements. The levels are preserved in this merge. " }, { "code": null, "e": 28424, "s": 28415, "text": "Example:" }, { "code": null, "e": 28426, "s": 28424, "text": "R" }, { "code": "fac1 <- as.factor(letters[1:3])print (\"Factor1 : \")print (fac1)sapply(fac1,class) fac2 <- as.factor(c(1:4))print (\"Factor2 : \")print (fac2)sapply(fac2,class) # combine into one factorcombined <- unlist(list(fac1,fac2))print (\"Combined Factor : \")print (combined) sapply(combined,class)", "e": 28715, "s": 28426, "text": null }, { "code": null, "e": 28722, "s": 28715, "text": "Output" }, { "code": null, "e": 28739, "s": 28722, "text": "[1] “Factor1 : “" }, { "code": null, "e": 28749, "s": 28739, "text": "[1] a b c" }, { "code": null, "e": 28763, "s": 28749, "text": "Levels: a b c" }, { "code": null, "e": 28794, "s": 28763, "text": "[1] “factor” “factor” “factor”" }, { "code": null, "e": 28811, "s": 28794, "text": "[1] “Factor2 : “" }, { "code": null, "e": 28823, "s": 28811, "text": "[1] 1 2 3 4" }, { "code": null, "e": 28839, "s": 28823, "text": "Levels: 1 2 3 4" }, { "code": null, "e": 28879, "s": 28839, "text": "[1] “factor” “factor” “factor” “factor”" }, { "code": null, "e": 28904, "s": 28879, "text": "[1] “Combined Factor : “" }, { "code": null, "e": 28922, "s": 28904, "text": "[1] a b c 1 2 3 4" }, { "code": null, "e": 28944, "s": 28922, "text": "Levels: a b c 1 2 3 4" }, { "code": null, "e": 29011, "s": 28944, "text": "[1] “factor” “factor” “factor” “factor” “factor” “factor” “factor”" }, { "code": null, "e": 29217, "s": 29011, "text": "The levels() method of the specific factor vector can be used to extract the individual levels in the form of independent strings. It returns the number of elements equivalent to the length of the vector. " }, { "code": null, "e": 29225, "s": 29217, "text": "Syntax:" }, { "code": null, "e": 29251, "s": 29225, "text": "levels (fac-vec)[fac-vec]" }, { "code": null, "e": 29423, "s": 29251, "text": "Since, these levels are each returned as strings, therefore they belong to the same data type. Hence, they are combined now to form an atomic vector using the c() method. " }, { "code": null, "e": 29431, "s": 29423, "text": "Syntax:" }, { "code": null, "e": 29447, "s": 29431, "text": "c (vec1 , vec2)" }, { "code": null, "e": 29509, "s": 29447, "text": " where vec1 and vec2 are vectors belonging to same data type " }, { "code": null, "e": 29518, "s": 29509, "text": "Example:" }, { "code": null, "e": 29520, "s": 29518, "text": "R" }, { "code": "fac1 <- factor(letters[1:3])print (\"Factor1 : \")print (fac1)sapply(fac1,class) fac2 <- factor(c(1:4))print (\"Factor2 : \")print (fac2)sapply(fac2,class) # extracting levels of factor1level1 <- levels(fac1)[fac1] # extracting levels of factor2level2 <- levels(fac2)[fac2] # combine into one factorcombined <- factor(c( level1,level2 ))print (\"Combined Factor : \")print (combined) sapply(combined,class)", "e": 29926, "s": 29520, "text": null }, { "code": null, "e": 29933, "s": 29926, "text": "Output" }, { "code": null, "e": 29950, "s": 29933, "text": "[1] “Factor1 : “" }, { "code": null, "e": 29960, "s": 29950, "text": "[1] a b c" }, { "code": null, "e": 29974, "s": 29960, "text": "Levels: a b c" }, { "code": null, "e": 30005, "s": 29974, "text": "[1] “factor” “factor” “factor”" }, { "code": null, "e": 30022, "s": 30005, "text": "[1] “Factor2 : “" }, { "code": null, "e": 30034, "s": 30022, "text": "[1] 1 2 3 4" }, { "code": null, "e": 30050, "s": 30034, "text": "Levels: 1 2 3 4" }, { "code": null, "e": 30090, "s": 30050, "text": "[1] “factor” “factor” “factor” “factor”" }, { "code": null, "e": 30115, "s": 30090, "text": "[1] “Combined Factor : “" }, { "code": null, "e": 30133, "s": 30115, "text": "[1] a b c 1 2 3 4" }, { "code": null, "e": 30155, "s": 30133, "text": "Levels: 1 2 3 4 a b c" }, { "code": null, "e": 30222, "s": 30155, "text": "[1] “factor” “factor” “factor” “factor” “factor” “factor” “factor”" }, { "code": null, "e": 30229, "s": 30222, "text": "Picked" }, { "code": null, "e": 30247, "s": 30229, "text": "R Factor-Programs" }, { "code": null, "e": 30257, "s": 30247, "text": "R-Factors" }, { "code": null, "e": 30268, "s": 30257, "text": "R Language" }, { "code": null, "e": 30279, "s": 30268, "text": "R Programs" }, { "code": null, "e": 30377, "s": 30279, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30429, "s": 30377, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30464, "s": 30429, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30502, "s": 30464, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30560, "s": 30502, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30603, "s": 30560, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30661, "s": 30603, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30704, "s": 30661, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30753, "s": 30704, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30803, "s": 30753, "text": "How to filter R dataframe by multiple conditions?" } ]
Language Localization in Android with Example - GeeksforGeeks
29 Oct, 2020 Language Localization is a process to change the application context into multiple languages based on the requirements. Android is an overall operating system that runs on millions of devices worldwide and among various groups. Since the diversity range is enormous, a feature that facilitates local languages adds an advantage to any Android application. Implementation of such a feature requires the need to handle text, audio files, numbers, currency, and graphics appropriately for the locals where our application is used. Through this article, we want to show the implementation of a feature that changes the context language (if explicitly declared) through an Android application. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. To make an application that changes the contextual language upon the device’s preferences in Android, follow the following steps: 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: Create a folder values-hi to store the custom messages Create a folder values-hi by following the following steps. The -hi extension defines that if the device’s preference is set to Hindi (hi), the context within the application would be set according to the data present in the values-hi folder. Click on Android and select the Project option: Now expand the folder until you find the res (Resources) folder, right-click on it, select new, and click Android Resource Directory. Set the directory name as values-hi The values-hi folder is now created Step 3: Create a strings.xml file Create a strings.xml file in this folder, that shall contain a custom message. Entities of this file should match the entities of the default strings.xml file. Now add a Values Resource File in the values-hi folder Give it a name, strings, it creates a .XML file strings.xml file is created in the values-hi folder Go back to the Android view and check if the newly created file is present. The file is available under the values/strings folder Step 4: Add the custom message values to string.xml (regular) and string.xml (hi) Add a custom message to the pre-existing as well as the newly created strings.xml file. The entities of both the file must be the same, context may differ. Below is the code for the strings.xml file. XML <resources> <string name="app_name">GFG | LanguageLocalization</string> <string name="custom_message">This application tests if the language localization works on the device</string> </resources> Below is the code for the strings.xml (hi) file. XML <?xml version="1.0" encoding="utf-8"?><resources> <!--custom_message in the desired language--> <!--App name also changes--> <string name="app_name">GFG | भाषा स्थानीयकरण</string> <string name="custom_message">यह एप्लिकेशन परीक्षण करता है कि भाषा स्थानीयकरण डिवाइस पर काम करती है या नहीं।</string> </resources> Step 5: Working with the activity_main.xml file Now go to the activity_main.xml file which represents the UI of the application. Create a TextView that would display the custom message. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--TextView to display the custom message--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:gravity="center" android:text="@string/custom_message" android:textAlignment="center" android:textSize="30sp" /> </RelativeLayout> Step 6: Working with the MainActivity.kt file No changes are made to the MainActivity.kt file. Keep the MainActivity.kt file unchanged. Kotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) }} android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Android UI Layouts Kotlin Array Retrofit with Kotlin Coroutine in Android How to Get Current Location in Android? Kotlin Setters and Getters
[ { "code": null, "e": 26381, "s": 26353, "text": "\n29 Oct, 2020" }, { "code": null, "e": 27237, "s": 26381, "text": "Language Localization is a process to change the application context into multiple languages based on the requirements. Android is an overall operating system that runs on millions of devices worldwide and among various groups. Since the diversity range is enormous, a feature that facilitates local languages adds an advantage to any Android application. Implementation of such a feature requires the need to handle text, audio files, numbers, currency, and graphics appropriately for the locals where our application is used. Through this article, we want to show the implementation of a feature that changes the context language (if explicitly declared) through an Android application. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. " }, { "code": null, "e": 27367, "s": 27237, "text": "To make an application that changes the contextual language upon the device’s preferences in Android, follow the following steps:" }, { "code": null, "e": 27396, "s": 27367, "text": "Step 1: Create a New Project" }, { "code": null, "e": 27560, "s": 27396, "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": 27623, "s": 27560, "text": "Step 2: Create a folder values-hi to store the custom messages" }, { "code": null, "e": 27867, "s": 27623, "text": "Create a folder values-hi by following the following steps. The -hi extension defines that if the device’s preference is set to Hindi (hi), the context within the application would be set according to the data present in the values-hi folder. " }, { "code": null, "e": 27915, "s": 27867, "text": "Click on Android and select the Project option:" }, { "code": null, "e": 28049, "s": 27915, "text": "Now expand the folder until you find the res (Resources) folder, right-click on it, select new, and click Android Resource Directory." }, { "code": null, "e": 28085, "s": 28049, "text": "Set the directory name as values-hi" }, { "code": null, "e": 28121, "s": 28085, "text": "The values-hi folder is now created" }, { "code": null, "e": 28156, "s": 28121, "text": "Step 3: Create a strings.xml file " }, { "code": null, "e": 28316, "s": 28156, "text": "Create a strings.xml file in this folder, that shall contain a custom message. Entities of this file should match the entities of the default strings.xml file." }, { "code": null, "e": 28371, "s": 28316, "text": "Now add a Values Resource File in the values-hi folder" }, { "code": null, "e": 28419, "s": 28371, "text": "Give it a name, strings, it creates a .XML file" }, { "code": null, "e": 28471, "s": 28419, "text": "strings.xml file is created in the values-hi folder" }, { "code": null, "e": 28547, "s": 28471, "text": "Go back to the Android view and check if the newly created file is present." }, { "code": null, "e": 28601, "s": 28547, "text": "The file is available under the values/strings folder" }, { "code": null, "e": 28683, "s": 28601, "text": "Step 4: Add the custom message values to string.xml (regular) and string.xml (hi)" }, { "code": null, "e": 28883, "s": 28683, "text": "Add a custom message to the pre-existing as well as the newly created strings.xml file. The entities of both the file must be the same, context may differ. Below is the code for the strings.xml file." }, { "code": null, "e": 28887, "s": 28883, "text": "XML" }, { "code": "<resources> <string name=\"app_name\">GFG | LanguageLocalization</string> <string name=\"custom_message\">This application tests if the language localization works on the device</string> </resources>", "e": 29094, "s": 28887, "text": null }, { "code": null, "e": 29143, "s": 29094, "text": "Below is the code for the strings.xml (hi) file." }, { "code": null, "e": 29147, "s": 29143, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <!--custom_message in the desired language--> <!--App name also changes--> <string name=\"app_name\">GFG | भाषा स्थानीयकरण</string> <string name=\"custom_message\">यह एप्लिकेशन परीक्षण करता है कि भाषा स्थानीयकरण डिवाइस पर काम करती है या नहीं।</string> </resources>", "e": 29467, "s": 29147, "text": null }, { "code": null, "e": 29515, "s": 29467, "text": "Step 5: Working with the activity_main.xml file" }, { "code": null, "e": 29703, "s": 29515, "text": "Now go to the activity_main.xml file which represents the UI of the application. Create a TextView that would display the custom message. Below is the code for the activity_main.xml file." }, { "code": null, "e": 29707, "s": 29703, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--TextView to display the custom message--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:gravity=\"center\" android:text=\"@string/custom_message\" android:textAlignment=\"center\" android:textSize=\"30sp\" /> </RelativeLayout>", "e": 30350, "s": 29707, "text": null }, { "code": null, "e": 30396, "s": 30350, "text": "Step 6: Working with the MainActivity.kt file" }, { "code": null, "e": 30486, "s": 30396, "text": "No changes are made to the MainActivity.kt file. Keep the MainActivity.kt file unchanged." }, { "code": null, "e": 30493, "s": 30486, "text": "Kotlin" }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) }}", "e": 30759, "s": 30493, "text": null }, { "code": null, "e": 30767, "s": 30759, "text": "android" }, { "code": null, "e": 30775, "s": 30767, "text": "Android" }, { "code": null, "e": 30782, "s": 30775, "text": "Kotlin" }, { "code": null, "e": 30790, "s": 30782, "text": "Android" }, { "code": null, "e": 30888, "s": 30790, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30926, "s": 30888, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 30965, "s": 30926, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 31015, "s": 30965, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 31057, "s": 31015, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 31108, "s": 31057, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 31127, "s": 31108, "text": "Android UI Layouts" }, { "code": null, "e": 31140, "s": 31127, "text": "Kotlin Array" }, { "code": null, "e": 31182, "s": 31140, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 31222, "s": 31182, "text": "How to Get Current Location in Android?" } ]
Array element with minimum sum of absolute differences - GeeksforGeeks
23 Aug, 2021 Given an array arr[] of N integers, the task is to find an element x from the array such that |arr[0] – x| + |arr[1] – x| + |arr[2] – x| + ... + |arr[n – 1] – x| is minimized, then print the minimized sum.Examples: Input: arr[] = {1, 3, 9, 3, 6} Output: 11 The optimal solution is to choose x = 3, which produces the sum |1 – 3| + |3 – 3| + |9 – 3| + |3 – 3| + |6 – 3| = 2 + 0 + 6 + 0 + 3 = 11Input: arr[] = {1, 2, 3, 4} Output: 4 A simple solution is to iterate through every element and check if it gives optimal solution or not. Time Complexity of this solution is O(n*n)An Efficient Approach: is to always pick x as the median of the array. If n is even and there are two medians then both the medians are optimal choices. The time complexity for the approach is O(n * log(n)) because the array will have to be sorted in order to find the median. Calculate and print the minimized sum when x is found (median of the array).Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimized sumint minSum(int arr[], int n){ // Sort the array sort(arr, arr + n); // Median of the array int x = arr[n / 2]; int sum = 0; // Calculate the minimized sum for (int i = 0; i < n; i++) sum += abs(arr[i] - x); // Return the required sum return sum;} // Driver codeint main(){ int arr[] = { 1, 3, 9, 3, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minSum(arr, n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function to return the minimized sumstatic int minSum(int arr[], int n){ // Sort the array Arrays.sort(arr); // Median of the array int x = arr[(int)n / 2]; int sum = 0; // Calculate the minimized sum for (int i = 0; i < n; i++) sum += Math.abs(arr[i] - x); // Return the required sum return sum;} // Driver codepublic static void main(String args[]){ int arr[] = { 1, 3, 9, 3, 6 }; int n = arr.length; System.out.println(minSum(arr, n));}} // This code is contribute by// Surendra_Gangwar # Python3 implementation of the approach # Function to return the minimized sumdef minSum(arr, n) : # Sort the array arr.sort(); # Median of the array x = arr[n // 2]; sum = 0; # Calculate the minimized sum for i in range(n) : sum += abs(arr[i] - x); # Return the required sum return sum; # Driver codeif __name__ == "__main__" : arr = [ 1, 3, 9, 3, 6 ]; n = len(arr) print(minSum(arr, n)); # This code is contributed by Ryuga // C# implementation of the approachusing System; class GFG{ // Function to return the minimized sumstatic int minSum(int []arr, int n){ // Sort the array Array.Sort(arr); // Median of the array int x = arr[(int)(n / 2)]; int sum = 0; // Calculate the minimized sum for (int i = 0; i < n; i++) sum += Math.Abs(arr[i] - x); // Return the required sum return sum;} // Driver codestatic void Main(){ int []arr = { 1, 3, 9, 3, 6 }; int n = arr.Length; Console.WriteLine(minSum(arr, n));}} // This code is contributed by mits <script> //Javascript implementation of the approach // Function to return the minimized sumfunction minSum(arr, n){ // Sort the array arr.sort(); // Median of the array let x = arr[Math.floor(n / 2)]; let sum = 0; // Calculate the minimized sum for (let i = 0; i < n; i++) sum += Math.abs(arr[i] - x); // Return the required sum return sum;} // Driver code let arr = [ 1, 3, 9, 3, 6 ]; let n = arr.length; document.write(minSum(arr, n)); // This code is contributed by Mayank Tyagi </script> 11 The time complexity of the above solution is O(n Log n). We can further optimize it to work in O(n) using linear time algorithm to find k-th largest element. ankthon Mithun Kumar SURENDRA_GANGWAR mayanktyagi1709 rajeev0719singh array-traversal-question median-finding Arrays C++ Programs Sorting Arrays Sorting 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 Header files in C/C++ and its uses Program to print ASCII Value of a character C++ Program for QuickSort How to return multiple values from a function in C or C++? Sorting a Map by value in C++ STL
[ { "code": null, "e": 26066, "s": 26038, "text": "\n23 Aug, 2021" }, { "code": null, "e": 26283, "s": 26066, "text": "Given an array arr[] of N integers, the task is to find an element x from the array such that |arr[0] – x| + |arr[1] – x| + |arr[2] – x| + ... + |arr[n – 1] – x| is minimized, then print the minimized sum.Examples: " }, { "code": null, "e": 26501, "s": 26283, "text": "Input: arr[] = {1, 3, 9, 3, 6} Output: 11 The optimal solution is to choose x = 3, which produces the sum |1 – 3| + |3 – 3| + |9 – 3| + |3 – 3| + |6 – 3| = 2 + 0 + 6 + 0 + 3 = 11Input: arr[] = {1, 2, 3, 4} Output: 4 " }, { "code": null, "e": 27052, "s": 26503, "text": "A simple solution is to iterate through every element and check if it gives optimal solution or not. Time Complexity of this solution is O(n*n)An Efficient Approach: is to always pick x as the median of the array. If n is even and there are two medians then both the medians are optimal choices. The time complexity for the approach is O(n * log(n)) because the array will have to be sorted in order to find the median. Calculate and print the minimized sum when x is found (median of the array).Below is the implementation of the above approach: " }, { "code": null, "e": 27056, "s": 27052, "text": "C++" }, { "code": null, "e": 27061, "s": 27056, "text": "Java" }, { "code": null, "e": 27069, "s": 27061, "text": "Python3" }, { "code": null, "e": 27072, "s": 27069, "text": "C#" }, { "code": null, "e": 27083, "s": 27072, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimized sumint minSum(int arr[], int n){ // Sort the array sort(arr, arr + n); // Median of the array int x = arr[n / 2]; int sum = 0; // Calculate the minimized sum for (int i = 0; i < n; i++) sum += abs(arr[i] - x); // Return the required sum return sum;} // Driver codeint main(){ int arr[] = { 1, 3, 9, 3, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minSum(arr, n); return 0;}", "e": 27632, "s": 27083, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the minimized sumstatic int minSum(int arr[], int n){ // Sort the array Arrays.sort(arr); // Median of the array int x = arr[(int)n / 2]; int sum = 0; // Calculate the minimized sum for (int i = 0; i < n; i++) sum += Math.abs(arr[i] - x); // Return the required sum return sum;} // Driver codepublic static void main(String args[]){ int arr[] = { 1, 3, 9, 3, 6 }; int n = arr.length; System.out.println(minSum(arr, n));}} // This code is contribute by// Surendra_Gangwar", "e": 28241, "s": 27632, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the minimized sumdef minSum(arr, n) : # Sort the array arr.sort(); # Median of the array x = arr[n // 2]; sum = 0; # Calculate the minimized sum for i in range(n) : sum += abs(arr[i] - x); # Return the required sum return sum; # Driver codeif __name__ == \"__main__\" : arr = [ 1, 3, 9, 3, 6 ]; n = len(arr) print(minSum(arr, n)); # This code is contributed by Ryuga", "e": 28725, "s": 28241, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the minimized sumstatic int minSum(int []arr, int n){ // Sort the array Array.Sort(arr); // Median of the array int x = arr[(int)(n / 2)]; int sum = 0; // Calculate the minimized sum for (int i = 0; i < n; i++) sum += Math.Abs(arr[i] - x); // Return the required sum return sum;} // Driver codestatic void Main(){ int []arr = { 1, 3, 9, 3, 6 }; int n = arr.Length; Console.WriteLine(minSum(arr, n));}} // This code is contributed by mits", "e": 29297, "s": 28725, "text": null }, { "code": "<script> //Javascript implementation of the approach // Function to return the minimized sumfunction minSum(arr, n){ // Sort the array arr.sort(); // Median of the array let x = arr[Math.floor(n / 2)]; let sum = 0; // Calculate the minimized sum for (let i = 0; i < n; i++) sum += Math.abs(arr[i] - x); // Return the required sum return sum;} // Driver code let arr = [ 1, 3, 9, 3, 6 ]; let n = arr.length; document.write(minSum(arr, n)); // This code is contributed by Mayank Tyagi </script>", "e": 29838, "s": 29297, "text": null }, { "code": null, "e": 29841, "s": 29838, "text": "11" }, { "code": null, "e": 30002, "s": 29843, "text": "The time complexity of the above solution is O(n Log n). We can further optimize it to work in O(n) using linear time algorithm to find k-th largest element. " }, { "code": null, "e": 30010, "s": 30002, "text": "ankthon" }, { "code": null, "e": 30023, "s": 30010, "text": "Mithun Kumar" }, { "code": null, "e": 30040, "s": 30023, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 30056, "s": 30040, "text": "mayanktyagi1709" }, { "code": null, "e": 30072, "s": 30056, "text": "rajeev0719singh" }, { "code": null, "e": 30097, "s": 30072, "text": "array-traversal-question" }, { "code": null, "e": 30112, "s": 30097, "text": "median-finding" }, { "code": null, "e": 30119, "s": 30112, "text": "Arrays" }, { "code": null, "e": 30132, "s": 30119, "text": "C++ Programs" }, { "code": null, "e": 30140, "s": 30132, "text": "Sorting" }, { "code": null, "e": 30147, "s": 30140, "text": "Arrays" }, { "code": null, "e": 30155, "s": 30147, "text": "Sorting" }, { "code": null, "e": 30253, "s": 30155, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30280, "s": 30253, "text": "Count pairs with given sum" }, { "code": null, "e": 30311, "s": 30280, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 30336, "s": 30311, "text": "Window Sliding Technique" }, { "code": null, "e": 30374, "s": 30336, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30395, "s": 30374, "text": "Next Greater Element" }, { "code": null, "e": 30430, "s": 30395, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 30474, "s": 30430, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 30500, "s": 30474, "text": "C++ Program for QuickSort" }, { "code": null, "e": 30559, "s": 30500, "text": "How to return multiple values from a function in C or C++?" } ]
Digital Band Pass Butterworth Filter in Python - GeeksforGeeks
17 Dec, 2020 In this article, we are going to discuss how to design a Digital Low Pass Butterworth Filter using Python. The Butterworth filter is a type of signal processing filter designed to have a frequency response as flat as possible in the pass band. Let us take the below specifications to design the filter and observe the Magnitude, Phase & Impulse Response of the Digital Butterworth Filter. A band-pass filter is a filter that passes frequencies within a range and rejects frequencies outside that range. The main difference can be spotted by observing the magnitude response of the Band Pass Filter. The passband of the filter is of a specific range, which means that the only signal’s within this range can be passed by the Bandpass filter. Any signal which doesn’t fall within the specified range is rejected by the filter. The specifications are as follows: Sampling rate of 40 kHz Pass band edge frequencies are 1400 Hz & 2100 Hz Stop band edge frequencies are 1050 Hz & 2450 Hz Pass band ripple of 0.4 dB Minimum stop band attenuation of 50 dB We will plot the magnitude, phase, and impulse response of the filter. Step-by-step Approach: Before starting, first, we will create a user-defined function to convert the edge frequencies, we are defining it as convert() method. Python3 # explicit function to convert# edge frequenciesdef convertX(f_sample, f): w = [] for i in range(len(f)): b = 2*((f[i]/2)/(f_sample/2)) w.append(b) omega_mine = [] for i in range(len(w)): c = (2/Td)*np.tan(w[i]/2) omega_mine.append(c) return omega_mine Now below are the steps: Step 1: Importing all the necessary libraries. Python3 # import required modules import numpy as np import matplotlib.pyplot as plt from scipy import signal import math Step 2: Define variables with the given specifications of the filter. Python3 # Specifications of Filter # sampling frequencyf_sample = 7000 # pass band frequencyf_pass = [1400, 2100] # stop band frequencyf_stop = [1050, 2450] # pass band ripplefs = 0.5 # Sampling TimeTd = 1 # pass band rippleg_pass = 0.4 # stop band attenuationg_stop = 50 Step 3: Building the filter using signal.buttord() function. Python3 # Conversion to prewrapped analog # frequency omega_p=convertX(f_sample,f_pass)omega_s=convertX(f_sample,f_stop) # Design of Filter using signal.buttord # function N, Wn = signal.buttord(omega_p, omega_s, g_pass, g_stop, analog=True) # Printing the values of order & cut-off frequency# N is the order print("Order of the Filter=", N) # Wn is the cut-off freq of the filter print("Cut-off frequency= {:} rad/s ".format(Wn)) # Conversion in Z-domain # b is the numerator of the filter & a is# the denominator b, a = signal.butter(N, Wn, 'bandpass', True) z, p = signal.bilinear(b, a, fs) # w is the freq in z-domain & h is the # magnitude in z-domain w, h = signal.freqz(z, p, 512) Step 4: Plotting the Magnitude Response. Python3 # Magnitude Responseplt.semilogx(w, 20*np.log10(abs(h)))plt.xscale('log')plt.title('Butterworth filter frequency response')plt.xlabel('Frequency [Hz]')plt.ylabel('Amplitude [dB]')plt.margins(0, 0.1)plt.grid(which='both', axis='both')plt.axvline(100, color='green')plt.show() Step 5: Plotting the Impulse Response. Python3 # Impulse Responseimp = signal.unit_impulse(40)c, d = signal.butter(N, 0.5)response = signal.lfilter(c, d, imp) plt.stem(np.arange(0, 40), imp, markerfmt='D', use_line_collection=True)plt.stem(np.arange(0, 40), response, use_line_collection=True)plt.margins(0, 0.1) plt.xlabel('Time [samples]')plt.ylabel('Amplitude')plt.grid(True)plt.show() Step 6: Plotting the Phase Response. Python3 # Frequency Responsefig, ax1 = plt.subplots()ax1.set_title('Digital filter frequency response')ax1.set_ylabel('Angle(radians)', color='g')ax1.set_xlabel('Frequency [Hz]') angles = np.unwrap(np.angle(h)) ax1.plot(w/2*np.pi, angles, 'g')ax1.grid()ax1.axis('tight')plt.show() Below is the complete program based on the above approach: Python3 # User-defined function to convert the # values of edge frequenciesdef convertX(f_sample,f): w=[] for i in range(len(f)): b=2*((f[i]/2)/(f_sample/2)) w.append(b) omega_mine=[] for i in range(len(w)): c=(2/Td)*np.tan(w[i]/2) omega_mine.append(c) return omega_mine # Importing Librariesimport numpy as npimport matplotlib.pyplot as pltfrom scipy import signalimport math # Specifications of Filter # sampling frequency f_sample =7000 # pass band frequency f_pass =[1400,2100] # stop band frequency f_stop =[1050,2450] # pass band ripple fs = 0.5 # Sampling Time Td = 1 # pass band ripple g_pass = 0.4 # stop band attenuation g_stop = 50 # Conversion to prewrapped analog# frequency omega_p=convertX(f_sample,f_pass)omega_s=convertX(f_sample,f_stop) # Design of Filter using signal.buttord # function N, Wn = signal.buttord(omega_p, omega_s, g_pass, g_stop, analog=True) # Printing the values of order & cut-off frequency# N is the order print("Order of the Filter=", N) # Wn is the cut-off freq of the filter print("Cut-off frequency= {:} rad/s ".format(Wn)) # Conversion in Z-domain # b is the numerator of the filter & a is # the denominator b, a = signal.butter(N, Wn, 'bandpass', True) z, p = signal.bilinear(b, a, fs) # w is the freq in z-domain & h is the magnitude# in z-domain w, h = signal.freqz(z, p, 512) # Magnitude Responseplt.semilogx(w, 20*np.log10(abs(h)))plt.xscale('log')plt.title('Butterworth filter frequency response')plt.xlabel('Frequency [Hz]')plt.ylabel('Amplitude [dB]')plt.margins(0, 0.1)plt.grid(which='both', axis='both')plt.axvline(100, color='green')plt.show() # Impulse Responseimp = signal.unit_impulse(40)c, d = signal.butter(N, 0.5)response = signal.lfilter(c, d, imp)plt.stem(np.arange(0, 40),imp,markerfmt='D',use_line_collection=True)plt.stem(np.arange(0,40), response,use_line_collection=True)plt.margins(0, 0.1)plt.xlabel('Time [samples]')plt.ylabel('Amplitude')plt.grid(True)plt.show() # Frequency Responsefig, ax1 = plt.subplots()ax1.set_title('Digital filter frequency response')ax1.set_ylabel('Angle(radians)', color='g')ax1.set_xlabel('Frequency [Hz]')angles = np.unwrap(np.angle(h))ax1.plot(w/2*np.pi, angles, 'g')ax1.grid()ax1.axis('tight')plt.show() Data Visualization Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n17 Dec, 2020" }, { "code": null, "e": 25926, "s": 25537, "text": "In this article, we are going to discuss how to design a Digital Low Pass Butterworth Filter using Python. The Butterworth filter is a type of signal processing filter designed to have a frequency response as flat as possible in the pass band. Let us take the below specifications to design the filter and observe the Magnitude, Phase & Impulse Response of the Digital Butterworth Filter." }, { "code": null, "e": 26040, "s": 25926, "text": "A band-pass filter is a filter that passes frequencies within a range and rejects frequencies outside that range." }, { "code": null, "e": 26362, "s": 26040, "text": "The main difference can be spotted by observing the magnitude response of the Band Pass Filter. The passband of the filter is of a specific range, which means that the only signal’s within this range can be passed by the Bandpass filter. Any signal which doesn’t fall within the specified range is rejected by the filter." }, { "code": null, "e": 26399, "s": 26362, "text": "The specifications are as follows: " }, { "code": null, "e": 26423, "s": 26399, "text": "Sampling rate of 40 kHz" }, { "code": null, "e": 26472, "s": 26423, "text": "Pass band edge frequencies are 1400 Hz & 2100 Hz" }, { "code": null, "e": 26521, "s": 26472, "text": "Stop band edge frequencies are 1050 Hz & 2450 Hz" }, { "code": null, "e": 26548, "s": 26521, "text": "Pass band ripple of 0.4 dB" }, { "code": null, "e": 26587, "s": 26548, "text": "Minimum stop band attenuation of 50 dB" }, { "code": null, "e": 26658, "s": 26587, "text": "We will plot the magnitude, phase, and impulse response of the filter." }, { "code": null, "e": 26681, "s": 26658, "text": "Step-by-step Approach:" }, { "code": null, "e": 26817, "s": 26681, "text": "Before starting, first, we will create a user-defined function to convert the edge frequencies, we are defining it as convert() method." }, { "code": null, "e": 26825, "s": 26817, "text": "Python3" }, { "code": "# explicit function to convert# edge frequenciesdef convertX(f_sample, f): w = [] for i in range(len(f)): b = 2*((f[i]/2)/(f_sample/2)) w.append(b) omega_mine = [] for i in range(len(w)): c = (2/Td)*np.tan(w[i]/2) omega_mine.append(c) return omega_mine", "e": 27133, "s": 26825, "text": null }, { "code": null, "e": 27158, "s": 27133, "text": "Now below are the steps:" }, { "code": null, "e": 27205, "s": 27158, "text": "Step 1: Importing all the necessary libraries." }, { "code": null, "e": 27213, "s": 27205, "text": "Python3" }, { "code": "# import required modules import numpy as np import matplotlib.pyplot as plt from scipy import signal import math", "e": 27327, "s": 27213, "text": null }, { "code": null, "e": 27397, "s": 27327, "text": "Step 2: Define variables with the given specifications of the filter." }, { "code": null, "e": 27405, "s": 27397, "text": "Python3" }, { "code": "# Specifications of Filter # sampling frequencyf_sample = 7000 # pass band frequencyf_pass = [1400, 2100] # stop band frequencyf_stop = [1050, 2450] # pass band ripplefs = 0.5 # Sampling TimeTd = 1 # pass band rippleg_pass = 0.4 # stop band attenuationg_stop = 50", "e": 27676, "s": 27405, "text": null }, { "code": null, "e": 27737, "s": 27676, "text": "Step 3: Building the filter using signal.buttord() function." }, { "code": null, "e": 27745, "s": 27737, "text": "Python3" }, { "code": "# Conversion to prewrapped analog # frequency omega_p=convertX(f_sample,f_pass)omega_s=convertX(f_sample,f_stop) # Design of Filter using signal.buttord # function N, Wn = signal.buttord(omega_p, omega_s, g_pass, g_stop, analog=True) # Printing the values of order & cut-off frequency# N is the order print(\"Order of the Filter=\", N) # Wn is the cut-off freq of the filter print(\"Cut-off frequency= {:} rad/s \".format(Wn)) # Conversion in Z-domain # b is the numerator of the filter & a is# the denominator b, a = signal.butter(N, Wn, 'bandpass', True) z, p = signal.bilinear(b, a, fs) # w is the freq in z-domain & h is the # magnitude in z-domain w, h = signal.freqz(z, p, 512)", "e": 28498, "s": 27745, "text": null }, { "code": null, "e": 28539, "s": 28498, "text": "Step 4: Plotting the Magnitude Response." }, { "code": null, "e": 28547, "s": 28539, "text": "Python3" }, { "code": "# Magnitude Responseplt.semilogx(w, 20*np.log10(abs(h)))plt.xscale('log')plt.title('Butterworth filter frequency response')plt.xlabel('Frequency [Hz]')plt.ylabel('Amplitude [dB]')plt.margins(0, 0.1)plt.grid(which='both', axis='both')plt.axvline(100, color='green')plt.show()", "e": 28822, "s": 28547, "text": null }, { "code": null, "e": 28861, "s": 28822, "text": "Step 5: Plotting the Impulse Response." }, { "code": null, "e": 28869, "s": 28861, "text": "Python3" }, { "code": "# Impulse Responseimp = signal.unit_impulse(40)c, d = signal.butter(N, 0.5)response = signal.lfilter(c, d, imp) plt.stem(np.arange(0, 40), imp, markerfmt='D', use_line_collection=True)plt.stem(np.arange(0, 40), response, use_line_collection=True)plt.margins(0, 0.1) plt.xlabel('Time [samples]')plt.ylabel('Amplitude')plt.grid(True)plt.show()", "e": 29213, "s": 28869, "text": null }, { "code": null, "e": 29250, "s": 29213, "text": "Step 6: Plotting the Phase Response." }, { "code": null, "e": 29258, "s": 29250, "text": "Python3" }, { "code": "# Frequency Responsefig, ax1 = plt.subplots()ax1.set_title('Digital filter frequency response')ax1.set_ylabel('Angle(radians)', color='g')ax1.set_xlabel('Frequency [Hz]') angles = np.unwrap(np.angle(h)) ax1.plot(w/2*np.pi, angles, 'g')ax1.grid()ax1.axis('tight')plt.show()", "e": 29533, "s": 29258, "text": null }, { "code": null, "e": 29592, "s": 29533, "text": "Below is the complete program based on the above approach:" }, { "code": null, "e": 29600, "s": 29592, "text": "Python3" }, { "code": "# User-defined function to convert the # values of edge frequenciesdef convertX(f_sample,f): w=[] for i in range(len(f)): b=2*((f[i]/2)/(f_sample/2)) w.append(b) omega_mine=[] for i in range(len(w)): c=(2/Td)*np.tan(w[i]/2) omega_mine.append(c) return omega_mine # Importing Librariesimport numpy as npimport matplotlib.pyplot as pltfrom scipy import signalimport math # Specifications of Filter # sampling frequency f_sample =7000 # pass band frequency f_pass =[1400,2100] # stop band frequency f_stop =[1050,2450] # pass band ripple fs = 0.5 # Sampling Time Td = 1 # pass band ripple g_pass = 0.4 # stop band attenuation g_stop = 50 # Conversion to prewrapped analog# frequency omega_p=convertX(f_sample,f_pass)omega_s=convertX(f_sample,f_stop) # Design of Filter using signal.buttord # function N, Wn = signal.buttord(omega_p, omega_s, g_pass, g_stop, analog=True) # Printing the values of order & cut-off frequency# N is the order print(\"Order of the Filter=\", N) # Wn is the cut-off freq of the filter print(\"Cut-off frequency= {:} rad/s \".format(Wn)) # Conversion in Z-domain # b is the numerator of the filter & a is # the denominator b, a = signal.butter(N, Wn, 'bandpass', True) z, p = signal.bilinear(b, a, fs) # w is the freq in z-domain & h is the magnitude# in z-domain w, h = signal.freqz(z, p, 512) # Magnitude Responseplt.semilogx(w, 20*np.log10(abs(h)))plt.xscale('log')plt.title('Butterworth filter frequency response')plt.xlabel('Frequency [Hz]')plt.ylabel('Amplitude [dB]')plt.margins(0, 0.1)plt.grid(which='both', axis='both')plt.axvline(100, color='green')plt.show() # Impulse Responseimp = signal.unit_impulse(40)c, d = signal.butter(N, 0.5)response = signal.lfilter(c, d, imp)plt.stem(np.arange(0, 40),imp,markerfmt='D',use_line_collection=True)plt.stem(np.arange(0,40), response,use_line_collection=True)plt.margins(0, 0.1)plt.xlabel('Time [samples]')plt.ylabel('Amplitude')plt.grid(True)plt.show() # Frequency Responsefig, ax1 = plt.subplots()ax1.set_title('Digital filter frequency response')ax1.set_ylabel('Angle(radians)', color='g')ax1.set_xlabel('Frequency [Hz]')angles = np.unwrap(np.angle(h))ax1.plot(w/2*np.pi, angles, 'g')ax1.grid()ax1.axis('tight')plt.show()", "e": 31932, "s": 29600, "text": null }, { "code": null, "e": 31951, "s": 31932, "text": "Data Visualization" }, { "code": null, "e": 31969, "s": 31951, "text": "Python-matplotlib" }, { "code": null, "e": 31976, "s": 31969, "text": "Python" }, { "code": null, "e": 32074, "s": 31976, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32106, "s": 32074, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32148, "s": 32106, "text": "Check if element exists in list in Python" }, { "code": null, "e": 32190, "s": 32148, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 32246, "s": 32190, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 32273, "s": 32246, "text": "Python Classes and Objects" }, { "code": null, "e": 32312, "s": 32273, "text": "Python | Get unique values from a list" }, { "code": null, "e": 32343, "s": 32312, "text": "Python | os.path.join() method" }, { "code": null, "e": 32365, "s": 32343, "text": "Defaultdict in Python" }, { "code": null, "e": 32394, "s": 32365, "text": "Create a directory in Python" } ]
Python | Key-Value to URL Parameter Conversion - GeeksforGeeks
13 Aug, 2019 Many times, while working in web development domain, we can encounter a problem in which we require to set as URL parameter some of the key-value pairs we have, either in form of tuples, or a key and value list. Let’s discuss a solution for both the cases. Method #1 : Using urllib.urlencode() ( with tuples )The urlencode function is root function that can perform the task that we wish to achieve. In case of tuples, we can just pass the tuples and encoder does the rest of conversion of string. Works only with Python2. # Python code to demonstrate working of# Key-Value to URL Parameter Conversion# Using urllib.urlencode() ( with tuples )import urllib # initializing tuplestest_tuples = (('Gfg', 1), ('is', 2), ('best', 3)) # printing original tuplesprint("The original tuples are : " + str(test_tuples)) # Using urllib.urlencode() ( with tuples )# Key-Value to URL Parameter Conversionres = urllib.urlencode(test_tuples) # printing URL stringprint("The URL parameter string is : " + str(res)) The original tuples are : (('Gfg', 1), ('is', 2), ('best', 3)) The URL parameter string is : Gfg=1&is=2&best=3 Method #2 : Using urllib.urlencode() ( with dictionary value list )This method is when we have a dictionary key and many values corresponding to them as a potential candidate for being the URL parameter. In this case we perform this function. This also works with just Python2. # Python code to demonstrate working of# Key-Value to URL Parameter Conversion# Using urllib.urlencode() ( with dictionary value list )import urllib # initializing dictionarytest_dict = {'gfg' : [1, 2, 3]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Using urllib.urlencode() ( with dictionary value list )# Key-Value to URL Parameter Conversionres = urllib.urlencode(test_dict, doseq = True) # printing URL stringprint("The URL parameter string is : " + str(res)) The original dictionary is : {'gfg': [1, 2, 3]} The URL parameter string is : gfg=1&gfg=2&gfg=3 Python dictionary-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? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n13 Aug, 2019" }, { "code": null, "e": 25794, "s": 25537, "text": "Many times, while working in web development domain, we can encounter a problem in which we require to set as URL parameter some of the key-value pairs we have, either in form of tuples, or a key and value list. Let’s discuss a solution for both the cases." }, { "code": null, "e": 26060, "s": 25794, "text": "Method #1 : Using urllib.urlencode() ( with tuples )The urlencode function is root function that can perform the task that we wish to achieve. In case of tuples, we can just pass the tuples and encoder does the rest of conversion of string. Works only with Python2." }, { "code": "# Python code to demonstrate working of# Key-Value to URL Parameter Conversion# Using urllib.urlencode() ( with tuples )import urllib # initializing tuplestest_tuples = (('Gfg', 1), ('is', 2), ('best', 3)) # printing original tuplesprint(\"The original tuples are : \" + str(test_tuples)) # Using urllib.urlencode() ( with tuples )# Key-Value to URL Parameter Conversionres = urllib.urlencode(test_tuples) # printing URL stringprint(\"The URL parameter string is : \" + str(res))", "e": 26540, "s": 26060, "text": null }, { "code": null, "e": 26652, "s": 26540, "text": "The original tuples are : (('Gfg', 1), ('is', 2), ('best', 3))\nThe URL parameter string is : Gfg=1&is=2&best=3\n" }, { "code": null, "e": 26932, "s": 26654, "text": "Method #2 : Using urllib.urlencode() ( with dictionary value list )This method is when we have a dictionary key and many values corresponding to them as a potential candidate for being the URL parameter. In this case we perform this function. This also works with just Python2." }, { "code": "# Python code to demonstrate working of# Key-Value to URL Parameter Conversion# Using urllib.urlencode() ( with dictionary value list )import urllib # initializing dictionarytest_dict = {'gfg' : [1, 2, 3]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Using urllib.urlencode() ( with dictionary value list )# Key-Value to URL Parameter Conversionres = urllib.urlencode(test_dict, doseq = True) # printing URL stringprint(\"The URL parameter string is : \" + str(res))", "e": 27444, "s": 26932, "text": null }, { "code": null, "e": 27541, "s": 27444, "text": "The original dictionary is : {'gfg': [1, 2, 3]}\nThe URL parameter string is : gfg=1&gfg=2&gfg=3\n" }, { "code": null, "e": 27568, "s": 27541, "text": "Python dictionary-programs" }, { "code": null, "e": 27575, "s": 27568, "text": "Python" }, { "code": null, "e": 27591, "s": 27575, "text": "Python Programs" }, { "code": null, "e": 27689, "s": 27591, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27721, "s": 27689, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27763, "s": 27721, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27805, "s": 27763, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27832, "s": 27805, "text": "Python Classes and Objects" }, { "code": null, "e": 27888, "s": 27832, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27910, "s": 27888, "text": "Defaultdict in Python" }, { "code": null, "e": 27949, "s": 27910, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27995, "s": 27949, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28033, "s": 27995, "text": "Python | Convert a list to dictionary" } ]
Amazon Interview | Set 53 (For SDE-1) - GeeksforGeeks
18 Jun, 2019 In each round they ask me why I want to join amazon, why I am leaving my previous company with such a short span(around 2.5 months) and project stuff.Interviewers were quite friendly. They would explain you till the point you fully don’t understand. And even while discussing approach and solving, they would clear your doubts if any. Online Test on InterviewStreet1. Given 2 string , find whether 2nd is sub-string of 1st or not. (it would be great if you solve with KMP)2. Given 2 rectangles , find whether they are overlapping or not.3. Given list of coins with various values (unlimited coins of each type) , find how many ways you can make a given value. (DP was expected.) Since it was not guaranteed that coin of value 1 would be present , we have to return -1 if the given value is not possible. All rounds on same day. 1st f2f:First I was ask to introduce myself and give a brief over my projects. Latter he ask me to explain any one of my project and the hardest task I have done.We have used infix to post ix and postfix evaluation for our generic search expression’s evaluation. Here we had a lot of discussion on why conversation from infix to post-fix was needed and all. 1. Given a String s and int r , first fill each character row wise and print column wise.for e.g. String s = “abcdefgh” and r = 3so filling column wise would give :a d gb e hc f and final ans would be adgbehcf.he just wanted the exact output. Internally how we handle string was not concern. 2. given a string or say number .. for e.g. 134 now with each number , as per mobile’s keypad , some letters would be associated.here 1 – > abc , 3->ghi, 4 ->jkl . So we should print all the permutation such that we take 1 character from each of the number.input number can be of any arbitrary length.lets say each digit has m numbers associated , then for the input of length n , we need to generate n^m possible strings. Took a map of which would return all the letters for the number. solved it using recursion. its quite similar to permutation of string. .Interviewer seemed quite impressed here. 2nd f2f1. Find integer part of sqrt of given number. Initially I gave o(root(n)) solution. Later solved with binary search(O(logn)). 2. Given an array of integers. replace each number with next higher number on its right side , which is nearer.(if not present than keep it as it is.)for e.g. input – > 3 4 6 1output->4 6 6 1 I suggested we can traverse from right side , we will take extra array (o(n) space complexity here) and in that array , we would store index of next higher nearer number.so it would be like if (a[i] < a[i+1] then store i+1; else traverse using index stored in auxiliary array Since we needed extra space to store indexes, he asked that the input is array of a structure which has number and higher Index, 2 fields. So that we don't need extra space and extra traversal. class Node { int val; int higher; } He was very interested to see how i keep track of indexes and how i traverse between them. It is o(n) with o(1) space complexity. (when we have a[i]>a[i+1] we don't do linear search , but we jump using the indexes, so its not o(n^2)) It was hard to convince him on complexity. 3. given a binary tree. connect all the node at the same level. each node would have left,right and nextSibling pointers. we need to fill nextSibling.solved with level order traversal . Similar to BFS on tree with queue. Only approach was needed, no code for this one. 3rd f2f (Hiring Manager)1. It was a design question. You have to design a game. it has different types of monsters and different weapons. hero would shoot monster. each monster would have some initial health. Each weapon would do some predefined damage to monster. when its health gets 0, monster would die/disappear. and there would be multiple levels. based on level, monster and their behavior would change. 2. Given a read only linked list with next and random pointer , clone the list. I told him that i know the solution and explained him the approach. It was with the use of hashmap and takes o(N) extra space. Then he ask me whether I know a o(1) space solution, since I didn't knew, i was told to solve this. With this , he told that I can modify link list.Initially I struggled, but with his help, in the end came up with working code. He was looking fine with implementation. Here I ask about the work culture and the process being followed at amazon.I ask lot of questions regarding tools and technology they use. Since I had work on scrum model , it was quite interesting. He seemed to be impressed here. 4th f2f(Dev Manager)1. Given 2 sorted linked list , merge them into single sorted list. Change the pointers, don't copy data. (same as merge part of mergesort on SLL) 2. Given binary tree, connect all the nodes which are in same column. 1 caveat was that same 1 node can have 2 parents. Here as in example, node 7 is being pointed by 2 and 6.Solved it using level order traversal. Used a Map : columNo, Node. it would store the last visited node of that column. So whenever we visit a node, first we check if its corresponding column is present in hashmap. if not , it means its the first node of column, put into map. if the column present , then we will get the node stored in map and current node would be its nextVerticleSibling. and we update the map.He deed the dry run with example and code and he was OK with final approach. 1 / \ 2 6 / \ / \ 3 7 8 / / 4 12 / \ \ 5 9 13 \ \ 10 14 \ 11 Finally after two days, I got call from HR that I am selected Many Many congratulations to the Priyank. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Amazon Interview Experiences Amazon Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Difference between ANN, CNN and RNN Zoho Interview | Set 3 (Off-Campus) Amazon Interview Experience for SDE-1 (Off-Campus) 2022 Directi Interview | Set 7 (Programming Questions) Amazon Interview Experience Amazon Interview Experience for SDE-1 EPAM Interview Experience (Off-Campus) Amazon Interview Experience (Off-Campus) 2022
[ { "code": null, "e": 26441, "s": 26413, "text": "\n18 Jun, 2019" }, { "code": null, "e": 26776, "s": 26441, "text": "In each round they ask me why I want to join amazon, why I am leaving my previous company with such a short span(around 2.5 months) and project stuff.Interviewers were quite friendly. They would explain you till the point you fully don’t understand. And even while discussing approach and solving, they would clear your doubts if any." }, { "code": null, "e": 27245, "s": 26776, "text": "Online Test on InterviewStreet1. Given 2 string , find whether 2nd is sub-string of 1st or not. (it would be great if you solve with KMP)2. Given 2 rectangles , find whether they are overlapping or not.3. Given list of coins with various values (unlimited coins of each type) , find how many ways you can make a given value. (DP was expected.) Since it was not guaranteed that coin of value 1 would be present , we have to return -1 if the given value is not possible." }, { "code": null, "e": 27269, "s": 27245, "text": "All rounds on same day." }, { "code": null, "e": 27627, "s": 27269, "text": "1st f2f:First I was ask to introduce myself and give a brief over my projects. Latter he ask me to explain any one of my project and the hardest task I have done.We have used infix to post ix and postfix evaluation for our generic search expression’s evaluation. Here we had a lot of discussion on why conversation from infix to post-fix was needed and all." }, { "code": null, "e": 27805, "s": 27627, "text": "1. Given a String s and int r , first fill each character row wise and print column wise.for e.g. String s = “abcdefgh” and r = 3so filling column wise would give :a d gb e hc f" }, { "code": null, "e": 27919, "s": 27805, "text": "and final ans would be adgbehcf.he just wanted the exact output. Internally how we handle string was not concern." }, { "code": null, "e": 28342, "s": 27919, "text": "2. given a string or say number .. for e.g. 134 now with each number , as per mobile’s keypad , some letters would be associated.here 1 – > abc , 3->ghi, 4 ->jkl . So we should print all the permutation such that we take 1 character from each of the number.input number can be of any arbitrary length.lets say each digit has m numbers associated , then for the input of length n , we need to generate n^m possible strings." }, { "code": null, "e": 28520, "s": 28342, "text": "Took a map of which would return all the letters for the number. solved it using recursion. its quite similar to permutation of string. .Interviewer seemed quite impressed here." }, { "code": null, "e": 28653, "s": 28520, "text": "2nd f2f1. Find integer part of sqrt of given number. Initially I gave o(root(n)) solution. Later solved with binary search(O(logn))." }, { "code": null, "e": 28845, "s": 28653, "text": "2. Given an array of integers. replace each number with next higher number on its right side , which is nearer.(if not present than keep it as it is.)for e.g. input – > 3 4 6 1output->4 6 6 1" }, { "code": null, "e": 29035, "s": 28845, "text": "I suggested we can traverse from right side , we will take extra array (o(n) space complexity here) and in that array , we would store index of next higher nearer number.so it would be like" }, { "code": null, "e": 29127, "s": 29035, "text": "if (a[i] < a[i+1]\n then store i+1;\nelse\n traverse using index stored in auxiliary array " }, { "code": null, "e": 29321, "s": 29127, "text": "Since we needed extra space to store indexes, he asked that the input is array of a structure which has number and higher Index, 2 fields. So that we don't need extra space and extra traversal." }, { "code": null, "e": 29363, "s": 29321, "text": "class Node {\n int val;\n int higher;\n}" }, { "code": null, "e": 29640, "s": 29363, "text": "He was very interested to see how i keep track of indexes and how i traverse between them. It is o(n) with o(1) space complexity. (when we have a[i]>a[i+1] we don't do linear search , but we jump using the indexes, so its not o(n^2)) It was hard to convince him on complexity." }, { "code": null, "e": 29909, "s": 29640, "text": "3. given a binary tree. connect all the node at the same level. each node would have left,right and nextSibling pointers. we need to fill nextSibling.solved with level order traversal . Similar to BFS on tree with queue. Only approach was needed, no code for this one." }, { "code": null, "e": 30320, "s": 29909, "text": "3rd f2f (Hiring Manager)1. It was a design question. You have to design a game. it has different types of monsters and different weapons. hero would shoot monster. each monster would have some initial health. Each weapon would do some predefined damage to monster. when its health gets 0, monster would die/disappear. and there would be multiple levels. based on level, monster and their behavior would change." }, { "code": null, "e": 30796, "s": 30320, "text": "2. Given a read only linked list with next and random pointer , clone the list. I told him that i know the solution and explained him the approach. It was with the use of hashmap and takes o(N) extra space. Then he ask me whether I know a o(1) space solution, since I didn't knew, i was told to solve this. With this , he told that I can modify link list.Initially I struggled, but with his help, in the end came up with working code. He was looking fine with implementation." }, { "code": null, "e": 31027, "s": 30796, "text": "Here I ask about the work culture and the process being followed at amazon.I ask lot of questions regarding tools and technology they use. Since I had work on scrum model , it was quite interesting. He seemed to be impressed here." }, { "code": null, "e": 31194, "s": 31027, "text": "4th f2f(Dev Manager)1. Given 2 sorted linked list , merge them into single sorted list. Change the pointers, don't copy data. (same as merge part of mergesort on SLL)" }, { "code": null, "e": 31860, "s": 31194, "text": "2. Given binary tree, connect all the nodes which are in same column. 1 caveat was that same 1 node can have 2 parents. Here as in example, node 7 is being pointed by 2 and 6.Solved it using level order traversal. Used a Map : columNo, Node. it would store the last visited node of that column. So whenever we visit a node, first we check if its corresponding column is present in hashmap. if not , it means its the first node of column, put into map. if the column present , then we will get the node stored in map and current node would be its nextVerticleSibling. and we update the map.He deed the dry run with example and code and he was OK with final approach." }, { "code": null, "e": 32065, "s": 31860, "text": " 1\n / \\\n 2 6\n / \\ / \\\n 3 7 8\n / / \n 4 12 \n / \\ \\ \n5 9 13\n \\ \\\n 10 14\n \\\n 11 " }, { "code": null, "e": 32128, "s": 32065, "text": "Finally after two days, I got call from HR that I am selected " }, { "code": null, "e": 32391, "s": 32128, "text": "Many Many congratulations to the Priyank. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 32398, "s": 32391, "text": "Amazon" }, { "code": null, "e": 32420, "s": 32398, "text": "Interview Experiences" }, { "code": null, "e": 32427, "s": 32420, "text": "Amazon" }, { "code": null, "e": 32525, "s": 32427, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32576, "s": 32525, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 32618, "s": 32576, "text": "Amazon AWS Interview Experience for SDE-1" }, { "code": null, "e": 32654, "s": 32618, "text": "Difference between ANN, CNN and RNN" }, { "code": null, "e": 32690, "s": 32654, "text": "Zoho Interview | Set 3 (Off-Campus)" }, { "code": null, "e": 32746, "s": 32690, "text": "Amazon Interview Experience for SDE-1 (Off-Campus) 2022" }, { "code": null, "e": 32796, "s": 32746, "text": "Directi Interview | Set 7 (Programming Questions)" }, { "code": null, "e": 32824, "s": 32796, "text": "Amazon Interview Experience" }, { "code": null, "e": 32862, "s": 32824, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 32901, "s": 32862, "text": "EPAM Interview Experience (Off-Campus)" } ]
Output of Java Program | Set 3 - GeeksforGeeks
25 Feb, 2022 Predict the output of the following Java Programs: Example1: Java // filename: Test.java class Test { // Declaring and initializing integer variable int x = 10; // Main driver method public static void main(String[] args) { // Creating an object of class inside main() Test t = new Test(); // Printing the value inside the object by // above created object System.out.println(t.x); }} 10 Output explanation: In Java, members can be initialized with the declaration of the class. This initialization works well when the initialization value is available and the initialization can be put on one line (See this for more details). Example 2: Java // filename: Test.java // Main classclass Test { // Declaring and initializing variables int y = 2; int x = y + 2; // main driver method public static void main(String[] args) { // Creating an object of class inside main() method Test m = new Test(); // Printing the value of x and y // using above object created System.out.println("x = " + m.x + ", y = " + m.y); }} x = 4, y = 2 Output explanation: A pretty straightforward solution: As y is initialized first with the value 2, then x is initialized as y + 2. So the value of x becomes 4. Geek have you ever wondered what will happen when a member is initialized in class declaration and constructor both? Example 3: Java // filename: Test.java // Main claspublic class Test { // Declaring and initializing integer with custom value int x = 2; // Constructor of this class // Parameterized constructor Test(int i) { x = i; } // Main driver method public static void main(String[] args) { // Creating object of class in main() Test t = new Test(5); // Printing the value System.out.println("x = " + t.x); }} x = 5 Output explanation: The initialization with the class declaration in Java is like initialization using Initializer List in C++. So, in the above program, the value assigned inside the constructor overwrites the previous value of x which is 2, and x becomes 5. Example 4: Java // filename: Test2.java // Class 1// Helper classclass Test1 { // Constructor of this class Test1(int x) { // Print statement whenever this constructor is // called System.out.println("Constructor called " + x); }} // Class 2// Class contains an instance of Test1// Main classclass Test2 { // Creating instance(object) of class1 in this class Test1 t1 = new Test1(10); // Constructor of this class Test2(int i) { t1 = new Test1(i); } // Main driver method public static void main(String[] args) { // Creating instance of this class inside main() Test2 t2 = new Test2(5); }} Constructor called 10 Constructor called 5 Output explanation: First t2 object is instantiated in the main method. As the order of initialization of local variables comes first then the constructor, first the instance variable (t1), in the class Test2 is allocated to the memory. In this line a new Test1 object is created, the constructor is called in class Test1 and ‘Constructor called 10’ is printed. Next, the constructor of Test2 is called and again a new object of the class Test1 is created and ‘Constructor called 5’ is printed. Please write comments if you find any of the answers/explanations incorrect, or want to share more information about the topics discussed above. RupaShankar mannparikh23edu verma_anushka sooda367 simranarora5sos Java-Output Java Program Output Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Stream In Java ArrayList in Java Stack Class in Java Singleton Class in Java Arrow operator -> in C/C++ with Examples Output of Java Program | Set 1 delete keyword in C++ Output of C Programs | Set 1 Output of C++ programs | Set 34 (File Handling)
[ { "code": null, "e": 25695, "s": 25667, "text": "\n25 Feb, 2022" }, { "code": null, "e": 25746, "s": 25695, "text": "Predict the output of the following Java Programs:" }, { "code": null, "e": 25756, "s": 25746, "text": "Example1:" }, { "code": null, "e": 25761, "s": 25756, "text": "Java" }, { "code": "// filename: Test.java class Test { // Declaring and initializing integer variable int x = 10; // Main driver method public static void main(String[] args) { // Creating an object of class inside main() Test t = new Test(); // Printing the value inside the object by // above created object System.out.println(t.x); }}", "e": 26137, "s": 25761, "text": null }, { "code": null, "e": 26143, "s": 26140, "text": "10" }, { "code": null, "e": 26165, "s": 26145, "text": "Output explanation:" }, { "code": null, "e": 26388, "s": 26167, "text": "In Java, members can be initialized with the declaration of the class. This initialization works well when the initialization value is available and the initialization can be put on one line (See this for more details). " }, { "code": null, "e": 26402, "s": 26390, "text": "Example 2:" }, { "code": null, "e": 26409, "s": 26404, "text": "Java" }, { "code": "// filename: Test.java // Main classclass Test { // Declaring and initializing variables int y = 2; int x = y + 2; // main driver method public static void main(String[] args) { // Creating an object of class inside main() method Test m = new Test(); // Printing the value of x and y // using above object created System.out.println(\"x = \" + m.x + \", y = \" + m.y); }}", "e": 26837, "s": 26409, "text": null }, { "code": null, "e": 26853, "s": 26840, "text": "x = 4, y = 2" }, { "code": null, "e": 26875, "s": 26855, "text": "Output explanation:" }, { "code": null, "e": 27017, "s": 26877, "text": "A pretty straightforward solution: As y is initialized first with the value 2, then x is initialized as y + 2. So the value of x becomes 4." }, { "code": null, "e": 27137, "s": 27019, "text": "Geek have you ever wondered what will happen when a member is initialized in class declaration and constructor both? " }, { "code": null, "e": 27150, "s": 27139, "text": "Example 3:" }, { "code": null, "e": 27157, "s": 27152, "text": "Java" }, { "code": "// filename: Test.java // Main claspublic class Test { // Declaring and initializing integer with custom value int x = 2; // Constructor of this class // Parameterized constructor Test(int i) { x = i; } // Main driver method public static void main(String[] args) { // Creating object of class in main() Test t = new Test(5); // Printing the value System.out.println(\"x = \" + t.x); }}", "e": 27601, "s": 27157, "text": null }, { "code": null, "e": 27610, "s": 27604, "text": "x = 5" }, { "code": null, "e": 27633, "s": 27612, "text": "Output explanation: " }, { "code": null, "e": 27876, "s": 27635, "text": "The initialization with the class declaration in Java is like initialization using Initializer List in C++. So, in the above program, the value assigned inside the constructor overwrites the previous value of x which is 2, and x becomes 5. " }, { "code": null, "e": 27889, "s": 27878, "text": "Example 4:" }, { "code": null, "e": 27896, "s": 27891, "text": "Java" }, { "code": "// filename: Test2.java // Class 1// Helper classclass Test1 { // Constructor of this class Test1(int x) { // Print statement whenever this constructor is // called System.out.println(\"Constructor called \" + x); }} // Class 2// Class contains an instance of Test1// Main classclass Test2 { // Creating instance(object) of class1 in this class Test1 t1 = new Test1(10); // Constructor of this class Test2(int i) { t1 = new Test1(i); } // Main driver method public static void main(String[] args) { // Creating instance of this class inside main() Test2 t2 = new Test2(5); }}", "e": 28546, "s": 27896, "text": null }, { "code": null, "e": 28592, "s": 28549, "text": "Constructor called 10\nConstructor called 5" }, { "code": null, "e": 28614, "s": 28594, "text": "Output explanation:" }, { "code": null, "e": 29092, "s": 28616, "text": "First t2 object is instantiated in the main method. As the order of initialization of local variables comes first then the constructor, first the instance variable (t1), in the class Test2 is allocated to the memory. In this line a new Test1 object is created, the constructor is called in class Test1 and ‘Constructor called 10’ is printed. Next, the constructor of Test2 is called and again a new object of the class Test1 is created and ‘Constructor called 5’ is printed. " }, { "code": null, "e": 29240, "s": 29094, "text": "Please write comments if you find any of the answers/explanations incorrect, or want to share more information about the topics discussed above. " }, { "code": null, "e": 29254, "s": 29242, "text": "RupaShankar" }, { "code": null, "e": 29270, "s": 29254, "text": "mannparikh23edu" }, { "code": null, "e": 29284, "s": 29270, "text": "verma_anushka" }, { "code": null, "e": 29293, "s": 29284, "text": "sooda367" }, { "code": null, "e": 29309, "s": 29293, "text": "simranarora5sos" }, { "code": null, "e": 29321, "s": 29309, "text": "Java-Output" }, { "code": null, "e": 29326, "s": 29321, "text": "Java" }, { "code": null, "e": 29341, "s": 29326, "text": "Program Output" }, { "code": null, "e": 29346, "s": 29341, "text": "Java" }, { "code": null, "e": 29444, "s": 29346, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29463, "s": 29444, "text": "Interfaces in Java" }, { "code": null, "e": 29478, "s": 29463, "text": "Stream In Java" }, { "code": null, "e": 29496, "s": 29478, "text": "ArrayList in Java" }, { "code": null, "e": 29516, "s": 29496, "text": "Stack Class in Java" }, { "code": null, "e": 29540, "s": 29516, "text": "Singleton Class in Java" }, { "code": null, "e": 29581, "s": 29540, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 29612, "s": 29581, "text": "Output of Java Program | Set 1" }, { "code": null, "e": 29634, "s": 29612, "text": "delete keyword in C++" }, { "code": null, "e": 29663, "s": 29634, "text": "Output of C Programs | Set 1" } ]
MATLAB | Convert video into slow motion - GeeksforGeeks
29 Mar, 2019 MATLAB also called Matrix Laboratory is a numerical computing environment and a platform for programming language. it was designed and developed by MathWorks. MATLAB is a framework that allows you to perform matrix manipulations, implementing algorithms, plotting functions and data, creating user-interfaces and interfacing with programs that are written in different programming languages i.e. C, C++, python, java etc. Video:A video is a set of images known as frames. It contains four dimensions i.e. 1st dimension is for the rows, the 2nd one is for the columns, 3rd is for the RGB channel representation and the other dimension also gets added called time or frame number. Framerate:Frame rate is defined as the number of frames per second or fps. It is the frequency (rate) at which consecutive images called frames to appear on a display. To convert a video in slow motion we have the decrease framerate of the video. Approach: Load the video into a variable obj by using VideoReader() Use a new variable obj2 to create a new copy of this video which is appearing in fast mode by usingVideoWriter() decrease the framerate of the video. open obj2. read all the frames one by one from obj and store them into a variable k. Write all the frames in obj2 using writeVideo() Close obj2. To get the link to the input video, click here. Below is the imnplementaions: % MATLAB program to convert video into slow motionclc;clear;close all; % load the video.obj = VideoReader('C:/Users/Gfg/Desktop/Sample1280.avi'); % Write in new variableobj2= VideoWriter('xyz.avi'); % decrease framerate obj2.FrameRate = 10; open(obj2); % for reading frames one by onewhile hasFrame(obj) k = readFrame(obj); % write the frames in obj2. obj2.writeVideo(k); end close(obj2); Output: MATLAB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Decision Tree System Design Tutorial Decision Tree Introduction with example Python | Decision tree implementation Copying Files to and from Docker Containers ML | Underfitting and Overfitting Clustering in Machine Learning KDD Process in Data Mining
[ { "code": null, "e": 25843, "s": 25815, "text": "\n29 Mar, 2019" }, { "code": null, "e": 26265, "s": 25843, "text": "MATLAB also called Matrix Laboratory is a numerical computing environment and a platform for programming language. it was designed and developed by MathWorks. MATLAB is a framework that allows you to perform matrix manipulations, implementing algorithms, plotting functions and data, creating user-interfaces and interfacing with programs that are written in different programming languages i.e. C, C++, python, java etc." }, { "code": null, "e": 26522, "s": 26265, "text": "Video:A video is a set of images known as frames. It contains four dimensions i.e. 1st dimension is for the rows, the 2nd one is for the columns, 3rd is for the RGB channel representation and the other dimension also gets added called time or frame number." }, { "code": null, "e": 26690, "s": 26522, "text": "Framerate:Frame rate is defined as the number of frames per second or fps. It is the frequency (rate) at which consecutive images called frames to appear on a display." }, { "code": null, "e": 26769, "s": 26690, "text": "To convert a video in slow motion we have the decrease framerate of the video." }, { "code": null, "e": 26779, "s": 26769, "text": "Approach:" }, { "code": null, "e": 26837, "s": 26779, "text": "Load the video into a variable obj by using VideoReader()" }, { "code": null, "e": 26950, "s": 26837, "text": "Use a new variable obj2 to create a new copy of this video which is appearing in fast mode by usingVideoWriter()" }, { "code": null, "e": 26987, "s": 26950, "text": "decrease the framerate of the video." }, { "code": null, "e": 26998, "s": 26987, "text": "open obj2." }, { "code": null, "e": 27072, "s": 26998, "text": "read all the frames one by one from obj and store them into a variable k." }, { "code": null, "e": 27120, "s": 27072, "text": "Write all the frames in obj2 using writeVideo()" }, { "code": null, "e": 27132, "s": 27120, "text": "Close obj2." }, { "code": null, "e": 27180, "s": 27132, "text": "To get the link to the input video, click here." }, { "code": null, "e": 27210, "s": 27180, "text": "Below is the imnplementaions:" }, { "code": "% MATLAB program to convert video into slow motionclc;clear;close all; % load the video.obj = VideoReader('C:/Users/Gfg/Desktop/Sample1280.avi'); % Write in new variableobj2= VideoWriter('xyz.avi'); % decrease framerate obj2.FrameRate = 10; open(obj2); % for reading frames one by onewhile hasFrame(obj) k = readFrame(obj); % write the frames in obj2. obj2.writeVideo(k); end close(obj2);", "e": 27668, "s": 27210, "text": null }, { "code": null, "e": 27676, "s": 27668, "text": "Output:" }, { "code": null, "e": 27683, "s": 27676, "text": "MATLAB" }, { "code": null, "e": 27709, "s": 27683, "text": "Advanced Computer Subject" }, { "code": null, "e": 27807, "s": 27709, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27830, "s": 27807, "text": "ML | Linear Regression" }, { "code": null, "e": 27853, "s": 27830, "text": "Reinforcement learning" }, { "code": null, "e": 27867, "s": 27853, "text": "Decision Tree" }, { "code": null, "e": 27890, "s": 27867, "text": "System Design Tutorial" }, { "code": null, "e": 27930, "s": 27890, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 27968, "s": 27930, "text": "Python | Decision tree implementation" }, { "code": null, "e": 28012, "s": 27968, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 28046, "s": 28012, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 28077, "s": 28046, "text": "Clustering in Machine Learning" } ]
How to change colorbar labels in matplotlib ? - GeeksforGeeks
29 Dec, 2021 In this article, we are going to see how to change color bar labels in matplotlib using Python. The colorbar() function is used to plot the color bar which belongs to the pyplot module of matplotlib adds a colorbar to a plot indicating the color scale. Syntax: matplotlib.pyplot.colorbar(mappable=None, cax=None, ax=None, **kwarg) Parameters: ax: This parameter is an optional parameter and it contains Axes or list of Axes. **kwarg(keyword arguments): This parameter is an optional parameter and are of two kinds: colorbar properties: extend:{‘neither’, ‘both’, ‘min’, ‘max’} makes pointed end(s) for out-of-range values. label:The label on the colorbar’s long axis. ticks:None or list of ticks or Locator. Returns:colorbar which is an instance of the class ‘matplotlib.colorbar.Colorbar’. To create the colorbar we will use color() methods, for this, we will create the dataset and then use a scatterplot for demonstration. Python3 # Python Program illustrating# pyplot.colorbar() methodimport numpy as npimport matplotlib.pyplot as plt # Dataset# List of total number of items purchased# from each productspurchaseCount = [100, 200, 150, 23, 30, 50, 156, 32, 67, 89] # List of total likes of 10 productslikes = [50, 70, 100, 10, 10, 34, 56, 18, 35, 45] # List of Like/Dislike ratio of 10 productsratio = [1, 0.53, 2, 0.76, 0.5, 2.125, 0.56, 1.28, 1.09, 1.02] # scatterplotplt.scatter(x=purchaseCount, y=likes, c=ratio, cmap="summer") plt.colorbar()plt.show() Output: To change the label’s font size we will use ax.tick_params() methods which increase the font of the labels. Python3 # Python Program illustrating# pyplot.colorbar() methodimport numpy as npimport matplotlib.pyplot as plt # Dataset# List of total number of items purchased# from each productspurchaseCount = [100, 200, 150, 23, 30, 50, 156, 32, 67, 89] # List of total likes of 10 productslikes = [50, 70, 100, 10, 10, 34, 56, 18, 35, 45] # List of Like/Dislike ratio of 10 productsratio = [1, 0.53, 2, 0.76, 0.5, 2.125, 0.56, 1.28, 1.09, 1.02] # scatterplotplt.scatter(x=purchaseCount, y=likes, c=ratio, cmap="summer") plt.colorbar().ax.tick_params(labelsize=10) plt.show() Output: To rotate the colorbar labels we will use set_xticklabels() and set_yticklabels() methods for horizontal and vertical. Example 1: Changing position horizontally Python3 # Python Program illustrating# pyplot.colorbar() methodimport numpy as npimport matplotlib.pyplot as plt # Dataset# List of total number of items purchased# from each productspurchaseCount = [100, 200, 150, 23, 30, 50, 156, 32, 67, 89] # List of total likes of 10 productslikes = [50, 70, 100, 10, 10, 34, 56, 18, 35, 45] # List of Like/Dislike ratio of 10 productsratio = [1, 0.53, 2, 0.76, 0.5, 2.125, 0.56, 1.28, 1.09, 1.02] # scatterplotplt.scatter(x=purchaseCount, y=likes, c=ratio, cmap="summer") plt.colorbar().ax.set_ylabel('Label', rotation=120) plt.show() Output: Example 2: Changing position vertically Python3 # Python Program illustrating# pyplot.colorbar() methodimport numpy as npimport matplotlib.pyplot as plt # Dataset# List of total number of items purchased# from each productspurchaseCount = [100, 200, 150, 23, 30, 50, 156, 32, 67, 89] # List of total likes of 10 productslikes = [50, 70, 100, 10, 10, 34, 56, 18, 35, 45] # List of Like/Dislike ratio of 10 productsratio = [1, 0.53, 2, 0.76, 0.5, 2.125, 0.56, 1.28, 1.09, 1.02] # scatterplotplt.scatter(x=purchaseCount, y=likes, c=ratio, cmap="summer")plt.colorbar(orientation="horizontal").ax.set_xticklabels(ratio, rotation=45) plt.show() Output: anikakapoor Picked Python-matplotlib 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": "\n29 Dec, 2021" }, { "code": null, "e": 25651, "s": 25555, "text": "In this article, we are going to see how to change color bar labels in matplotlib using Python." }, { "code": null, "e": 25808, "s": 25651, "text": "The colorbar() function is used to plot the color bar which belongs to the pyplot module of matplotlib adds a colorbar to a plot indicating the color scale." }, { "code": null, "e": 25886, "s": 25808, "text": "Syntax: matplotlib.pyplot.colorbar(mappable=None, cax=None, ax=None, **kwarg)" }, { "code": null, "e": 25898, "s": 25886, "text": "Parameters:" }, { "code": null, "e": 25980, "s": 25898, "text": "ax: This parameter is an optional parameter and it contains Axes or list of Axes." }, { "code": null, "e": 26070, "s": 25980, "text": "**kwarg(keyword arguments): This parameter is an optional parameter and are of two kinds:" }, { "code": null, "e": 26091, "s": 26070, "text": "colorbar properties:" }, { "code": null, "e": 26178, "s": 26091, "text": "extend:{‘neither’, ‘both’, ‘min’, ‘max’} makes pointed end(s) for out-of-range values." }, { "code": null, "e": 26223, "s": 26178, "text": "label:The label on the colorbar’s long axis." }, { "code": null, "e": 26263, "s": 26223, "text": "ticks:None or list of ticks or Locator." }, { "code": null, "e": 26351, "s": 26263, "text": "Returns:colorbar which is an instance of the class ‘matplotlib.colorbar.Colorbar’. " }, { "code": null, "e": 26486, "s": 26351, "text": "To create the colorbar we will use color() methods, for this, we will create the dataset and then use a scatterplot for demonstration." }, { "code": null, "e": 26494, "s": 26486, "text": "Python3" }, { "code": "# Python Program illustrating# pyplot.colorbar() methodimport numpy as npimport matplotlib.pyplot as plt # Dataset# List of total number of items purchased# from each productspurchaseCount = [100, 200, 150, 23, 30, 50, 156, 32, 67, 89] # List of total likes of 10 productslikes = [50, 70, 100, 10, 10, 34, 56, 18, 35, 45] # List of Like/Dislike ratio of 10 productsratio = [1, 0.53, 2, 0.76, 0.5, 2.125, 0.56, 1.28, 1.09, 1.02] # scatterplotplt.scatter(x=purchaseCount, y=likes, c=ratio, cmap=\"summer\") plt.colorbar()plt.show()", "e": 27044, "s": 26494, "text": null }, { "code": null, "e": 27052, "s": 27044, "text": "Output:" }, { "code": null, "e": 27160, "s": 27052, "text": "To change the label’s font size we will use ax.tick_params() methods which increase the font of the labels." }, { "code": null, "e": 27168, "s": 27160, "text": "Python3" }, { "code": "# Python Program illustrating# pyplot.colorbar() methodimport numpy as npimport matplotlib.pyplot as plt # Dataset# List of total number of items purchased# from each productspurchaseCount = [100, 200, 150, 23, 30, 50, 156, 32, 67, 89] # List of total likes of 10 productslikes = [50, 70, 100, 10, 10, 34, 56, 18, 35, 45] # List of Like/Dislike ratio of 10 productsratio = [1, 0.53, 2, 0.76, 0.5, 2.125, 0.56, 1.28, 1.09, 1.02] # scatterplotplt.scatter(x=purchaseCount, y=likes, c=ratio, cmap=\"summer\") plt.colorbar().ax.tick_params(labelsize=10) plt.show()", "e": 27759, "s": 27168, "text": null }, { "code": null, "e": 27767, "s": 27759, "text": "Output:" }, { "code": null, "e": 27886, "s": 27767, "text": "To rotate the colorbar labels we will use set_xticklabels() and set_yticklabels() methods for horizontal and vertical." }, { "code": null, "e": 27928, "s": 27886, "text": "Example 1: Changing position horizontally" }, { "code": null, "e": 27936, "s": 27928, "text": "Python3" }, { "code": "# Python Program illustrating# pyplot.colorbar() methodimport numpy as npimport matplotlib.pyplot as plt # Dataset# List of total number of items purchased# from each productspurchaseCount = [100, 200, 150, 23, 30, 50, 156, 32, 67, 89] # List of total likes of 10 productslikes = [50, 70, 100, 10, 10, 34, 56, 18, 35, 45] # List of Like/Dislike ratio of 10 productsratio = [1, 0.53, 2, 0.76, 0.5, 2.125, 0.56, 1.28, 1.09, 1.02] # scatterplotplt.scatter(x=purchaseCount, y=likes, c=ratio, cmap=\"summer\") plt.colorbar().ax.set_ylabel('Label', rotation=120) plt.show()", "e": 28563, "s": 27936, "text": null }, { "code": null, "e": 28571, "s": 28563, "text": "Output:" }, { "code": null, "e": 28611, "s": 28571, "text": "Example 2: Changing position vertically" }, { "code": null, "e": 28619, "s": 28611, "text": "Python3" }, { "code": "# Python Program illustrating# pyplot.colorbar() methodimport numpy as npimport matplotlib.pyplot as plt # Dataset# List of total number of items purchased# from each productspurchaseCount = [100, 200, 150, 23, 30, 50, 156, 32, 67, 89] # List of total likes of 10 productslikes = [50, 70, 100, 10, 10, 34, 56, 18, 35, 45] # List of Like/Dislike ratio of 10 productsratio = [1, 0.53, 2, 0.76, 0.5, 2.125, 0.56, 1.28, 1.09, 1.02] # scatterplotplt.scatter(x=purchaseCount, y=likes, c=ratio, cmap=\"summer\")plt.colorbar(orientation=\"horizontal\").ax.set_xticklabels(ratio, rotation=45) plt.show()", "e": 29232, "s": 28619, "text": null }, { "code": null, "e": 29240, "s": 29232, "text": "Output:" }, { "code": null, "e": 29252, "s": 29240, "text": "anikakapoor" }, { "code": null, "e": 29259, "s": 29252, "text": "Picked" }, { "code": null, "e": 29277, "s": 29259, "text": "Python-matplotlib" }, { "code": null, "e": 29284, "s": 29277, "text": "Python" }, { "code": null, "e": 29382, "s": 29284, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29414, "s": 29382, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29456, "s": 29414, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29498, "s": 29456, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29554, "s": 29498, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29581, "s": 29554, "text": "Python Classes and Objects" }, { "code": null, "e": 29612, "s": 29581, "text": "Python | os.path.join() method" }, { "code": null, "e": 29651, "s": 29612, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29680, "s": 29651, "text": "Create a directory in Python" }, { "code": null, "e": 29702, "s": 29680, "text": "Defaultdict in Python" } ]
Using Neo4j with PySpark on Databricks | by Lukas Böhres | Towards Data Science
With the recent release of the official Neo4j Connector for Apache Spark leveraging the Spark DataSource API, there has been a fundamental change in the way that Neo4j data can be queried from within an Apache Spark environment. Alongside this change, the previous Neo4j Spark Connector was marked as deprecated. In this article, I’d like to share an updated end-to-end workflow of setting up a fully interconnected pairing of Neo4j and Spark that makes use of the new connector’s capabilities. In the process, we will first set up a Neo4j cloud instance using an Azure virtual machine. Afterwards, we will set up an Azure Databricks instance running Spark before finally establishing a connection between both resources using the new Neo4j Connector for Apache Spark. If you already have an up-and-running instance of Neo4j or Databricks, you might of course want to skip the respective steps. However, please note the compatibility information at the top of each step. First, a quick word on compatibility: The connector we are going to use supports Neo4j versions 3.5 and above. Versions prior to 3.5 are not supported. It does however support both Neo4j Enterprise and Community as well as single instance VMs, Causal Clusters and Neo4j Aura. This article is going to focus on the workflow for a single instance VM. As our Neo4j instance, we will use the official Neo4j Enterprise VM image. The latest version is listed as Neo4j Enterprise VM version 4.1 in the Azure marketplace. If you don’t have an Enterprise license, there are images of the Community version offered by Websoft9 as well as Container Images by Bitnami: After the VM is deployed, navigate to it’s Networking tab to make sure that its port settings are correct: In order to query it from Spark, a Bolt port must allow inbound traffic. By default, this is port 7687. Additionally, we will use the Neo4j Web interface to populate the database, for which we need an open HTTP or HTTPS port. By default, they are mapped to port numbers 7474 and 7473. If any of these port rules are missing, add them by clicking the Add Inbound Port Rule button. Once you verified the port settings, grab the VM’s public IP from its Overview tab and connect to it via HTTP by navigating to http://YOUR.VM.IP.ADDRESS:7474 in your browser. With a freshly started VM, it might take a few minutes before Neo4j has started up and accepts inbound connections. If you use VPN or Proxies, make sure they are configured accordingly, otherwise you might receive a “This site can’t be reached” error. If all settings are correct, the Neo4j Browser Web UI will pop up: You will be prompted for login credentials. Enter the default username and password to log in to your database: username: neo4j password: neo4j On your first access, you will immediately have to change the default password for security reasons. After choosing a solid password and logging in, you can populate the database. In this guide, we will use the Cypher query language to create a simple dummy dataset by typing the following into the command line: UNWIND range(1,100) as idCREATE (p:Person {id:id}) WITH collect(p) as peopleUNWIND people as p1UNWIND range(1,10) as friendWITH p1, people[(p1.id + friend) % size(people)] as p2CREATE (p1)-[:KNOWS {years: abs(p2.id - p2.id)}]->(p2) As a result, a data structure similar to the following will be created, where each Person node is tagged with an ID and each KNOWS relation has an additional (arbitrary) attribute years that describes how long the two parties have known each other: That’s it! Our Neo4j graph database is up and running and can’t wait to be queried from Spark. We will now move on to setting up an appropriate Spark environment. Again, an important note on compatibility: At the time of writing, Neo4j does not support a connector for Spark 3.0. As such, we will have to fall back to a Spark 2.4 environment in order to communicate with Neo4j. For our setup, we will use an Azure Databricks instance. Search for databricks on the Azure marketplace and create a new resource. Apart from the usual settings (resource group, name, location and pricing tier), no special configuration settings are required. Once deployed, open up your Databricks workspace by navigating to your Azure resource’s overview tab and clicking the Launch Workspace button. First, we will need a cluster to work with. Navigate to the Clusters tab and click the Create Cluster button to display the cluster configuration tool: Choose a cluster name and availability mode and configure the size and amount of worker nodes to your liking. Now, remember that we are forced to use a Spark 2 setup — luckily, Databricks still offers a variety of Spark 2.4.5 distributions. Make sure to select one of them in the Databricks Runtime Version field, e.g. Runtime Version 6.6 running Spark 2.4.5 and Scala 2.11. Start your cluster and you’re good to go! Since we now have both Neo4j and Databricks up and running, it’s time to focus on the connection between them. In order to do so, we will need to add the Neo4j Connector for Apache Spark to our Databricks cluster. In Databricks, navigate to the cluster tab. Select the previously created cluster and access its libraries options: Now, add the Neo4j Connector for Apache Spark by clicking the Install New button, select Maven and clicking Search Packages. Type ‘neo4j’ to see all available options. At the time of writing, there are three packages coming up in the search: neo4j-spark-connector: This is the deprecated connector version (2.4). It is no longer actively supported by the developers. neo4j-connector-apache-spark_2.11: This is the current connector version (4.0) and the one we are going to use. neo4j-connector-apache-spark_2.12: This is the current connector version as well, the only difference being that is is written for Scala version 2.12. Since our Databricks environment runs Scala 2.11, this one is not suitable for our purpose. According to the developers, the split in two separate connectors is necessary due to API differences: Because of the differences in the APIs, different JAR files are needed depending on your scala version. Ensure that you have the appropriate JAR file for your environment. After the connector is installed, create a new Jupyter notebook in the Workspace tab (right click → Create New). Try reading the node data of your Neo4j database by running the following command after inserting your Neo4j VM’s IP, username and password: df = spark.read.format("org.neo4j.spark.DataSource")\ .option("url", "bolt://XXX.XXX.XXX.XXX:7687")\ .option("authentication.type", "basic")\ .option("authentication.basic.username", "neo4j")\ .option("authentication.basic.password", "password")\ .option("labels", "Person")\ .load()display(df) In case you receive an Unable to connect error, make sure your Neo4j VM is still running and its Bolt port accepts inbound traffic. If the query returns java.lang.NoSuchMethodError: scala.Product.$init$(Lscala/Product;)V you most likely installed the connector for the wrong Scala version — make sure you select the Scala 2.11 version (see above). If all worked out, the query will return a DataFrame similar to this: As an alternative to Python, you can also use Scala for your queries by adding the %scala magic command at the top of your Notebook cells: %scalaimport org.apache.spark.sql.{SaveMode, SparkSession}val spark = SparkSession.builder().getOrCreate()val df = spark.read.format("org.neo4j.spark.DataSource") .option("url", "bolt://XXX.XXX.XXX.XXX:7687") .option("authentication.type", "basic") .option("authentication.basic.username", "neo4j") .option("authentication.basic.password", "password") .option("labels", "Person") .load()display(df) Writing to your Graph Database works similar in a similar way. In the following query, we will update our original data to include names for the first two nodes: df = spark.createDataFrame( [(1, "John"),(2, "Thomas")], ["id", "name"])df.write.format("org.neo4j.spark.DataSource")\ .option("url”, "bolt://XXX.XXX.XXX.XXX:7687")\ .option("authentication.type", "basic")\ .option("authentication.basic.username", "neo4j")\ .option("authentication.basic.password", "password")\ .option("labels", ":Person")\ .option("node.keys", "id")\ .mode("Overwrite")\ .save() Note that we use the “Overwrite” mode along with setting the node.keys option to the DataFrame’s id column in order to append the new values to our existing nodes. In fact, running the read query again returns our previous result updated with a name property for the first two nodes: And that’s it! 🎉 You have successfully set up a fully cloud-based and interconnected pair of Apache Spark and Neo4j, allowing you to leverage the full potential of “traditional” Big Data and Graph Databases working hand in hand. For more query examples and syntax overview, take a deep dive into the official Neo4j Connector for Apache Spark documentation or check the quick guides on reading and writing from/to Neo4j. Additional examples can be found in the Zeppelin notebook example repository. The connector also supports Cypher queries, allowing you to re-use existing queries from Neo4j Desktop / Web applications. Examples for Cypher queries can be found on the official Cypher page.
[ { "code": null, "e": 667, "s": 172, "text": "With the recent release of the official Neo4j Connector for Apache Spark leveraging the Spark DataSource API, there has been a fundamental change in the way that Neo4j data can be queried from within an Apache Spark environment. Alongside this change, the previous Neo4j Spark Connector was marked as deprecated. In this article, I’d like to share an updated end-to-end workflow of setting up a fully interconnected pairing of Neo4j and Spark that makes use of the new connector’s capabilities." }, { "code": null, "e": 1143, "s": 667, "text": "In the process, we will first set up a Neo4j cloud instance using an Azure virtual machine. Afterwards, we will set up an Azure Databricks instance running Spark before finally establishing a connection between both resources using the new Neo4j Connector for Apache Spark. If you already have an up-and-running instance of Neo4j or Databricks, you might of course want to skip the respective steps. However, please note the compatibility information at the top of each step." }, { "code": null, "e": 1492, "s": 1143, "text": "First, a quick word on compatibility: The connector we are going to use supports Neo4j versions 3.5 and above. Versions prior to 3.5 are not supported. It does however support both Neo4j Enterprise and Community as well as single instance VMs, Causal Clusters and Neo4j Aura. This article is going to focus on the workflow for a single instance VM." }, { "code": null, "e": 1800, "s": 1492, "text": "As our Neo4j instance, we will use the official Neo4j Enterprise VM image. The latest version is listed as Neo4j Enterprise VM version 4.1 in the Azure marketplace. If you don’t have an Enterprise license, there are images of the Community version offered by Websoft9 as well as Container Images by Bitnami:" }, { "code": null, "e": 2287, "s": 1800, "text": "After the VM is deployed, navigate to it’s Networking tab to make sure that its port settings are correct: In order to query it from Spark, a Bolt port must allow inbound traffic. By default, this is port 7687. Additionally, we will use the Neo4j Web interface to populate the database, for which we need an open HTTP or HTTPS port. By default, they are mapped to port numbers 7474 and 7473. If any of these port rules are missing, add them by clicking the Add Inbound Port Rule button." }, { "code": null, "e": 2714, "s": 2287, "text": "Once you verified the port settings, grab the VM’s public IP from its Overview tab and connect to it via HTTP by navigating to http://YOUR.VM.IP.ADDRESS:7474 in your browser. With a freshly started VM, it might take a few minutes before Neo4j has started up and accepts inbound connections. If you use VPN or Proxies, make sure they are configured accordingly, otherwise you might receive a “This site can’t be reached” error." }, { "code": null, "e": 2781, "s": 2714, "text": "If all settings are correct, the Neo4j Browser Web UI will pop up:" }, { "code": null, "e": 2893, "s": 2781, "text": "You will be prompted for login credentials. Enter the default username and password to log in to your database:" }, { "code": null, "e": 2909, "s": 2893, "text": "username: neo4j" }, { "code": null, "e": 2925, "s": 2909, "text": "password: neo4j" }, { "code": null, "e": 3238, "s": 2925, "text": "On your first access, you will immediately have to change the default password for security reasons. After choosing a solid password and logging in, you can populate the database. In this guide, we will use the Cypher query language to create a simple dummy dataset by typing the following into the command line:" }, { "code": null, "e": 3470, "s": 3238, "text": "UNWIND range(1,100) as idCREATE (p:Person {id:id}) WITH collect(p) as peopleUNWIND people as p1UNWIND range(1,10) as friendWITH p1, people[(p1.id + friend) % size(people)] as p2CREATE (p1)-[:KNOWS {years: abs(p2.id - p2.id)}]->(p2)" }, { "code": null, "e": 3719, "s": 3470, "text": "As a result, a data structure similar to the following will be created, where each Person node is tagged with an ID and each KNOWS relation has an additional (arbitrary) attribute years that describes how long the two parties have known each other:" }, { "code": null, "e": 3882, "s": 3719, "text": "That’s it! Our Neo4j graph database is up and running and can’t wait to be queried from Spark. We will now move on to setting up an appropriate Spark environment." }, { "code": null, "e": 4097, "s": 3882, "text": "Again, an important note on compatibility: At the time of writing, Neo4j does not support a connector for Spark 3.0. As such, we will have to fall back to a Spark 2.4 environment in order to communicate with Neo4j." }, { "code": null, "e": 4357, "s": 4097, "text": "For our setup, we will use an Azure Databricks instance. Search for databricks on the Azure marketplace and create a new resource. Apart from the usual settings (resource group, name, location and pricing tier), no special configuration settings are required." }, { "code": null, "e": 4500, "s": 4357, "text": "Once deployed, open up your Databricks workspace by navigating to your Azure resource’s overview tab and clicking the Launch Workspace button." }, { "code": null, "e": 4652, "s": 4500, "text": "First, we will need a cluster to work with. Navigate to the Clusters tab and click the Create Cluster button to display the cluster configuration tool:" }, { "code": null, "e": 5027, "s": 4652, "text": "Choose a cluster name and availability mode and configure the size and amount of worker nodes to your liking. Now, remember that we are forced to use a Spark 2 setup — luckily, Databricks still offers a variety of Spark 2.4.5 distributions. Make sure to select one of them in the Databricks Runtime Version field, e.g. Runtime Version 6.6 running Spark 2.4.5 and Scala 2.11." }, { "code": null, "e": 5069, "s": 5027, "text": "Start your cluster and you’re good to go!" }, { "code": null, "e": 5283, "s": 5069, "text": "Since we now have both Neo4j and Databricks up and running, it’s time to focus on the connection between them. In order to do so, we will need to add the Neo4j Connector for Apache Spark to our Databricks cluster." }, { "code": null, "e": 5399, "s": 5283, "text": "In Databricks, navigate to the cluster tab. Select the previously created cluster and access its libraries options:" }, { "code": null, "e": 5641, "s": 5399, "text": "Now, add the Neo4j Connector for Apache Spark by clicking the Install New button, select Maven and clicking Search Packages. Type ‘neo4j’ to see all available options. At the time of writing, there are three packages coming up in the search:" }, { "code": null, "e": 5766, "s": 5641, "text": "neo4j-spark-connector: This is the deprecated connector version (2.4). It is no longer actively supported by the developers." }, { "code": null, "e": 5878, "s": 5766, "text": "neo4j-connector-apache-spark_2.11: This is the current connector version (4.0) and the one we are going to use." }, { "code": null, "e": 6121, "s": 5878, "text": "neo4j-connector-apache-spark_2.12: This is the current connector version as well, the only difference being that is is written for Scala version 2.12. Since our Databricks environment runs Scala 2.11, this one is not suitable for our purpose." }, { "code": null, "e": 6224, "s": 6121, "text": "According to the developers, the split in two separate connectors is necessary due to API differences:" }, { "code": null, "e": 6396, "s": 6224, "text": "Because of the differences in the APIs, different JAR files are needed depending on your scala version. Ensure that you have the appropriate JAR file for your environment." }, { "code": null, "e": 6650, "s": 6396, "text": "After the connector is installed, create a new Jupyter notebook in the Workspace tab (right click → Create New). Try reading the node data of your Neo4j database by running the following command after inserting your Neo4j VM’s IP, username and password:" }, { "code": null, "e": 6945, "s": 6650, "text": "df = spark.read.format(\"org.neo4j.spark.DataSource\")\\ .option(\"url\", \"bolt://XXX.XXX.XXX.XXX:7687\")\\ .option(\"authentication.type\", \"basic\")\\ .option(\"authentication.basic.username\", \"neo4j\")\\ .option(\"authentication.basic.password\", \"password\")\\ .option(\"labels\", \"Person\")\\ .load()display(df)" }, { "code": null, "e": 7098, "s": 6945, "text": "In case you receive an Unable to connect error, make sure your Neo4j VM is still running and its Bolt port accepts inbound traffic. If the query returns" }, { "code": null, "e": 7166, "s": 7098, "text": "java.lang.NoSuchMethodError: scala.Product.$init$(Lscala/Product;)V" }, { "code": null, "e": 7293, "s": 7166, "text": "you most likely installed the connector for the wrong Scala version — make sure you select the Scala 2.11 version (see above)." }, { "code": null, "e": 7363, "s": 7293, "text": "If all worked out, the query will return a DataFrame similar to this:" }, { "code": null, "e": 7502, "s": 7363, "text": "As an alternative to Python, you can also use Scala for your queries by adding the %scala magic command at the top of your Notebook cells:" }, { "code": null, "e": 7901, "s": 7502, "text": "%scalaimport org.apache.spark.sql.{SaveMode, SparkSession}val spark = SparkSession.builder().getOrCreate()val df = spark.read.format(\"org.neo4j.spark.DataSource\") .option(\"url\", \"bolt://XXX.XXX.XXX.XXX:7687\") .option(\"authentication.type\", \"basic\") .option(\"authentication.basic.username\", \"neo4j\") .option(\"authentication.basic.password\", \"password\") .option(\"labels\", \"Person\") .load()display(df)" }, { "code": null, "e": 8063, "s": 7901, "text": "Writing to your Graph Database works similar in a similar way. In the following query, we will update our original data to include names for the first two nodes:" }, { "code": null, "e": 8461, "s": 8063, "text": "df = spark.createDataFrame( [(1, \"John\"),(2, \"Thomas\")], [\"id\", \"name\"])df.write.format(\"org.neo4j.spark.DataSource\")\\ .option(\"url”, \"bolt://XXX.XXX.XXX.XXX:7687\")\\ .option(\"authentication.type\", \"basic\")\\ .option(\"authentication.basic.username\", \"neo4j\")\\ .option(\"authentication.basic.password\", \"password\")\\ .option(\"labels\", \":Person\")\\ .option(\"node.keys\", \"id\")\\ .mode(\"Overwrite\")\\ .save()" }, { "code": null, "e": 8745, "s": 8461, "text": "Note that we use the “Overwrite” mode along with setting the node.keys option to the DataFrame’s id column in order to append the new values to our existing nodes. In fact, running the read query again returns our previous result updated with a name property for the first two nodes:" }, { "code": null, "e": 8974, "s": 8745, "text": "And that’s it! 🎉 You have successfully set up a fully cloud-based and interconnected pair of Apache Spark and Neo4j, allowing you to leverage the full potential of “traditional” Big Data and Graph Databases working hand in hand." } ]
How to get android notifications when the app was closed?
This example demonstrate about How to get android notifications when the app was closed Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <? xml version = "1.0" encoding = "utf-8" ?> <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android :layout_width = "match_parent" android :layout_height = "match_parent" android :padding = "16dp" tools :context = ".MainActivity" > <Button android :layout_width = "match_parent" android :layout_height = "wrap_content" android :layout_centerInParent = "true" android :onClick = "closeApp" android :text = "close App for notification" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity package app.tutorialspoint.com.notifyme ; import android.content.Intent ; import android.os.Bundle ; import android.support.v7.app.AppCompatActivity ; import android.view.View ; public class MainActivity extends AppCompatActivity { @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState) ; setContentView(R.layout. activity_main ) ; } @Override protected void onStop () { super .onStop() ; startService( new Intent( this, NotificationService. class )) ; } public void closeApp (View view) { finish() ; } } Step 4 − Add the following code to src/NotificationService package app.tutorialspoint.com.notifyme ; import android.app.NotificationChannel ; import android.app.NotificationManager ; import android.app.Service ; import android.content.Intent ; import android.os.Handler ; import android.os.IBinder ; import android.support.v4.app.NotificationCompat ; import android.util.Log ; import java.util.Timer ; import java.util.TimerTask ; public class NotificationService extends Service { public static final String NOTIFICATION_CHANNEL_ID = "10001" ; private final static String default_notification_channel_id = "default" ; Timer timer ; TimerTask timerTask ; String TAG = "Timers" ; int Your_X_SECS = 5 ; @Override public IBinder onBind (Intent arg0) { return null; } @Override public int onStartCommand (Intent intent , int flags , int startId) { Log. e ( TAG , "onStartCommand" ) ; super .onStartCommand(intent , flags , startId) ; startTimer() ; return START_STICKY ; } @Override public void onCreate () { Log. e ( TAG , "onCreate" ) ; } @Override public void onDestroy () { Log. e ( TAG , "onDestroy" ) ; stopTimerTask() ; super .onDestroy() ; } //we are going to use a handler to be able to run in our TimerTask final Handler handler = new Handler() ; public void startTimer () { timer = new Timer() ; initializeTimerTask() ; timer .schedule( timerTask , 5000 , Your_X_SECS * 1000 ) ; // } public void stopTimerTask () { if ( timer != null ) { timer .cancel() ; timer = null; } } public void initializeTimerTask () { timerTask = new TimerTask() { public void run () { handler .post( new Runnable() { public void run () { createNotification() ; } }) ; } } ; } private void createNotification () { NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ; NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext() , default_notification_channel_id ) ; mBuilder.setContentTitle( "My Notification" ) ; mBuilder.setContentText( "Notification Listener Service Example" ) ; mBuilder.setTicker( "Notification Listener Service Example" ) ; mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ; mBuilder.setAutoCancel( true ) ; if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) { int importance = NotificationManager. IMPORTANCE_HIGH ; NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ; mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ; assert mNotificationManager != null; mNotificationManager.createNotificationChannel(notificationChannel) ; } assert mNotificationManager != null; mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ; } } Step 5 − Add the following code to AndroidManifest.xml <? xml version = "1.0" encoding = "utf-8" ?> <manifest xmlns: android = "http://schemas.android.com/apk/res/android" package = "app.tutorialspoint.com.notifyme" > <uses-permission android :name = "android.permission.VIBRATE" /> <application android :allowBackup = "true" android :icon = "@mipmap/ic_launcher" android :label = "@string/app_name" android :roundIcon = "@mipmap/ic_launcher_round" android :supportsRtl = "true" android :theme = "@style/AppTheme" > <activity android :name = ".MainActivity" > <intent-filter> <action android :name = "android.intent.action.MAIN" /> <category android :name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android :name = ".NotificationService" android :label = "@string/app_name" > <intent-filter> <action android :name = "app.tutorialspoint.com.notifyme.NotificationService" /> <category android :name = "android.intent.category.DEFAULT" /> </intent-filter> </service> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code
[ { "code": null, "e": 1150, "s": 1062, "text": "This example demonstrate about How to get android notifications when the app was closed" }, { "code": null, "e": 1279, "s": 1150, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1344, "s": 1279, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1928, "s": 1344, "text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width = \"match_parent\"\n android :layout_height = \"match_parent\"\n android :padding = \"16dp\"\n tools :context = \".MainActivity\" >\n <Button\n android :layout_width = \"match_parent\"\n android :layout_height = \"wrap_content\"\n android :layout_centerInParent = \"true\"\n android :onClick = \"closeApp\"\n android :text = \"close App for notification\" />\n</RelativeLayout>" }, { "code": null, "e": 1980, "s": 1928, "text": "Step 3 − Add the following code to src/MainActivity" }, { "code": null, "e": 2584, "s": 1980, "text": "package app.tutorialspoint.com.notifyme ;\nimport android.content.Intent ;\nimport android.os.Bundle ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.View ;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n }\n @Override\n protected void onStop () {\n super .onStop() ;\n startService( new Intent( this, NotificationService. class )) ;\n }\n public void closeApp (View view) {\n finish() ;\n }\n}" }, { "code": null, "e": 2643, "s": 2584, "text": "Step 4 − Add the following code to src/NotificationService" }, { "code": null, "e": 5754, "s": 2643, "text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.NotificationChannel ;\nimport android.app.NotificationManager ;\nimport android.app.Service ;\nimport android.content.Intent ;\nimport android.os.Handler ;\nimport android.os.IBinder ;\nimport android.support.v4.app.NotificationCompat ;\nimport android.util.Log ;\nimport java.util.Timer ;\nimport java.util.TimerTask ;\npublic class NotificationService extends Service {\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n Timer timer ;\n TimerTask timerTask ;\n String TAG = \"Timers\" ;\n int Your_X_SECS = 5 ;\n @Override\n public IBinder onBind (Intent arg0) {\n return null;\n }\n @Override\n public int onStartCommand (Intent intent , int flags , int startId) {\n Log. e ( TAG , \"onStartCommand\" ) ;\n super .onStartCommand(intent , flags , startId) ;\n startTimer() ;\n return START_STICKY ;\n }\n @Override\n public void onCreate () {\n Log. e ( TAG , \"onCreate\" ) ;\n }\n @Override\n public void onDestroy () {\n Log. e ( TAG , \"onDestroy\" ) ;\n stopTimerTask() ;\n super .onDestroy() ;\n }\n //we are going to use a handler to be able to run in our TimerTask\n final Handler handler = new Handler() ;\n public void startTimer () {\n timer = new Timer() ;\n initializeTimerTask() ;\n timer .schedule( timerTask , 5000 , Your_X_SECS * 1000 ) ; //\n }\n public void stopTimerTask () {\n if ( timer != null ) {\n timer .cancel() ;\n timer = null;\n }\n }\n public void initializeTimerTask () {\n timerTask = new TimerTask() {\n public void run () {\n handler .post( new Runnable() {\n public void run () {\n createNotification() ;\n }\n }) ;\n }\n } ;\n }\n private void createNotification () {\n NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ;\n NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext() , default_notification_channel_id ) ;\n mBuilder.setContentTitle( \"My Notification\" ) ;\n mBuilder.setContentText( \"Notification Listener Service Example\" ) ;\n mBuilder.setTicker( \"Notification Listener Service Example\" ) ;\n mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;\n mBuilder.setAutoCancel( true ) ;\n if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {\n int importance = NotificationManager. IMPORTANCE_HIGH ;\n NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , \"NOTIFICATION_CHANNEL_NAME\" , importance) ;\n mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;\n assert mNotificationManager != null;\n mNotificationManager.createNotificationChannel(notificationChannel) ;\n }\n assert mNotificationManager != null;\n mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;\n }\n}" }, { "code": null, "e": 5809, "s": 5754, "text": "Step 5 − Add the following code to AndroidManifest.xml" }, { "code": null, "e": 6969, "s": 5809, "text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package = \"app.tutorialspoint.com.notifyme\" >\n <uses-permission android :name = \"android.permission.VIBRATE\" />\n <application\n android :allowBackup = \"true\"\n android :icon = \"@mipmap/ic_launcher\"\n android :label = \"@string/app_name\"\n android :roundIcon = \"@mipmap/ic_launcher_round\"\n android :supportsRtl = \"true\"\n android :theme = \"@style/AppTheme\" >\n <activity android :name = \".MainActivity\" >\n <intent-filter>\n <action android :name = \"android.intent.action.MAIN\" />\n <category android :name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <service\n android :name = \".NotificationService\"\n android :label = \"@string/app_name\" >\n <intent-filter>\n <action\n android :name = \"app.tutorialspoint.com.notifyme.NotificationService\" />\n <category android :name = \"android.intent.category.DEFAULT\" />\n </intent-filter>\n </service>\n </application>\n</manifest>" }, { "code": null, "e": 7316, "s": 6969, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 7358, "s": 7316, "text": "Click here to download the project code" } ]
column command in Linux with examples - GeeksforGeeks
28 Sep, 2021 column command in Linux is used to display the contents of a file in columns. The input may be taken from the standard input or from the file. This command basically breaks the input into multiple columns. Rows are filled before columns. Empty lines from the input are ignored unless the -e option is used. Syntax: column [-entx] [-c columns] [-s sep] [file ...] Example: Suppose you have a text file with the following contents: sample file To display the information of the text file in form of columns, you enter the command: column filename.txt displays result Suppose, you want to sort into different columns the entries that are separated by particular delimiters. For example, this sample text file: Sample text file To separate the column based on the delimiter “|”, you would give the following command, which in turn produces the given output: output based on delimiter specified In case you give multiple delimiters(same type), the command treats them as a single one. For example: sample text file Upon application of command yields the output: Output(with multiple delimiters of same type) Options: -J : This option specifies the system to display the output in JSON format. -c : Defines the width of the output based upon the total number of characters allowed in one row. -d : Used to define that the header is NOT to be printed. -N : It defines the column names, and each name is separated by a comma(“, “). -H : It is used to hide the specified columns from being displayed. -V : Displays version information and exits. -h : Shows help information and exits. -s : Defines the column delimiter for output. -t : Applied for creating a table by determining the number of columns. -R : Used to right-align text in a specific column. -T : Allows the system to truncate text wherever necessary so that the column width can be adjusted to ensure that the column doesn’t become too wide. -O : Allows the user to define the order in which columns have to be displayed. -L : Inserts empty lines after each row. varshagumber28 linux-command Linux-text-processing-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments tar command in Linux with examples UDP Server-Client implementation in C Conditional Statements | Shell Script Cat command in Linux with examples touch command in Linux with Examples echo command in Linux with Examples Compiling with g++ Tail command in Linux with examples Mutex lock for Linux Thread Synchronization ps command in Linux with Examples
[ { "code": null, "e": 23617, "s": 23589, "text": "\n28 Sep, 2021" }, { "code": null, "e": 23925, "s": 23617, "text": "column command in Linux is used to display the contents of a file in columns. The input may be taken from the standard input or from the file. This command basically breaks the input into multiple columns. Rows are filled before columns. Empty lines from the input are ignored unless the -e option is used. " }, { "code": null, "e": 23934, "s": 23925, "text": "Syntax: " }, { "code": null, "e": 23982, "s": 23934, "text": "column [-entx] [-c columns] [-s sep] [file ...]" }, { "code": null, "e": 23993, "s": 23982, "text": "Example: " }, { "code": null, "e": 24052, "s": 23993, "text": "Suppose you have a text file with the following contents: " }, { "code": null, "e": 24064, "s": 24052, "text": "sample file" }, { "code": null, "e": 24152, "s": 24064, "text": "To display the information of the text file in form of columns, you enter the command: " }, { "code": null, "e": 24172, "s": 24152, "text": "column filename.txt" }, { "code": null, "e": 24188, "s": 24172, "text": "displays result" }, { "code": null, "e": 24331, "s": 24188, "text": "Suppose, you want to sort into different columns the entries that are separated by particular delimiters. For example, this sample text file: " }, { "code": null, "e": 24348, "s": 24331, "text": "Sample text file" }, { "code": null, "e": 24479, "s": 24348, "text": "To separate the column based on the delimiter “|”, you would give the following command, which in turn produces the given output: " }, { "code": null, "e": 24515, "s": 24479, "text": "output based on delimiter specified" }, { "code": null, "e": 24619, "s": 24515, "text": "In case you give multiple delimiters(same type), the command treats them as a single one. For example: " }, { "code": null, "e": 24636, "s": 24619, "text": "sample text file" }, { "code": null, "e": 24684, "s": 24636, "text": "Upon application of command yields the output: " }, { "code": null, "e": 24730, "s": 24684, "text": "Output(with multiple delimiters of same type)" }, { "code": null, "e": 24741, "s": 24730, "text": "Options: " }, { "code": null, "e": 24817, "s": 24741, "text": "-J : This option specifies the system to display the output in JSON format." }, { "code": null, "e": 24916, "s": 24817, "text": "-c : Defines the width of the output based upon the total number of characters allowed in one row." }, { "code": null, "e": 24974, "s": 24916, "text": "-d : Used to define that the header is NOT to be printed." }, { "code": null, "e": 25053, "s": 24974, "text": "-N : It defines the column names, and each name is separated by a comma(“, “)." }, { "code": null, "e": 25121, "s": 25053, "text": "-H : It is used to hide the specified columns from being displayed." }, { "code": null, "e": 25166, "s": 25121, "text": "-V : Displays version information and exits." }, { "code": null, "e": 25205, "s": 25166, "text": "-h : Shows help information and exits." }, { "code": null, "e": 25251, "s": 25205, "text": "-s : Defines the column delimiter for output." }, { "code": null, "e": 25323, "s": 25251, "text": "-t : Applied for creating a table by determining the number of columns." }, { "code": null, "e": 25375, "s": 25323, "text": "-R : Used to right-align text in a specific column." }, { "code": null, "e": 25526, "s": 25375, "text": "-T : Allows the system to truncate text wherever necessary so that the column width can be adjusted to ensure that the column doesn’t become too wide." }, { "code": null, "e": 25606, "s": 25526, "text": "-O : Allows the user to define the order in which columns have to be displayed." }, { "code": null, "e": 25647, "s": 25606, "text": "-L : Inserts empty lines after each row." }, { "code": null, "e": 25664, "s": 25649, "text": "varshagumber28" }, { "code": null, "e": 25678, "s": 25664, "text": "linux-command" }, { "code": null, "e": 25709, "s": 25678, "text": "Linux-text-processing-commands" }, { "code": null, "e": 25716, "s": 25709, "text": "Picked" }, { "code": null, "e": 25727, "s": 25716, "text": "Linux-Unix" }, { "code": null, "e": 25825, "s": 25727, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25834, "s": 25825, "text": "Comments" }, { "code": null, "e": 25847, "s": 25834, "text": "Old Comments" }, { "code": null, "e": 25882, "s": 25847, "text": "tar command in Linux with examples" }, { "code": null, "e": 25920, "s": 25882, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 25958, "s": 25920, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 25993, "s": 25958, "text": "Cat command in Linux with examples" }, { "code": null, "e": 26030, "s": 25993, "text": "touch command in Linux with Examples" }, { "code": null, "e": 26066, "s": 26030, "text": "echo command in Linux with Examples" }, { "code": null, "e": 26085, "s": 26066, "text": "Compiling with g++" }, { "code": null, "e": 26121, "s": 26085, "text": "Tail command in Linux with examples" }, { "code": null, "e": 26165, "s": 26121, "text": "Mutex lock for Linux Thread Synchronization" } ]
How to get the default blue colour of matplotlib.pyplot.scatter?
The default color of a scatter point is blue. To get the default blue color of matplotlib scatter point, we can annotate them using annotate() method. Create a figure and a set of subplots using subplots() method. Plot a scatter point at (-1, 1) location. Add some label for that point. Plot a scatter point at (-0.9, 1) location. Add some label for that point. Plot a scatter point at (1.9, 1) location. Add some label for that point. Scale the x and y axes using xlim and ylim method. To display the figure, use show() method. from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True fig, ax = plt.subplots() ax.scatter(-1, 1) ax.annotate("default color", xy=(-0.9, 1)) ax.scatter(1, 1, c='#1f77b4') ax.annotate("using hex", xy=(1.1, 1)) ax.set_xlim(-2, 3) ax.set_ylim(-1, 2) plt.show()
[ { "code": null, "e": 1213, "s": 1062, "text": "The default color of a scatter point is blue. To get the default blue color of matplotlib scatter point, we can annotate them using annotate() method." }, { "code": null, "e": 1276, "s": 1213, "text": "Create a figure and a set of subplots using subplots() method." }, { "code": null, "e": 1318, "s": 1276, "text": "Plot a scatter point at (-1, 1) location." }, { "code": null, "e": 1349, "s": 1318, "text": "Add some label for that point." }, { "code": null, "e": 1393, "s": 1349, "text": "Plot a scatter point at (-0.9, 1) location." }, { "code": null, "e": 1424, "s": 1393, "text": "Add some label for that point." }, { "code": null, "e": 1467, "s": 1424, "text": "Plot a scatter point at (1.9, 1) location." }, { "code": null, "e": 1498, "s": 1467, "text": "Add some label for that point." }, { "code": null, "e": 1549, "s": 1498, "text": "Scale the x and y axes using xlim and ylim method." }, { "code": null, "e": 1591, "s": 1549, "text": "To display the figure, use show() method." }, { "code": null, "e": 1918, "s": 1591, "text": "from matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nfig, ax = plt.subplots()\nax.scatter(-1, 1)\nax.annotate(\"default color\", xy=(-0.9, 1))\nax.scatter(1, 1, c='#1f77b4')\nax.annotate(\"using hex\", xy=(1.1, 1))\nax.set_xlim(-2, 3)\nax.set_ylim(-1, 2)\nplt.show()" } ]
Remove item from a nested array by indices in JavaScript
Suppose, we have a nested array of objects like this − const arr = [ { value: 'some value' }, { array: [ { value: 'some value' }, { array: [ { value: 'some value' }, { value: 'some value' }, ], }, { value: 'some value' }, { array: [ { value: 'some value' }, { array: [ { value: 'delete me' }, { value: 'some value' }, ] }, ], }, ], } ]; We are required to write a JavaScript function that takes in one such array as the first argument and an array of indices as the second argument. Our function should delete the value property at all the indices specified by the array (second argument). The code for this will be − const arr = [ { value: 'some value' }, { array: [ { value: 'some value' }, { array: [ { value: 'some value' }, { value: 'some value' }, ], }, { value: 'some value' }, { array: [ { value: 'some value' }, { array: [ { value: 'delete me' }, { value: 'some value' }, ] }, ], }, ], } ]; const keys = [1, 3, 1, 0]; const getKeys = (arr, keys) => { const recursiveFind = (arr, level) => { const res = []; arr.forEach((el, ind) => { if (keys[level] !== ind) { return res.push(el); }; if (level + 1 !== keys.length && el.array) { res.push({ array: recursiveFind(el.array, level + 1) }); }; }); return res; }; return recursiveFind(arr, 0); }; console.log(JSON.stringify(getKeys(arr, keys), undefined, 4)); And the output in the console will be − [ { "value": "some value" }, { "array": [ { "value": "some value" }, { "array": [ { "value": "some value" }, { "value": "some value" } ] }, { "value": "some value" }, { "array": [ { "value": "some value" }, { "array": [ { "value": "some value" } ] } ] } ] } ]
[ { "code": null, "e": 1117, "s": 1062, "text": "Suppose, we have a nested array of objects like this −" }, { "code": null, "e": 1675, "s": 1117, "text": "const arr = [\n { value: 'some value' },\n {\n array: [\n { value: 'some value' },\n {\n array: [\n { value: 'some value' },\n { value: 'some value' },\n ],\n },\n { value: 'some value' },\n {\n array: [\n { value: 'some value' },\n {\n array: [\n { value: 'delete me' },\n { value: 'some value' },\n ]\n },\n ],\n },\n ],\n }\n];" }, { "code": null, "e": 1821, "s": 1675, "text": "We are required to write a JavaScript function that takes in one such array as the first argument and an array of indices as the second argument." }, { "code": null, "e": 1928, "s": 1821, "text": "Our function should delete the value property at all the indices specified by the array (second argument)." }, { "code": null, "e": 1956, "s": 1928, "text": "The code for this will be −" }, { "code": null, "e": 3021, "s": 1956, "text": "const arr = [\n { value: 'some value' },\n {\n array: [\n { value: 'some value' },\n {\n array: [\n { value: 'some value' },\n { value: 'some value' },\n ],\n },\n { value: 'some value' },\n {\n array: [\n { value: 'some value' },\n {\n array: [\n { value: 'delete me' },\n { value: 'some value' },\n ]\n },\n ],\n },\n ],\n }\n];\nconst keys = [1, 3, 1, 0];\nconst getKeys = (arr, keys) => {\n const recursiveFind = (arr, level) => {\n const res = [];\n arr.forEach((el, ind) => {\n if (keys[level] !== ind) {\n return res.push(el);\n };\n if (level + 1 !== keys.length && el.array) {\n res.push({ array: recursiveFind(el.array, level + 1) });\n };\n });\n return res;\n };\n return recursiveFind(arr, 0);\n};\nconsole.log(JSON.stringify(getKeys(arr, keys), undefined, 4));" }, { "code": null, "e": 3061, "s": 3021, "text": "And the output in the console will be −" }, { "code": null, "e": 3771, "s": 3061, "text": "[\n {\n \"value\": \"some value\"\n },\n {\n \"array\": [\n {\n \"value\": \"some value\"\n },\n {\n \"array\": [\n {\n \"value\": \"some value\"\n },\n {\n \"value\": \"some value\"\n }\n ]\n },\n {\n \"value\": \"some value\"\n },\n {\n \"array\": [\n {\n \"value\": \"some value\"\n },\n {\n \"array\": [\n {\n \"value\": \"some value\"\n }\n ]\n }\n ]\n }\n ]\n }\n]" } ]
Stock Market Analytics with PCA. From Principal Component Analysis to... | by Yao Lei Xu | Towards Data Science
Principal Component Analysis (PCA) is a powerful data analytics tool used in many areas of machine learning. However, despite its versatility and effectiveness, its application in finance is not as widely discussed. Today, I will talk about how PCA can be used in the stock market, how it relates to the Capital Asset Pricing Model (CAPM), and how we can use PCA to analyse the impact of COVID19. (You can find the full code and additional resources here) The first principal component explains most of the variance in the data. In a nutshell, Principal Component Analysis (PCA) decomposes the data into many vectors called principal components that essentially “summarise” the given data. More specifically, these summaries are linear combinations of the input features that try to explain as much variance in the data as possible. By convention, these principal components are ordered by the amount of variance they can explain, with the first principal component explaining most of the data. The returns of a stock can be decomposed into: (1) the returns of the risk-free asset, (2) the returns of the market factor, and (3) the idiosyncratic returns of the stock. Overall, the market factor is the primary driver of all stock returns. The Capital Asset Pricing Model (CAPM) is a famous framework for pricing the returns of an asset such as a stock, with many interesting connections to the modern portfolio theory, which I will discuss in a future post. Before diving into the details of the CAPM, it is important to understand the notion of risk-free assets and the market factor. A risk-free asset is essentially an asset than can give you returns at virtually no risk (e.g. a government bond). The market factor instead monitors the state of the overall stock market as a whole and is often measured through an index such as the S&P500. Generally speaking, the overall market is more volatile/risky than government bonds, but it also provides more returns to the investors. With those definitions in mind, let’s look at the concept of the Security Market Line (SML) from CAPM. In practice, SML decomposes the returns of a stock r_i into three main factors: r_f: risk-free returnbeta_i * (r_m-r_f): market factor returne_i: idiosyncratic return r_f: risk-free return beta_i * (r_m-r_f): market factor return e_i: idiosyncratic return The intuition behind this equation is that: (1) the return of a stock should be at least equal to the return of the risk-free asset (otherwise why take the extra risk in the first place?) (2) the return of the asset is also explained by the market factor, which is captured by the term (r_m-r_f) (measures the excess return of the market with respect to the risk-free asset) and beta_i (measures the degree to which the asset is affected by the market factor). (3) the return of a stock is also affected by idiosyncratic factors, which are stock specific factors (e.g. the earnings release of a stock affects that individual stock only, but not the overall market). Empirically speaking, the market factor is the primary driver of the stock market returns, as it tends to explain most of the returns of any given stock in any given day. When applying PCA to daily stock returns, the first principal component approximates the market factor. Let’s consider the 500 stocks in the S&P500 index, and compute their daily returns, as shown in the figures below. rs = prices.apply(np.log).diff(1) rs.plot(title='Daily Returns of the Stocks in the S&P500') crs = rs.cumsum().apply(np.exp)crs.plot(title='Cumulative Returns of the Stocks in the S&P500') The figures above show the daily returns and the cumulative returns of the 500 stocks in the S&P500 since the beginning of 2020. The amount of raw data can look quite overwhelming, so let’s process them via PCA by computing the 1st principal component of the daily returns. The figure below shows the values of the 1st principal component, which is essentially a vector of dimension 500 that contains a value for each of the 500 stocks. from sklearn.decomposition import PCApca = PCA(1).fit(rs.fillna(0))pc1 = pd.Series(index=rs.columns, data=pca.components_[0])pc1.plot(xticks=[], title='First Principal Component of the S&P500') Recall that (1) the first principal component represents the linear combination of the input data that explains most of the variance, and (2) the primary driver of stock returns is the overall market factor. This implies that if we formulate a portfolio of stocks by allocating the cash proportionally to the 1st principal component (i.e. linear combination of the input data), we can replicate the returns of the S&P500 approximately (i.e. the primary driver of stock returns). weights = abs(pc1)/sum(abs(pc1)) # l1norm = 1myrs = (weights*rs).sum(1)rs_df = pd.concat([myrs, market_rs], 1)rs_df.columns = ["PCA Portfolio", "S&P500"]crs_df = rs_df.cumsum().apply(np.exp)crs_df.plot(subplots=True); As shown in the figure above, our PCA portfolio can work as a proxy for the market factor, which is the primary driver of stock returns (hence explaining most of the variance!). Note that although they are similar, the PCA portfolio doesn’t replicate the S&P500 exactly, since the S&P500 is a market-capitalisation weighted average of the 500 stocks, while the weights in the PCA portfolio is influenced by the explained variance. Using PCA, we can cluster together businesses that were most/least affected by the COVID19 pandemic, without any prior knowledge of their fundamentals. As you probably know, 2020 has been a wild ride for the stock market due to the COVID19 pandemic. Using PCA, we can analyse how this pandemic affected the individual stocks. For instance, let’s look a the 1st principal component, and select the stocks that have the most and the least negative PCA weights, as shown below. fig, ax = plt.subplots(2,1)pc1.nsmallest(10).plot.bar(ax=ax[0], color='green', grid=True, title='Stocks with Most Negative PCA Weights')pc1.nlargest(10).plot.bar(ax=ax[1], color='blue', grid=True, title='Stocks with Least Negative PCA Weights') Notice from the figure above how the most negative stocks are in the tourism and the energy sector. This makes sense since COVID19 heavily impacted the travelling business, as well as the energy companies that provide fuel for those businesses. On the other hand, the least impacted companies fall into the consumer goods sectors, which also makes sense since this sector benefited from the boost in sales of consumer goods due to the quarantine measures. Therefore, by applying PCA, we were able to cluster together the best and worst businesses that were affected by the COVID19 pandemic, without any prior knowledge of their fundamentals! In addition, we can formulate a winning portfolio that is long the top 10 companies according to the PCA weights. As shown in the figure below, the resulting portfolio would have performed significantly better than the market, since it invested in companies that actually benefited from the pandemic. Note that this portfolio is formed with look-ahead bias, where portfolio weights are computed using future data that were not available at the time of market downturn. The PCA used in this way is therefore a backward looking analytics tool. For more information about look-ahead bias and how to avoid them, check this article out. myrs = rs[pc1.nlargest(10).index].mean(1)mycrs = myrs.cumsum().apply(np.exp)market_crs = market_rs.cumsum().apply(np.exp)mycrs.plot(title='PCA Portfolio vs. S&P500')market_crs.plot()plt.legend(['PCA Selection', 'S&P500']) I hope you enjoyed the article! Follow me if you would like to see more content like this. Also, check out my website for the full code and additional resources.
[ { "code": null, "e": 263, "s": 47, "text": "Principal Component Analysis (PCA) is a powerful data analytics tool used in many areas of machine learning. However, despite its versatility and effectiveness, its application in finance is not as widely discussed." }, { "code": null, "e": 444, "s": 263, "text": "Today, I will talk about how PCA can be used in the stock market, how it relates to the Capital Asset Pricing Model (CAPM), and how we can use PCA to analyse the impact of COVID19." }, { "code": null, "e": 503, "s": 444, "text": "(You can find the full code and additional resources here)" }, { "code": null, "e": 576, "s": 503, "text": "The first principal component explains most of the variance in the data." }, { "code": null, "e": 1042, "s": 576, "text": "In a nutshell, Principal Component Analysis (PCA) decomposes the data into many vectors called principal components that essentially “summarise” the given data. More specifically, these summaries are linear combinations of the input features that try to explain as much variance in the data as possible. By convention, these principal components are ordered by the amount of variance they can explain, with the first principal component explaining most of the data." }, { "code": null, "e": 1286, "s": 1042, "text": "The returns of a stock can be decomposed into: (1) the returns of the risk-free asset, (2) the returns of the market factor, and (3) the idiosyncratic returns of the stock. Overall, the market factor is the primary driver of all stock returns." }, { "code": null, "e": 1505, "s": 1286, "text": "The Capital Asset Pricing Model (CAPM) is a famous framework for pricing the returns of an asset such as a stock, with many interesting connections to the modern portfolio theory, which I will discuss in a future post." }, { "code": null, "e": 2028, "s": 1505, "text": "Before diving into the details of the CAPM, it is important to understand the notion of risk-free assets and the market factor. A risk-free asset is essentially an asset than can give you returns at virtually no risk (e.g. a government bond). The market factor instead monitors the state of the overall stock market as a whole and is often measured through an index such as the S&P500. Generally speaking, the overall market is more volatile/risky than government bonds, but it also provides more returns to the investors." }, { "code": null, "e": 2211, "s": 2028, "text": "With those definitions in mind, let’s look at the concept of the Security Market Line (SML) from CAPM. In practice, SML decomposes the returns of a stock r_i into three main factors:" }, { "code": null, "e": 2298, "s": 2211, "text": "r_f: risk-free returnbeta_i * (r_m-r_f): market factor returne_i: idiosyncratic return" }, { "code": null, "e": 2320, "s": 2298, "text": "r_f: risk-free return" }, { "code": null, "e": 2361, "s": 2320, "text": "beta_i * (r_m-r_f): market factor return" }, { "code": null, "e": 2387, "s": 2361, "text": "e_i: idiosyncratic return" }, { "code": null, "e": 2431, "s": 2387, "text": "The intuition behind this equation is that:" }, { "code": null, "e": 2575, "s": 2431, "text": "(1) the return of a stock should be at least equal to the return of the risk-free asset (otherwise why take the extra risk in the first place?)" }, { "code": null, "e": 2848, "s": 2575, "text": "(2) the return of the asset is also explained by the market factor, which is captured by the term (r_m-r_f) (measures the excess return of the market with respect to the risk-free asset) and beta_i (measures the degree to which the asset is affected by the market factor)." }, { "code": null, "e": 3053, "s": 2848, "text": "(3) the return of a stock is also affected by idiosyncratic factors, which are stock specific factors (e.g. the earnings release of a stock affects that individual stock only, but not the overall market)." }, { "code": null, "e": 3224, "s": 3053, "text": "Empirically speaking, the market factor is the primary driver of the stock market returns, as it tends to explain most of the returns of any given stock in any given day." }, { "code": null, "e": 3328, "s": 3224, "text": "When applying PCA to daily stock returns, the first principal component approximates the market factor." }, { "code": null, "e": 3443, "s": 3328, "text": "Let’s consider the 500 stocks in the S&P500 index, and compute their daily returns, as shown in the figures below." }, { "code": null, "e": 3536, "s": 3443, "text": "rs = prices.apply(np.log).diff(1) rs.plot(title='Daily Returns of the Stocks in the S&P500')" }, { "code": null, "e": 3632, "s": 3536, "text": "crs = rs.cumsum().apply(np.exp)crs.plot(title='Cumulative Returns of the Stocks in the S&P500')" }, { "code": null, "e": 4069, "s": 3632, "text": "The figures above show the daily returns and the cumulative returns of the 500 stocks in the S&P500 since the beginning of 2020. The amount of raw data can look quite overwhelming, so let’s process them via PCA by computing the 1st principal component of the daily returns. The figure below shows the values of the 1st principal component, which is essentially a vector of dimension 500 that contains a value for each of the 500 stocks." }, { "code": null, "e": 4263, "s": 4069, "text": "from sklearn.decomposition import PCApca = PCA(1).fit(rs.fillna(0))pc1 = pd.Series(index=rs.columns, data=pca.components_[0])pc1.plot(xticks=[], title='First Principal Component of the S&P500')" }, { "code": null, "e": 4742, "s": 4263, "text": "Recall that (1) the first principal component represents the linear combination of the input data that explains most of the variance, and (2) the primary driver of stock returns is the overall market factor. This implies that if we formulate a portfolio of stocks by allocating the cash proportionally to the 1st principal component (i.e. linear combination of the input data), we can replicate the returns of the S&P500 approximately (i.e. the primary driver of stock returns)." }, { "code": null, "e": 4960, "s": 4742, "text": "weights = abs(pc1)/sum(abs(pc1)) # l1norm = 1myrs = (weights*rs).sum(1)rs_df = pd.concat([myrs, market_rs], 1)rs_df.columns = [\"PCA Portfolio\", \"S&P500\"]crs_df = rs_df.cumsum().apply(np.exp)crs_df.plot(subplots=True);" }, { "code": null, "e": 5391, "s": 4960, "text": "As shown in the figure above, our PCA portfolio can work as a proxy for the market factor, which is the primary driver of stock returns (hence explaining most of the variance!). Note that although they are similar, the PCA portfolio doesn’t replicate the S&P500 exactly, since the S&P500 is a market-capitalisation weighted average of the 500 stocks, while the weights in the PCA portfolio is influenced by the explained variance." }, { "code": null, "e": 5543, "s": 5391, "text": "Using PCA, we can cluster together businesses that were most/least affected by the COVID19 pandemic, without any prior knowledge of their fundamentals." }, { "code": null, "e": 5717, "s": 5543, "text": "As you probably know, 2020 has been a wild ride for the stock market due to the COVID19 pandemic. Using PCA, we can analyse how this pandemic affected the individual stocks." }, { "code": null, "e": 5866, "s": 5717, "text": "For instance, let’s look a the 1st principal component, and select the stocks that have the most and the least negative PCA weights, as shown below." }, { "code": null, "e": 6111, "s": 5866, "text": "fig, ax = plt.subplots(2,1)pc1.nsmallest(10).plot.bar(ax=ax[0], color='green', grid=True, title='Stocks with Most Negative PCA Weights')pc1.nlargest(10).plot.bar(ax=ax[1], color='blue', grid=True, title='Stocks with Least Negative PCA Weights')" }, { "code": null, "e": 6567, "s": 6111, "text": "Notice from the figure above how the most negative stocks are in the tourism and the energy sector. This makes sense since COVID19 heavily impacted the travelling business, as well as the energy companies that provide fuel for those businesses. On the other hand, the least impacted companies fall into the consumer goods sectors, which also makes sense since this sector benefited from the boost in sales of consumer goods due to the quarantine measures." }, { "code": null, "e": 6753, "s": 6567, "text": "Therefore, by applying PCA, we were able to cluster together the best and worst businesses that were affected by the COVID19 pandemic, without any prior knowledge of their fundamentals!" }, { "code": null, "e": 7054, "s": 6753, "text": "In addition, we can formulate a winning portfolio that is long the top 10 companies according to the PCA weights. As shown in the figure below, the resulting portfolio would have performed significantly better than the market, since it invested in companies that actually benefited from the pandemic." }, { "code": null, "e": 7385, "s": 7054, "text": "Note that this portfolio is formed with look-ahead bias, where portfolio weights are computed using future data that were not available at the time of market downturn. The PCA used in this way is therefore a backward looking analytics tool. For more information about look-ahead bias and how to avoid them, check this article out." }, { "code": null, "e": 7607, "s": 7385, "text": "myrs = rs[pc1.nlargest(10).index].mean(1)mycrs = myrs.cumsum().apply(np.exp)market_crs = market_rs.cumsum().apply(np.exp)mycrs.plot(title='PCA Portfolio vs. S&P500')market_crs.plot()plt.legend(['PCA Selection', 'S&P500'])" }, { "code": null, "e": 7698, "s": 7607, "text": "I hope you enjoyed the article! Follow me if you would like to see more content like this." } ]
D3.js - Zooming API
Zooming helps to scale your content. You can focus on a particular region using the click-and-drag approach. In this chapter, we will discuss Zooming API in detail. You can load the Zooming API directly from the “d3js.org” using the following script. <script src = "https://d3js.org/d3-color.v1.min.js"></script> <script src = "https://d3js.org/d3-dispatch.v1.min.js"></script> <script src = "https://d3js.org/d3-ease.v1.min.js"></script> <script src = "https://d3js.org/d3-interpolate.v1.min.js"></script> <script src = "https://d3js.org/d3-selection.v1.min.js"></script> <script src = "https://d3js.org/d3-timer.v1.min.js"></script> <script src = "https://d3js.org/d3-transition.v1.min.js"></script> <script src = "https://d3js.org/d3-drag.v1.min.js"></script> <script src = "https://d3js.org/d3-zoom.v1.min.js"></script> <body> <script> </script> </body> Following are some of the most commonly used Zooming API Methods. d3.zoom() zoom(selection) zoom.transform(selection, transform) zoom.translateBy(selection, x, y) zoom.translateTo(selection, x, y) zoom.scaleTo(selection, k) zoom.scaleBy(selection, k) zoom.filter([filter]) zoom.wheelDelta([delta]) zoom.extent([extent]) zoom.scaleExtent([extent]) zoom.translateExtent([extent]) zoom.clickDistance([distance]) zoom.duration([duration]) zoom.interpolate([interpolate]) zoom.on(typenames[, listener]) Let us go through all these Zooming API methods in brief. It creates a new zoom behavior. We can access it using the script below. <script> var zoom = d3.zoom(); </script> It is used to apply the zoom transformation on a selected element. For example, you can instantiate a mousedown.zoom behavior using the following syntax. selection.call(d3.zoom().on("mousedown.zoom", mousedowned)); It is used to set the current zoom transform of the selected elements to the specified transform. For example, we can reset the zoom transform to the identity transform using the syntax below. selection.call(zoom.transform, d3.zoomIdentity); We can also reset the zoom transform to the identity transform for 1000 milliseconds using the following syntax. selection.transition().duration(1000).call(zoom.transform, d3.zoomIdentity); It is used to translate the current zoom transform of the selected elements by x and y values. You can specify x and y translation values either as numbers or as functions that returns numbers. If a function is invoked for the selected element, then it is passed through the current datum ‘d’ and index ‘i' for DOM. A sample code is defined below. zoom.translateBy(selection, x, y) { zoom.transform(selection, function() { return constrain(this.__zoom.translate( x = = = "function" ? x.apply(this, arguments) : x, y = = = "function" ? y.apply(this, arguments) : y ); } }; It is used to translate the current zoom transform of the selected elements to the specified position of x and y. It is used to scale the current zoom transform of the selected elements to k. Here, k is a scale factor, specified as numbers or functions. zoom.scaleTo = function(selection, k) { zoom.transform(selection, function() { k = = = "function" ? k.apply(this, arguments) : k; }); }; It is used to scale the current zoon transform of the selected elements by k. Here, k is a scale factor, specified either as numbers or as functions that returns numbers. zoom.scaleBy = function(selection, k) { zoom.scaleTo(selection, function() { var k0 = this.__zoom.k, k1 = k = = = "function" ? k.apply(this, arguments) : k; return k0 * k1; }); }; It is used to set the filter to the specified function for zoom behavior. If the filter is not specified, it returns the current filter as shown below. function filter() { return !d3.event.button; } The value of Δ is returned by the wheel delta function. If delta is not specified, it returns the current wheel delta function. It is used to set the extent to the specified array points. If the extent is not specified, it returns the current extent accessor, which defaults to [[0, 0], [width, height]], where width is the client width of the element and height is its client height. It is used to set the scale extent to the specified array of numbers [k0, k1]. Here, k0 is the minimum allowed scale factor. While, k1 is the maximum allowed scale factor. If extent is not specified, it returns the current scale extent, which defaults to [0, ∞]. Consider the sample code that is defined below. selection .call(zoom) .on("wheel", function() { d3.event.preventDefault(); }); The user can try to zoom by wheeling, when already at the corresponding limit of the scale extent. If we want to prevent scrolling on wheel input regardless of the scale extent, register a wheel event listener to prevent the browser default behavior. If the extent is specified, it sets the translate extent to the specified array of points. If extent is not specified, it returns the current translate extent, which defaults to [[-∞, -∞], [+∞, +∞]]. This method is used to set the maximum distance that the zoomable area can move between up and down, which will trigger a subsequent click event. This method is used to set the duration for zoom transitions on double-click and double-tap to the specified number of milliseconds and returns the zoom behavior. If the duration is not specified, it returns the current duration, which defaults to 250 milliseconds, which is defined below. selection .call(zoom) .on("dblclick.zoom", null); This method is used to interpolate for zoom transitions to the specified function. If interpolate is not specified, it returns the current interpolation factory, which defaults to d3.interpolateZoom. If the listener is specified, it sets the event listener for the specified typenames and returns the zoom behavior. The typenames is a string containing one or more typename separated by whitespace. Each typename is a type, optionally followed by a period (.) and a name, such as zoom.one and zoom.second. The name allows multiple listeners to be registered for the same type. This type must be from one of the following − Start − after zooming begins (such as on mousedown). Start − after zooming begins (such as on mousedown). Zoom − after a change to the zoom transform (such as on mousemove). Zoom − after a change to the zoom transform (such as on mousemove). End − after zooming ends (such as on mouseup ). End − after zooming ends (such as on mouseup ). In the next chapter, we will discuss the different requests API in D3.js. Print Add Notes Bookmark this page
[ { "code": null, "e": 2295, "s": 2130, "text": "Zooming helps to scale your content. You can focus on a particular region using the click-and-drag approach. In this chapter, we will discuss Zooming API in detail." }, { "code": null, "e": 2381, "s": 2295, "text": "You can load the Zooming API directly from the “d3js.org” using the following script." }, { "code": null, "e": 2995, "s": 2381, "text": "<script src = \"https://d3js.org/d3-color.v1.min.js\"></script>\n<script src = \"https://d3js.org/d3-dispatch.v1.min.js\"></script>\n<script src = \"https://d3js.org/d3-ease.v1.min.js\"></script>\n<script src = \"https://d3js.org/d3-interpolate.v1.min.js\"></script>\n<script src = \"https://d3js.org/d3-selection.v1.min.js\"></script>\n<script src = \"https://d3js.org/d3-timer.v1.min.js\"></script>\n<script src = \"https://d3js.org/d3-transition.v1.min.js\"></script>\n<script src = \"https://d3js.org/d3-drag.v1.min.js\"></script>\n<script src = \"https://d3js.org/d3-zoom.v1.min.js\"></script>\n\n<body>\n <script>\n </script>\n</body>" }, { "code": null, "e": 3061, "s": 2995, "text": "Following are some of the most commonly used Zooming API Methods." }, { "code": null, "e": 3071, "s": 3061, "text": "d3.zoom()" }, { "code": null, "e": 3087, "s": 3071, "text": "zoom(selection)" }, { "code": null, "e": 3124, "s": 3087, "text": "zoom.transform(selection, transform)" }, { "code": null, "e": 3158, "s": 3124, "text": "zoom.translateBy(selection, x, y)" }, { "code": null, "e": 3192, "s": 3158, "text": "zoom.translateTo(selection, x, y)" }, { "code": null, "e": 3219, "s": 3192, "text": "zoom.scaleTo(selection, k)" }, { "code": null, "e": 3246, "s": 3219, "text": "zoom.scaleBy(selection, k)" }, { "code": null, "e": 3268, "s": 3246, "text": "zoom.filter([filter])" }, { "code": null, "e": 3293, "s": 3268, "text": "zoom.wheelDelta([delta])" }, { "code": null, "e": 3315, "s": 3293, "text": "zoom.extent([extent])" }, { "code": null, "e": 3342, "s": 3315, "text": "zoom.scaleExtent([extent])" }, { "code": null, "e": 3373, "s": 3342, "text": "zoom.translateExtent([extent])" }, { "code": null, "e": 3404, "s": 3373, "text": "zoom.clickDistance([distance])" }, { "code": null, "e": 3430, "s": 3404, "text": "zoom.duration([duration])" }, { "code": null, "e": 3462, "s": 3430, "text": "zoom.interpolate([interpolate])" }, { "code": null, "e": 3493, "s": 3462, "text": "zoom.on(typenames[, listener])" }, { "code": null, "e": 3551, "s": 3493, "text": "Let us go through all these Zooming API methods in brief." }, { "code": null, "e": 3624, "s": 3551, "text": "It creates a new zoom behavior. We can access it using the script below." }, { "code": null, "e": 3668, "s": 3624, "text": "<script>\n var zoom = d3.zoom();\n</script>" }, { "code": null, "e": 3822, "s": 3668, "text": "It is used to apply the zoom transformation on a selected element. For example, you can instantiate a mousedown.zoom behavior using the following syntax." }, { "code": null, "e": 3883, "s": 3822, "text": "selection.call(d3.zoom().on(\"mousedown.zoom\", mousedowned));" }, { "code": null, "e": 4076, "s": 3883, "text": "It is used to set the current zoom transform of the selected elements to the specified transform. For example, we can reset the zoom transform to the identity transform using the syntax below." }, { "code": null, "e": 4125, "s": 4076, "text": "selection.call(zoom.transform, d3.zoomIdentity);" }, { "code": null, "e": 4238, "s": 4125, "text": "We can also reset the zoom transform to the identity transform for 1000 milliseconds using the following syntax." }, { "code": null, "e": 4315, "s": 4238, "text": "selection.transition().duration(1000).call(zoom.transform, d3.zoomIdentity);" }, { "code": null, "e": 4663, "s": 4315, "text": "It is used to translate the current zoom transform of the selected elements by x and y values. You can specify x and y translation values either as numbers or as functions that returns numbers. If a function is invoked for the selected element, then it is passed through the current datum ‘d’ and index ‘i' for DOM. A sample code is defined below." }, { "code": null, "e": 4923, "s": 4663, "text": "zoom.translateBy(selection, x, y) {\n zoom.transform(selection, function() {\n return constrain(this.__zoom.translate(\n x = = = \"function\" ? x.apply(this, arguments) : x,\n y = = = \"function\" ? y.apply(this, arguments) : y\n );\n }\n};" }, { "code": null, "e": 5037, "s": 4923, "text": "It is used to translate the current zoom transform of the selected elements to the specified position of x and y." }, { "code": null, "e": 5177, "s": 5037, "text": "It is used to scale the current zoom transform of the selected elements to k. Here, k is a scale factor, specified as numbers or functions." }, { "code": null, "e": 5326, "s": 5177, "text": "zoom.scaleTo = function(selection, k) {\n zoom.transform(selection, function() {\n k = = = \"function\" ? k.apply(this, arguments) : k;\n });\n};" }, { "code": null, "e": 5497, "s": 5326, "text": "It is used to scale the current zoon transform of the selected elements by k. Here, k is a scale factor, specified either as numbers or as functions that returns numbers." }, { "code": null, "e": 5701, "s": 5497, "text": "zoom.scaleBy = function(selection, k) {\n zoom.scaleTo(selection, function() {\n var k0 = this.__zoom.k,\n k1 = k = = = \"function\" ? k.apply(this, arguments) : k;\n return k0 * k1;\n });\n};" }, { "code": null, "e": 5853, "s": 5701, "text": "It is used to set the filter to the specified function for zoom behavior. If the filter is not specified, it returns the current filter as shown below." }, { "code": null, "e": 5903, "s": 5853, "text": "function filter() {\n return !d3.event.button;\n}" }, { "code": null, "e": 6031, "s": 5903, "text": "The value of Δ is returned by the wheel delta function. If delta is not specified, it returns the current wheel delta function." }, { "code": null, "e": 6288, "s": 6031, "text": "It is used to set the extent to the specified array points. If the extent is not specified, it returns the current extent accessor, which defaults to [[0, 0], [width, height]], where width is the client width of the element and height is its client height." }, { "code": null, "e": 6599, "s": 6288, "text": "It is used to set the scale extent to the specified array of numbers [k0, k1]. Here, k0 is the minimum allowed scale factor. While, k1 is the maximum allowed scale factor. If extent is not specified, it returns the current scale extent, which defaults to [0, ∞]. Consider the sample code that is defined below." }, { "code": null, "e": 6684, "s": 6599, "text": "selection\n .call(zoom)\n .on(\"wheel\", function() { d3.event.preventDefault(); });" }, { "code": null, "e": 6935, "s": 6684, "text": "The user can try to zoom by wheeling, when already at the corresponding limit of the scale extent. If we want to prevent scrolling on wheel input regardless of the scale extent, register a wheel event listener to prevent the browser default behavior." }, { "code": null, "e": 7135, "s": 6935, "text": "If the extent is specified, it sets the translate extent to the specified array of points. If extent is not specified, it returns the current translate extent, which defaults to [[-∞, -∞], [+∞, +∞]]." }, { "code": null, "e": 7281, "s": 7135, "text": "This method is used to set the maximum distance that the zoomable area can move between up and down, which will trigger a subsequent click event." }, { "code": null, "e": 7571, "s": 7281, "text": "This method is used to set the duration for zoom transitions on double-click and double-tap to the specified number of milliseconds and returns the zoom behavior. If the duration is not specified, it returns the current duration, which defaults to 250 milliseconds, which is defined below." }, { "code": null, "e": 7627, "s": 7571, "text": "selection\n .call(zoom)\n .on(\"dblclick.zoom\", null);" }, { "code": null, "e": 7827, "s": 7627, "text": "This method is used to interpolate for zoom transitions to the specified function. If interpolate is not specified, it returns the current interpolation factory, which defaults to d3.interpolateZoom." }, { "code": null, "e": 8250, "s": 7827, "text": "If the listener is specified, it sets the event listener for the specified typenames and returns the zoom behavior. The typenames is a string containing one or more typename separated by whitespace. Each typename is a type, optionally followed by a period (.) and a name, such as zoom.one and zoom.second. The name allows multiple listeners to be registered for the same type. This type must be from one of the following −" }, { "code": null, "e": 8304, "s": 8250, "text": "Start − after zooming begins (such as on mousedown). " }, { "code": null, "e": 8358, "s": 8304, "text": "Start − after zooming begins (such as on mousedown). " }, { "code": null, "e": 8427, "s": 8358, "text": "Zoom − after a change to the zoom transform (such as on mousemove). " }, { "code": null, "e": 8496, "s": 8427, "text": "Zoom − after a change to the zoom transform (such as on mousemove). " }, { "code": null, "e": 8544, "s": 8496, "text": "End − after zooming ends (such as on mouseup )." }, { "code": null, "e": 8592, "s": 8544, "text": "End − after zooming ends (such as on mouseup )." }, { "code": null, "e": 8666, "s": 8592, "text": "In the next chapter, we will discuss the different requests API in D3.js." }, { "code": null, "e": 8673, "s": 8666, "text": " Print" }, { "code": null, "e": 8684, "s": 8673, "text": " Add Notes" } ]
Machine Learning - Correlation Matrix Plot
Correlation is an indication about the changes between two variables. In our previous chapters, we have discussed Pearson’s Correlation coefficients and the importance of Correlation too. We can plot correlation matrix to show which variable is having a high or low correlation in respect to another variable. In the following example, Python script will generate and plot correlation matrix for the Pima Indian Diabetes dataset. It can be generated with the help of corr() function on Pandas DataFrame and plotted with the help of pyplot. from matplotlib import pyplot from pandas import read_csv import numpy Path = r"C:\pima-indians-diabetes.csv" names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] data = read_csv(Path, names = names) correlations = data.corr() fig = pyplot.figure() ax = fig.add_subplot(111) cax = ax.matshow(correlations, vmin=-1, vmax=1) fig.colorbar(cax) ticks = numpy.arange(0,9,1) ax.set_xticks(ticks) ax.set_yticks(ticks) ax.set_xticklabels(names) ax.set_yticklabels(names) pyplot.show() From the above output of correlation matrix, we can see that it is symmetrical i.e. the bottom left is same as the top right. It is also observed that each variable is positively correlated with each other. 168 Lectures 13.5 hours Er. Himanshu Vasishta 64 Lectures 10.5 hours Eduonix Learning Solutions 91 Lectures 10 hours Abhilash Nelson 54 Lectures 6 hours Abhishek And Pukhraj 49 Lectures 5 hours Abhishek And Pukhraj 35 Lectures 4 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2614, "s": 2304, "text": "Correlation is an indication about the changes between two variables. In our previous chapters, we have discussed Pearson’s Correlation coefficients and the importance of Correlation too. We can plot correlation matrix to show which variable is having a high or low correlation in respect to another variable." }, { "code": null, "e": 2844, "s": 2614, "text": "In the following example, Python script will generate and plot correlation matrix for the Pima Indian Diabetes dataset. It can be generated with the help of corr() function on Pandas DataFrame and plotted with the help of pyplot." }, { "code": null, "e": 3349, "s": 2844, "text": "from matplotlib import pyplot\nfrom pandas import read_csv\nimport numpy\nPath = r\"C:\\pima-indians-diabetes.csv\"\nnames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']\ndata = read_csv(Path, names = names)\ncorrelations = data.corr()\nfig = pyplot.figure()\nax = fig.add_subplot(111)\ncax = ax.matshow(correlations, vmin=-1, vmax=1)\nfig.colorbar(cax)\nticks = numpy.arange(0,9,1)\nax.set_xticks(ticks)\nax.set_yticks(ticks)\nax.set_xticklabels(names)\nax.set_yticklabels(names)\npyplot.show()" }, { "code": null, "e": 3556, "s": 3349, "text": "From the above output of correlation matrix, we can see that it is symmetrical i.e. the bottom left is same as the top right. It is also observed that each variable is positively correlated with each other." }, { "code": null, "e": 3593, "s": 3556, "text": "\n 168 Lectures \n 13.5 hours \n" }, { "code": null, "e": 3616, "s": 3593, "text": " Er. Himanshu Vasishta" }, { "code": null, "e": 3652, "s": 3616, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 3680, "s": 3652, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3714, "s": 3680, "text": "\n 91 Lectures \n 10 hours \n" }, { "code": null, "e": 3731, "s": 3714, "text": " Abhilash Nelson" }, { "code": null, "e": 3764, "s": 3731, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3786, "s": 3764, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 3819, "s": 3786, "text": "\n 49 Lectures \n 5 hours \n" }, { "code": null, "e": 3841, "s": 3819, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 3874, "s": 3841, "text": "\n 35 Lectures \n 4 hours \n" }, { "code": null, "e": 3896, "s": 3874, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 3903, "s": 3896, "text": " Print" }, { "code": null, "e": 3914, "s": 3903, "text": " Add Notes" } ]
TypeScript - Strings
The String object lets you work with a series of characters. It wraps the string primitive data type with a number of helper methods. var var_name = new String(string); A list of the methods available in String object along with their description is given below − Returns a reference to the String function that created the object. Returns the length of the string. The prototype property allows you to add properties and methods to an object. A list of the methods available in String object along with their description is given below − Returns the character at the specified index. Returns a number indicating the Unicode value of the character at the given index. Combines the text of two strings and returns a new string. Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found. Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found. Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. match() Used to match a regular expression against a string. Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring. Executes the search for a match between a regular expression and a specified string. Extracts a section of a string and returns a new string. Splits a String object into an array of strings by separating the string into substrings. Returns the characters in a string beginning at the specified location through the specified number of characters. Returns the characters in a string between two indexes into the string. The characters within a string are converted to lower case while respecting the current locale. The characters within a string are converted to upper case while respecting the current locale. Returns the calling string value converted to lower case. Returns a string representing the specified object. Returns the calling string value converted to uppercase. Returns the primitive value of the specified object. 45 Lectures 4 hours Antonio Papa 41 Lectures 7 hours Haider Malik 60 Lectures 2.5 hours Skillbakerystudios 77 Lectures 8 hours Sean Bradley 77 Lectures 3.5 hours TELCOMA Global 19 Lectures 3 hours Christopher Frewin Print Add Notes Bookmark this page
[ { "code": null, "e": 2182, "s": 2048, "text": "The String object lets you work with a series of characters. It wraps the string primitive data type with a number of helper methods." }, { "code": null, "e": 2218, "s": 2182, "text": "var var_name = new String(string);\n" }, { "code": null, "e": 2313, "s": 2218, "text": "A list of the methods available in String object along with their description is given below −" }, { "code": null, "e": 2381, "s": 2313, "text": "Returns a reference to the String function that created the object." }, { "code": null, "e": 2415, "s": 2381, "text": "Returns the length of the string." }, { "code": null, "e": 2493, "s": 2415, "text": "The prototype property allows you to add properties and methods to an object." }, { "code": null, "e": 2588, "s": 2493, "text": "A list of the methods available in String object along with their description is given below −" }, { "code": null, "e": 2634, "s": 2588, "text": "Returns the character at the specified index." }, { "code": null, "e": 2717, "s": 2634, "text": "Returns a number indicating the Unicode value of the character at the given index." }, { "code": null, "e": 2776, "s": 2717, "text": "Combines the text of two strings and returns a new string." }, { "code": null, "e": 2895, "s": 2776, "text": "Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found." }, { "code": null, "e": 3013, "s": 2895, "text": "Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found." }, { "code": null, "e": 3140, "s": 3013, "text": "Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order." }, { "code": null, "e": 3148, "s": 3140, "text": "match()" }, { "code": null, "e": 3201, "s": 3148, "text": "Used to match a regular expression against a string." }, { "code": null, "e": 3324, "s": 3201, "text": "Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring." }, { "code": null, "e": 3409, "s": 3324, "text": "Executes the search for a match between a regular expression and a specified string." }, { "code": null, "e": 3466, "s": 3409, "text": "Extracts a section of a string and returns a new string." }, { "code": null, "e": 3556, "s": 3466, "text": "Splits a String object into an array of strings by separating the string into substrings." }, { "code": null, "e": 3671, "s": 3556, "text": "Returns the characters in a string beginning at the specified location through the specified number of characters." }, { "code": null, "e": 3743, "s": 3671, "text": "Returns the characters in a string between two indexes into the string." }, { "code": null, "e": 3839, "s": 3743, "text": "The characters within a string are converted to lower case while respecting the current locale." }, { "code": null, "e": 3935, "s": 3839, "text": "The characters within a string are converted to upper case while respecting the current locale." }, { "code": null, "e": 3993, "s": 3935, "text": "Returns the calling string value converted to lower case." }, { "code": null, "e": 4045, "s": 3993, "text": "Returns a string representing the specified object." }, { "code": null, "e": 4102, "s": 4045, "text": "Returns the calling string value converted to uppercase." }, { "code": null, "e": 4155, "s": 4102, "text": "Returns the primitive value of the specified object." }, { "code": null, "e": 4188, "s": 4155, "text": "\n 45 Lectures \n 4 hours \n" }, { "code": null, "e": 4202, "s": 4188, "text": " Antonio Papa" }, { "code": null, "e": 4235, "s": 4202, "text": "\n 41 Lectures \n 7 hours \n" }, { "code": null, "e": 4249, "s": 4235, "text": " Haider Malik" }, { "code": null, "e": 4284, "s": 4249, "text": "\n 60 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4304, "s": 4284, "text": " Skillbakerystudios" }, { "code": null, "e": 4337, "s": 4304, "text": "\n 77 Lectures \n 8 hours \n" }, { "code": null, "e": 4351, "s": 4337, "text": " Sean Bradley" }, { "code": null, "e": 4386, "s": 4351, "text": "\n 77 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4402, "s": 4386, "text": " TELCOMA Global" }, { "code": null, "e": 4435, "s": 4402, "text": "\n 19 Lectures \n 3 hours \n" }, { "code": null, "e": 4455, "s": 4435, "text": " Christopher Frewin" }, { "code": null, "e": 4462, "s": 4455, "text": " Print" }, { "code": null, "e": 4473, "s": 4462, "text": " Add Notes" } ]
MFC - Tree Control
A Tree View Control is a window that displays a hierarchical list of items, such as the headings in a document, the entries in an index, or the files and directories on a disk. Each item consists of a label and an optional bitmapped image, and each item can have a list of subitems associated with it. By clicking an item, the user can expand and collapse the associated list of subitems. It is represented by CTreeCtrl class. Create Creates a tree view control and attaches it to a CTreeCtrl object. CreateDragImage Creates a dragging bitmap for the specified tree view item. CreateEx Creates a tree control with the specified Windows extended styles and attaches it to a CTreeCtrl object DeleteAllItems Deletes all items in a tree view control. DeleteItem Deletes a new item in a tree view control. EditLabel Edits a specified tree view item in-place. EndEditLabelNow Cancels the edit operation on the label of a tree-view item in the current tree-view control. EnsureVisible Ensures that a tree view item is visible in its tree view control. Expand Expands, or collapses, the child items of the specified tree view item. GetBkColor Retrieves the current background color of the control. GetCheck Retrieves the check state of a tree control item. GetChildItem Retrieves the child of a specified tree view item. GetCount Retrieves the number of tree items associated with a tree view control. GetDropHilightItem Retrieves the target of a drag-and-drop operation. GetEditControl Retrieves the handle of the edit control used to edit the specified tree view item. GetExtendedStyle Retrieves the extended styles that the current treeview control is using. GetFirstVisibleItem Retrieves the first visible item of the specified tree view item. GetImageList Retrieves the handle of the image list associated with a tree view control. GetIndent Retrieves the offset (in pixels) of a tree view item from its parent. GetInsertMarkColor Retrieves the color used to draw the insertion mark for the tree view. GetItem Retrieves the attributes of a specified tree view item. GetItemData Returns the 32-bit application-specific value associated with an item. GetItemExpandedImageIndex Retrieves the index of the image to display when the specified item of the current tree-view control is in the expanded state. GetItemHeight Retrieves the current height of the tree view items. GetItemImage Retrieves the images associated with an item. GetItemPartRect Retrieves the bounding rectangle for a specified part of a specified item in the current tree-view control. GetItemRect Retrieves the bounding rectangle of a tree view item. GetItemState Returns the state of an item. GetItemStateEx Retrieves the extended state of the specified item in the current tree-view control. GetItemText Returns the text of an item. GetLastVisibleItem Retrieves the last expanded item in the current treeview control. GetLineColor Retrieves the current line color for the tree view control. GetNextItem Retrieves the next tree view item that matches a specified relationship. GetNextSiblingItem Retrieves the next sibling of the specified tree view item. GetNextVisibleItem Retrieves the next visible item of the specified tree view item. GetParentItem Retrieves the parent of the specified tree view item. GetPrevSiblingItem Retrieves the previous sibling of the specified tree view item. GetPrevVisibleItem Retrieves the previous visible item of the specified tree view item. GetRootItem Retrieves the root of the specified tree view item. GetScrollTime Retrieves the maximum scroll time for the tree view control. GetSelectedCount Retrieves the number of selected items in the current tree-view control. GetSelectedItem Retrieves the currently selected tree view item. GetTextColor Retrieves the current text color of the control. GetToolTips Retrieves the handle to the child ToolTip control used by a tree view control. GetVisibleCount Retrieves the number of visible tree items associated with a tree view control. HitTest Returns the current position of the cursor related to the CTreeCtrl object. InsertItem Inserts a new item in a tree view control. ItemHasChildren Returns nonzero if the specified item has child items MapAccIdToItem Maps the specified accessibility identifier to the handle to a tree-view item in the current tree-view control. MapItemToAccID Maps the specified handle to a tree-view item in the current tree-view control to an accessibility identifier. Select Selects, scrolls into view, or redraws a specified tree view item. SelectDropTarget Redraws the tree item as the target of a drag-and-drop operation. SelectItem Selects a specified tree view item. SelectSetFirstVisible Selects a specified tree view item as the first visible item. SetAutoscrollInfo Sets the autoscroll rate of the current tree-view control. SetBkColor Sets the background color of the control. SetCheck Sets the check state of a tree control item. SetExtendedStyle Sets the extended styles for the current tree-view control SetImageList Sets the handle of the image list associated with a tree view control. SetIndent Sets the offset (in pixels) of a tree view item from its parent. SetInsertMark Sets the insertion mark in a tree view control. SetInsertMarkColor Sets the color used to draw the insertion mark for the tree view. SetItem Sets the attributes of a specified tree view item. SetItemData Sets the 32-bit application-specific value associated with an item. SetItemExpandedImageIndex Sets the index of the image to display when the specified item of the current tree-view control is in the expanded state. SetItemHeight Sets the height of the tree view items. SetItemImage Associates images with an item. SetItemState Sets the state of an item. SetItemStateEx Sets the extended state of the specified item in the current tree-view control. SetItemText Sets the text of an item. SetLineColor Sets the current line color for the tree view control. SetScrollTime Sets the maximum scroll time for the tree view control. SetTextColor Sets the text color of the control. SetToolTips Sets a tree view control's child ToolTip control. ShowInfoTip Displays the infotip for the specified item in the current tree-view control. SortChildren Sorts the children of a given parent item. SortChildrenCB Sorts the children of a given parent item using an application-defined sort function. Let us look into a simple example by creating a new MFC dialog based project. Step 1 − Once the project is created you will see the TODO line, which is the Caption of Text Control. Remove the Caption and set its ID to IDC_STATIC_TXT. Step 2 − Add a value variable m_strTree for the Static Text control. Step 3 − From the Controls toolbox, drag the Tree Control. Step 4 − On the dialog box, click the Tree Control to select it. On the Properties window, set the Has Buttons, the Has Lines, the Lines At Root, the Client Edge and the Modal Frame properties to True. Step 5 − Add a control variable m_treeCtrl for Tee Control. Step 6 − Here is initialization of tree control in OnInitDialog() BOOL CMFCTreeControlDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here HTREEITEM hItem, hCar; hItem = m_treeCtrl.InsertItem(L"Car Listing", TVI_ROOT); hCar = m_treeCtrl.InsertItem(L"Economy", hItem); m_treeCtrl.InsertItem(L"BH-733", hCar); m_treeCtrl.InsertItem(L"SD-397", hCar); m_treeCtrl.InsertItem(L"JU-538", hCar); m_treeCtrl.InsertItem(L"DI-285", hCar); m_treeCtrl.InsertItem(L"AK-830", hCar); hCar = m_treeCtrl.InsertItem(L"Compact", hItem); m_treeCtrl.InsertItem(L"HG-490", hCar); m_treeCtrl.InsertItem(L"PE-473", hCar); hCar = m_treeCtrl.InsertItem(L"Standard", hItem); m_treeCtrl.InsertItem(L"SO-398", hCar); m_treeCtrl.InsertItem(L"DF-438", hCar); m_treeCtrl.InsertItem(L"IS-833", hCar); hCar = m_treeCtrl.InsertItem(L"Full Size", hItem); m_treeCtrl.InsertItem(L"PD-304", hCar); hCar = m_treeCtrl.InsertItem(L"Mini Van", hItem); m_treeCtrl.InsertItem(L"ID-497", hCar); m_treeCtrl.InsertItem(L"RU-304", hCar); m_treeCtrl.InsertItem(L"DK-905", hCar); hCar = m_treeCtrl.InsertItem(L"SUV", hItem); m_treeCtrl.InsertItem(L"FE-948", hCar); m_treeCtrl.InsertItem(L"AD-940", hCar); hCar = m_treeCtrl.InsertItem(L"Truck", hItem); m_treeCtrl.InsertItem(L"HD-394", hCar); return TRUE; // return TRUE unless you set the focus to a control } Step 7 − When the above code is compiled and executed, you will see the following output. Print Add Notes Bookmark this page
[ { "code": null, "e": 2494, "s": 2067, "text": "A Tree View Control is a window that displays a hierarchical list of items, such as the headings in a document, the entries in an index, or the files and directories on a disk. Each item consists of a label and an optional bitmapped image, and each item can have a list of subitems associated with it. By clicking an item, the user can expand and collapse the associated list of subitems. It is represented by CTreeCtrl class." }, { "code": null, "e": 2501, "s": 2494, "text": "Create" }, { "code": null, "e": 2568, "s": 2501, "text": "Creates a tree view control and attaches it to a CTreeCtrl object." }, { "code": null, "e": 2584, "s": 2568, "text": "CreateDragImage" }, { "code": null, "e": 2644, "s": 2584, "text": "Creates a dragging bitmap for the specified tree view item." }, { "code": null, "e": 2653, "s": 2644, "text": "CreateEx" }, { "code": null, "e": 2757, "s": 2653, "text": "Creates a tree control with the specified Windows extended styles and attaches it to a CTreeCtrl object" }, { "code": null, "e": 2772, "s": 2757, "text": "DeleteAllItems" }, { "code": null, "e": 2814, "s": 2772, "text": "Deletes all items in a tree view control." }, { "code": null, "e": 2825, "s": 2814, "text": "DeleteItem" }, { "code": null, "e": 2868, "s": 2825, "text": "Deletes a new item in a tree view control." }, { "code": null, "e": 2878, "s": 2868, "text": "EditLabel" }, { "code": null, "e": 2921, "s": 2878, "text": "Edits a specified tree view item in-place." }, { "code": null, "e": 2937, "s": 2921, "text": "EndEditLabelNow" }, { "code": null, "e": 3031, "s": 2937, "text": "Cancels the edit operation on the label of a tree-view item in the current tree-view control." }, { "code": null, "e": 3045, "s": 3031, "text": "EnsureVisible" }, { "code": null, "e": 3112, "s": 3045, "text": "Ensures that a tree view item is visible in its tree view control." }, { "code": null, "e": 3119, "s": 3112, "text": "Expand" }, { "code": null, "e": 3191, "s": 3119, "text": "Expands, or collapses, the child items of the specified tree view item." }, { "code": null, "e": 3202, "s": 3191, "text": "GetBkColor" }, { "code": null, "e": 3257, "s": 3202, "text": "Retrieves the current background color of the control." }, { "code": null, "e": 3266, "s": 3257, "text": "GetCheck" }, { "code": null, "e": 3316, "s": 3266, "text": "Retrieves the check state of a tree control item." }, { "code": null, "e": 3329, "s": 3316, "text": "GetChildItem" }, { "code": null, "e": 3380, "s": 3329, "text": "Retrieves the child of a specified tree view item." }, { "code": null, "e": 3389, "s": 3380, "text": "GetCount" }, { "code": null, "e": 3461, "s": 3389, "text": "Retrieves the number of tree items associated with a tree view control." }, { "code": null, "e": 3480, "s": 3461, "text": "GetDropHilightItem" }, { "code": null, "e": 3531, "s": 3480, "text": "Retrieves the target of a drag-and-drop operation." }, { "code": null, "e": 3546, "s": 3531, "text": "GetEditControl" }, { "code": null, "e": 3630, "s": 3546, "text": "Retrieves the handle of the edit control used to edit the specified tree view item." }, { "code": null, "e": 3647, "s": 3630, "text": "GetExtendedStyle" }, { "code": null, "e": 3721, "s": 3647, "text": "Retrieves the extended styles that the current treeview control is using." }, { "code": null, "e": 3741, "s": 3721, "text": "GetFirstVisibleItem" }, { "code": null, "e": 3807, "s": 3741, "text": "Retrieves the first visible item of the specified tree view item." }, { "code": null, "e": 3820, "s": 3807, "text": "GetImageList" }, { "code": null, "e": 3896, "s": 3820, "text": "Retrieves the handle of the image list associated with a tree view control." }, { "code": null, "e": 3906, "s": 3896, "text": "GetIndent" }, { "code": null, "e": 3976, "s": 3906, "text": "Retrieves the offset (in pixels) of a tree view item from its parent." }, { "code": null, "e": 3995, "s": 3976, "text": "GetInsertMarkColor" }, { "code": null, "e": 4066, "s": 3995, "text": "Retrieves the color used to draw the insertion mark for the tree view." }, { "code": null, "e": 4074, "s": 4066, "text": "GetItem" }, { "code": null, "e": 4130, "s": 4074, "text": "Retrieves the attributes of a specified tree view item." }, { "code": null, "e": 4142, "s": 4130, "text": "GetItemData" }, { "code": null, "e": 4213, "s": 4142, "text": "Returns the 32-bit application-specific value associated with an item." }, { "code": null, "e": 4239, "s": 4213, "text": "GetItemExpandedImageIndex" }, { "code": null, "e": 4366, "s": 4239, "text": "Retrieves the index of the image to display when the specified item of the current tree-view control is in the expanded state." }, { "code": null, "e": 4380, "s": 4366, "text": "GetItemHeight" }, { "code": null, "e": 4433, "s": 4380, "text": "Retrieves the current height of the tree view items." }, { "code": null, "e": 4446, "s": 4433, "text": "GetItemImage" }, { "code": null, "e": 4492, "s": 4446, "text": "Retrieves the images associated with an item." }, { "code": null, "e": 4508, "s": 4492, "text": "GetItemPartRect" }, { "code": null, "e": 4616, "s": 4508, "text": "Retrieves the bounding rectangle for a specified part of a specified item in the current tree-view control." }, { "code": null, "e": 4628, "s": 4616, "text": "GetItemRect" }, { "code": null, "e": 4682, "s": 4628, "text": "Retrieves the bounding rectangle of a tree view item." }, { "code": null, "e": 4695, "s": 4682, "text": "GetItemState" }, { "code": null, "e": 4725, "s": 4695, "text": "Returns the state of an item." }, { "code": null, "e": 4740, "s": 4725, "text": "GetItemStateEx" }, { "code": null, "e": 4825, "s": 4740, "text": "Retrieves the extended state of the specified item in the current tree-view control." }, { "code": null, "e": 4837, "s": 4825, "text": "GetItemText" }, { "code": null, "e": 4866, "s": 4837, "text": "Returns the text of an item." }, { "code": null, "e": 4885, "s": 4866, "text": "GetLastVisibleItem" }, { "code": null, "e": 4951, "s": 4885, "text": "Retrieves the last expanded item in the current treeview control." }, { "code": null, "e": 4964, "s": 4951, "text": "GetLineColor" }, { "code": null, "e": 5024, "s": 4964, "text": "Retrieves the current line color for the tree view control." }, { "code": null, "e": 5036, "s": 5024, "text": "GetNextItem" }, { "code": null, "e": 5109, "s": 5036, "text": "Retrieves the next tree view item that matches a specified relationship." }, { "code": null, "e": 5128, "s": 5109, "text": "GetNextSiblingItem" }, { "code": null, "e": 5188, "s": 5128, "text": "Retrieves the next sibling of the specified tree view item." }, { "code": null, "e": 5207, "s": 5188, "text": "GetNextVisibleItem" }, { "code": null, "e": 5272, "s": 5207, "text": "Retrieves the next visible item of the specified tree view item." }, { "code": null, "e": 5286, "s": 5272, "text": "GetParentItem" }, { "code": null, "e": 5340, "s": 5286, "text": "Retrieves the parent of the specified tree view item." }, { "code": null, "e": 5359, "s": 5340, "text": "GetPrevSiblingItem" }, { "code": null, "e": 5423, "s": 5359, "text": "Retrieves the previous sibling of the specified tree view item." }, { "code": null, "e": 5442, "s": 5423, "text": "GetPrevVisibleItem" }, { "code": null, "e": 5511, "s": 5442, "text": "Retrieves the previous visible item of the specified tree view item." }, { "code": null, "e": 5523, "s": 5511, "text": "GetRootItem" }, { "code": null, "e": 5575, "s": 5523, "text": "Retrieves the root of the specified tree view item." }, { "code": null, "e": 5589, "s": 5575, "text": "GetScrollTime" }, { "code": null, "e": 5650, "s": 5589, "text": "Retrieves the maximum scroll time for the tree view control." }, { "code": null, "e": 5667, "s": 5650, "text": "GetSelectedCount" }, { "code": null, "e": 5740, "s": 5667, "text": "Retrieves the number of selected items in the current tree-view control." }, { "code": null, "e": 5756, "s": 5740, "text": "GetSelectedItem" }, { "code": null, "e": 5805, "s": 5756, "text": "Retrieves the currently selected tree view item." }, { "code": null, "e": 5818, "s": 5805, "text": "GetTextColor" }, { "code": null, "e": 5867, "s": 5818, "text": "Retrieves the current text color of the control." }, { "code": null, "e": 5879, "s": 5867, "text": "GetToolTips" }, { "code": null, "e": 5958, "s": 5879, "text": "Retrieves the handle to the child ToolTip control used by a tree view control." }, { "code": null, "e": 5974, "s": 5958, "text": "GetVisibleCount" }, { "code": null, "e": 6054, "s": 5974, "text": "Retrieves the number of visible tree items associated with a tree view control." }, { "code": null, "e": 6062, "s": 6054, "text": "HitTest" }, { "code": null, "e": 6138, "s": 6062, "text": "Returns the current position of the cursor related to the CTreeCtrl object." }, { "code": null, "e": 6149, "s": 6138, "text": "InsertItem" }, { "code": null, "e": 6192, "s": 6149, "text": "Inserts a new item in a tree view control." }, { "code": null, "e": 6208, "s": 6192, "text": "ItemHasChildren" }, { "code": null, "e": 6262, "s": 6208, "text": "Returns nonzero if the specified item has child items" }, { "code": null, "e": 6277, "s": 6262, "text": "MapAccIdToItem" }, { "code": null, "e": 6389, "s": 6277, "text": "Maps the specified accessibility identifier to the handle to a tree-view item in the current tree-view control." }, { "code": null, "e": 6404, "s": 6389, "text": "MapItemToAccID" }, { "code": null, "e": 6515, "s": 6404, "text": "Maps the specified handle to a tree-view item in the current tree-view control to an accessibility identifier." }, { "code": null, "e": 6522, "s": 6515, "text": "Select" }, { "code": null, "e": 6589, "s": 6522, "text": "Selects, scrolls into view, or redraws a specified tree view item." }, { "code": null, "e": 6606, "s": 6589, "text": "SelectDropTarget" }, { "code": null, "e": 6672, "s": 6606, "text": "Redraws the tree item as the target of a drag-and-drop operation." }, { "code": null, "e": 6683, "s": 6672, "text": "SelectItem" }, { "code": null, "e": 6719, "s": 6683, "text": "Selects a specified tree view item." }, { "code": null, "e": 6741, "s": 6719, "text": "SelectSetFirstVisible" }, { "code": null, "e": 6803, "s": 6741, "text": "Selects a specified tree view item as the first visible item." }, { "code": null, "e": 6821, "s": 6803, "text": "SetAutoscrollInfo" }, { "code": null, "e": 6880, "s": 6821, "text": "Sets the autoscroll rate of the current tree-view control." }, { "code": null, "e": 6891, "s": 6880, "text": "SetBkColor" }, { "code": null, "e": 6933, "s": 6891, "text": "Sets the background color of the control." }, { "code": null, "e": 6942, "s": 6933, "text": "SetCheck" }, { "code": null, "e": 6987, "s": 6942, "text": "Sets the check state of a tree control item." }, { "code": null, "e": 7004, "s": 6987, "text": "SetExtendedStyle" }, { "code": null, "e": 7063, "s": 7004, "text": "Sets the extended styles for the current tree-view control" }, { "code": null, "e": 7076, "s": 7063, "text": "SetImageList" }, { "code": null, "e": 7147, "s": 7076, "text": "Sets the handle of the image list associated with a tree view control." }, { "code": null, "e": 7157, "s": 7147, "text": "SetIndent" }, { "code": null, "e": 7222, "s": 7157, "text": "Sets the offset (in pixels) of a tree view item from its parent." }, { "code": null, "e": 7236, "s": 7222, "text": "SetInsertMark" }, { "code": null, "e": 7284, "s": 7236, "text": "Sets the insertion mark in a tree view control." }, { "code": null, "e": 7303, "s": 7284, "text": "SetInsertMarkColor" }, { "code": null, "e": 7369, "s": 7303, "text": "Sets the color used to draw the insertion mark for the tree view." }, { "code": null, "e": 7377, "s": 7369, "text": "SetItem" }, { "code": null, "e": 7428, "s": 7377, "text": "Sets the attributes of a specified tree view item." }, { "code": null, "e": 7440, "s": 7428, "text": "SetItemData" }, { "code": null, "e": 7508, "s": 7440, "text": "Sets the 32-bit application-specific value associated with an item." }, { "code": null, "e": 7534, "s": 7508, "text": "SetItemExpandedImageIndex" }, { "code": null, "e": 7656, "s": 7534, "text": "Sets the index of the image to display when the specified item of the current tree-view control is in the expanded state." }, { "code": null, "e": 7670, "s": 7656, "text": "SetItemHeight" }, { "code": null, "e": 7710, "s": 7670, "text": "Sets the height of the tree view items." }, { "code": null, "e": 7723, "s": 7710, "text": "SetItemImage" }, { "code": null, "e": 7755, "s": 7723, "text": "Associates images with an item." }, { "code": null, "e": 7768, "s": 7755, "text": "SetItemState" }, { "code": null, "e": 7795, "s": 7768, "text": "Sets the state of an item." }, { "code": null, "e": 7810, "s": 7795, "text": "SetItemStateEx" }, { "code": null, "e": 7890, "s": 7810, "text": "Sets the extended state of the specified item in the current tree-view control." }, { "code": null, "e": 7902, "s": 7890, "text": "SetItemText" }, { "code": null, "e": 7928, "s": 7902, "text": "Sets the text of an item." }, { "code": null, "e": 7941, "s": 7928, "text": "SetLineColor" }, { "code": null, "e": 7996, "s": 7941, "text": "Sets the current line color for the tree view control." }, { "code": null, "e": 8010, "s": 7996, "text": "SetScrollTime" }, { "code": null, "e": 8066, "s": 8010, "text": "Sets the maximum scroll time for the tree view control." }, { "code": null, "e": 8079, "s": 8066, "text": "SetTextColor" }, { "code": null, "e": 8115, "s": 8079, "text": "Sets the text color of the control." }, { "code": null, "e": 8127, "s": 8115, "text": "SetToolTips" }, { "code": null, "e": 8177, "s": 8127, "text": "Sets a tree view control's child ToolTip control." }, { "code": null, "e": 8189, "s": 8177, "text": "ShowInfoTip" }, { "code": null, "e": 8267, "s": 8189, "text": "Displays the infotip for the specified item in the current tree-view control." }, { "code": null, "e": 8280, "s": 8267, "text": "SortChildren" }, { "code": null, "e": 8323, "s": 8280, "text": "Sorts the children of a given parent item." }, { "code": null, "e": 8338, "s": 8323, "text": "SortChildrenCB" }, { "code": null, "e": 8424, "s": 8338, "text": "Sorts the children of a given parent item using an application-defined sort function." }, { "code": null, "e": 8502, "s": 8424, "text": "Let us look into a simple example by creating a new MFC dialog based project." }, { "code": null, "e": 8658, "s": 8502, "text": "Step 1 − Once the project is created you will see the TODO line, which is the Caption of Text Control. Remove the Caption and set its ID to IDC_STATIC_TXT." }, { "code": null, "e": 8727, "s": 8658, "text": "Step 2 − Add a value variable m_strTree for the Static Text control." }, { "code": null, "e": 8786, "s": 8727, "text": "Step 3 − From the Controls toolbox, drag the Tree Control." }, { "code": null, "e": 8988, "s": 8786, "text": "Step 4 − On the dialog box, click the Tree Control to select it. On the Properties window, set the Has Buttons, the Has Lines, the Lines At Root, the Client Edge and the Modal Frame properties to True." }, { "code": null, "e": 9048, "s": 8988, "text": "Step 5 − Add a control variable m_treeCtrl for Tee Control." }, { "code": null, "e": 9114, "s": 9048, "text": "Step 6 − Here is initialization of tree control in OnInitDialog()" }, { "code": null, "e": 10723, "s": 9114, "text": "BOOL CMFCTreeControlDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n HTREEITEM hItem, hCar;\n hItem = m_treeCtrl.InsertItem(L\"Car Listing\", TVI_ROOT);\n hCar = m_treeCtrl.InsertItem(L\"Economy\", hItem);\n m_treeCtrl.InsertItem(L\"BH-733\", hCar);\n m_treeCtrl.InsertItem(L\"SD-397\", hCar);\n m_treeCtrl.InsertItem(L\"JU-538\", hCar);\n m_treeCtrl.InsertItem(L\"DI-285\", hCar);\n m_treeCtrl.InsertItem(L\"AK-830\", hCar);\n hCar = m_treeCtrl.InsertItem(L\"Compact\", hItem);\n m_treeCtrl.InsertItem(L\"HG-490\", hCar);\n m_treeCtrl.InsertItem(L\"PE-473\", hCar);\n hCar = m_treeCtrl.InsertItem(L\"Standard\", hItem);\n m_treeCtrl.InsertItem(L\"SO-398\", hCar);\n m_treeCtrl.InsertItem(L\"DF-438\", hCar);\n m_treeCtrl.InsertItem(L\"IS-833\", hCar);\n hCar = m_treeCtrl.InsertItem(L\"Full Size\", hItem);\n m_treeCtrl.InsertItem(L\"PD-304\", hCar);\n hCar = m_treeCtrl.InsertItem(L\"Mini Van\", hItem);\n m_treeCtrl.InsertItem(L\"ID-497\", hCar);\n m_treeCtrl.InsertItem(L\"RU-304\", hCar);\n m_treeCtrl.InsertItem(L\"DK-905\", hCar);\n hCar = m_treeCtrl.InsertItem(L\"SUV\", hItem);\n m_treeCtrl.InsertItem(L\"FE-948\", hCar);\n m_treeCtrl.InsertItem(L\"AD-940\", hCar);\n hCar = m_treeCtrl.InsertItem(L\"Truck\", hItem);\n m_treeCtrl.InsertItem(L\"HD-394\", hCar);\n\n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 10813, "s": 10723, "text": "Step 7 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 10820, "s": 10813, "text": " Print" }, { "code": null, "e": 10831, "s": 10820, "text": " Add Notes" } ]
Write your own atoi()
22 Jun, 2022 The atoi() function in C takes a string (which represents an integer) as an argument and returns its value of type int. So basically the function is used to convert a string argument to an integer. Syntax: int atoi(const char strn) Parameters: The function accepts one parameter strn which refers to the string argument that is needed to be converted into its integer equivalent. Return Value: If strn is a valid input, then the function returns the equivalent integer number for the passed string number. If no valid conversion takes place, then the function returns zero. Example: C++ C #include <bits/stdc++.h>using namespace std; int main(){ int val; char strn1[] = "12546"; val = atoi(strn1); cout <<"String value = " << strn1 << endl; cout <<"Integer value = " << val << endl; char strn2[] = "GeeksforGeeks"; val = atoi(strn2); cout <<"String value = " << strn2 << endl; cout <<"Integer value = " << val <<endl; return (0);} // This code is contributed by shivanisinghss2110 #include <stdio.h>#include <stdlib.h>#include <string.h> int main(){ int val; char strn1[] = "12546"; val = atoi(strn1); printf("String value = %s\n", strn1); printf("Integer value = %d\n", val); char strn2[] = "GeeksforGeeks"; val = atoi(strn2); printf("String value = %s\n", strn2); printf("Integer value = %d\n", val); return (0);} String value = 12546 Integer value = 12546 String value = GeeksforGeeks Integer value = 0 Time Complexity: O(1) Auxiliary Space: O(1) Now let’s understand various ways in which one can create there own atoi() function supported by various conditions: Approach 1: Following is a simple implementation of conversion without considering any special case. Initialize the result as 0. Start from the first character and update result for every character. For every character update the answer as result = result * 10 + (s[i] – ‘0’) C++ C Java Python3 C# Javascript // A simple C++ program for// implementation of atoi#include <bits/stdc++.h>using namespace std; // A simple atoi() functionint myAtoi(char* str){ // Initialize result int res = 0; // Iterate through all characters // of input string and update result // take ASCII character of corresponding digit and // subtract the code from '0' to get numerical // value and multiply res by 10 to shuffle // digits left to update running total for (int i = 0; str[i] != '\0'; ++i) res = res * 10 + str[i] - '0'; // return result. return res;} // Driver codeint main(){ char str[] = "89789"; // Function call int val = myAtoi(str); cout << val; return 0;} // This is code is contributed by rathbhupendra // Program to implement atoi() in C#include <stdio.h> // A simple atoi() functionint myAtoi(char* str){ // Initialize result int res = 0; // Iterate through all characters // of input string and update result // take ASCII character of corresponding digit and // subtract the code from '0' to get numerical // value and multiply res by 10 to shuffle // digits left to update running total for (int i = 0; str[i] != '\0'; ++i) res = res * 10 + str[i] - '0'; // return result. return res;} // Driver Codeint main(){ char str[] = "89789"; // Function call int val = myAtoi(str); printf("%d ", val); return 0;} // A simple Java program for// implementation of atoiclass GFG { // A simple atoi() function static int myAtoi(String str) { // Initialize result int res = 0; // Iterate through all characters // of input string and update result // take ASCII character of corresponding digit and // subtract the code from '0' to get numerical // value and multiply res by 10 to shuffle // digits left to update running total for (int i = 0; i < str.length(); ++i) res = res * 10 + str.charAt(i) - '0'; // return result. return res; } // Driver code public static void main(String[] args) { String str = "89789"; // Function call int val = myAtoi(str); System.out.println(val); }} // This code is contributed by PrinciRaj1992 # Python program for implementation of atoi # A simple atoi() function def myAtoi(string): res = 0 # Iterate through all characters of # input string and update result for i in range(len(string)): res = res * 10 + (ord(string[i]) - ord('0')) return res # Driver programstring = "89789" # Function callprint (myAtoi(string)) # This code is contributed by BHAVYA JAIN // A simple C# program for implementation// of atoiusing System; class GFG { // A simple atoi() function static int myAtoi(string str) { int res = 0; // Initialize result // Iterate through all characters // of input string and update result // take ASCII character of corresponding digit and // subtract the code from '0' to get numerical // value and multiply res by 10 to shuffle // digits left to update running total for (int i = 0; i < str.Length; ++i) res = res * 10 + str[i] - '0'; // return result. return res; } // Driver code public static void Main() { string str = "89789"; // Function call int val = myAtoi(str); Console.Write(val); }} // This code is contributed by Sam007. <script>// A simple Javascript program for// implementation of atoi // A simple atoi() functionfunction myAtoi(str){ // Initialize result let res = 0; // Iterate through all characters // of input string and update result // take ASCII character of corresponding digit and // subtract the code from '0' to get numerical // value and multiply res by 10 to shuffle // digits left to update running total for (let i = 0; i < str.length; ++i) res = res * 10 + str[i].charCodeAt(0) - '0'.charCodeAt(0); // return result. return res;} // Driver codelet str = "89789"; // Function calllet val = myAtoi(str);document.write(val); // This code is contributed by rag2127</script> 89789 Time Complexity : O(n) where n is the length of string str. Approach 2: This implementation handles the negative numbers. If the first character is ‘-‘ then store the sign as negative and then convert the rest of the string to number using the previous approach while multiplying sign with it. C++ C Java Python3 C# Javascript // A C++ program for// implementation of atoi#include <bits/stdc++.h>using namespace std; // A simple atoi() functionint myAtoi(char* str){ // Initialize result int res = 0; // Initialize sign as positive int sign = 1; // Initialize index of first digit int i = 0; // If number is negative, // then update sign if (str[0] == '-') { sign = -1; // Also update index of first digit i++; } // Iterate through all digits // and update the result for (; str[i] != '\0'; i++) res = res * 10 + str[i] - '0'; // Return result with sign return sign * res;} // Driver codeint main(){ char str[] = "-123"; // Function call int val = myAtoi(str); cout << val; return 0;} // This is code is contributed by rathbhupendra // A C program for// implementation of atoi#include <stdio.h> // A simple atoi() functionint myAtoi(char* str){ // Initialize result int res = 0; // Initialize sign as positive int sign = 1; // Initialize index of first digit int i = 0; // If number is negative, // then update sign if (str[0] == '-') { sign = -1; // Also update index of first digit i++; } // Iterate through all digits // and update the result for (; str[i] != '\0'; ++i) res = res * 10 + str[i] - '0'; // Return result with sign return sign * res;} // Driver codeint main(){ char str[] = "-123"; // Function call int val = myAtoi(str); printf("%d ", val); return 0;} // Java program for// implementation of atoiclass GFG { // A simple atoi() function static int myAtoi(char[] str) { // Initialize result int res = 0; // Initialize sign as positive int sign = 1; // Initialize index of first digit int i = 0; // If number is negative, then // update sign if (str[0] == '-') { sign = -1; // Also update index of first // digit i++; } // Iterate through all digits // and update the result for (; i < str.length; ++i) res = res * 10 + str[i] - '0'; // Return result with sign return sign * res; } // Driver code public static void main(String[] args) { char[] str = "-123".toCharArray(); // Function call int val = myAtoi(str); System.out.println(val); }} // This code is contributed by 29AjayKumar # Python program for implementation of atoi # A simple atoi() function def myAtoi(string): res = 0 # initialize sign as positive sign = 1 i = 0 # if number is negative then update sign if string[0] == '-': sign = -1 i += 1 # Iterate through all characters # of input string and update result for j in range(i, len(string)): res = res*10+(ord(string[j])-ord('0')) return sign * res # Driver codestring = "-123" # Function callprint (myAtoi(string)) # This code is contributed by BHAVYA JAIN // C# program for implementation of atoiusing System; class GFG { // A simple atoi() function static int myAtoi(string str) { // Initialize result int res = 0; // Initialize sign as positive int sign = 1; // Initialize index of first digit int i = 0; // If number is negative, then // update sign if (str[0] == '-') { sign = -1; // Also update index of first // digit i++; } // Iterate through all digits // and update the result for (; i < str.Length; ++i) res = res * 10 + str[i] - '0'; // Return result with sign return sign * res; } // Driver code public static void Main() { string str = "-123"; // Function call int val = myAtoi(str); Console.Write(val); }} // This code is contributed by Sam007. <script> // JavaScript program for implementation of atoi // A simple atoi() function function myAtoi(str) { // Initialize result var res = 0; // Initialize sign as positive var sign = 1; // Initialize index of first digit var i = 0; // If number is negative, then // update sign if (str[0] == '-') { sign = -1; // Also update index of first // digit i++; } // Iterate through all digits // and update the result for (; i < str.length; ++i) res = res * 10 + str[i].charCodeAt(0) - '0'.charCodeAt(0); // Return result with sign return sign * res; } // Driver code var str = "-129"; var val=myAtoi(str); document.write(val); </script> <! --This code is contributed by nirajgusain5 --> -123 Time Complexity : O(n) where n is the length of string str. Approach 3: Four corner cases needs to be handled: Discards all leading whitespaces Sign of the number Overflow Invalid input To remove the leading whitespaces run a loop until a character of the digit is reached. If the number is greater than or equal to INT_MAX/10. Then return INT_MAX if the sign is positive and return INT_MIN if the sign is negative. The other cases are handled in previous approaches. Dry Run: Below is the implementation of the above approach: C++ C Java Python3 C# Javascript // A simple C++ program for// implementation of atoi#include <bits/stdc++.h>using namespace std; int myAtoi(const char* str){ int sign = 1, base = 0, i = 0; // if whitespaces then ignore. while (str[i] == ' ') { i++; } // sign of number if (str[i] == '-' || str[i] == '+') { sign = 1 - 2 * (str[i++] == '-'); } // checking for valid input while (str[i] >= '0' && str[i] <= '9') { // handling overflow test case if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) { if (sign == 1) return INT_MAX; else return INT_MIN; } base = 10 * base + (str[i++] - '0'); } return base * sign;} // Driver Codeint main(){ char str[] = " -123"; // Functional Code int val = myAtoi(str); cout <<" "<< val; return 0;} // This code is contributed by shivanisinghss2110 // A simple C++ program for// implementation of atoi#include <stdio.h>#include <limits.h> int myAtoi(const char* str){ int sign = 1, base = 0, i = 0; // if whitespaces then ignore. while (str[i] == ' ') { i++; } // sign of number if (str[i] == '-' || str[i] == '+') { sign = 1 - 2 * (str[i++] == '-'); } // checking for valid input while (str[i] >= '0' && str[i] <= '9') { // handling overflow test case if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) { if (sign == 1) return INT_MAX; else return INT_MIN; } base = 10 * base + (str[i++] - '0'); } return base * sign;} // Driver Codeint main(){ char str[] = " -123"; // Functional Code int val = myAtoi(str); printf("%d ", val); return 0;}// This code is contributed by Yogesh shukla. // A simple Java program for// implementation of atoiclass GFG { static int myAtoi(char[] str) { int sign = 1, base = 0, i = 0; // if whitespaces then ignore. while (str[i] == ' ') { i++; } // sign of number if (str[i] == '-' || str[i] == '+') { sign = 1 - 2 * (str[i++] == '-' ? 1 : 0); } // checking for valid input while (i < str.length && str[i] >= '0' && str[i] <= '9') { // handling overflow test case if (base > Integer.MAX_VALUE / 10 || (base == Integer.MAX_VALUE / 10 && str[i] - '0' > 7)) { if (sign == 1) return Integer.MAX_VALUE; else return Integer.MIN_VALUE; } base = 10 * base + (str[i++] - '0'); } return base * sign; } // Driver code public static void main(String[] args) { char str[] = " -123".toCharArray(); // Function call int val = myAtoi(str); System.out.printf("%d ", val); }} // This code is contributed by 29AjayKumar # A simple Python3 program for# implementation of atoiimport sys def myAtoi(Str): sign, base, i = 1, 0, 0 # If whitespaces then ignore. while (Str[i] == ' '): i += 1 # Sign of number if (Str[i] == '-' or Str[i] == '+'): sign = 1 - 2 * (Str[i] == '-') i += 1 # Checking for valid input while (i < len(Str) and Str[i] >= '0' and Str[i] <= '9'): # Handling overflow test case if (base > (sys.maxsize // 10) or (base == (sys.maxsize // 10) and (Str[i] - '0') > 7)): if (sign == 1): return sys.maxsize else: return -(sys.maxsize) base = 10 * base + (ord(Str[i]) - ord('0')) i += 1 return base * sign # Driver CodeStr = list(" -123") # Functional Codeval = myAtoi(Str) print(val) # This code is contributed by divyeshrabadiya07 // A simple C# program for implementation of atoiusing System; class GFG { static int myAtoi(char[] str) { int sign = 1, Base = 0, i = 0; // if whitespaces then ignore. while (str[i] == ' ') { i++; } // sign of number if (str[i] == '-' || str[i] == '+') { sign = 1 - 2 * (str[i++] == '-' ? 1 : 0); } // checking for valid input while ( i < str.Length && str[i] >= '0' && str[i] <= '9') { // handling overflow test case if (Base > int.MaxValue / 10 || (Base == int.MaxValue / 10 && str[i] - '0' > 7)) { if (sign == 1) return int.MaxValue; else return int.MinValue; } Base = 10 * Base + (str[i++] - '0'); } return Base * sign; } // Driver code public static void Main(String[] args) { char[] str = " -123".ToCharArray(); int val = myAtoi(str); Console.Write("{0} ", val); }} // This code is contributed by 29AjayKumar <script>// A simple JavaScript program for// implementation of atoi function myAtoi(str) { var sign = 1, base = 0, i = 0; // if whitespaces then ignore. while (str[i] == ' ') { i++; } // sign of number if (str[i] == '-' || str[i] == '+') { sign = 1 - 2 * (str[i++] == '-'); } // checking for valid input while (str[i] >= '0' && str[i] <= '9') { // handling overflow test case if (base > Number.MAX_VALUE/ 10 || (base == Number.MAX_VALUE / 10 && str[i] - '0' > 7)) { if (sign == 1) return Number.MAX_VALUE; else return Number.MAX_VALUE; } base = 10 * base + (str[i++] - '0'); } return base * sign;} // Driver code var str = " -123"; // Function call var val = myAtoi(str); document.write(" ", val); // This code is contributed by shivanisinghss2110</script> -123 Complexity Analysis for all the above Approaches: Time Complexity: O(n). Only one traversal of string is needed. Space Complexity: O(1). As no extra space is required. Recursive program for atoi(). Exercise: Write your won atof() that takes a string (which represents an floating point value) as an argument and returns its value as double. This article is compiled by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Yogesh Shukla 1 rathbhupendra suraj_shinde princiraj1992 29AjayKumar andrew1234 officeofdevang divyeshrabadiya07 rag2127 saurabh1990aror nirajgusain5 avanitrachhadiya2155 shivanisinghss2110 ajayshendkar harikrishnanar amartyaghoshgfg akashish__ Adobe Amazon Code Brew Microsoft Morgan Stanley Payu Strings Morgan Stanley Amazon Microsoft Payu Adobe Code Brew Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2022" }, { "code": null, "e": 250, "s": 52, "text": "The atoi() function in C takes a string (which represents an integer) as an argument and returns its value of type int. So basically the function is used to convert a string argument to an integer." }, { "code": null, "e": 260, "s": 250, "text": "Syntax: " }, { "code": null, "e": 286, "s": 260, "text": "int atoi(const char strn)" }, { "code": null, "e": 434, "s": 286, "text": "Parameters: The function accepts one parameter strn which refers to the string argument that is needed to be converted into its integer equivalent." }, { "code": null, "e": 628, "s": 434, "text": "Return Value: If strn is a valid input, then the function returns the equivalent integer number for the passed string number. If no valid conversion takes place, then the function returns zero." }, { "code": null, "e": 638, "s": 628, "text": "Example: " }, { "code": null, "e": 642, "s": 638, "text": "C++" }, { "code": null, "e": 644, "s": 642, "text": "C" }, { "code": "#include <bits/stdc++.h>using namespace std; int main(){ int val; char strn1[] = \"12546\"; val = atoi(strn1); cout <<\"String value = \" << strn1 << endl; cout <<\"Integer value = \" << val << endl; char strn2[] = \"GeeksforGeeks\"; val = atoi(strn2); cout <<\"String value = \" << strn2 << endl; cout <<\"Integer value = \" << val <<endl; return (0);} // This code is contributed by shivanisinghss2110", "e": 1069, "s": 644, "text": null }, { "code": "#include <stdio.h>#include <stdlib.h>#include <string.h> int main(){ int val; char strn1[] = \"12546\"; val = atoi(strn1); printf(\"String value = %s\\n\", strn1); printf(\"Integer value = %d\\n\", val); char strn2[] = \"GeeksforGeeks\"; val = atoi(strn2); printf(\"String value = %s\\n\", strn2); printf(\"Integer value = %d\\n\", val); return (0);}", "e": 1437, "s": 1069, "text": null }, { "code": null, "e": 1527, "s": 1437, "text": "String value = 12546\nInteger value = 12546\nString value = GeeksforGeeks\nInteger value = 0" }, { "code": null, "e": 1549, "s": 1527, "text": "Time Complexity: O(1)" }, { "code": null, "e": 1571, "s": 1549, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 1688, "s": 1571, "text": "Now let’s understand various ways in which one can create there own atoi() function supported by various conditions:" }, { "code": null, "e": 1790, "s": 1688, "text": "Approach 1: Following is a simple implementation of conversion without considering any special case. " }, { "code": null, "e": 1818, "s": 1790, "text": "Initialize the result as 0." }, { "code": null, "e": 1888, "s": 1818, "text": "Start from the first character and update result for every character." }, { "code": null, "e": 1965, "s": 1888, "text": "For every character update the answer as result = result * 10 + (s[i] – ‘0’)" }, { "code": null, "e": 1969, "s": 1965, "text": "C++" }, { "code": null, "e": 1971, "s": 1969, "text": "C" }, { "code": null, "e": 1976, "s": 1971, "text": "Java" }, { "code": null, "e": 1984, "s": 1976, "text": "Python3" }, { "code": null, "e": 1987, "s": 1984, "text": "C#" }, { "code": null, "e": 1998, "s": 1987, "text": "Javascript" }, { "code": "// A simple C++ program for// implementation of atoi#include <bits/stdc++.h>using namespace std; // A simple atoi() functionint myAtoi(char* str){ // Initialize result int res = 0; // Iterate through all characters // of input string and update result // take ASCII character of corresponding digit and // subtract the code from '0' to get numerical // value and multiply res by 10 to shuffle // digits left to update running total for (int i = 0; str[i] != '\\0'; ++i) res = res * 10 + str[i] - '0'; // return result. return res;} // Driver codeint main(){ char str[] = \"89789\"; // Function call int val = myAtoi(str); cout << val; return 0;} // This is code is contributed by rathbhupendra", "e": 2749, "s": 1998, "text": null }, { "code": "// Program to implement atoi() in C#include <stdio.h> // A simple atoi() functionint myAtoi(char* str){ // Initialize result int res = 0; // Iterate through all characters // of input string and update result // take ASCII character of corresponding digit and // subtract the code from '0' to get numerical // value and multiply res by 10 to shuffle // digits left to update running total for (int i = 0; str[i] != '\\0'; ++i) res = res * 10 + str[i] - '0'; // return result. return res;} // Driver Codeint main(){ char str[] = \"89789\"; // Function call int val = myAtoi(str); printf(\"%d \", val); return 0;}", "e": 3416, "s": 2749, "text": null }, { "code": "// A simple Java program for// implementation of atoiclass GFG { // A simple atoi() function static int myAtoi(String str) { // Initialize result int res = 0; // Iterate through all characters // of input string and update result // take ASCII character of corresponding digit and // subtract the code from '0' to get numerical // value and multiply res by 10 to shuffle // digits left to update running total for (int i = 0; i < str.length(); ++i) res = res * 10 + str.charAt(i) - '0'; // return result. return res; } // Driver code public static void main(String[] args) { String str = \"89789\"; // Function call int val = myAtoi(str); System.out.println(val); }} // This code is contributed by PrinciRaj1992", "e": 4286, "s": 3416, "text": null }, { "code": "# Python program for implementation of atoi # A simple atoi() function def myAtoi(string): res = 0 # Iterate through all characters of # input string and update result for i in range(len(string)): res = res * 10 + (ord(string[i]) - ord('0')) return res # Driver programstring = \"89789\" # Function callprint (myAtoi(string)) # This code is contributed by BHAVYA JAIN", "e": 4679, "s": 4286, "text": null }, { "code": "// A simple C# program for implementation// of atoiusing System; class GFG { // A simple atoi() function static int myAtoi(string str) { int res = 0; // Initialize result // Iterate through all characters // of input string and update result // take ASCII character of corresponding digit and // subtract the code from '0' to get numerical // value and multiply res by 10 to shuffle // digits left to update running total for (int i = 0; i < str.Length; ++i) res = res * 10 + str[i] - '0'; // return result. return res; } // Driver code public static void Main() { string str = \"89789\"; // Function call int val = myAtoi(str); Console.Write(val); }} // This code is contributed by Sam007.", "e": 5512, "s": 4679, "text": null }, { "code": "<script>// A simple Javascript program for// implementation of atoi // A simple atoi() functionfunction myAtoi(str){ // Initialize result let res = 0; // Iterate through all characters // of input string and update result // take ASCII character of corresponding digit and // subtract the code from '0' to get numerical // value and multiply res by 10 to shuffle // digits left to update running total for (let i = 0; i < str.length; ++i) res = res * 10 + str[i].charCodeAt(0) - '0'.charCodeAt(0); // return result. return res;} // Driver codelet str = \"89789\"; // Function calllet val = myAtoi(str);document.write(val); // This code is contributed by rag2127</script>", "e": 6287, "s": 5512, "text": null }, { "code": null, "e": 6293, "s": 6287, "text": "89789" }, { "code": null, "e": 6356, "s": 6293, "text": "Time Complexity : O(n) where n is the length of string str." }, { "code": null, "e": 6591, "s": 6356, "text": "Approach 2: This implementation handles the negative numbers. If the first character is ‘-‘ then store the sign as negative and then convert the rest of the string to number using the previous approach while multiplying sign with it. " }, { "code": null, "e": 6595, "s": 6591, "text": "C++" }, { "code": null, "e": 6597, "s": 6595, "text": "C" }, { "code": null, "e": 6602, "s": 6597, "text": "Java" }, { "code": null, "e": 6610, "s": 6602, "text": "Python3" }, { "code": null, "e": 6613, "s": 6610, "text": "C#" }, { "code": null, "e": 6624, "s": 6613, "text": "Javascript" }, { "code": "// A C++ program for// implementation of atoi#include <bits/stdc++.h>using namespace std; // A simple atoi() functionint myAtoi(char* str){ // Initialize result int res = 0; // Initialize sign as positive int sign = 1; // Initialize index of first digit int i = 0; // If number is negative, // then update sign if (str[0] == '-') { sign = -1; // Also update index of first digit i++; } // Iterate through all digits // and update the result for (; str[i] != '\\0'; i++) res = res * 10 + str[i] - '0'; // Return result with sign return sign * res;} // Driver codeint main(){ char str[] = \"-123\"; // Function call int val = myAtoi(str); cout << val; return 0;} // This is code is contributed by rathbhupendra", "e": 7425, "s": 6624, "text": null }, { "code": "// A C program for// implementation of atoi#include <stdio.h> // A simple atoi() functionint myAtoi(char* str){ // Initialize result int res = 0; // Initialize sign as positive int sign = 1; // Initialize index of first digit int i = 0; // If number is negative, // then update sign if (str[0] == '-') { sign = -1; // Also update index of first digit i++; } // Iterate through all digits // and update the result for (; str[i] != '\\0'; ++i) res = res * 10 + str[i] - '0'; // Return result with sign return sign * res;} // Driver codeint main(){ char str[] = \"-123\"; // Function call int val = myAtoi(str); printf(\"%d \", val); return 0;}", "e": 8159, "s": 7425, "text": null }, { "code": "// Java program for// implementation of atoiclass GFG { // A simple atoi() function static int myAtoi(char[] str) { // Initialize result int res = 0; // Initialize sign as positive int sign = 1; // Initialize index of first digit int i = 0; // If number is negative, then // update sign if (str[0] == '-') { sign = -1; // Also update index of first // digit i++; } // Iterate through all digits // and update the result for (; i < str.length; ++i) res = res * 10 + str[i] - '0'; // Return result with sign return sign * res; } // Driver code public static void main(String[] args) { char[] str = \"-123\".toCharArray(); // Function call int val = myAtoi(str); System.out.println(val); }} // This code is contributed by 29AjayKumar", "e": 9116, "s": 8159, "text": null }, { "code": "# Python program for implementation of atoi # A simple atoi() function def myAtoi(string): res = 0 # initialize sign as positive sign = 1 i = 0 # if number is negative then update sign if string[0] == '-': sign = -1 i += 1 # Iterate through all characters # of input string and update result for j in range(i, len(string)): res = res*10+(ord(string[j])-ord('0')) return sign * res # Driver codestring = \"-123\" # Function callprint (myAtoi(string)) # This code is contributed by BHAVYA JAIN", "e": 9662, "s": 9116, "text": null }, { "code": "// C# program for implementation of atoiusing System; class GFG { // A simple atoi() function static int myAtoi(string str) { // Initialize result int res = 0; // Initialize sign as positive int sign = 1; // Initialize index of first digit int i = 0; // If number is negative, then // update sign if (str[0] == '-') { sign = -1; // Also update index of first // digit i++; } // Iterate through all digits // and update the result for (; i < str.Length; ++i) res = res * 10 + str[i] - '0'; // Return result with sign return sign * res; } // Driver code public static void Main() { string str = \"-123\"; // Function call int val = myAtoi(str); Console.Write(val); }} // This code is contributed by Sam007.", "e": 10593, "s": 9662, "text": null }, { "code": "<script> // JavaScript program for implementation of atoi // A simple atoi() function function myAtoi(str) { // Initialize result var res = 0; // Initialize sign as positive var sign = 1; // Initialize index of first digit var i = 0; // If number is negative, then // update sign if (str[0] == '-') { sign = -1; // Also update index of first // digit i++; } // Iterate through all digits // and update the result for (; i < str.length; ++i) res = res * 10 + str[i].charCodeAt(0) - '0'.charCodeAt(0); // Return result with sign return sign * res; } // Driver code var str = \"-129\"; var val=myAtoi(str); document.write(val); </script> <! --This code is contributed by nirajgusain5 -->", "e": 11499, "s": 10593, "text": null }, { "code": null, "e": 11504, "s": 11499, "text": "-123" }, { "code": null, "e": 11567, "s": 11504, "text": "Time Complexity : O(n) where n is the length of string str." }, { "code": null, "e": 11619, "s": 11567, "text": "Approach 3: Four corner cases needs to be handled: " }, { "code": null, "e": 11652, "s": 11619, "text": "Discards all leading whitespaces" }, { "code": null, "e": 11671, "s": 11652, "text": "Sign of the number" }, { "code": null, "e": 11680, "s": 11671, "text": "Overflow" }, { "code": null, "e": 11694, "s": 11680, "text": "Invalid input" }, { "code": null, "e": 11977, "s": 11694, "text": "To remove the leading whitespaces run a loop until a character of the digit is reached. If the number is greater than or equal to INT_MAX/10. Then return INT_MAX if the sign is positive and return INT_MIN if the sign is negative. The other cases are handled in previous approaches. " }, { "code": null, "e": 11987, "s": 11977, "text": "Dry Run: " }, { "code": null, "e": 12039, "s": 11987, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 12043, "s": 12039, "text": "C++" }, { "code": null, "e": 12045, "s": 12043, "text": "C" }, { "code": null, "e": 12050, "s": 12045, "text": "Java" }, { "code": null, "e": 12058, "s": 12050, "text": "Python3" }, { "code": null, "e": 12061, "s": 12058, "text": "C#" }, { "code": null, "e": 12072, "s": 12061, "text": "Javascript" }, { "code": "// A simple C++ program for// implementation of atoi#include <bits/stdc++.h>using namespace std; int myAtoi(const char* str){ int sign = 1, base = 0, i = 0; // if whitespaces then ignore. while (str[i] == ' ') { i++; } // sign of number if (str[i] == '-' || str[i] == '+') { sign = 1 - 2 * (str[i++] == '-'); } // checking for valid input while (str[i] >= '0' && str[i] <= '9') { // handling overflow test case if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) { if (sign == 1) return INT_MAX; else return INT_MIN; } base = 10 * base + (str[i++] - '0'); } return base * sign;} // Driver Codeint main(){ char str[] = \" -123\"; // Functional Code int val = myAtoi(str); cout <<\" \"<< val; return 0;} // This code is contributed by shivanisinghss2110", "e": 13037, "s": 12072, "text": null }, { "code": "// A simple C++ program for// implementation of atoi#include <stdio.h>#include <limits.h> int myAtoi(const char* str){ int sign = 1, base = 0, i = 0; // if whitespaces then ignore. while (str[i] == ' ') { i++; } // sign of number if (str[i] == '-' || str[i] == '+') { sign = 1 - 2 * (str[i++] == '-'); } // checking for valid input while (str[i] >= '0' && str[i] <= '9') { // handling overflow test case if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) { if (sign == 1) return INT_MAX; else return INT_MIN; } base = 10 * base + (str[i++] - '0'); } return base * sign;} // Driver Codeint main(){ char str[] = \" -123\"; // Functional Code int val = myAtoi(str); printf(\"%d \", val); return 0;}// This code is contributed by Yogesh shukla.", "e": 13992, "s": 13037, "text": null }, { "code": "// A simple Java program for// implementation of atoiclass GFG { static int myAtoi(char[] str) { int sign = 1, base = 0, i = 0; // if whitespaces then ignore. while (str[i] == ' ') { i++; } // sign of number if (str[i] == '-' || str[i] == '+') { sign = 1 - 2 * (str[i++] == '-' ? 1 : 0); } // checking for valid input while (i < str.length && str[i] >= '0' && str[i] <= '9') { // handling overflow test case if (base > Integer.MAX_VALUE / 10 || (base == Integer.MAX_VALUE / 10 && str[i] - '0' > 7)) { if (sign == 1) return Integer.MAX_VALUE; else return Integer.MIN_VALUE; } base = 10 * base + (str[i++] - '0'); } return base * sign; } // Driver code public static void main(String[] args) { char str[] = \" -123\".toCharArray(); // Function call int val = myAtoi(str); System.out.printf(\"%d \", val); }} // This code is contributed by 29AjayKumar", "e": 15196, "s": 13992, "text": null }, { "code": "# A simple Python3 program for# implementation of atoiimport sys def myAtoi(Str): sign, base, i = 1, 0, 0 # If whitespaces then ignore. while (Str[i] == ' '): i += 1 # Sign of number if (Str[i] == '-' or Str[i] == '+'): sign = 1 - 2 * (Str[i] == '-') i += 1 # Checking for valid input while (i < len(Str) and Str[i] >= '0' and Str[i] <= '9'): # Handling overflow test case if (base > (sys.maxsize // 10) or (base == (sys.maxsize // 10) and (Str[i] - '0') > 7)): if (sign == 1): return sys.maxsize else: return -(sys.maxsize) base = 10 * base + (ord(Str[i]) - ord('0')) i += 1 return base * sign # Driver CodeStr = list(\" -123\") # Functional Codeval = myAtoi(Str) print(val) # This code is contributed by divyeshrabadiya07", "e": 16113, "s": 15196, "text": null }, { "code": "// A simple C# program for implementation of atoiusing System; class GFG { static int myAtoi(char[] str) { int sign = 1, Base = 0, i = 0; // if whitespaces then ignore. while (str[i] == ' ') { i++; } // sign of number if (str[i] == '-' || str[i] == '+') { sign = 1 - 2 * (str[i++] == '-' ? 1 : 0); } // checking for valid input while ( i < str.Length && str[i] >= '0' && str[i] <= '9') { // handling overflow test case if (Base > int.MaxValue / 10 || (Base == int.MaxValue / 10 && str[i] - '0' > 7)) { if (sign == 1) return int.MaxValue; else return int.MinValue; } Base = 10 * Base + (str[i++] - '0'); } return Base * sign; } // Driver code public static void Main(String[] args) { char[] str = \" -123\".ToCharArray(); int val = myAtoi(str); Console.Write(\"{0} \", val); }} // This code is contributed by 29AjayKumar", "e": 17220, "s": 16113, "text": null }, { "code": "<script>// A simple JavaScript program for// implementation of atoi function myAtoi(str) { var sign = 1, base = 0, i = 0; // if whitespaces then ignore. while (str[i] == ' ') { i++; } // sign of number if (str[i] == '-' || str[i] == '+') { sign = 1 - 2 * (str[i++] == '-'); } // checking for valid input while (str[i] >= '0' && str[i] <= '9') { // handling overflow test case if (base > Number.MAX_VALUE/ 10 || (base == Number.MAX_VALUE / 10 && str[i] - '0' > 7)) { if (sign == 1) return Number.MAX_VALUE; else return Number.MAX_VALUE; } base = 10 * base + (str[i++] - '0'); } return base * sign;} // Driver code var str = \" -123\"; // Function call var val = myAtoi(str); document.write(\" \", val); // This code is contributed by shivanisinghss2110</script>", "e": 18203, "s": 17220, "text": null }, { "code": null, "e": 18209, "s": 18203, "text": " -123" }, { "code": null, "e": 18260, "s": 18209, "text": "Complexity Analysis for all the above Approaches: " }, { "code": null, "e": 18323, "s": 18260, "text": "Time Complexity: O(n). Only one traversal of string is needed." }, { "code": null, "e": 18378, "s": 18323, "text": "Space Complexity: O(1). As no extra space is required." }, { "code": null, "e": 18408, "s": 18378, "text": "Recursive program for atoi()." }, { "code": null, "e": 18551, "s": 18408, "text": "Exercise: Write your won atof() that takes a string (which represents an floating point value) as an argument and returns its value as double." }, { "code": null, "e": 18940, "s": 18551, "text": "This article is compiled by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 18956, "s": 18940, "text": "Yogesh Shukla 1" }, { "code": null, "e": 18970, "s": 18956, "text": "rathbhupendra" }, { "code": null, "e": 18983, "s": 18970, "text": "suraj_shinde" }, { "code": null, "e": 18997, "s": 18983, "text": "princiraj1992" }, { "code": null, "e": 19009, "s": 18997, "text": "29AjayKumar" }, { "code": null, "e": 19020, "s": 19009, "text": "andrew1234" }, { "code": null, "e": 19035, "s": 19020, "text": "officeofdevang" }, { "code": null, "e": 19053, "s": 19035, "text": "divyeshrabadiya07" }, { "code": null, "e": 19061, "s": 19053, "text": "rag2127" }, { "code": null, "e": 19077, "s": 19061, "text": "saurabh1990aror" }, { "code": null, "e": 19090, "s": 19077, "text": "nirajgusain5" }, { "code": null, "e": 19111, "s": 19090, "text": "avanitrachhadiya2155" }, { "code": null, "e": 19130, "s": 19111, "text": "shivanisinghss2110" }, { "code": null, "e": 19143, "s": 19130, "text": "ajayshendkar" }, { "code": null, "e": 19158, "s": 19143, "text": "harikrishnanar" }, { "code": null, "e": 19174, "s": 19158, "text": "amartyaghoshgfg" }, { "code": null, "e": 19185, "s": 19174, "text": "akashish__" }, { "code": null, "e": 19191, "s": 19185, "text": "Adobe" }, { "code": null, "e": 19198, "s": 19191, "text": "Amazon" }, { "code": null, "e": 19208, "s": 19198, "text": "Code Brew" }, { "code": null, "e": 19218, "s": 19208, "text": "Microsoft" }, { "code": null, "e": 19233, "s": 19218, "text": "Morgan Stanley" }, { "code": null, "e": 19238, "s": 19233, "text": "Payu" }, { "code": null, "e": 19246, "s": 19238, "text": "Strings" }, { "code": null, "e": 19261, "s": 19246, "text": "Morgan Stanley" }, { "code": null, "e": 19268, "s": 19261, "text": "Amazon" }, { "code": null, "e": 19278, "s": 19268, "text": "Microsoft" }, { "code": null, "e": 19283, "s": 19278, "text": "Payu" }, { "code": null, "e": 19289, "s": 19283, "text": "Adobe" }, { "code": null, "e": 19299, "s": 19289, "text": "Code Brew" }, { "code": null, "e": 19307, "s": 19299, "text": "Strings" } ]
Python | shutil.unpack_archive() method
08 Nov, 2021 Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.unpack_archive() method in Python is used to unpack an archive file. Syntax: shutil.unpack_archive(filename [, extract_dir [, format]])Parameter: filename: A path-like object representing the full path of archived file. A path-like object is either a string or bytes object representing a path. extract_dir (optional): A path-like object representing the path of the target directory where the archive is unpacked. A path-like object is either a string or bytes object representing a path. This is an optional parameter and if not provided the current working directory is used as target directory. formats (optional): A string representing an archive format. The value of format can be any one of “zip”, “tar”, “gztar”, “bztar”, or “xztar” or any other registered unpacking format. This is also an optional parameter and if not provided, the extension of archived file name is used as format. An unpacker must be registered for this extension otherwise ‘ValueError’ exception will be raised. Return Type: This method does not return any value. Code #1: Use of shutil.unpack_archive() method to unpack an archive file Python3 # Python program to explain shutil.unpack_archive() method # importing shutil moduleimport shutil # Full path of# the archive filefilename = "/home/User/Downloads/file.zip" # Target directoryextract_dir = "/home/ihritik/Documents" # Format of archive filearchive_format = "zip" # Unpack the archive fileshutil.unpack_archive(filename, extract_dir, archive_format)print("Archive file unpacked successfully.") Archive file unpacked successfully. Code #2: Use of shutil.unpack_archive() method to unpack an archive file Python3 # Python program to explain shutil.unpack_archive() method # importing shutil moduleimport shutil # Full path of# the archive filefilename = "/home/User/Downloads/file.zip" # Unpack the archived fileshutil.unpack_archive(filename)print("Archive file unpacked successfully.") # As extract_dir and format parameters# are not provided So,# shutil.unpack_archive() method will# unpack the archive file in# current working directory and extension# of the archive filename i.e zip# will be taken as format to unpack Archive file unpacked successfully. sooda367 prachisoda1234 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Nov, 2021" }, { "code": null, "e": 351, "s": 28, "text": "Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.unpack_archive() method in Python is used to unpack an archive file. " }, { "code": null, "e": 1328, "s": 351, "text": "Syntax: shutil.unpack_archive(filename [, extract_dir [, format]])Parameter: filename: A path-like object representing the full path of archived file. A path-like object is either a string or bytes object representing a path. extract_dir (optional): A path-like object representing the path of the target directory where the archive is unpacked. A path-like object is either a string or bytes object representing a path. This is an optional parameter and if not provided the current working directory is used as target directory. formats (optional): A string representing an archive format. The value of format can be any one of “zip”, “tar”, “gztar”, “bztar”, or “xztar” or any other registered unpacking format. This is also an optional parameter and if not provided, the extension of archived file name is used as format. An unpacker must be registered for this extension otherwise ‘ValueError’ exception will be raised. Return Type: This method does not return any value. " }, { "code": null, "e": 1403, "s": 1328, "text": "Code #1: Use of shutil.unpack_archive() method to unpack an archive file " }, { "code": null, "e": 1411, "s": 1403, "text": "Python3" }, { "code": "# Python program to explain shutil.unpack_archive() method # importing shutil moduleimport shutil # Full path of# the archive filefilename = \"/home/User/Downloads/file.zip\" # Target directoryextract_dir = \"/home/ihritik/Documents\" # Format of archive filearchive_format = \"zip\" # Unpack the archive fileshutil.unpack_archive(filename, extract_dir, archive_format)print(\"Archive file unpacked successfully.\")", "e": 1820, "s": 1411, "text": null }, { "code": null, "e": 1856, "s": 1820, "text": "Archive file unpacked successfully." }, { "code": null, "e": 1933, "s": 1858, "text": "Code #2: Use of shutil.unpack_archive() method to unpack an archive file " }, { "code": null, "e": 1941, "s": 1933, "text": "Python3" }, { "code": "# Python program to explain shutil.unpack_archive() method # importing shutil moduleimport shutil # Full path of# the archive filefilename = \"/home/User/Downloads/file.zip\" # Unpack the archived fileshutil.unpack_archive(filename)print(\"Archive file unpacked successfully.\") # As extract_dir and format parameters# are not provided So,# shutil.unpack_archive() method will# unpack the archive file in# current working directory and extension# of the archive filename i.e zip# will be taken as format to unpack ", "e": 2456, "s": 1941, "text": null }, { "code": null, "e": 2492, "s": 2456, "text": "Archive file unpacked successfully." }, { "code": null, "e": 2503, "s": 2494, "text": "sooda367" }, { "code": null, "e": 2518, "s": 2503, "text": "prachisoda1234" }, { "code": null, "e": 2533, "s": 2518, "text": "python-utility" }, { "code": null, "e": 2540, "s": 2533, "text": "Python" } ]
How to control the height and width of the default alert dialog in android?
This example demonstrates how do I control the height and width of the default alert dialog in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/relativeLayout" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Alert Dialog" android:layout_centerInParent="true" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.RelativeLayout; public class MainActivity extends AppCompatActivity{ Button button; RelativeLayout relativeLayout; Context context; Activity myActivity; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); relativeLayout = findViewById(R.id.relativeLayout); context = getApplicationContext(); button = findViewById(R.id.button); myActivity = MainActivity.this; button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(myActivity); builder.setTitle("My Action Bar"); builder.setMessage("This is my custom Action bar, do you like it?"); builder.setPositiveButton("Yes", null); builder.setNegativeButton("No", null); AlertDialog alertDialog = builder.create(); alertDialog.show(); WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(); layoutParams.copyFrom(alertDialog.getWindow().getAttributes()); layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT; alertDialog.getWindow().setAttributes(layoutParams); } }); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
[ { "code": null, "e": 1291, "s": 1187, "text": "This example demonstrates how do I control the height and width of the default alert dialog in android." }, { "code": null, "e": 1420, "s": 1291, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1485, "s": 1420, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2028, "s": 1485, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:id=\"@+id/relativeLayout\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Show Alert Dialog\"\n android:layout_centerInParent=\"true\" />\n</RelativeLayout>" }, { "code": null, "e": 2085, "s": 2028, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3835, "s": 2085, "text": "import android.app.Activity;\nimport android.app.AlertDialog;\nimport android.content.Context;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.view.WindowManager;\nimport android.widget.Button;\nimport android.widget.RelativeLayout;\n public class MainActivity extends AppCompatActivity{\n Button button;\n RelativeLayout relativeLayout;\n Context context;\n Activity myActivity;\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n relativeLayout = findViewById(R.id.relativeLayout);\n context = getApplicationContext();\n button = findViewById(R.id.button);\n myActivity = MainActivity.this;\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n AlertDialog.Builder builder = new AlertDialog.Builder(myActivity);\n builder.setTitle(\"My Action Bar\");\n builder.setMessage(\"This is my custom Action bar, do you like it?\");\n builder.setPositiveButton(\"Yes\", null);\n builder.setNegativeButton(\"No\", null);\n AlertDialog alertDialog = builder.create();\n alertDialog.show();\n WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();\n layoutParams.copyFrom(alertDialog.getWindow().getAttributes());\n layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;\n layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;\n alertDialog.getWindow().setAttributes(layoutParams);\n }\n });\n }\n}" }, { "code": null, "e": 3891, "s": 3835, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4561, "s": 3891, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\npackage=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4908, "s": 4561, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" } ]
KPIT Interview Experience | Set 1
29 Oct, 2017 Round 1: It was an Online test.The online test was conducted only for EC, EEE and EI. CS and IS students were not allowed.The test questions were based on aptitude, basics of C, microcontroller and 2 coding questions. Test duration was 3 hours and was conducted remotely using a webcam.The test platform was METTL.The coding questions were: Replace all zeroes in an integer with 1 and print it.Input = 12006. Output= 12116 Input = 12006. Output= 12116 Find the number of times digit 3 occurs in each and every number in the inclusive range from [a, b].Input = 2 34 Output = 6 Input = 2 34 Output = 6 7 students were shortlisted after this round. Further process was in Bangalore. It was a pool campus. Another simple coding round was conducted in Bangalore. The question was Print all the digits of a given integer on a new line.Input = 5689 Output: 5 6 8 9 Input = 4294967296 Output: 4 2 9 4 9 6 7 2 9 6 Round 2:This was a Technical Round.In this round, they asked me about my interests. I told programming. Then they asked some simple questions on bit manipulation and I answered all of them correctly.The interviewer seemed happy and asked about my projects for half an hour.Then he asked me if I was interested in Digital Electronics and Microcontroller. I said that at the moment I was not comfortable with Microcontroller.He then asked me to wait.In this round everybody was asked about Microcontroller questions like the architecture of 8086, questions on protocols used by Arduino and microprocessor since their main work is based on embedded systems used in automobiles.Round 3:This was HR Round. HR was very friendly. He asked about my hobbies first and my area of interest.He asked standard questions like:Tell me about yourselfWhy KPIT?What are your strengths?I told him about my strengths and about my projects. I told him that I was article contributor in GeeksforGeeks and had won a Bronze Medal in a hackathon conducted by HackerRank. He was really happy and asked me to wait.After this round results were announced. 10 students got the offer. Everybody was offered a Position of Trainee Software Engineer.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.My Personal Notes arrow_drop_upSave Input = 5689 Output: 5 6 8 9 Input = 4294967296 Output: 4 2 9 4 9 6 7 2 9 6 Round 2:This was a Technical Round.In this round, they asked me about my interests. I told programming. Then they asked some simple questions on bit manipulation and I answered all of them correctly.The interviewer seemed happy and asked about my projects for half an hour.Then he asked me if I was interested in Digital Electronics and Microcontroller. I said that at the moment I was not comfortable with Microcontroller.He then asked me to wait.In this round everybody was asked about Microcontroller questions like the architecture of 8086, questions on protocols used by Arduino and microprocessor since their main work is based on embedded systems used in automobiles. Round 3:This was HR Round. HR was very friendly. He asked about my hobbies first and my area of interest.He asked standard questions like: Tell me about yourself Why KPIT? What are your strengths? I told him about my strengths and about my projects. I told him that I was article contributor in GeeksforGeeks and had won a Bronze Medal in a hackathon conducted by HackerRank. He was really happy and asked me to wait.After this round results were announced. 10 students got the offer. Everybody was offered a Position of Trainee Software Engineer. 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. Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Google SWE Interview Experience (Google Online Coding Challenge) 2022 Amazon Interview Experience for SDE 1 Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022 Google Interview Questions Amazon Interview Experience SDE-2 (3 Years Experienced) TCS Ninja Interview Experience (2020 batch) Write It Up: Share Your Interview Experiences Samsung RnD Coding Round Questions Amazon Interview Experience for SDE-1 Nagarro Interview Experience
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Oct, 2017" }, { "code": null, "e": 63, "s": 54, "text": "Round 1:" }, { "code": null, "e": 395, "s": 63, "text": "It was an Online test.The online test was conducted only for EC, EEE and EI. CS and IS students were not allowed.The test questions were based on aptitude, basics of C, microcontroller and 2 coding questions. Test duration was 3 hours and was conducted remotely using a webcam.The test platform was METTL.The coding questions were:" }, { "code": null, "e": 477, "s": 395, "text": "Replace all zeroes in an integer with 1 and print it.Input = 12006.\nOutput= 12116" }, { "code": null, "e": 506, "s": 477, "text": "Input = 12006.\nOutput= 12116" }, { "code": null, "e": 632, "s": 506, "text": "Find the number of times digit 3 occurs in each and every number in the inclusive range from [a, b].Input = 2 34\nOutput = 6\n" }, { "code": null, "e": 658, "s": 632, "text": "Input = 2 34\nOutput = 6\n" }, { "code": null, "e": 833, "s": 658, "text": "7 students were shortlisted after this round. Further process was in Bangalore. It was a pool campus. Another simple coding round was conducted in Bangalore. The question was" }, { "code": null, "e": 2609, "s": 833, "text": "Print all the digits of a given integer on a new line.Input = 5689\nOutput:\n\n5\n\n6\n\n8\n\n9\n\nInput = 4294967296\nOutput:\n\n4\n\n2\n\n9\n\n4\n\n9\n\n6\n\n7\n\n2\n\n9\n\n6\nRound 2:This was a Technical Round.In this round, they asked me about my interests. I told programming. Then they asked some simple questions on bit manipulation and I answered all of them correctly.The interviewer seemed happy and asked about my projects for half an hour.Then he asked me if I was interested in Digital Electronics and Microcontroller. I said that at the moment I was not comfortable with Microcontroller.He then asked me to wait.In this round everybody was asked about Microcontroller questions like the architecture of 8086, questions on protocols used by Arduino and microprocessor since their main work is based on embedded systems used in automobiles.Round 3:This was HR Round. HR was very friendly. He asked about my hobbies first and my area of interest.He asked standard questions like:Tell me about yourselfWhy KPIT?What are your strengths?I told him about my strengths and about my projects. I told him that I was article contributor in GeeksforGeeks and had won a Bronze Medal in a hackathon conducted by HackerRank. He was really happy and asked me to wait.After this round results were announced. 10 students got the offer. Everybody was offered a Position of Trainee Software Engineer.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.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 2701, "s": 2609, "text": "Input = 5689\nOutput:\n\n5\n\n6\n\n8\n\n9\n\nInput = 4294967296\nOutput:\n\n4\n\n2\n\n9\n\n4\n\n9\n\n6\n\n7\n\n2\n\n9\n\n6\n" }, { "code": null, "e": 3376, "s": 2701, "text": "Round 2:This was a Technical Round.In this round, they asked me about my interests. I told programming. Then they asked some simple questions on bit manipulation and I answered all of them correctly.The interviewer seemed happy and asked about my projects for half an hour.Then he asked me if I was interested in Digital Electronics and Microcontroller. I said that at the moment I was not comfortable with Microcontroller.He then asked me to wait.In this round everybody was asked about Microcontroller questions like the architecture of 8086, questions on protocols used by Arduino and microprocessor since their main work is based on embedded systems used in automobiles." }, { "code": null, "e": 3515, "s": 3376, "text": "Round 3:This was HR Round. HR was very friendly. He asked about my hobbies first and my area of interest.He asked standard questions like:" }, { "code": null, "e": 3538, "s": 3515, "text": "Tell me about yourself" }, { "code": null, "e": 3548, "s": 3538, "text": "Why KPIT?" }, { "code": null, "e": 3573, "s": 3548, "text": "What are your strengths?" }, { "code": null, "e": 3924, "s": 3573, "text": "I told him about my strengths and about my projects. I told him that I was article contributor in GeeksforGeeks and had won a Bronze Medal in a hackathon conducted by HackerRank. He was really happy and asked me to wait.After this round results were announced. 10 students got the offer. Everybody was offered a Position of Trainee Software Engineer." }, { "code": null, "e": 4179, "s": 3924, "text": "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": 4304, "s": 4179, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4326, "s": 4304, "text": "Interview Experiences" }, { "code": null, "e": 4424, "s": 4326, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4494, "s": 4424, "text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022" }, { "code": null, "e": 4532, "s": 4494, "text": "Amazon Interview Experience for SDE 1" }, { "code": null, "e": 4605, "s": 4532, "text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022" }, { "code": null, "e": 4632, "s": 4605, "text": "Google Interview Questions" }, { "code": null, "e": 4688, "s": 4632, "text": "Amazon Interview Experience SDE-2 (3 Years Experienced)" }, { "code": null, "e": 4732, "s": 4688, "text": "TCS Ninja Interview Experience (2020 batch)" }, { "code": null, "e": 4778, "s": 4732, "text": "Write It Up: Share Your Interview Experiences" }, { "code": null, "e": 4813, "s": 4778, "text": "Samsung RnD Coding Round Questions" }, { "code": null, "e": 4851, "s": 4813, "text": "Amazon Interview Experience for SDE-1" } ]
Password Cracking with Medusa in Linux
02 Dec, 2020 In today’s world, the majority of people are generally aware that malicious users and hackers can steal their confidential information through various attacks. However, most people don’t really understand the specific attacks that they are vulnerable to. So in this article, We are going to learn about Password Attacks. Password Attacks means a third party trying to gain access to your systems by cracking a user’s password,it may sound illegal but it depends on us whether we want to use it for good things or bad things. Password Attacks are useful in various Cyber Events as well as we can perform it on our own system in case we forgot the password. In this article, we are going to perform brute force attacks with the help of the Medusa tool in Kali Linux. Methods of Cracking Password: There are a number of ways to crack passwords. Some of them are old-fashioned yet very effective. Guessing Social Engineering Dictionary Attacks Shoulder Surfing Rainbow Tables Brute Force Attacks Password Probability Matrix Note: Don’t use this method of password cracking for unethical purposes and without prior permission from the owner. Keep it Ethical and Enjoy !! Medusa : Medusa is a modular, speedy, and parallel, login brute-forcer. It is a very powerful and lightweight tool. Medusa tool is used to brute-force credentials in as many protocols as possible which eventually lead to remote code execution. It currently has over 21 modules, some of which are: PcAnywhere, POP3, CVS, FTP, HTTP, IMAP, SMB, SMTP (VRFY), SNMP, SSHv2, MS-SQL, MySQL, NCP (NetWare), PostgreSQL, rexec, rlogin, rsh, Telnet, SVN, VNC, VmAuthd and a generic wrapper module. Kali Linux comes with pre-installed Medusa. If you don’t have the Medusa tool installed in your system. Simply, run the following command on your terminal consisting of the apt package manager to install the Medusa tool. sudo apt-get install medusa Brute Force Attack using Medusa : We are going to crack the password of SSH service in this Brute Force Attack using Medusa. Step 1: To run medusa in your system simply type medusa in the terminal. medusa Step 2: If you need help regarding Medusa Tool. Simply, type medusa -h in the terminal. medusa -h Step 3: To avoid ssh connection error first start the ssh services with the below command. sudo service ssh start Step 4: To crack the Password for ssh service, type the below command medusa -h 10.0.2.15 -u lalit -P /home/lalit/Desktop/Password_List.txt -M ssh -n 22 In the above command : medusa – to execute the medusa tool -h – is used to specify the Target Host or IP address -u – It means username to test -P – we can use -p to test a single password or -P to use a text file containing a lot of Passwords for Brute Force Attack -M – It means the name of the module to execute, I am using ssh here. -n – It means the port number After the complete execution of the above command. You can see the Success keyword with the Right Password. Cyber-security Technical Scripter 2020 Linux-Unix Technical Scripter 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 mv command in Linux with examples chmod command in Linux with examples Array Basics in Shell Scripting | Set 1 Introduction to Linux Operating System Basic Operators in Shell Scripting
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Dec, 2020" }, { "code": null, "e": 819, "s": 54, "text": "In today’s world, the majority of people are generally aware that malicious users and hackers can steal their confidential information through various attacks. However, most people don’t really understand the specific attacks that they are vulnerable to. So in this article, We are going to learn about Password Attacks. Password Attacks means a third party trying to gain access to your systems by cracking a user’s password,it may sound illegal but it depends on us whether we want to use it for good things or bad things. Password Attacks are useful in various Cyber Events as well as we can perform it on our own system in case we forgot the password. In this article, we are going to perform brute force attacks with the help of the Medusa tool in Kali Linux." }, { "code": null, "e": 849, "s": 819, "text": "Methods of Cracking Password:" }, { "code": null, "e": 948, "s": 849, "text": "There are a number of ways to crack passwords. Some of them are old-fashioned yet very effective. " }, { "code": null, "e": 957, "s": 948, "text": "Guessing" }, { "code": null, "e": 976, "s": 957, "text": "Social Engineering" }, { "code": null, "e": 995, "s": 976, "text": "Dictionary Attacks" }, { "code": null, "e": 1012, "s": 995, "text": "Shoulder Surfing" }, { "code": null, "e": 1027, "s": 1012, "text": "Rainbow Tables" }, { "code": null, "e": 1047, "s": 1027, "text": "Brute Force Attacks" }, { "code": null, "e": 1075, "s": 1047, "text": "Password Probability Matrix" }, { "code": null, "e": 1221, "s": 1075, "text": "Note: Don’t use this method of password cracking for unethical purposes and without prior permission from the owner. Keep it Ethical and Enjoy !!" }, { "code": null, "e": 1231, "s": 1221, "text": "Medusa : " }, { "code": null, "e": 1931, "s": 1231, "text": "Medusa is a modular, speedy, and parallel, login brute-forcer. It is a very powerful and lightweight tool. Medusa tool is used to brute-force credentials in as many protocols as possible which eventually lead to remote code execution. It currently has over 21 modules, some of which are: PcAnywhere, POP3, CVS, FTP, HTTP, IMAP, SMB, SMTP (VRFY), SNMP, SSHv2, MS-SQL, MySQL, NCP (NetWare), PostgreSQL, rexec, rlogin, rsh, Telnet, SVN, VNC, VmAuthd and a generic wrapper module. Kali Linux comes with pre-installed Medusa. If you don’t have the Medusa tool installed in your system. Simply, run the following command on your terminal consisting of the apt package manager to install the Medusa tool." }, { "code": null, "e": 1959, "s": 1931, "text": "sudo apt-get install medusa" }, { "code": null, "e": 1994, "s": 1959, "text": " Brute Force Attack using Medusa :" }, { "code": null, "e": 2085, "s": 1994, "text": "We are going to crack the password of SSH service in this Brute Force Attack using Medusa." }, { "code": null, "e": 2159, "s": 2085, "text": " Step 1: To run medusa in your system simply type medusa in the terminal." }, { "code": null, "e": 2166, "s": 2159, "text": "medusa" }, { "code": null, "e": 2254, "s": 2166, "text": "Step 2: If you need help regarding Medusa Tool. Simply, type medusa -h in the terminal." }, { "code": null, "e": 2264, "s": 2254, "text": "medusa -h" }, { "code": null, "e": 2355, "s": 2264, "text": "Step 3: To avoid ssh connection error first start the ssh services with the below command." }, { "code": null, "e": 2378, "s": 2355, "text": "sudo service ssh start" }, { "code": null, "e": 2448, "s": 2378, "text": "Step 4: To crack the Password for ssh service, type the below command" }, { "code": null, "e": 2531, "s": 2448, "text": "medusa -h 10.0.2.15 -u lalit -P /home/lalit/Desktop/Password_List.txt -M ssh -n 22" }, { "code": null, "e": 2554, "s": 2531, "text": "In the above command :" }, { "code": null, "e": 2590, "s": 2554, "text": "medusa – to execute the medusa tool" }, { "code": null, "e": 2644, "s": 2590, "text": "-h – is used to specify the Target Host or IP address" }, { "code": null, "e": 2675, "s": 2644, "text": "-u – It means username to test" }, { "code": null, "e": 2798, "s": 2675, "text": "-P – we can use -p to test a single password or -P to use a text file containing a lot of Passwords for Brute Force Attack" }, { "code": null, "e": 2868, "s": 2798, "text": "-M – It means the name of the module to execute, I am using ssh here." }, { "code": null, "e": 2898, "s": 2868, "text": "-n – It means the port number" }, { "code": null, "e": 3006, "s": 2898, "text": "After the complete execution of the above command. You can see the Success keyword with the Right Password." }, { "code": null, "e": 3021, "s": 3006, "text": "Cyber-security" }, { "code": null, "e": 3045, "s": 3021, "text": "Technical Scripter 2020" }, { "code": null, "e": 3056, "s": 3045, "text": "Linux-Unix" }, { "code": null, "e": 3075, "s": 3056, "text": "Technical Scripter" }, { "code": null, "e": 3173, "s": 3075, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3199, "s": 3173, "text": "Docker - COPY Instruction" }, { "code": null, "e": 3234, "s": 3199, "text": "scp command in Linux with Examples" }, { "code": null, "e": 3271, "s": 3234, "text": "chown command in Linux with Examples" }, { "code": null, "e": 3300, "s": 3271, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 3337, "s": 3300, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 3371, "s": 3337, "text": "mv command in Linux with examples" }, { "code": null, "e": 3408, "s": 3371, "text": "chmod command in Linux with examples" }, { "code": null, "e": 3448, "s": 3408, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 3487, "s": 3448, "text": "Introduction to Linux Operating System" } ]
Conditional select between dates in MySQL for maximum and minimum values of price set in a table?
You need to use CASE statement to conditional select between dates to find the minimum and maximum price. Wrap up the CASE statement with aggregate function MIN() and MAX(). The syntax is as follows: SELECT MIN(CASE WHEN CURDATE() BETWEEN yourStartDateColumnName AND yourEndDateColumnName THEN yourLowPriceColumnName ELSE yourHighPriceColumnName END) AS anyVariableName, MAX(CASE WHEN CURDATE() BETWEEN yourStartDateColumnName AND yourEndDateColumnName THEN yourLowPriceColumnName ELSE yourHighPriceColumnName END) AS anyVariableName FROM yourTableName; To understand the above syntax, let us create a table. The query to create a table is as follows: mysql> create table ConditionalSelect -> ( -> Id int NOT NULL AUTO_INCREMENT, -> StartDate datetime, -> EndDate datetime, -> LowerPrice int, -> HigherPrice int, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.69 sec) Insert some records in the table using insert command. The query is as follows: mysql> insert into ConditionalSelect(StartDate,EndDate,LowerPrice,HigherPrice) values('2019-01-02','2019-04-02',5,10); Query OK, 1 row affected (0.12 sec) mysql> insert into ConditionalSelect(StartDate,EndDate,LowerPrice,HigherPrice) values('2019-04-02','2019-04-20',0,20); Query OK, 1 row affected (0.17 sec) mysql> insert into ConditionalSelect(StartDate,EndDate,LowerPrice,HigherPrice) values('2019-04-03','2019-04-21',0,30); Query OK, 1 row affected (0.17 sec) Display all records from the table using select statement. The query is as follows: mysql> select *from ConditionalSelect; The following is the output: +----+---------------------+---------------------+------------+-------------+ | Id | StartDate | EndDate | LowerPrice | HigherPrice | +----+---------------------+---------------------+------------+-------------+ | 1 | 2019-01-02 00:00:00 | 2019-04-02 00:00:00 | 5 | 10 | | 2 | 2019-04-02 00:00:00 | 2019-04-20 00:00:00 | 0 | 20 | | 3 | 2019-04-03 00:00:00 | 2019-04-21 00:00:00 | 0 | 30 | +----+---------------------+---------------------+------------+-------------+ 3 rows in set (0.00 sec) Here is the query to select min and max price between dates: mysql> SELECT -> MIN(CASE WHEN CURDATE() BETWEEN StartDate AND EndDate THEN LowerPrice ELSE HigherPrice END) AS MinimumValue, -> MAX(CASE WHEN CURDATE() BETWEEN StartDate AND EndDate THEN LowerPrice ELSE HigherPrice END) AS MaximumValue -> from ConditionalSelect; The following is the output: +--------------+--------------+ | MinimumValue | MaximumValue | +--------------+--------------+ | 5 | 30 | +--------------+--------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1262, "s": 1062, "text": "You need to use CASE statement to conditional select between dates to find the minimum and maximum price. Wrap up the CASE statement with aggregate function MIN() and MAX(). The syntax is as follows:" }, { "code": null, "e": 1617, "s": 1262, "text": "SELECT\nMIN(CASE WHEN CURDATE() BETWEEN yourStartDateColumnName AND yourEndDateColumnName THEN yourLowPriceColumnName ELSE yourHighPriceColumnName END) AS anyVariableName,\n\nMAX(CASE WHEN CURDATE() BETWEEN yourStartDateColumnName AND yourEndDateColumnName THEN yourLowPriceColumnName ELSE yourHighPriceColumnName END) AS anyVariableName FROM yourTableName;" }, { "code": null, "e": 1715, "s": 1617, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows:" }, { "code": null, "e": 1962, "s": 1715, "text": "mysql> create table ConditionalSelect\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> StartDate datetime,\n -> EndDate datetime,\n -> LowerPrice int,\n -> HigherPrice int,\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.69 sec)" }, { "code": null, "e": 2042, "s": 1962, "text": "Insert some records in the table using insert command. The query is as follows:" }, { "code": null, "e": 2507, "s": 2042, "text": "mysql> insert into ConditionalSelect(StartDate,EndDate,LowerPrice,HigherPrice) values('2019-01-02','2019-04-02',5,10);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into ConditionalSelect(StartDate,EndDate,LowerPrice,HigherPrice) values('2019-04-02','2019-04-20',0,20);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into ConditionalSelect(StartDate,EndDate,LowerPrice,HigherPrice) values('2019-04-03','2019-04-21',0,30);\nQuery OK, 1 row affected (0.17 sec)" }, { "code": null, "e": 2591, "s": 2507, "text": "Display all records from the table using select statement. The query is as follows:" }, { "code": null, "e": 2630, "s": 2591, "text": "mysql> select *from ConditionalSelect;" }, { "code": null, "e": 2659, "s": 2630, "text": "The following is the output:" }, { "code": null, "e": 3230, "s": 2659, "text": "+----+---------------------+---------------------+------------+-------------+\n| Id | StartDate | EndDate | LowerPrice | HigherPrice |\n+----+---------------------+---------------------+------------+-------------+\n| 1 | 2019-01-02 00:00:00 | 2019-04-02 00:00:00 | 5 | 10 |\n| 2 | 2019-04-02 00:00:00 | 2019-04-20 00:00:00 | 0 | 20 |\n| 3 | 2019-04-03 00:00:00 | 2019-04-21 00:00:00 | 0 | 30 |\n+----+---------------------+---------------------+------------+-------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 3291, "s": 3230, "text": "Here is the query to select min and max price between dates:" }, { "code": null, "e": 3564, "s": 3291, "text": "mysql> SELECT\n -> MIN(CASE WHEN CURDATE() BETWEEN StartDate AND EndDate THEN LowerPrice ELSE HigherPrice END) AS MinimumValue,\n -> MAX(CASE WHEN CURDATE() BETWEEN StartDate AND EndDate THEN LowerPrice ELSE HigherPrice END) AS MaximumValue\n -> from ConditionalSelect;" }, { "code": null, "e": 3593, "s": 3564, "text": "The following is the output:" }, { "code": null, "e": 3777, "s": 3593, "text": "+--------------+--------------+\n| MinimumValue | MaximumValue |\n+--------------+--------------+\n| 5 | 30 |\n+--------------+--------------+\n1 row in set (0.00 sec)" } ]
Machine Learning - Bagged Decision Tree
As we know that bagging ensemble methods work well with the algorithms that have high variance and, in this concern, the best one is decision tree algorithm. In the following Python recipe, we are going to build bagged decision tree ensemble model by using BaggingClassifier function of sklearn with DecisionTreeClasifier (a classification & regression trees algorithm) on Pima Indians diabetes dataset. First, import the required packages as follows − from pandas import read_csv from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score from sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassifier Now, we need to load the Pima diabetes dataset as we did in the previous examples − path = r"C:\pima-indians-diabetes.csv" headernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] data = read_csv(path, names=headernames) array = data.values X = array[:,0:8] Y = array[:,8] Next, give the input for 10-fold cross validation as follows − seed = 7 kfold = KFold(n_splits = 10, random_state = seed) cart = DecisionTreeClassifier() We need to provide the number of trees we are going to build. Here we are building 150 trees − num_trees = 150 Next, build the model with the help of following script − model = BaggingClassifier(base_estimator = cart, n_estimators = num_trees, random_state = seed) Calculate and print the result as follows − results = cross_val_score(model, X, Y, cv=kfold) print(results.mean()) Output 0.7733766233766234 The output above shows that we got around 77% accuracy of our bagged decision tree classifier model. 168 Lectures 13.5 hours Er. Himanshu Vasishta 64 Lectures 10.5 hours Eduonix Learning Solutions 91 Lectures 10 hours Abhilash Nelson 54 Lectures 6 hours Abhishek And Pukhraj 49 Lectures 5 hours Abhishek And Pukhraj 35 Lectures 4 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2708, "s": 2304, "text": "As we know that bagging ensemble methods work well with the algorithms that have high variance and, in this concern, the best one is decision tree algorithm. In the following Python recipe, we are going to build bagged decision tree ensemble model by using BaggingClassifier function of sklearn with DecisionTreeClasifier (a classification & regression trees algorithm) on Pima Indians diabetes dataset." }, { "code": null, "e": 2757, "s": 2708, "text": "First, import the required packages as follows −" }, { "code": null, "e": 2974, "s": 2757, "text": "from pandas import read_csv\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.ensemble import BaggingClassifier\nfrom sklearn.tree import DecisionTreeClassifier" }, { "code": null, "e": 3058, "s": 2974, "text": "Now, we need to load the Pima diabetes dataset as we did in the previous examples −" }, { "code": null, "e": 3277, "s": 3058, "text": "path = r\"C:\\pima-indians-diabetes.csv\"\nheadernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']\ndata = read_csv(path, names=headernames)\narray = data.values\nX = array[:,0:8]\nY = array[:,8]" }, { "code": null, "e": 3340, "s": 3277, "text": "Next, give the input for 10-fold cross validation as follows −" }, { "code": null, "e": 3431, "s": 3340, "text": "seed = 7\nkfold = KFold(n_splits = 10, random_state = seed)\ncart = DecisionTreeClassifier()" }, { "code": null, "e": 3526, "s": 3431, "text": "We need to provide the number of trees we are going to build. Here we are building 150 trees −" }, { "code": null, "e": 3543, "s": 3526, "text": "num_trees = 150\n" }, { "code": null, "e": 3601, "s": 3543, "text": "Next, build the model with the help of following script −" }, { "code": null, "e": 3698, "s": 3601, "text": "model = BaggingClassifier(base_estimator = cart, n_estimators = num_trees, random_state = seed)\n" }, { "code": null, "e": 3742, "s": 3698, "text": "Calculate and print the result as follows −" }, { "code": null, "e": 3814, "s": 3742, "text": "results = cross_val_score(model, X, Y, cv=kfold)\nprint(results.mean())\n" }, { "code": null, "e": 3821, "s": 3814, "text": "Output" }, { "code": null, "e": 3841, "s": 3821, "text": "0.7733766233766234\n" }, { "code": null, "e": 3942, "s": 3841, "text": "The output above shows that we got around 77% accuracy of our bagged decision tree classifier model." }, { "code": null, "e": 3979, "s": 3942, "text": "\n 168 Lectures \n 13.5 hours \n" }, { "code": null, "e": 4002, "s": 3979, "text": " Er. Himanshu Vasishta" }, { "code": null, "e": 4038, "s": 4002, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 4066, "s": 4038, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4100, "s": 4066, "text": "\n 91 Lectures \n 10 hours \n" }, { "code": null, "e": 4117, "s": 4100, "text": " Abhilash Nelson" }, { "code": null, "e": 4150, "s": 4117, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 4172, "s": 4150, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4205, "s": 4172, "text": "\n 49 Lectures \n 5 hours \n" }, { "code": null, "e": 4227, "s": 4205, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4260, "s": 4227, "text": "\n 35 Lectures \n 4 hours \n" }, { "code": null, "e": 4282, "s": 4260, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4289, "s": 4282, "text": " Print" }, { "code": null, "e": 4300, "s": 4289, "text": " Add Notes" } ]
Python | os.WIFSTOPPED() method - GeeksforGeeks
26 Aug, 2019 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.WIFSTOPPED() method in Python is used to check whether a process has been stopped. This method takes process status code as returned by os.wait(), os.system() or os.waitpid() method as a parameter and returns True if the process has been stopped, otherwise returns False. Syntax: os.WIFSTOPPED(status) Parameter:status: This parameter takes process status code (an integer value) as returned by os.system(), os.wait() or os.waitpid() method. Return type: This method returns a boolean value of class ‘bool’. This method returns True if the process has been stopped, otherwise returns False. Code: Use of os.WIFSTOPPED() method # Python program to explain os.WIFSTOPPED() method # importing os and signal module import os, signal # Create a child process# using os.fork() method pid = os.fork() # pid greater than 0# indicates the parent process if pid : # Send signal 'SIGSTOP' # to child process # using os.kill() method # signal will cause the child # process to stop os.kill(pid, signal.SIGSTOP) # Get the child's pid and # status code using # os.waitpid() method info = os.waitpid(pid, os.WSTOPPED) # info is a tuple # info[0] represents child's pid # info[1] represents exit status code print("\nIn parent process") # Check whether the child process # has been stopped or not # using os.WIFSTOPPED() method isStopped = os.WIFSTOPPED(info[1]) print("Has child process been stopped?") print(isStopped) else : print("In Child process") print("Process ID:", os.getpid()) print("Hello ! Geeks") In Child process Process ID: 10224 Hello! Geeks In parent process Has child process been stopped? True References: https://docs.python.org/3/library/os.html#os.WIFSTOPPED python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n26 Aug, 2019" }, { "code": null, "e": 24511, "s": 24292, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality." }, { "code": null, "e": 24786, "s": 24511, "text": "os.WIFSTOPPED() method in Python is used to check whether a process has been stopped. This method takes process status code as returned by os.wait(), os.system() or os.waitpid() method as a parameter and returns True if the process has been stopped, otherwise returns False." }, { "code": null, "e": 24816, "s": 24786, "text": "Syntax: os.WIFSTOPPED(status)" }, { "code": null, "e": 24956, "s": 24816, "text": "Parameter:status: This parameter takes process status code (an integer value) as returned by os.system(), os.wait() or os.waitpid() method." }, { "code": null, "e": 25105, "s": 24956, "text": "Return type: This method returns a boolean value of class ‘bool’. This method returns True if the process has been stopped, otherwise returns False." }, { "code": null, "e": 25141, "s": 25105, "text": "Code: Use of os.WIFSTOPPED() method" }, { "code": "# Python program to explain os.WIFSTOPPED() method # importing os and signal module import os, signal # Create a child process# using os.fork() method pid = os.fork() # pid greater than 0# indicates the parent process if pid : # Send signal 'SIGSTOP' # to child process # using os.kill() method # signal will cause the child # process to stop os.kill(pid, signal.SIGSTOP) # Get the child's pid and # status code using # os.waitpid() method info = os.waitpid(pid, os.WSTOPPED) # info is a tuple # info[0] represents child's pid # info[1] represents exit status code print(\"\\nIn parent process\") # Check whether the child process # has been stopped or not # using os.WIFSTOPPED() method isStopped = os.WIFSTOPPED(info[1]) print(\"Has child process been stopped?\") print(isStopped) else : print(\"In Child process\") print(\"Process ID:\", os.getpid()) print(\"Hello ! Geeks\") ", "e": 26127, "s": 25141, "text": null }, { "code": null, "e": 26232, "s": 26127, "text": "In Child process\nProcess ID: 10224\nHello! Geeks\n\nIn parent process\nHas child process been stopped?\nTrue\n" }, { "code": null, "e": 26300, "s": 26232, "text": "References: https://docs.python.org/3/library/os.html#os.WIFSTOPPED" }, { "code": null, "e": 26317, "s": 26300, "text": "python-os-module" }, { "code": null, "e": 26324, "s": 26317, "text": "Python" }, { "code": null, "e": 26422, "s": 26324, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26454, "s": 26422, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26510, "s": 26454, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26552, "s": 26510, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26594, "s": 26552, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26616, "s": 26594, "text": "Defaultdict in Python" }, { "code": null, "e": 26655, "s": 26616, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26686, "s": 26655, "text": "Python | os.path.join() method" }, { "code": null, "e": 26741, "s": 26686, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26770, "s": 26741, "text": "Create a directory in Python" } ]
Decrease a row value by 1 in MySQL?
You can increase and decrease row value by 1 in MySQL using UPDATE command. The syntax is as follows − UPDATE yourTableName set yourColumnName = yourColumnName-1 where condition; Let us create a table to decrease row value by 1. The following is the query − mysql> create table IncrementAndDecrementValue −> ( −> UserId int, −> UserScores int −> ); Query OK, 0 rows affected (0.60 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into IncrementAndDecrementValue values(101,20000); Query OK, 1 row affected (0.13 sec) mysql> insert into IncrementAndDecrementValue values(102,30000); Query OK, 1 row affected (0.20 sec) mysql> insert into IncrementAndDecrementValue values(103,40000); Query OK, 1 row affected (0.11 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from IncrementAndDecrementValue; The following is the output; +--------+------------+ | UserId | UserScores | +--------+------------+ | 101 | 20000 | | 102 | 30000 | | 103 | 40000 | +--------+------------+ 3 rows in set (0.00 sec) Here is the query to decrease the UserScores value by 1 with where condition. mysql> update IncrementAndDecrementValue set UserScores = UserScores-1 where UserId = 103; Query OK, 1 row affected (0.41 sec) Rows matched: 1 Changed: 1 Warnings: 0 Let us check whether the value is updated or not. The query is as follows − mysql> select *from IncrementAndDecrementValue; The following is the output displaying that we have successfully decremented a row value − +--------+------------+ | UserId | UserScores | +--------+------------+ | 101 | 20000 | | 102 | 30000 | | 103 | 39999 | +--------+------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1165, "s": 1062, "text": "You can increase and decrease row value by 1 in MySQL using UPDATE command. The syntax is as follows −" }, { "code": null, "e": 1241, "s": 1165, "text": "UPDATE yourTableName set yourColumnName = yourColumnName-1 where condition;" }, { "code": null, "e": 1320, "s": 1241, "text": "Let us create a table to decrease row value by 1. The following is the query −" }, { "code": null, "e": 1460, "s": 1320, "text": "mysql> create table IncrementAndDecrementValue\n −> (\n −> UserId int,\n −> UserScores int\n −> );\nQuery OK, 0 rows affected (0.60 sec)" }, { "code": null, "e": 1541, "s": 1460, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 1846, "s": 1541, "text": "mysql> insert into IncrementAndDecrementValue values(101,20000);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into IncrementAndDecrementValue values(102,30000);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into IncrementAndDecrementValue values(103,40000);\nQuery OK, 1 row affected (0.11 sec)" }, { "code": null, "e": 1931, "s": 1846, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 1979, "s": 1931, "text": "mysql> select *from IncrementAndDecrementValue;" }, { "code": null, "e": 2008, "s": 1979, "text": "The following is the output;" }, { "code": null, "e": 2201, "s": 2008, "text": "+--------+------------+\n| UserId | UserScores |\n+--------+------------+\n| 101 | 20000 |\n| 102 | 30000 |\n| 103 | 40000 |\n+--------+------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2279, "s": 2201, "text": "Here is the query to decrease the UserScores value by 1 with where condition." }, { "code": null, "e": 2445, "s": 2279, "text": "mysql> update IncrementAndDecrementValue set UserScores = UserScores-1 where UserId = 103;\nQuery OK, 1 row affected (0.41 sec)\nRows matched: 1 Changed: 1 Warnings: 0" }, { "code": null, "e": 2521, "s": 2445, "text": "Let us check whether the value is updated or not. The query is as follows −" }, { "code": null, "e": 2569, "s": 2521, "text": "mysql> select *from IncrementAndDecrementValue;" }, { "code": null, "e": 2660, "s": 2569, "text": "The following is the output displaying that we have successfully decremented a row value −" }, { "code": null, "e": 2853, "s": 2660, "text": "+--------+------------+\n| UserId | UserScores |\n+--------+------------+\n| 101 | 20000 |\n| 102 | 30000 |\n| 103 | 39999 |\n+--------+------------+\n3 rows in set (0.00 sec)" } ]
How can I get enum possible values in a MySQL database using PHP?
You can get the enum possible values in a MySQL database with the help of INFORMATION_SCHEMA.COLUMNS table. The syntax is as follows − SELECT COLUMN_TYPE AS anyAliasName FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ‘yourDatabaseName’ AND TABLE_NAME = 'yourTableName' AND COLUMN_NAME = 'yourEnumColumnName'; To understand the above syntax, let us create a table with an ENUM data type. The query to create a table is as follows − mysql> create table EnumDemo -> ( -> Id int, -> Color ENUM('RED','GREEN','BLUE','BLACK','ORANGE') -> ); Query OK, 0 rows affected (0.66 sec) Here the table ‘EnumDemo’ is present in the ‘sample’ database. Now you can implement the above syntax to get the all possible enum values from a column. The query is as follows − mysql> SELECT -> COLUMN_TYPE as AllPossibleEnumValues -> FROM -> INFORMATION_SCHEMA.COLUMNS -> WHERE -> TABLE_SCHEMA = 'sample' AND TABLE_NAME = 'EnumDemo' AND COLUMN_NAME = 'Color'; +---------------------------------------------+ | AllPossibleEnumValues | +---------------------------------------------+ | enum('RED','GREEN','BLUE','BLACK','ORANGE') | +---------------------------------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1197, "s": 1062, "text": "You can get the enum possible values in a MySQL database with the help of INFORMATION_SCHEMA.COLUMNS table. The syntax is as follows −" }, { "code": null, "e": 1386, "s": 1197, "text": "SELECT\n COLUMN_TYPE AS anyAliasName\nFROM\n INFORMATION_SCHEMA.COLUMNS\nWHERE\n TABLE_SCHEMA = ‘yourDatabaseName’ AND TABLE_NAME = 'yourTableName' AND COLUMN_NAME = 'yourEnumColumnName';" }, { "code": null, "e": 1508, "s": 1386, "text": "To understand the above syntax, let us create a table with an ENUM data type. The query to create a table is as follows −" }, { "code": null, "e": 1649, "s": 1508, "text": "mysql> create table EnumDemo\n-> (\n-> Id int,\n-> Color ENUM('RED','GREEN','BLUE','BLACK','ORANGE')\n-> );\nQuery OK, 0 rows affected (0.66 sec)" }, { "code": null, "e": 1802, "s": 1649, "text": "Here the table ‘EnumDemo’ is present in the ‘sample’ database. Now you can implement the above syntax to get the all possible enum values from a column." }, { "code": null, "e": 1828, "s": 1802, "text": "The query is as follows −" }, { "code": null, "e": 2011, "s": 1828, "text": "mysql> SELECT\n-> COLUMN_TYPE as AllPossibleEnumValues\n-> FROM\n-> INFORMATION_SCHEMA.COLUMNS\n-> WHERE\n-> TABLE_SCHEMA = 'sample' AND TABLE_NAME = 'EnumDemo' AND COLUMN_NAME = 'Color';" }, { "code": null, "e": 2275, "s": 2011, "text": "+---------------------------------------------+\n| AllPossibleEnumValues |\n+---------------------------------------------+\n| enum('RED','GREEN','BLUE','BLACK','ORANGE') |\n+---------------------------------------------+\n1 row in set (0.00 sec)" } ]
How to make JOptionPane to handle Yes, No and Closed buttons in Java?
For this, create JOptionPane.QUESTION_MESSAGE and with the user action display individual messages, for example − int res = JOptionPane.showOptionDialog(new JFrame(), "Do you like Cricket?", "Hobbies", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[] { "Yes", "No" }, JOptionPane.YES_OPTION); if (res == JOptionPane.YES_OPTION) { System.out.println("Selected Yes!"); } Above, we have displayed a message on console if the user will selects YES button. The following is an example to make JOptionPane to handle Yes, No and Closed buttons − package my; import javax.swing.JFrame; import javax.swing.JOptionPane; public class SwingDemo { public static void main(String args[]) { int res = JOptionPane.showOptionDialog(new JFrame(), "Do you like Cricket?","Hobbies", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[] { "Yes", "No" }, JOptionPane.YES_OPTION); if (res == JOptionPane.YES_OPTION) { System.out.println("Selected Yes!"); } else if (res == JOptionPane.NO_OPTION) { System.out.println("Selected No!"); } else if (res == JOptionPane.CLOSED_OPTION) { System.out.println("Window closed without selecting!"); } } } Let’s say you selected “Yes” above. The following will be visible in the Console in that case − Let’s say you selected “No” above. The following will be visible in the Console in that case − Let’s say you pressed “Cancel” (close) above. The following will be visible in the Console in that case −
[ { "code": null, "e": 1176, "s": 1062, "text": "For this, create JOptionPane.QUESTION_MESSAGE and with the user action display individual messages, for example −" }, { "code": null, "e": 1461, "s": 1176, "text": "int res = JOptionPane.showOptionDialog(new JFrame(), \"Do you like Cricket?\", \"Hobbies\",\nJOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,\nnew Object[] { \"Yes\", \"No\" }, JOptionPane.YES_OPTION);\nif (res == JOptionPane.YES_OPTION) {\n System.out.println(\"Selected Yes!\");\n}" }, { "code": null, "e": 1631, "s": 1461, "text": "Above, we have displayed a message on console if the user will selects YES button. The following is an example to make JOptionPane to handle Yes, No and Closed buttons −" }, { "code": null, "e": 2316, "s": 1631, "text": "package my;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\npublic class SwingDemo {\n public static void main(String args[]) {\n int res = JOptionPane.showOptionDialog(new JFrame(), \"Do you like Cricket?\",\"Hobbies\",\n JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,\n new Object[] { \"Yes\", \"No\" }, JOptionPane.YES_OPTION);\n if (res == JOptionPane.YES_OPTION) {\n System.out.println(\"Selected Yes!\");\n } else if (res == JOptionPane.NO_OPTION) {\n System.out.println(\"Selected No!\");\n } else if (res == JOptionPane.CLOSED_OPTION) {\n System.out.println(\"Window closed without selecting!\");\n }\n }\n}" }, { "code": null, "e": 2412, "s": 2316, "text": "Let’s say you selected “Yes” above. The following will be visible in the Console in that case −" }, { "code": null, "e": 2507, "s": 2412, "text": "Let’s say you selected “No” above. The following will be visible in the Console in that case −" }, { "code": null, "e": 2613, "s": 2507, "text": "Let’s say you pressed “Cancel” (close) above. The following will be visible in the Console in that case −" } ]
Thompson Sampling. Multi-Armed Bandits: Part 5 | by Steve Roberts | Towards Data Science
Over the last few parts in this series we’ve been looking at increasingly complex methods of solving the Multi-Armed Bandit problem. We’ve now reached the final and most complex of all the methods we’re going to look at: Thompson Sampling. If you’re not already familiar with the bandit problem and its terminology you may want to first take a look at the earlier parts of this series, which are as follows: Part 1: Mathematical Framework and Terminology- all the basic information needed to get started Part 2: The Bandit Framework- a description of the code and test framework Part 3: Bandit Algorithms- The Greedy Algorithm- The Optimistic-Greedy Algorithm- The Epsilon-Greedy Algorithm (ε-Greedy)- Regret Part 4: The Upper Confidence Bound (UCB) Bandit Algorithm All code for the bandit algorithms and testing framework can be found on github: Multi_Armed_Bandits Baby Robot is lost in the mall. Using Reinforcement Learning we want to help him find his way back to his mum. However, before he can even begin looking for her, he needs to recharge, from a set of power sockets that each give a slightly different amount of charge. Using the strategies from the multi-armed bandit problem we need to find the best socket, in the shortest amount of time, to allow Baby Robot to get charged up and on his way. Baby Robot has entered a charging room containing 5 different power sockets. Each of these sockets returns a slightly different amount of charge. We want to get Baby Robot charged up in the minimum amount of time, so we need to locate the best socket and then use it until charging is complete. This is identical to the Multi-Armed Bandit problem except that, instead of looking for a slot machine that gives the best payout, we’re looking for a power socket that gives the most charge. Up until now, all of the methods we’ve seen for tackling the Bandit Problem have selected their actions based on the current averages of the rewards received from those actions. Thompson Sampling (also sometimes referred to as the Bayesian Bandits algorithm) takes a slightly different approach; rather than just refining an estimate of the mean reward it extends this, to instead build up a probability model from the obtained rewards, and then samples from this to choose an action. In this way, not only is an increasingly accurate estimate of the possible reward obtained, but the model also provides a level of confidence in this reward, and this confidence increases as more samples are collected. This process of updating your beliefs as more evidence becomes available is known as Bayesian Inference. As an introduction, and to make things easier to work with, let’s simplify the power socket problem. Now, instead of each socket returning a varying amount of charge, each socket will either return some charge or no charge; the rewards have only two possible values: 1 when the chosen socket supplies a charge and 0 when it doesn’t. When a random variable has only two possible outcomes its behaviour can be described by the Bernoulli distribution. So now, instead of the amount of charge varying per socket, the probability of a socket producing a charge varies with each socket. We want to find the socket with the highest probability of returning a charge, rather than the socket that gives the most charge. As already mentioned, Thompson Sampling generates a model of the reward probabilities. When, as in this case, the available rewards are binary (win or lose, yes or no, charge or no charge) then the Beta distribution is ideal to model this type of probability. (For more information on the relationship between the Beta and Bernoulli distributions check out this excellent article:Beta Distribution — Intuition, Examples, and Derivation). The Beta distribution takes two parameters, ‘α’ (alpha) and ‘β’ (beta). In the simplest terms these parameters can be thought of as respectively the count of successes and failures. Additionally, a Beta distribution has a mean value given by: Initially we have no idea what the probability is of any given socket producing an output, so we can start by setting both ‘α’ and ‘β’ to one, which produces a flat line Uniform distribution (shown as the flat, red, line in figure 5.1). This initial guess at the probability of the socket producing an output is known as the Prior Probability; it is the probability of the specific event occurring before we have collected any evidence and in this case is represented by the Beta distribution Beta(1,1). Once we test a socket, and obtain a reward, we can modify our belief in the likelihood of that socket returning some charge. This new probability, after some evidence has been collected, is known as the Posterior Probability. Again this is given by a Beta distribution, but now the values of ‘α’ and ‘β’ are updated with the value of the returned reward. So, if a socket returns some charge, the reward will be 1 and ‘α’, the count of the number of successes, will increment by 1. The count of the number of failures, ‘β’, will not increase. If instead no reward was obtained, then ‘α’ will stay the same and ‘β’ will increment by 1. As more data is collected the Beta distribution moves from being a flat line to become an increasingly accurate model of the probability of the mean reward. By maintaining the values of ‘α’ and ‘β’ a Thompson sampling algorithm is able to describe the estimated mean reward and the level of confidence in this estimate. In contrast to the Greedy algorithm, which at each time step selects the action with the highest estimated reward, even if the confidence in that estimate is low, Thompson sampling instead samples from the Beta distribution of each action and chooses the action with the highest returned value. Since actions that have been tried infrequently have wide distributions (see the blue curve in figure 5.1), they have a larger range of possible values. In this way, a socket that currently has a low estimated mean reward, but has been tested fewer times than a socket with a higher estimated mean, can return a larger sample value and therefore become the selected socket at this time step. In the graph above, the blue curve has a lower estimated mean reward than the green curve. Therefore, under Greedy selection, green would be chosen and the blue socket would never be selected. In contrast, Thompson Sampling effectively considers the full width of the curve, which for the blue socket can be seen to extend beyond that of the green socket. In this case the blue socket may be selected in preference to the green one. As the number of trials of a socket increases the confidence in the estimated mean increases. This is reflected in the probability distribution becoming narrower and the sampled value will then be drawn from a range of values that are closer to the true mean (see the green curve in figure 5.1). As a result, exploration decreases and exploitation increases, since the sockets with a higher probability of returning a reward will begin to be selected with increasing frequency. On the other hand, sockets with a low estimated mean will start to be selected less frequently and will tend to be dropped early from the selection process. Consequently, their true mean may never be found. Since we are only interested in finding the socket with the highest probability of returning a reward, and finding it as quickly as possible, we don’t care if full information of poorly performing sockets is never obtained. As in the socket experiments we carried out in previous parts of this series, we will be using a basic socket class, on top of which we add the specific functionality for the algorithm being studied. Then, using this new class, we run it through a set of experiments using the same test harness for all bandit algorithms. Full details of the power socket base class and the accompanying test system are given in Part 2 of this series and all the code can be found on github. The implementation of Bernoulli Thompson sampling, as described above, is shown in the BernoulliThompsonSocket class: In this class we initialise ‘α’ and ‘β’ to one, to give the Uniform Distribution. Then, when updating, we simply increment ‘α’ if the socket returned a reward, otherwise we update ‘β’. The “sample” function draws a value from the Beta distribution, using the current values of ‘α’ and ‘β’ as its parameters. The evolution of the Beta distribution for each power socket, where we are using the simpler probabilistic power sockets, can be seen in Figure 5.2 below. To keep things simple, we’ve reduced the number of sockets to three and these have true probabilities 0.3 (green), 0.7(red) and 0.8 (blue) of returning some power when tested. In Figure 5.2 above, the true means of 0.3, 0.7 and 0.8 are shown by the dashed lines. The legend displays the number of trials for each socket and the number of successes that have resulted from these trials. The main points to note from Figure 5.2 are the following: At time step 0 (not shown) all Beta distributions will have their α and β values set to one, to give a flat Uniform distribution. Since all sockets have the same initial distribution, at time step 1 the blue power socket is selected arbitrarily. When tested it gives a reward, so its α value gets incremented by 1 and its probability density curve shifts to the right. The green and red sockets have not yet been tested, so retain their initial flat distribution (with the green curve being hidden behind the red curve). At the second time step the blue socket is again selected and again it returns a reward. The blue curve squeezes slightly more to the right, since this socket has been tested twice and has returned a reward both times, the possibility still exists that this socket will return a reward every time it is selected. By the 5th trial the blue socket has been selected once more, but this time it failed to give a reward. As a result the probability that it always returns a value drops to zero (at probability = 1.0). On the other hand, the green socket has now been tested twice and is yet to return a value, hence its probability density curve is shifted to the left with its highest value at probability =0, as there’s still a chance this socket never returns a reward. At 15 trials the red socket has now been tried a couple of times. Since it’s returned a reward once, it has an estimated mean reward probability of 0.5. At this stage the blue socket has been tried 11 times and has returned a reward on 6 of these trials, giving it a slightly higher estimated reward probability of 0.54. In a Greedy system the blue socket would therefore be the chosen socket, however because the red socket has been tried less times than the blue socket, it can be seen to have a much wider probability density curve, giving it a good chance of being selected in preference to the blue socket. The more times a socket is tested, the more confident we are in its estimate and the narrower its probability density curve becomes. The best socket will then be used more often and testing of the sub-optimal sockets will tail off. This behaviour can be seen at the end of our test, when the blue socket has been tried much more often than either of the two other sockets. It can also be seen that the green socket did finally return a reward on 2 of its trials. Consequently, it’s no longer possible that this is a socket that never returns a reward, so the probability of this happening (returning a reward with probability = 0) drops to zero. It can also be seen that neither the blue nor red sockets have probability density curves centred exactly on their true mean probabilities. If the test was run for more time steps then the blue curve would eventually settle on the true mean value, but the red socket will have a greatly reduced number of trials (if any) and so may never come to find its true value. As mentioned, this isn’t an issue, since we’re only interested in finding the best socket, not the true mean values of the other sockets. The simplified socket problem we’ve used so far is a good way to grasp the concepts of Bayesian Thompson Sampling. However, to use this method with our actual socket problem, in which the sockets aren’t binary, but instead return a variable amount of charge, we need to change things slightly. In the previous problem we modelled the socket’s behaviour using a Beta distribution. This was chosen because the simplified socket output had only two possible outcomes, some charge or no charge, and could therefore be described using a Bernoulli distribution. When a value drawn from a Bernoulli distribution (the likelihood value) is multiplied by a value drawn from a Beta distribution (the prior probability), then the resultant value (the posterior probability) also has a Beta distribution. When this occurs, such that the likelihood multiplied by the prior results in a posterior with the same distribution type as the prior, the prior is referred to as a Conjugate Prior. With our standard socket problem, each socket returns a real value described by a normal distribution. If we assume we know the variance of our socket (which is actually 1, since we use an unmodified version of the numpy randn function in our code), then from the table of conjugate priors on Wikipedia we can see that the conjugate prior also has a normal distribution. If we don’t know the variance of our distribution, or we’re using a different distribution, then we simply need to pick one of other conjugate priors from the table and adjust our algorithm accordingly. So we can model the output of a socket using a normal distribution and gradually refine this model by updating its mean and variance parameters. If, instead of using the variance, we use the precision ‘τ’ (tau), where precision is just one over the variance (precision τ = 1/variance), then we can use the simple update rules for the mean ‘μ0’ and total precision ‘τ0’ given by: where; ‘τ’ is the precision of the actual socket output, which in our case is just 1. ’n’ is the number of times the socket has been tested. ‘xi’ is the output received at each test ‘i’ of this socket (equivalent to the reward ‘Ri’ that we’ve used up till now). ‘μ0’ is the estimated mean (the mean of the distribution used to model the output). ‘τ0’ is the total precision of the distribution used to model the output. At a first glance this looks rather intimidating, but all it’s basically saying is that we have 2 parameters ‘μ0’ and ‘τ0’ that we’ll update each time we test a socket, just as we did with ‘α’ and ‘β’ for the Bernoulli socket. Except in that case those parameters represented the number of successes and failures of the socket, whereas ‘μ0’ and ‘τ0’ represent the estimated mean and the precision, representing the confidence in the estimated mean. Additionally we can make a couple of other simplifications: We know that the amount of charge returned from a socket has a variance of 1 and so the precision ‘τ’ is also 1. Therefore the update of the socket precision is simply τ0 = τ0 + n, where n is the number of times the socket has been tested, so each time a socket gets tested we simply increment its precision by 1. For the estimated mean the numerator contains a sum over all of the outputs produced by the socket, multiplied by ‘τ’. As we saw way back in the Sample Average Estimates section of Part 1, it’s not a good idea to retain the sum of rewards, since this could potentially grow to an unmanageable size. However, in our base socket implement we always calculate ‘Qt(a)’, the estimated value of action ‘a’ at time step ‘t’, which is given by: In this equation ‘Ri’ is the reward obtained at each of the time steps when action ‘a’ was taken and is identical to the term ‘xi’ used in the update equation above. Therefore we can simply replace the summation in the update equation with ‘nQt(a)’ and end up with the following simplified update equation: With these simplifications we tame the scary mathematics! It’s now clear that all we need to do is to keep estimates of the mean and precision of the reward from each socket and then use 2 simple rules to update these values. Things become even clearer when these equations are translated into code. The associated code for a Gaussian Thompson sampling socket is shown below. This retains all of the basic functionality we’ve used in previous socket types and adds the parameters and update function for the posterior distribution that is used to model the socket output. Note that in this update function we’ve replaced the summation over all of the observed rewards with ‘self.n * self.Q’. This gives us exactly the same value without having to retain the sum of rewards which, as described previously, could potentially grow to an unmanageable size. The two update functions, given in the equations above, translate into the simple lines of code shown in the update function. The other main points to note are: The ‘sample’ function, instead of simply returning ‘Q’, the estimate of the socket’s reward value, instead returns a value sampled from the normal distribution that we’re using to model the socket output (the posterior, with mean ‘self.μ_0’ and precision ‘self.τ_0’). As with the Beta distribution, used to model the socket output for binary outputs, we want our prior distribution to start with a distribution that’s close to the uniform distribution, giving a flat probability distribution curve and therefore the potential to return a sampled value with a wide range of possible values. So, initially we set the precision of the posterior to be a very small value (self.τ_0 = 0.0001). In this way sockets that have not yet been tried will be more likely to be selected, much like the Optimistic-Greedy algorithm. If you look back at the code for the base power socket, when a socket is sampled it returns an amount of charge given by a normal distribution around its true mean value: In the charge function above, The numpy “randn” function returns a random value from a normal distribution of mean 0 and variance 1. By adding the true socket reward value ‘q’ to this, we shift the mean to get the distribution to be centred on the actual output of the socket. In the sample function of the Thompson socket a very similar function can be seen: Except in this case the normal is centred on self.μ_0, the posterior mean. Additionally, it can be seen that randn is now divided by the square root of the posterior precision self.τ_0. Remember that the precision is just one over the variance and that variance is the standard deviation squared. Therefore dividing by the square root of the precision is identical to multiplying by the standard deviation. This is what changes the width of the distribution, reducing it as more samples occur and we become more confident in our estimated mean. As with the Bernoulli experiment done previously, we’ve observed the socket selection over 1000 trials, as shown by the probability density curves below. Due to the posterior distributions starting out with almost flat curves, each of the 5 sockets gets tested once during the first 5 trials. After this, socket 4 (shown as the red curve) dominates the further trials. By the end of the tests it has a tall, thin, curve centred on a value of 12 (the true socket reward value) indicating a high level of confidence in this value. The only other socket that is tested more than once, over the first 200 tests, is socket 5 (the purple curve, which has a true socket reward of 10). However, it is only tested 3 times and therefore has a small, fat, distribution curve, indicating a low confidence in its value. From Figure 5.3 its clear to see how Thompson sampling quickly locates and then exploits the best socket, with the other sockets being left largely untested. In this way the algorithm manages to return a large, and nearly optimal, accumulated reward. The regret obtained when using the Thompson Sampling algorithm with our standard socket selection problem is shown in Figure 5.4 below. As was seen for the UCB algorithm, the regret is practically zero, meaning that the best socket was nearly always chosen. This can also be seen in the plot of Cumulative Reward vs Time, in which the actual obtained reward is such a close match for the optimal that it obscured by this curve on the graph. As was seen with the probability density curves for Gaussian Thompson Sampling, the algorithm quickly locks onto the best action and then ruthlessly exploits this, resulting in a very low level of regret. As with the UCB algorithm, Thompson Sampling can be shown to have logarithmic regret, where the value of the regret falls to almost zero as time progresses. (Due to the very small number of actions, and the distinct reward values of each socket, this logarithmic decline in the regret isn’t seen in our experiment, since we’re already down near to zero regret.) For a more in-depth look at Thompson Sampling, its uses and mathematical framework check out the following: “A Tutorial on Thompson Sampling” Daniel J. Russo, et al. Algorithms that solve the bandit problem need to find a way to balance the trade-off between exploitation and exploration. They need to look for the best actions to take while at the same time trying to make use of the information they’ve already gained. In simple approaches, such as Epsilon-Greedy, this trade-off is achieved by mainly using the action that currently gives the most reward and adding simple exploration by now and again randomly trying some of the other actions. In more complex solutions, such as UCB, again the actions with the highest mean reward are selected most often but this is balanced by a confidence measure. This ensures that actions that have not been selected often will get tested. Thompson Sampling takes a different approach to these other methods. Instead of simply maintaining an estimate of the reward, it gradually refines a model of the probability of the reward for each action and actions are chosen by sampling from this distribution. It is therefore possible to get an estimate for the mean reward value of an action, plus a measure of confidence for that estimate. As we saw in our experiments, this allows it to quickly locate and lock onto the optimal action, to give a near optimal accumulated return. But is Thompson Sampling the best bandit algorithm and, more importantly, is it the one we should use to charge Baby Robot? To know the answers to these questions you’ll need to wait until the final part of this series, when we have the bandit algorithms go head-to-head in a final showdown! < Part 4: Part 6 >UCB Bandit Algorithm A Comparison of Bandit Algorithms We’ve looked at the theory behind Thompson Sampling and investigated how it can be used on a couple of simple problems. To see how this can be extended further, to work when the data comes from a normal distribution with unknown mean and variance, check out the article below...
[ { "code": null, "e": 411, "s": 171, "text": "Over the last few parts in this series we’ve been looking at increasingly complex methods of solving the Multi-Armed Bandit problem. We’ve now reached the final and most complex of all the methods we’re going to look at: Thompson Sampling." }, { "code": null, "e": 579, "s": 411, "text": "If you’re not already familiar with the bandit problem and its terminology you may want to first take a look at the earlier parts of this series, which are as follows:" }, { "code": null, "e": 675, "s": 579, "text": "Part 1: Mathematical Framework and Terminology- all the basic information needed to get started" }, { "code": null, "e": 750, "s": 675, "text": "Part 2: The Bandit Framework- a description of the code and test framework" }, { "code": null, "e": 880, "s": 750, "text": "Part 3: Bandit Algorithms- The Greedy Algorithm- The Optimistic-Greedy Algorithm- The Epsilon-Greedy Algorithm (ε-Greedy)- Regret" }, { "code": null, "e": 938, "s": 880, "text": "Part 4: The Upper Confidence Bound (UCB) Bandit Algorithm" }, { "code": null, "e": 1039, "s": 938, "text": "All code for the bandit algorithms and testing framework can be found on github: Multi_Armed_Bandits" }, { "code": null, "e": 1305, "s": 1039, "text": "Baby Robot is lost in the mall. Using Reinforcement Learning we want to help him find his way back to his mum. However, before he can even begin looking for her, he needs to recharge, from a set of power sockets that each give a slightly different amount of charge." }, { "code": null, "e": 1481, "s": 1305, "text": "Using the strategies from the multi-armed bandit problem we need to find the best socket, in the shortest amount of time, to allow Baby Robot to get charged up and on his way." }, { "code": null, "e": 1776, "s": 1481, "text": "Baby Robot has entered a charging room containing 5 different power sockets. Each of these sockets returns a slightly different amount of charge. We want to get Baby Robot charged up in the minimum amount of time, so we need to locate the best socket and then use it until charging is complete." }, { "code": null, "e": 1968, "s": 1776, "text": "This is identical to the Multi-Armed Bandit problem except that, instead of looking for a slot machine that gives the best payout, we’re looking for a power socket that gives the most charge." }, { "code": null, "e": 2453, "s": 1968, "text": "Up until now, all of the methods we’ve seen for tackling the Bandit Problem have selected their actions based on the current averages of the rewards received from those actions. Thompson Sampling (also sometimes referred to as the Bayesian Bandits algorithm) takes a slightly different approach; rather than just refining an estimate of the mean reward it extends this, to instead build up a probability model from the obtained rewards, and then samples from this to choose an action." }, { "code": null, "e": 2777, "s": 2453, "text": "In this way, not only is an increasingly accurate estimate of the possible reward obtained, but the model also provides a level of confidence in this reward, and this confidence increases as more samples are collected. This process of updating your beliefs as more evidence becomes available is known as Bayesian Inference." }, { "code": null, "e": 3226, "s": 2777, "text": "As an introduction, and to make things easier to work with, let’s simplify the power socket problem. Now, instead of each socket returning a varying amount of charge, each socket will either return some charge or no charge; the rewards have only two possible values: 1 when the chosen socket supplies a charge and 0 when it doesn’t. When a random variable has only two possible outcomes its behaviour can be described by the Bernoulli distribution." }, { "code": null, "e": 3488, "s": 3226, "text": "So now, instead of the amount of charge varying per socket, the probability of a socket producing a charge varies with each socket. We want to find the socket with the highest probability of returning a charge, rather than the socket that gives the most charge." }, { "code": null, "e": 3748, "s": 3488, "text": "As already mentioned, Thompson Sampling generates a model of the reward probabilities. When, as in this case, the available rewards are binary (win or lose, yes or no, charge or no charge) then the Beta distribution is ideal to model this type of probability." }, { "code": null, "e": 3926, "s": 3748, "text": "(For more information on the relationship between the Beta and Bernoulli distributions check out this excellent article:Beta Distribution — Intuition, Examples, and Derivation)." }, { "code": null, "e": 4108, "s": 3926, "text": "The Beta distribution takes two parameters, ‘α’ (alpha) and ‘β’ (beta). In the simplest terms these parameters can be thought of as respectively the count of successes and failures." }, { "code": null, "e": 4169, "s": 4108, "text": "Additionally, a Beta distribution has a mean value given by:" }, { "code": null, "e": 4406, "s": 4169, "text": "Initially we have no idea what the probability is of any given socket producing an output, so we can start by setting both ‘α’ and ‘β’ to one, which produces a flat line Uniform distribution (shown as the flat, red, line in figure 5.1)." }, { "code": null, "e": 4673, "s": 4406, "text": "This initial guess at the probability of the socket producing an output is known as the Prior Probability; it is the probability of the specific event occurring before we have collected any evidence and in this case is represented by the Beta distribution Beta(1,1)." }, { "code": null, "e": 5028, "s": 4673, "text": "Once we test a socket, and obtain a reward, we can modify our belief in the likelihood of that socket returning some charge. This new probability, after some evidence has been collected, is known as the Posterior Probability. Again this is given by a Beta distribution, but now the values of ‘α’ and ‘β’ are updated with the value of the returned reward." }, { "code": null, "e": 5627, "s": 5028, "text": "So, if a socket returns some charge, the reward will be 1 and ‘α’, the count of the number of successes, will increment by 1. The count of the number of failures, ‘β’, will not increase. If instead no reward was obtained, then ‘α’ will stay the same and ‘β’ will increment by 1. As more data is collected the Beta distribution moves from being a flat line to become an increasingly accurate model of the probability of the mean reward. By maintaining the values of ‘α’ and ‘β’ a Thompson sampling algorithm is able to describe the estimated mean reward and the level of confidence in this estimate." }, { "code": null, "e": 6314, "s": 5627, "text": "In contrast to the Greedy algorithm, which at each time step selects the action with the highest estimated reward, even if the confidence in that estimate is low, Thompson sampling instead samples from the Beta distribution of each action and chooses the action with the highest returned value. Since actions that have been tried infrequently have wide distributions (see the blue curve in figure 5.1), they have a larger range of possible values. In this way, a socket that currently has a low estimated mean reward, but has been tested fewer times than a socket with a higher estimated mean, can return a larger sample value and therefore become the selected socket at this time step." }, { "code": null, "e": 6747, "s": 6314, "text": "In the graph above, the blue curve has a lower estimated mean reward than the green curve. Therefore, under Greedy selection, green would be chosen and the blue socket would never be selected. In contrast, Thompson Sampling effectively considers the full width of the curve, which for the blue socket can be seen to extend beyond that of the green socket. In this case the blue socket may be selected in preference to the green one." }, { "code": null, "e": 7225, "s": 6747, "text": "As the number of trials of a socket increases the confidence in the estimated mean increases. This is reflected in the probability distribution becoming narrower and the sampled value will then be drawn from a range of values that are closer to the true mean (see the green curve in figure 5.1). As a result, exploration decreases and exploitation increases, since the sockets with a higher probability of returning a reward will begin to be selected with increasing frequency." }, { "code": null, "e": 7656, "s": 7225, "text": "On the other hand, sockets with a low estimated mean will start to be selected less frequently and will tend to be dropped early from the selection process. Consequently, their true mean may never be found. Since we are only interested in finding the socket with the highest probability of returning a reward, and finding it as quickly as possible, we don’t care if full information of poorly performing sockets is never obtained." }, { "code": null, "e": 8131, "s": 7656, "text": "As in the socket experiments we carried out in previous parts of this series, we will be using a basic socket class, on top of which we add the specific functionality for the algorithm being studied. Then, using this new class, we run it through a set of experiments using the same test harness for all bandit algorithms. Full details of the power socket base class and the accompanying test system are given in Part 2 of this series and all the code can be found on github." }, { "code": null, "e": 8249, "s": 8131, "text": "The implementation of Bernoulli Thompson sampling, as described above, is shown in the BernoulliThompsonSocket class:" }, { "code": null, "e": 8434, "s": 8249, "text": "In this class we initialise ‘α’ and ‘β’ to one, to give the Uniform Distribution. Then, when updating, we simply increment ‘α’ if the socket returned a reward, otherwise we update ‘β’." }, { "code": null, "e": 8557, "s": 8434, "text": "The “sample” function draws a value from the Beta distribution, using the current values of ‘α’ and ‘β’ as its parameters." }, { "code": null, "e": 8712, "s": 8557, "text": "The evolution of the Beta distribution for each power socket, where we are using the simpler probabilistic power sockets, can be seen in Figure 5.2 below." }, { "code": null, "e": 8888, "s": 8712, "text": "To keep things simple, we’ve reduced the number of sockets to three and these have true probabilities 0.3 (green), 0.7(red) and 0.8 (blue) of returning some power when tested." }, { "code": null, "e": 9098, "s": 8888, "text": "In Figure 5.2 above, the true means of 0.3, 0.7 and 0.8 are shown by the dashed lines. The legend displays the number of trials for each socket and the number of successes that have resulted from these trials." }, { "code": null, "e": 9157, "s": 9098, "text": "The main points to note from Figure 5.2 are the following:" }, { "code": null, "e": 9287, "s": 9157, "text": "At time step 0 (not shown) all Beta distributions will have their α and β values set to one, to give a flat Uniform distribution." }, { "code": null, "e": 9678, "s": 9287, "text": "Since all sockets have the same initial distribution, at time step 1 the blue power socket is selected arbitrarily. When tested it gives a reward, so its α value gets incremented by 1 and its probability density curve shifts to the right. The green and red sockets have not yet been tested, so retain their initial flat distribution (with the green curve being hidden behind the red curve)." }, { "code": null, "e": 9991, "s": 9678, "text": "At the second time step the blue socket is again selected and again it returns a reward. The blue curve squeezes slightly more to the right, since this socket has been tested twice and has returned a reward both times, the possibility still exists that this socket will return a reward every time it is selected." }, { "code": null, "e": 10447, "s": 9991, "text": "By the 5th trial the blue socket has been selected once more, but this time it failed to give a reward. As a result the probability that it always returns a value drops to zero (at probability = 1.0). On the other hand, the green socket has now been tested twice and is yet to return a value, hence its probability density curve is shifted to the left with its highest value at probability =0, as there’s still a chance this socket never returns a reward." }, { "code": null, "e": 11059, "s": 10447, "text": "At 15 trials the red socket has now been tried a couple of times. Since it’s returned a reward once, it has an estimated mean reward probability of 0.5. At this stage the blue socket has been tried 11 times and has returned a reward on 6 of these trials, giving it a slightly higher estimated reward probability of 0.54. In a Greedy system the blue socket would therefore be the chosen socket, however because the red socket has been tried less times than the blue socket, it can be seen to have a much wider probability density curve, giving it a good chance of being selected in preference to the blue socket." }, { "code": null, "e": 11705, "s": 11059, "text": "The more times a socket is tested, the more confident we are in its estimate and the narrower its probability density curve becomes. The best socket will then be used more often and testing of the sub-optimal sockets will tail off. This behaviour can be seen at the end of our test, when the blue socket has been tried much more often than either of the two other sockets. It can also be seen that the green socket did finally return a reward on 2 of its trials. Consequently, it’s no longer possible that this is a socket that never returns a reward, so the probability of this happening (returning a reward with probability = 0) drops to zero." }, { "code": null, "e": 12210, "s": 11705, "text": "It can also be seen that neither the blue nor red sockets have probability density curves centred exactly on their true mean probabilities. If the test was run for more time steps then the blue curve would eventually settle on the true mean value, but the red socket will have a greatly reduced number of trials (if any) and so may never come to find its true value. As mentioned, this isn’t an issue, since we’re only interested in finding the best socket, not the true mean values of the other sockets." }, { "code": null, "e": 12504, "s": 12210, "text": "The simplified socket problem we’ve used so far is a good way to grasp the concepts of Bayesian Thompson Sampling. However, to use this method with our actual socket problem, in which the sockets aren’t binary, but instead return a variable amount of charge, we need to change things slightly." }, { "code": null, "e": 13185, "s": 12504, "text": "In the previous problem we modelled the socket’s behaviour using a Beta distribution. This was chosen because the simplified socket output had only two possible outcomes, some charge or no charge, and could therefore be described using a Bernoulli distribution. When a value drawn from a Bernoulli distribution (the likelihood value) is multiplied by a value drawn from a Beta distribution (the prior probability), then the resultant value (the posterior probability) also has a Beta distribution. When this occurs, such that the likelihood multiplied by the prior results in a posterior with the same distribution type as the prior, the prior is referred to as a Conjugate Prior." }, { "code": null, "e": 13759, "s": 13185, "text": "With our standard socket problem, each socket returns a real value described by a normal distribution. If we assume we know the variance of our socket (which is actually 1, since we use an unmodified version of the numpy randn function in our code), then from the table of conjugate priors on Wikipedia we can see that the conjugate prior also has a normal distribution. If we don’t know the variance of our distribution, or we’re using a different distribution, then we simply need to pick one of other conjugate priors from the table and adjust our algorithm accordingly." }, { "code": null, "e": 14138, "s": 13759, "text": "So we can model the output of a socket using a normal distribution and gradually refine this model by updating its mean and variance parameters. If, instead of using the variance, we use the precision ‘τ’ (tau), where precision is just one over the variance (precision τ = 1/variance), then we can use the simple update rules for the mean ‘μ0’ and total precision ‘τ0’ given by:" }, { "code": null, "e": 14145, "s": 14138, "text": "where;" }, { "code": null, "e": 14224, "s": 14145, "text": "‘τ’ is the precision of the actual socket output, which in our case is just 1." }, { "code": null, "e": 14279, "s": 14224, "text": "’n’ is the number of times the socket has been tested." }, { "code": null, "e": 14400, "s": 14279, "text": "‘xi’ is the output received at each test ‘i’ of this socket (equivalent to the reward ‘Ri’ that we’ve used up till now)." }, { "code": null, "e": 14484, "s": 14400, "text": "‘μ0’ is the estimated mean (the mean of the distribution used to model the output)." }, { "code": null, "e": 14558, "s": 14484, "text": "‘τ0’ is the total precision of the distribution used to model the output." }, { "code": null, "e": 15007, "s": 14558, "text": "At a first glance this looks rather intimidating, but all it’s basically saying is that we have 2 parameters ‘μ0’ and ‘τ0’ that we’ll update each time we test a socket, just as we did with ‘α’ and ‘β’ for the Bernoulli socket. Except in that case those parameters represented the number of successes and failures of the socket, whereas ‘μ0’ and ‘τ0’ represent the estimated mean and the precision, representing the confidence in the estimated mean." }, { "code": null, "e": 15067, "s": 15007, "text": "Additionally we can make a couple of other simplifications:" }, { "code": null, "e": 15381, "s": 15067, "text": "We know that the amount of charge returned from a socket has a variance of 1 and so the precision ‘τ’ is also 1. Therefore the update of the socket precision is simply τ0 = τ0 + n, where n is the number of times the socket has been tested, so each time a socket gets tested we simply increment its precision by 1." }, { "code": null, "e": 15818, "s": 15381, "text": "For the estimated mean the numerator contains a sum over all of the outputs produced by the socket, multiplied by ‘τ’. As we saw way back in the Sample Average Estimates section of Part 1, it’s not a good idea to retain the sum of rewards, since this could potentially grow to an unmanageable size. However, in our base socket implement we always calculate ‘Qt(a)’, the estimated value of action ‘a’ at time step ‘t’, which is given by:" }, { "code": null, "e": 16125, "s": 15818, "text": "In this equation ‘Ri’ is the reward obtained at each of the time steps when action ‘a’ was taken and is identical to the term ‘xi’ used in the update equation above. Therefore we can simply replace the summation in the update equation with ‘nQt(a)’ and end up with the following simplified update equation:" }, { "code": null, "e": 16425, "s": 16125, "text": "With these simplifications we tame the scary mathematics! It’s now clear that all we need to do is to keep estimates of the mean and precision of the reward from each socket and then use 2 simple rules to update these values. Things become even clearer when these equations are translated into code." }, { "code": null, "e": 16697, "s": 16425, "text": "The associated code for a Gaussian Thompson sampling socket is shown below. This retains all of the basic functionality we’ve used in previous socket types and adds the parameters and update function for the posterior distribution that is used to model the socket output." }, { "code": null, "e": 16978, "s": 16697, "text": "Note that in this update function we’ve replaced the summation over all of the observed rewards with ‘self.n * self.Q’. This gives us exactly the same value without having to retain the sum of rewards which, as described previously, could potentially grow to an unmanageable size." }, { "code": null, "e": 17104, "s": 16978, "text": "The two update functions, given in the equations above, translate into the simple lines of code shown in the update function." }, { "code": null, "e": 17139, "s": 17104, "text": "The other main points to note are:" }, { "code": null, "e": 17407, "s": 17139, "text": "The ‘sample’ function, instead of simply returning ‘Q’, the estimate of the socket’s reward value, instead returns a value sampled from the normal distribution that we’re using to model the socket output (the posterior, with mean ‘self.μ_0’ and precision ‘self.τ_0’)." }, { "code": null, "e": 17955, "s": 17407, "text": "As with the Beta distribution, used to model the socket output for binary outputs, we want our prior distribution to start with a distribution that’s close to the uniform distribution, giving a flat probability distribution curve and therefore the potential to return a sampled value with a wide range of possible values. So, initially we set the precision of the posterior to be a very small value (self.τ_0 = 0.0001). In this way sockets that have not yet been tried will be more likely to be selected, much like the Optimistic-Greedy algorithm." }, { "code": null, "e": 18126, "s": 17955, "text": "If you look back at the code for the base power socket, when a socket is sampled it returns an amount of charge given by a normal distribution around its true mean value:" }, { "code": null, "e": 18403, "s": 18126, "text": "In the charge function above, The numpy “randn” function returns a random value from a normal distribution of mean 0 and variance 1. By adding the true socket reward value ‘q’ to this, we shift the mean to get the distribution to be centred on the actual output of the socket." }, { "code": null, "e": 18486, "s": 18403, "text": "In the sample function of the Thompson socket a very similar function can be seen:" }, { "code": null, "e": 19031, "s": 18486, "text": "Except in this case the normal is centred on self.μ_0, the posterior mean. Additionally, it can be seen that randn is now divided by the square root of the posterior precision self.τ_0. Remember that the precision is just one over the variance and that variance is the standard deviation squared. Therefore dividing by the square root of the precision is identical to multiplying by the standard deviation. This is what changes the width of the distribution, reducing it as more samples occur and we become more confident in our estimated mean." }, { "code": null, "e": 19560, "s": 19031, "text": "As with the Bernoulli experiment done previously, we’ve observed the socket selection over 1000 trials, as shown by the probability density curves below. Due to the posterior distributions starting out with almost flat curves, each of the 5 sockets gets tested once during the first 5 trials. After this, socket 4 (shown as the red curve) dominates the further trials. By the end of the tests it has a tall, thin, curve centred on a value of 12 (the true socket reward value) indicating a high level of confidence in this value." }, { "code": null, "e": 19838, "s": 19560, "text": "The only other socket that is tested more than once, over the first 200 tests, is socket 5 (the purple curve, which has a true socket reward of 10). However, it is only tested 3 times and therefore has a small, fat, distribution curve, indicating a low confidence in its value." }, { "code": null, "e": 20089, "s": 19838, "text": "From Figure 5.3 its clear to see how Thompson sampling quickly locates and then exploits the best socket, with the other sockets being left largely untested. In this way the algorithm manages to return a large, and nearly optimal, accumulated reward." }, { "code": null, "e": 20225, "s": 20089, "text": "The regret obtained when using the Thompson Sampling algorithm with our standard socket selection problem is shown in Figure 5.4 below." }, { "code": null, "e": 20735, "s": 20225, "text": "As was seen for the UCB algorithm, the regret is practically zero, meaning that the best socket was nearly always chosen. This can also be seen in the plot of Cumulative Reward vs Time, in which the actual obtained reward is such a close match for the optimal that it obscured by this curve on the graph. As was seen with the probability density curves for Gaussian Thompson Sampling, the algorithm quickly locks onto the best action and then ruthlessly exploits this, resulting in a very low level of regret." }, { "code": null, "e": 20892, "s": 20735, "text": "As with the UCB algorithm, Thompson Sampling can be shown to have logarithmic regret, where the value of the regret falls to almost zero as time progresses." }, { "code": null, "e": 21097, "s": 20892, "text": "(Due to the very small number of actions, and the distinct reward values of each socket, this logarithmic decline in the regret isn’t seen in our experiment, since we’re already down near to zero regret.)" }, { "code": null, "e": 21205, "s": 21097, "text": "For a more in-depth look at Thompson Sampling, its uses and mathematical framework check out the following:" }, { "code": null, "e": 21263, "s": 21205, "text": "“A Tutorial on Thompson Sampling” Daniel J. Russo, et al." }, { "code": null, "e": 21518, "s": 21263, "text": "Algorithms that solve the bandit problem need to find a way to balance the trade-off between exploitation and exploration. They need to look for the best actions to take while at the same time trying to make use of the information they’ve already gained." }, { "code": null, "e": 21979, "s": 21518, "text": "In simple approaches, such as Epsilon-Greedy, this trade-off is achieved by mainly using the action that currently gives the most reward and adding simple exploration by now and again randomly trying some of the other actions. In more complex solutions, such as UCB, again the actions with the highest mean reward are selected most often but this is balanced by a confidence measure. This ensures that actions that have not been selected often will get tested." }, { "code": null, "e": 22514, "s": 21979, "text": "Thompson Sampling takes a different approach to these other methods. Instead of simply maintaining an estimate of the reward, it gradually refines a model of the probability of the reward for each action and actions are chosen by sampling from this distribution. It is therefore possible to get an estimate for the mean reward value of an action, plus a measure of confidence for that estimate. As we saw in our experiments, this allows it to quickly locate and lock onto the optimal action, to give a near optimal accumulated return." }, { "code": null, "e": 22806, "s": 22514, "text": "But is Thompson Sampling the best bandit algorithm and, more importantly, is it the one we should use to charge Baby Robot? To know the answers to these questions you’ll need to wait until the final part of this series, when we have the bandit algorithms go head-to-head in a final showdown!" }, { "code": null, "e": 22943, "s": 22806, "text": "< Part 4: Part 6 >UCB Bandit Algorithm A Comparison of Bandit Algorithms" } ]
TestLink - Import Data
TestLink supports XML and CVS file to import data. It supports importing the data for test suites, test cases, requirements, test execution results, keywords, etc. However, for few cases it supports only XML and in few cases both XML and CVS. Following table displays the functionalities that support import and those that support file format. Sample File − Following is the XML file with keywords that can be used to import test suites. <testsuite name = "Child Suite2"> <details>abc</details> <testcase name = "Sample test case2"> <summary>test case sample- update</summary> <preconditions>1. TestLink should be installed</preconditions> <steps> <step> <step_number>1</step_number> <actions>Go to www.google.com</actions> <expectedresults>Google Home page should display</expectedresults> </step> </steps> <keywords> <keyword name = "Sample Test"> <notes>abc</notes> </keyword> </keywords> </testcase> </testsuite> If you don’t want to add the keyword, the keyword section can be removed from the XML file. If you don’t want to add the keyword, the keyword section can be removed from the XML file. If you want to import multiple test cases, add <testcase> section multiple times with all sub-nodes. If you want to import multiple test cases, add <testcase> section multiple times with all sub-nodes. If only test cases need to be imported in an already existing test suite, remove the <testsuite> tag and start the XML file with <testcase>. If only test cases need to be imported in an already existing test suite, remove the <testsuite> tag and start the XML file with <testcase>. Step 1 − To import the test suite, go to Test Specifications → Test Specification from the dashboard. Step 2 − Select the project and the folder on the left pane where you want to import the test suite. OR To import only test cases, select the nearest test suite folders where the test cases should be imported. Step 3 − Click the Actions icon on the right pane as shown below. It displays the test suite operations. Step 4 − Click the Import icon as shown below − OR To upload only test cases, click the Import icon present in Test Case Operations (below the Test Suite Operations). It opens the Import Test Suite page. By default, the file type is selected as XML. Step 5 − Fill in the following details − File − Select the XML file and upload it. Max size of the file should be 400KB. File − Select the XML file and upload it. Max size of the file should be 400KB. Consider test case as duplicate if: Select the appropriate option from the list. Consider test case as duplicate if: Select the appropriate option from the list. Action for duplicate: Select the appropriate option from the list. Action for duplicate: Select the appropriate option from the list. Step 6 − Click the Upload file button as shown below − Step 7 − After import, a successful message is displayed as shown below. Sample XLS file to import multiple test cases as the following − Unlock panic button Press panic button Press confirm The first row won’t be imported. It is supposed to have a column description. Step 1 − To import test cases, go to Test Specifications → Test Specification from the dashboard. Step 2 − Select the nearest test suite folders, where the test cases should be imported. Step 3 − Click the Actions icon on the right pane. It displays Test Case Operations. Step 4 − Click the Import icon as shown below. It opens the Import test case page. Step 5 − By default, the file type selected is XML. Change it to XLS/CSV and enter the following details − File − Select the file and upload it. Max size of the file should be 400KB. File − Select the file and upload it. Max size of the file should be 400KB. Consider test case as duplicate if − Select the appropriate option from the list. Consider test case as duplicate if − Select the appropriate option from the list. Action for duplicate − Select the appropriate option from the list. Action for duplicate − Select the appropriate option from the list. Step 6 − Click the Upload file button as shown below. TestLink supports XML and CSV file to import the requirements. Sample XML file for Requirement would be as follows − <requirements> <requirement> <docid>ENG-0001</docid> <title>Add a product</title> <description>ABC</description> </requirement> <requirement> <docid>ENG-0002</docid> <title>Add price </title> <description>Price</description> </requirement> </requirements> Sample CSV file for Requirement would be as follows − ENG-0001,Add a product,ABC ENG-0002,Add price,Price Step 1 − To import the requirements, go to Requirement Specification → Requirement Specification from the dashboard. Step 2 − Select the Requirement Specification folder where the requirements should be imported on the left panel. Step 3 − Click the Action icon present on the top of the right pane. It displays the Requirement Operations page. Step 4 − Click the Import button as shown below. It displays the requirement import page. Step 5 − Enter the following details. File Type − You can select CSV, XML or other forms of CSV and XML files as listed. File Type − You can select CSV, XML or other forms of CSV and XML files as listed. File − Upload the corresponding file. File − Upload the corresponding file. Consider test case as duplicate if − Select the appropriate option from the list. Consider test case as duplicate if − Select the appropriate option from the list. Action for duplicate − Select the appropriate option from the list. Action for duplicate − Select the appropriate option from the list. Step 6 − Click the Upload file button as shown below. After upload, it displays Import done message along with the imported details. After upload, it displays Import done message along with the imported details. Similarly, keywords, platforms, and results can be imported using supported file and the respective section accessing the dashboard. Print Add Notes Bookmark this page
[ { "code": null, "e": 2561, "s": 2318, "text": "TestLink supports XML and CVS file to import data. It supports importing the data for test suites, test cases, requirements, test execution results, keywords, etc. However, for few cases it supports only XML and in few cases both XML and CVS." }, { "code": null, "e": 2662, "s": 2561, "text": "Following table displays the functionalities that support import and those that support file format." }, { "code": null, "e": 2756, "s": 2662, "text": "Sample File − Following is the XML file with keywords that can be used to import test suites." }, { "code": null, "e": 3378, "s": 2756, "text": "<testsuite name = \"Child Suite2\">\n <details>abc</details>\n <testcase name = \"Sample test case2\">\n <summary>test case sample- update</summary>\n <preconditions>1. TestLink should be installed</preconditions>\n \n <steps>\n <step>\n <step_number>1</step_number>\n <actions>Go to www.google.com</actions>\n <expectedresults>Google Home page should display</expectedresults>\n </step>\n </steps>\n \n <keywords>\n <keyword name = \"Sample Test\">\n <notes>abc</notes>\n </keyword>\n </keywords>\n </testcase>\n</testsuite>" }, { "code": null, "e": 3470, "s": 3378, "text": "If you don’t want to add the keyword, the keyword section can be removed from the XML file." }, { "code": null, "e": 3562, "s": 3470, "text": "If you don’t want to add the keyword, the keyword section can be removed from the XML file." }, { "code": null, "e": 3663, "s": 3562, "text": "If you want to import multiple test cases, add <testcase> section multiple times with all sub-nodes." }, { "code": null, "e": 3764, "s": 3663, "text": "If you want to import multiple test cases, add <testcase> section multiple times with all sub-nodes." }, { "code": null, "e": 3905, "s": 3764, "text": "If only test cases need to be imported in an already existing test suite, remove the <testsuite> tag and start the XML file with <testcase>." }, { "code": null, "e": 4046, "s": 3905, "text": "If only test cases need to be imported in an already existing test suite, remove the <testsuite> tag and start the XML file with <testcase>." }, { "code": null, "e": 4148, "s": 4046, "text": "Step 1 − To import the test suite, go to Test Specifications → Test Specification from the dashboard." }, { "code": null, "e": 4249, "s": 4148, "text": "Step 2 − Select the project and the folder on the left pane where you want to import the test suite." }, { "code": null, "e": 4252, "s": 4249, "text": "OR" }, { "code": null, "e": 4358, "s": 4252, "text": "To import only test cases, select the nearest test suite folders where the test cases should be imported." }, { "code": null, "e": 4424, "s": 4358, "text": "Step 3 − Click the Actions icon on the right pane as shown below." }, { "code": null, "e": 4463, "s": 4424, "text": "It displays the test suite operations." }, { "code": null, "e": 4511, "s": 4463, "text": "Step 4 − Click the Import icon as shown below −" }, { "code": null, "e": 4514, "s": 4511, "text": "OR" }, { "code": null, "e": 4630, "s": 4514, "text": "To upload only test cases, click the Import icon present in Test Case Operations (below the Test Suite Operations)." }, { "code": null, "e": 4713, "s": 4630, "text": "It opens the Import Test Suite page. By default, the file type is selected as XML." }, { "code": null, "e": 4754, "s": 4713, "text": "Step 5 − Fill in the following details −" }, { "code": null, "e": 4834, "s": 4754, "text": "File − Select the XML file and upload it. Max size of the file should be 400KB." }, { "code": null, "e": 4914, "s": 4834, "text": "File − Select the XML file and upload it. Max size of the file should be 400KB." }, { "code": null, "e": 4995, "s": 4914, "text": "Consider test case as duplicate if: Select the appropriate option from the list." }, { "code": null, "e": 5076, "s": 4995, "text": "Consider test case as duplicate if: Select the appropriate option from the list." }, { "code": null, "e": 5143, "s": 5076, "text": "Action for duplicate: Select the appropriate option from the list." }, { "code": null, "e": 5210, "s": 5143, "text": "Action for duplicate: Select the appropriate option from the list." }, { "code": null, "e": 5265, "s": 5210, "text": "Step 6 − Click the Upload file button as shown below −" }, { "code": null, "e": 5338, "s": 5265, "text": "Step 7 − After import, a successful message is displayed as shown below." }, { "code": null, "e": 5403, "s": 5338, "text": "Sample XLS file to import multiple test cases as the following −" }, { "code": null, "e": 5423, "s": 5403, "text": "Unlock panic button" }, { "code": null, "e": 5442, "s": 5423, "text": "Press panic button" }, { "code": null, "e": 5456, "s": 5442, "text": "Press confirm" }, { "code": null, "e": 5534, "s": 5456, "text": "The first row won’t be imported. It is supposed to have a column description." }, { "code": null, "e": 5632, "s": 5534, "text": "Step 1 − To import test cases, go to Test Specifications → Test Specification from the dashboard." }, { "code": null, "e": 5721, "s": 5632, "text": "Step 2 − Select the nearest test suite folders, where the test cases should be imported." }, { "code": null, "e": 5772, "s": 5721, "text": "Step 3 − Click the Actions icon on the right pane." }, { "code": null, "e": 5806, "s": 5772, "text": "It displays Test Case Operations." }, { "code": null, "e": 5853, "s": 5806, "text": "Step 4 − Click the Import icon as shown below." }, { "code": null, "e": 5889, "s": 5853, "text": "It opens the Import test case page." }, { "code": null, "e": 5996, "s": 5889, "text": "Step 5 − By default, the file type selected is XML. Change it to XLS/CSV and enter the following details −" }, { "code": null, "e": 6072, "s": 5996, "text": "File − Select the file and upload it. Max size of the file should be 400KB." }, { "code": null, "e": 6148, "s": 6072, "text": "File − Select the file and upload it. Max size of the file should be 400KB." }, { "code": null, "e": 6230, "s": 6148, "text": "Consider test case as duplicate if − Select the appropriate option from the list." }, { "code": null, "e": 6312, "s": 6230, "text": "Consider test case as duplicate if − Select the appropriate option from the list." }, { "code": null, "e": 6380, "s": 6312, "text": "Action for duplicate − Select the appropriate option from the list." }, { "code": null, "e": 6448, "s": 6380, "text": "Action for duplicate − Select the appropriate option from the list." }, { "code": null, "e": 6502, "s": 6448, "text": "Step 6 − Click the Upload file button as shown below." }, { "code": null, "e": 6565, "s": 6502, "text": "TestLink supports XML and CSV file to import the requirements." }, { "code": null, "e": 6619, "s": 6565, "text": "Sample XML file for Requirement would be as follows −" }, { "code": null, "e": 6927, "s": 6619, "text": "<requirements>\n <requirement>\n <docid>ENG-0001</docid>\n <title>Add a product</title>\n <description>ABC</description>\n </requirement>\n \n <requirement>\n <docid>ENG-0002</docid>\n <title>Add price </title>\n <description>Price</description>\n </requirement>\n</requirements>" }, { "code": null, "e": 6981, "s": 6927, "text": "Sample CSV file for Requirement would be as follows −" }, { "code": null, "e": 7035, "s": 6981, "text": "ENG-0001,Add a product,ABC\n\nENG-0002,Add price,Price\n" }, { "code": null, "e": 7152, "s": 7035, "text": "Step 1 − To import the requirements, go to Requirement Specification → Requirement Specification from the dashboard." }, { "code": null, "e": 7266, "s": 7152, "text": "Step 2 − Select the Requirement Specification folder where the requirements should be imported on the left panel." }, { "code": null, "e": 7335, "s": 7266, "text": "Step 3 − Click the Action icon present on the top of the right pane." }, { "code": null, "e": 7380, "s": 7335, "text": "It displays the Requirement Operations page." }, { "code": null, "e": 7429, "s": 7380, "text": "Step 4 − Click the Import button as shown below." }, { "code": null, "e": 7470, "s": 7429, "text": "It displays the requirement import page." }, { "code": null, "e": 7508, "s": 7470, "text": "Step 5 − Enter the following details." }, { "code": null, "e": 7591, "s": 7508, "text": "File Type − You can select CSV, XML or other forms of CSV and XML files as listed." }, { "code": null, "e": 7674, "s": 7591, "text": "File Type − You can select CSV, XML or other forms of CSV and XML files as listed." }, { "code": null, "e": 7712, "s": 7674, "text": "File − Upload the corresponding file." }, { "code": null, "e": 7750, "s": 7712, "text": "File − Upload the corresponding file." }, { "code": null, "e": 7832, "s": 7750, "text": "Consider test case as duplicate if − Select the appropriate option from the list." }, { "code": null, "e": 7914, "s": 7832, "text": "Consider test case as duplicate if − Select the appropriate option from the list." }, { "code": null, "e": 7982, "s": 7914, "text": "Action for duplicate − Select the appropriate option from the list." }, { "code": null, "e": 8050, "s": 7982, "text": "Action for duplicate − Select the appropriate option from the list." }, { "code": null, "e": 8104, "s": 8050, "text": "Step 6 − Click the Upload file button as shown below." }, { "code": null, "e": 8183, "s": 8104, "text": "After upload, it displays Import done message along with the imported details." }, { "code": null, "e": 8262, "s": 8183, "text": "After upload, it displays Import done message along with the imported details." }, { "code": null, "e": 8395, "s": 8262, "text": "Similarly, keywords, platforms, and results can be imported using supported file and the respective section accessing the dashboard." }, { "code": null, "e": 8402, "s": 8395, "text": " Print" }, { "code": null, "e": 8413, "s": 8402, "text": " Add Notes" } ]
Spring MVC - Resource Bundle View Resolver Example
The ResourceBundleViewResolver is used to resolve the view names using view beans defined in the properties file. The following example shows how to use the ResourceBundleViewResolver using the Spring Web MVC Framework. <bean class = "org.springframework.web.servlet.view.ResourceBundleViewResolver"> <property name = "basename" value = "views" /> </bean> Here, the basename refers to name of the resource bundle, which carries the views. The default name of the resource bundle is views.properties, which can be overridden using the basename property. hello.(class) = org.springframework.web.servlet.view.JstlView hello.url = /WEB-INF/jsp/hello.jsp For example, using the above configuration, if URI − /hello is requested, DispatcherServlet will forward the request to the hello.jsp defined by bean hello in the views.properties. /hello is requested, DispatcherServlet will forward the request to the hello.jsp defined by bean hello in the views.properties. Here, "hello" is the view name to be matched. Whereas, class refers to the view type and URL is the view's location. Here, "hello" is the view name to be matched. Whereas, class refers to the view type and URL is the view's location. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using Spring Web Framework. package com.tutorialspoint; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.ui.ModelMap; @Controller @RequestMapping("/hello") public class HelloController{ @RequestMapping(method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute("message", "Hello Spring MVC Framework!"); return "hello"; } } <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:context = "http://www.springframework.org/schema/context" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = " http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package = "com.tutorialspoint" /> <bean class = "org.springframework.web.servlet.view.ResourceBundleViewResolver"> <property name = "basename" value = "views" /> </bean> </beans> hello.(class) = org.springframework.web.servlet.view.JstlView hello.url = /WEB-INF/jsp/hello.jsp <%@ page contentType="text/html; charset=UTF-8" %> <html> <head> <title>Hello World</title> </head> <body> <h2>${message}</h2> </body> </html> Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat's webapps folder. Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try to access the URL − http://localhost:8080/HelloWeb/hello and if everything is fine with the Spring Web Application, we will see the following screen. Print Add Notes Bookmark this page
[ { "code": null, "e": 3011, "s": 2791, "text": "The ResourceBundleViewResolver is used to resolve the view names using view beans defined in the properties file. The following example shows how to use the ResourceBundleViewResolver using the Spring Web MVC Framework." }, { "code": null, "e": 3150, "s": 3011, "text": "<bean class = \"org.springframework.web.servlet.view.ResourceBundleViewResolver\">\n <property name = \"basename\" value = \"views\" />\n</bean>" }, { "code": null, "e": 3347, "s": 3150, "text": "Here, the basename refers to name of the resource bundle, which carries the views. The default name of the resource bundle is views.properties, which can be overridden using the basename property." }, { "code": null, "e": 3445, "s": 3347, "text": "hello.(class) = org.springframework.web.servlet.view.JstlView\nhello.url = /WEB-INF/jsp/hello.jsp\n" }, { "code": null, "e": 3498, "s": 3445, "text": "For example, using the above configuration, if URI −" }, { "code": null, "e": 3626, "s": 3498, "text": "/hello is requested, DispatcherServlet will forward the request to the hello.jsp defined by bean hello in the views.properties." }, { "code": null, "e": 3754, "s": 3626, "text": "/hello is requested, DispatcherServlet will forward the request to the hello.jsp defined by bean hello in the views.properties." }, { "code": null, "e": 3871, "s": 3754, "text": "Here, \"hello\" is the view name to be matched. Whereas, class refers to the view type and URL is the view's location." }, { "code": null, "e": 3988, "s": 3871, "text": "Here, \"hello\" is the view name to be matched. Whereas, class refers to the view type and URL is the view's location." }, { "code": null, "e": 4155, "s": 3988, "text": "To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using Spring Web Framework." }, { "code": null, "e": 4662, "s": 4155, "text": "package com.tutorialspoint;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.ui.ModelMap;\n\n@Controller\n@RequestMapping(\"/hello\")\npublic class HelloController{\n \n @RequestMapping(method = RequestMethod.GET)\n public String printHello(ModelMap model) {\n model.addAttribute(\"message\", \"Hello Spring MVC Framework!\");\n\n return \"hello\";\n }\n\n}" }, { "code": null, "e": 5344, "s": 4662, "text": "<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:context = \"http://www.springframework.org/schema/context\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"\n http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\n http://www.springframework.org/schema/context \n http://www.springframework.org/schema/context/spring-context-3.0.xsd\">\n\n <context:component-scan base-package = \"com.tutorialspoint\" />\n\n <bean class = \"org.springframework.web.servlet.view.ResourceBundleViewResolver\">\n <property name = \"basename\" value = \"views\" />\n </bean>\n</beans>" }, { "code": null, "e": 5441, "s": 5344, "text": "hello.(class) = org.springframework.web.servlet.view.JstlView\nhello.url = /WEB-INF/jsp/hello.jsp" }, { "code": null, "e": 5608, "s": 5441, "text": "<%@ page contentType=\"text/html; charset=UTF-8\" %>\n<html>\n <head>\n <title>Hello World</title>\n </head>\n <body>\n <h2>${message}</h2>\n </body>\n</html>" }, { "code": null, "e": 5819, "s": 5608, "text": "Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat's webapps folder." }, { "code": null, "e": 6105, "s": 5819, "text": "Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try to access the URL − http://localhost:8080/HelloWeb/hello and if everything is fine with the Spring Web Application, we will see the following screen." }, { "code": null, "e": 6112, "s": 6105, "text": " Print" }, { "code": null, "e": 6123, "s": 6112, "text": " Add Notes" } ]
Python | Numpy matrix.itemset() - GeeksforGeeks
15 Apr, 2019 With the help of Numpy matrix.itemset() method, we can set the items in a given matrix by just providing index number and item. Syntax : matrix.itemset(index, item) Return : Return new matrix having item Example #1 :In this example we can see that we are able to set the item with the help of method matrix.itemset() by providing index number and item. # import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[6, 1; 2, 3]') # applying matrix.itemset() methodgfg.itemset((1, 0), 5) print(gfg) [[6 1] [5 3]] Example #2 : # import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]') # applying matrix.itemset() methodgfg.itemset((2, 0), 10) print(gfg) [[ 1 2 3] [ 4 5 6] [10 8 9]] Python numpy-Matrix Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists sum() function in Python *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe Print lists in Python (4 Different Ways)
[ { "code": null, "e": 24873, "s": 24845, "text": "\n15 Apr, 2019" }, { "code": null, "e": 25001, "s": 24873, "text": "With the help of Numpy matrix.itemset() method, we can set the items in a given matrix by just providing index number and item." }, { "code": null, "e": 25038, "s": 25001, "text": "Syntax : matrix.itemset(index, item)" }, { "code": null, "e": 25077, "s": 25038, "text": "Return : Return new matrix having item" }, { "code": null, "e": 25226, "s": 25077, "text": "Example #1 :In this example we can see that we are able to set the item with the help of method matrix.itemset() by providing index number and item." }, { "code": "# import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[6, 1; 2, 3]') # applying matrix.itemset() methodgfg.itemset((1, 0), 5) print(gfg)", "e": 25429, "s": 25226, "text": null }, { "code": null, "e": 25445, "s": 25429, "text": "[[6 1]\n [5 3]]\n" }, { "code": null, "e": 25458, "s": 25445, "text": "Example #2 :" }, { "code": "# import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]') # applying matrix.itemset() methodgfg.itemset((2, 0), 10) print(gfg)", "e": 25679, "s": 25458, "text": null }, { "code": null, "e": 25717, "s": 25679, "text": "[[ 1 2 3]\n [ 4 5 6]\n [10 8 9]]\n" }, { "code": null, "e": 25746, "s": 25717, "text": "Python numpy-Matrix Function" }, { "code": null, "e": 25759, "s": 25746, "text": "Python-numpy" }, { "code": null, "e": 25766, "s": 25759, "text": "Python" }, { "code": null, "e": 25864, "s": 25766, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25882, "s": 25864, "text": "Python Dictionary" }, { "code": null, "e": 25904, "s": 25882, "text": "Enumerate() in Python" }, { "code": null, "e": 25936, "s": 25904, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25978, "s": 25936, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26004, "s": 25978, "text": "Python String | replace()" }, { "code": null, "e": 26041, "s": 26004, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26066, "s": 26041, "text": "sum() function in Python" }, { "code": null, "e": 26095, "s": 26066, "text": "*args and **kwargs in Python" }, { "code": null, "e": 26151, "s": 26095, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
How to hide action bar in android?
This example demonstrate about How to hide action bar in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" android:background="#000" tools:context=".MainActivity"> <DigitalClock android:id="@+id/digital" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="30sp" android:textColor="#FFF" android:layout_centerHorizontal="true"/> </LinearLayout> In the above code, we have taken the digital clock view to show a clock. Step 3− Add the following code to java/MainActivity.xml package com.example.myapplication; import android.annotation.TargetApi; import android.content.pm.ActivityInfo; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import android.view.WindowManager; public class MainActivity extends AppCompatActivity { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportActionBar().hide(); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1128, "s": 1062, "text": "This example demonstrate about How to hide action bar in android." }, { "code": null, "e": 1257, "s": 1128, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1322, "s": 1257, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1940, "s": 1322, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:gravity=\"center\"\n android:background=\"#000\"\n tools:context=\".MainActivity\">\n <DigitalClock android:id=\"@+id/digital\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:textSize=\"30sp\"\n android:textColor=\"#FFF\"\n android:layout_centerHorizontal=\"true\"/>\n</LinearLayout>" }, { "code": null, "e": 2013, "s": 1940, "text": "In the above code, we have taken the digital clock view to show a clock." }, { "code": null, "e": 2069, "s": 2013, "text": "Step 3− Add the following code to java/MainActivity.xml" }, { "code": null, "e": 2771, "s": 2069, "text": "package com.example.myapplication;\n\nimport android.annotation.TargetApi;\nimport android.content.pm.ActivityInfo;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.view.Window;\nimport android.view.WindowManager;\n\npublic class MainActivity extends AppCompatActivity {\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n getSupportActionBar().hide();\n }\n}" }, { "code": null, "e": 3118, "s": 2771, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 3158, "s": 3118, "text": "Click here to download the project code" } ]
The Ultimate Guide to Your Terminal Makeover 2021 | by Shinichi Okada | Towards Data Science
[Latest update 2021–12–17, Starship and Nerd Fonts.] Table of Contents· Introduction ∘ Homebrew· iTerm2· Zsh· Oh-My-Zsh ∘ Errors ∘ Shortcut for toggling hidden files· Themes ∘ Starship (Updated) ∘ iTerm2 Theme· Oh-My-Zsh and plugins ∘ 1. git plugin ∘ 2. alias ∘ 3. alias dirs and cd - ∘ 4. autojump plugin ∘ 5. brew plugin ∘ 6. zsh-syntax-highlighting plugin ∘ 7. zsh-autosuggestions plugin· Duplicate a tab· Shaping up terminal command history· Creating aliases· Useful commands· Terminal Shortcuts· Task management· Fun with Terminal ∘ Screensaver ∘ FIGlet ∘ Colors ∘ Fonts· Weather reports on your terminal· macOS/Linux commands ∘ Terminal calendars ∘ date ∘ ditto ∘ Common terminal commands· Conclusion· Update Log· Newsletter Do you use your terminal all day? Is the terminal the first app you start after restarting your computer? In this article, you will find how to improve your terminal look and practical commands for your day-to-day work. [Update] You can install all packages in this article with a line of code, see this article. towardsdatascience.com You need to have Homebrew installed. If you don’t have it, you can install it by running the following in a terminal. $ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" Homebrew requires Command Line Tools for Xcode. But if you don’t have it, the installation will install it for you. Using a text editor (Vim/VSCode/TextEdit) add the following: # ~/.zshrc export PATH=$(brew --prefix)/bin:$PATH Then source ~/.zshrc: $ . ~/.zshrc This will load ~/.zshrc. Run brew help to see if it is installed. towardsdatascience.com towardsdatascience.com iTerm2 is a replacement for the terminal and it works on Macs. iTerm2 brings the terminal modern looks with great features. You can download iterm2 or you can install iTerm2 with Homebrew. $ brew install iterm2 Zsh is a shell designed for interactive use and it is also a powerful scripting language. You can find your shell. $ echo $SHELL/bin/zsh And find your zsh version. $ zsh --versionzsh 5.8 (x86_64-apple-darwin20.0) If you don’t have it then install it with Homebrew. $ brew install zsh If your shell is not zsh, run the following. $ chsh -s /bin/zsh Then restart your iTerm2 or open a new tab in iTerm2. $ echo $SHELL Oh-My-Zsh is an open-source, community-driven framework for managing your ZSH configuration. It comes bundled with a ton of helpful functions, helpers, plugins, themes. You can install Oh-My-Zsh with running one of the following commands in iTerm. You can install this via the command-line with either curl or wget. via curl $ sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" via wget $ sh -c "$(wget -O- https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" You can see the terminal prompt change to ~. Update Oh-My-Zsh: $ omz update Oh-My-Zsh may overwrites ~/.zshrc, you need to add the path to brew. This time you need to add it before plugins. Using a text editor (Vim/VSCode/TextEdit): # ~/.zshrc export PATH=$(brew --prefix)/bin:$PATH plugins=(git) Do you have the following errors? Or You need to change the access permission to these files. These commands will fix them. Run the followings on your terminal: $ chmod 755 $(brew --prefix)/share/zsh$ chmod 755 $(brew --prefix)/share/zsh/site-functions And open another tab. You can toggle showing hidden files in Finder by Command + Shift + Period. betterprogramming.pub betterprogramming.pub In this section, you will find Starship and iTem2 themes. You just need to use one of them. I used to use iTerm2 theme, but now I use Starship. I started using the Starship and I quite like it. The Starship is a minimal, blazing-fast, and infinitely customizable prompt. After installing iTerm2, Zsh, Oh-My-Zsh as I explained before you install the Starship. For example, if you are a Homebrew user: $ brew install starship Add the following to the end of ~/.zshrc: From your terminal: $ echo 'eval "$(starship init zsh)"' >> ~/.zshrc Or if you know Vim (or TextEdit for beginners): eval "$(starship init zsh)" We change the iTerm2 theme to Minimal. We change the color presets to Snazzy: Starship recommends using Nerd-font. You can install it with brew: $ brew tap homebrew/cask-fonts$ brew install --cask font-hack-nerd-font Or you can install Fira Code using brew: $ brew tap homebrew/cask-fonts && brew install --cask font-fira-code-nerd-font Select Hack Nerd Font Mono under iTerm2 Preference > Profile > Text: Or select FiraCode Nerd Font Mono: In one of my npm package directories, it shows Git status, repo version, and Node version with icons. The [!] is one of Starship Git status options and it is telling you that the directory is modified. If you want to know what’s going in the status bar, use the starship explain command: $ starship explain You can change the prompt using the Starship configuration. Powerline iTerm has more than 200 themes. My favorite themes are Cobalt2 and Oceanic next. Let’s install Cobalt2. Download this repo and drop the cobalt2.zsh-theme file in to the ~/.oh-my-zsh/themes/ directory. Command + C to copy the file and Command + Option + V to cut-paste.Open up your ZSH preferences at ~/.zshrc and change the theme variable to ZSH_THEME=cobalt2. Download this repo and drop the cobalt2.zsh-theme file in to the ~/.oh-my-zsh/themes/ directory. Command + C to copy the file and Command + Option + V to cut-paste. Open up your ZSH preferences at ~/.zshrc and change the theme variable to ZSH_THEME=cobalt2. 3. Install Powerline and necessary fonts - one way is using PIP $ pip3 install --user powerline-status You may need to upgrade PIP. $ pip3 install --upgrade pip 4. Install all necessary fonts by downloading or cloning the git repository. $ git clone https://github.com/powerline/fonts$ cd fonts$ ./install.sh If you wish to remove the fonts directory. $ ..$ rm -rf fonts 5. In iTerm2 access the Preferences pane on the Profiles tab. 6. Under the Colors tab import the cobalt2.itermcolors file via the Color Presets drop-down. 7. Under the Text tab change the font for each type (Regular and Non-ASCII) to ‘Inconsolata for Powerline’. 8. Refresh ZSH by typing source ~/.zshrc on the command line. VS Code terminal For your VS Code terminal, you need to add the following to Setting(JSON). { "terminal.integrated.fontFamily":"Inconsolata for Powerline",} If you feel a bit adventurous, try powerlevel10k theme. Oh-My-Zsh has built-in commands. Oh-My-Zsh’s power comes with its plugins. There are more than 260 plugins are available. The zsh git plugin provides many aliases and a few useful functions. To install it, add git to the plugins array in your .zshrc file. Open .zshrc with your text editor: plugins=(git) The following is an example workflow using the git plugin. # make a directory and cd into it$ mkdir -p Datascience/terminal-article && cd $_# create a new git repo$ git initInitialized empty Git repository in /Users/shinokada/DataScience/terminal-article/.git/# Add a README.md$ echo "# Terminal-article" >> README.md# git add .$ ga .# git commit -m $ gcmsg "First commit"[master (root-commit) 128f2b9] First commit1 file changed, 1 insertion(+)create mode 100644 README.md# git remote add$ gra origin git@github.com:shinokada/terminal-article.git # modify a file$ echo "more fix" >> README.md# git status$ gst# git add .$ ga .# git commit and message$ gcmsg "Update"# git push origin$ ggp You can use alias to see all your alias commands. Please see this page for more aliases. You use aliases cd -, cd -2, etc. with the dirs command as you can see in the above image. The dirs displays the contents of the directory stack. The current directory is always the "top" of the directory stack. cd -2 changes directory to the second in the directory stack. autojump plugin loads the autojump navigation tool. autojump is a faster way to navigate your filesystem. It works by maintaining a database of the directories you use the most from the command line. First, install it on your Mac OS. $ brew install autojump# or for port user$ port install autojump To use it, add autojump to the plugins array in your .zshrc file: # no comma between plugins required plugins=(git autojump) Add the following to the end of ~/.zshrc (Intel x86_64 or arm64): [ -f $(brew --prefix)/etc/profile.d/autojump.sh ] && . $(brew --prefix)/etc/profile.d/autojump.sh Reload .zshrc by so .zshrc on your terminal or open a new tab. By changing your directory, autojump records directories. You type j + first few letters of a directory. e.g j Data. The brew plugin adds several aliases for common brew commands. To use it, add brew to the plugins array of your .zshrc file: plugins=(git autojump brew) After adding brew to plugins, the following message will come. You can start using it. Create your own alias In .zshrc add the following. buou will update, show outdated and upgrade. # brew update && brew outdated && brew upgrade ➡️ buoualias buou="brew update && brew outdated && brew upgrade && brew cleanup" Install zsh-syntax-highlighting by cloning the repository in oh-my-zsh’s plugins directory: $ git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting Note that zsh-syntax-highlighting must be the last plugin sourced. Activate the plugin in ~/.zshrc: plugins=(some other plugins zsh-syntax-highlighting) Restart iTerm2, open a new tab, or run source .zshrc. Before: After: The zsh-autosuggestions is fish-like autosuggestion for zsh. Clone the repository into $ZSH_CUSTOM/plugins (by default ~/.oh-my-zsh/custom/plugins): Clone the repository into $ZSH_CUSTOM/plugins (by default ~/.oh-my-zsh/custom/plugins): $ git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions 2. Add the plugin to the list of plugins in ~/.zshrc: plugins=(git brew zsh-syntax-highlighting zsh-autosuggestions) 3. Start a new terminal session or open a new terminal tab. $ source ~/.zshrc When you press CMD+T, iTerm will open a new tab and the location is the ~ or home directory. I’d like to duplicate a tab with the same directory. On your iTerm, press CMD+, to open settings. Press Keys and select Key Bindings. Click + sign at the bottom left and choose your keyboard shortcut, like Shift+CMD+T. Select Duplicate Tab in the action. History is stored in ~/.zsh_history or ~/.bash_history or ~/.history depending on your shell. History is stored for 1000 or 2000 lines depending on your system. You can find the number of history: $ echo $HISTSIZE 50000$ echo $HISTFILE/Users/shinokada/.zsh_history$ echo $SAVEHIST10000 HISTSIZE is the maximum number of lines that are kept in a session and SAVEHIST is the maximum number of lines that are kept in the history file. HISTFILE is the file name where your system is saving history. You can change these numbers by adding the following to .zshrc. HISTSIZE=5000SAVEHIST=5000 reverse-i-search allows you to search for a command from the history file. Press CTRL+r to start it and type whatever you remember to search. If you keep pressing CTRL+r, the terminal searches the next command in the history file. You can see all your command history using a bash command history. # shows all command history$ history# shows first 10 commands$ history | head# shows last 10 commands$ hisotry | tail# shows less history$ history | less# Use grep to search your command history$ history | grep Search-word# Use grep to do a case-insensitive search of your command history$ hisotry | grep -i search-word In order to remove commands from your history list, you add the following to your .zshrc : setopt HIST_IGNORE_SPACE This removes command lines from the history list when the first character on the line is a space. # This won't work$ cd ~# This will work because there is a space before the command$ cd ~ You may not want common commands in the command history. Adding the following to zshrc prevent ll ls la cd man scp vim nvim less ping open file which whois drill uname md5sum traceroute commands in the command history. zshaddhistory() { local line=${1%%$'\n'} local cmd=${line%% *} # Only those that satisfy all of the following conditions are added to the history [[ ${#line} -ge 5 && ${cmd} != ll && ${cmd} != ls && ${cmd} != la && ${cmd} != cd && ${cmd} != man && ${cmd} != scp && ${cmd} != vim && ${cmd} != nvim && ${cmd} != less && ${cmd} != ping && ${cmd} != open && ${cmd} != file && ${cmd} != which && ${cmd} != whois && ${cmd} != drill && ${cmd} != uname && ${cmd} != md5sum && ${cmd} != pacman && ${cmd} != xdg-open && ${cmd} != traceroute && ${cmd} != speedtest-cli ]]}zshaddhistory As I showed before withbuou, you can add your own alias to .zshrc file. # brew update && brew outdated && brew upgradealias buou="brew update && brew outdated && brew upgrade && brew cleanup"# npm outdated -g --depth=0 && npm update -galias npmou="npm outdated -g --depth=0 && npm update -g" I havevirtualenv and virtualenvwrapper installed. And the following aliases allow me to use note to start a Jupyter environment and Jupyter notebook. lab will start the environment and Jupyterlab. # start jupyter environmentalias wj='workon jupyter'# start jupyter notebookalias note='workon jupyter && jupyter notebook'# start jupyterlabalias lab='workon jupyter && jupyter lab' # Repeat the last command$ !!# Clear the screen$ clear # Or you can clear the screen with CTRL+l, as well Instead of using the rm command, I suggest using rmtrash. It will move the file to OS X’s Trash rather than removing permanently. You can install it using brew: $ brew install rmtrash And create an alias in your ~/.zshrc file: alias del="rmtrash" Removing files in Download directory: # Using autojump$ j Down$ del ./* You can find more keyboard shortcuts for Mac here. You can use taskworrior to manage your todo-list from the command line. If you are Homebrew user: $ brew install task You can find other OS installations from this page. You can find a quick demonstration, best practices and example commands in the doc. $ task add Buy milkCreated task 1.$ task listID Description-- -----------1 Buy milk Use +/ - to add/delete tags. $ task add Buy cake +shopping -lunch Use project: to add Project. $ task add Update a file project: 'Medium article A' Use task ID modify to modify a list. $ task modify 1 Buy milk and bread Use task ID done when you complete a task. $ task 1 done pipes.sh is an animated terminal screensaver. You can install it using Homebrew: $ brew install pipes-sh Find out the options: $ pipes.sh -hUsage: pipes.sh [OPTION]...Animated pipes terminal screensaver. -p [1-] number of pipes (D=1). -t [0-9] type of pipes, can be used more than once (D=0). -c [0-7] color of pipes, can be used more than once (D=1 2 3 4 5 6 7 0). -t c[16 chars] custom type of pipes. -f [20-100] framerate (D=75). -s [5-15] probability of a straight fitting (D=13). -r LIMIT reset after x characters, 0 if no limit (D=2000). -R randomize starting position and direction. -B no bold effect. -C no color. -K pipes keep their color and type when hitting the screen edge. -h help (this screen). -v print version number. You can change the number of pipes using the -p option and the type of pipes using the -t option, etc. $ pipes.sh -p4 -t2 When you press any key, it stops. You can install cmatrix if you are fun of Matrix movies. $ brew install cmatrix# run cmatrix$ cmatrix You need to press Ctrl-c to stop the screen saver. I created the title image with FIGlet. FIGlet is a program for making large letters out of ordinary texts. $ brew install figlet$ printf "\e[92m" && figlet -f standard "Terminal Tips" printf "\e[92m" sets the output color. You can print your terminal color code. $ for code in {30..37}; do \echo -en "\e[${code}m"'\\e['"$code"'m'"\e[0m"; \echo -en " \e[$code;1m"'\\e['"$code"';1m'"\e[0m"; \echo -en " \e[$code;3m"'\\e['"$code"';3m'"\e[0m"; \echo -en " \e[$code;4m"'\\e['"$code"';4m'"\e[0m"; \echo -e " \e[$((code+60))m"'\\e['"$((code+60))"'m'"\e[0m"; \done Now you can change the color using one of the colors. -f standard sets the font. You can select a wide variety of fonts. You can print the weather report on your terminal using wttr.in. $ curl wttr.in/CityName If you want to find the weather for your current location, run curl wttr.in. You can find more options: $ curl wttr.in/:help You can add an alias to your .zshrc. For ZSH, you need to add \ to escape a special character like ?. # weatheralias we='curl wttr.in/Tokyo' #current, narrow, quiet, no Followalias we1='curl wttr.in/Tokyo\?1nqF' #+1day, narrow, quiet, no Followalias we2='curl wttr.in/Tokyo\?2nqF' #+2days, same as above macOS is based on the Unix operating system and has almost the same commands as Linux. I already mentioned the dir command before. Let me list more commands which you use regularly. You can display a calendar on your terminal. # Current month calendar$ cal# Yearly calendar$ cal 2020# Current month + 2 months$ cal -A 2 Try date to display time. ditto copies files and folders. Now, you know how to beef up your terminal. I hope this article will boost your productivity when working in your terminal. And you can have some fun with your terminal or check the weather report and calendar. Find out your favorite themes and plugins to suit your needs. What do you have in your .zshrc file? Please share your GitHub link. 2021–12–17, Starship and Nerd Fonts. 2021–011–20, M1 Pro chip and fira-code-nerd-font 2021–06–11, M1 chip, autojump 2021–5–23, oh-my-zsh error, for M1 chip, Duplicate Tab 2021–03–30, 2021 version 2021–02–22, Fun with Terminal 2021–02–15, Weather Get full access to every story on Medium by becoming a member.
[ { "code": null, "e": 224, "s": 171, "text": "[Latest update 2021–12–17, Starship and Nerd Fonts.]" }, { "code": null, "e": 922, "s": 224, "text": "Table of Contents· Introduction ∘ Homebrew· iTerm2· Zsh· Oh-My-Zsh ∘ Errors ∘ Shortcut for toggling hidden files· Themes ∘ Starship (Updated) ∘ iTerm2 Theme· Oh-My-Zsh and plugins ∘ 1. git plugin ∘ 2. alias ∘ 3. alias dirs and cd - ∘ 4. autojump plugin ∘ 5. brew plugin ∘ 6. zsh-syntax-highlighting plugin ∘ 7. zsh-autosuggestions plugin· Duplicate a tab· Shaping up terminal command history· Creating aliases· Useful commands· Terminal Shortcuts· Task management· Fun with Terminal ∘ Screensaver ∘ FIGlet ∘ Colors ∘ Fonts· Weather reports on your terminal· macOS/Linux commands ∘ Terminal calendars ∘ date ∘ ditto ∘ Common terminal commands· Conclusion· Update Log· Newsletter" }, { "code": null, "e": 1142, "s": 922, "text": "Do you use your terminal all day? Is the terminal the first app you start after restarting your computer? In this article, you will find how to improve your terminal look and practical commands for your day-to-day work." }, { "code": null, "e": 1235, "s": 1142, "text": "[Update] You can install all packages in this article with a line of code, see this article." }, { "code": null, "e": 1258, "s": 1235, "text": "towardsdatascience.com" }, { "code": null, "e": 1376, "s": 1258, "text": "You need to have Homebrew installed. If you don’t have it, you can install it by running the following in a terminal." }, { "code": null, "e": 1476, "s": 1376, "text": "$ /bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)\"" }, { "code": null, "e": 1592, "s": 1476, "text": "Homebrew requires Command Line Tools for Xcode. But if you don’t have it, the installation will install it for you." }, { "code": null, "e": 1653, "s": 1592, "text": "Using a text editor (Vim/VSCode/TextEdit) add the following:" }, { "code": null, "e": 1704, "s": 1653, "text": "# ~/.zshrc export PATH=$(brew --prefix)/bin:$PATH " }, { "code": null, "e": 1726, "s": 1704, "text": "Then source ~/.zshrc:" }, { "code": null, "e": 1739, "s": 1726, "text": "$ . ~/.zshrc" }, { "code": null, "e": 1764, "s": 1739, "text": "This will load ~/.zshrc." }, { "code": null, "e": 1805, "s": 1764, "text": "Run brew help to see if it is installed." }, { "code": null, "e": 1828, "s": 1805, "text": "towardsdatascience.com" }, { "code": null, "e": 1851, "s": 1828, "text": "towardsdatascience.com" }, { "code": null, "e": 1975, "s": 1851, "text": "iTerm2 is a replacement for the terminal and it works on Macs. iTerm2 brings the terminal modern looks with great features." }, { "code": null, "e": 2040, "s": 1975, "text": "You can download iterm2 or you can install iTerm2 with Homebrew." }, { "code": null, "e": 2062, "s": 2040, "text": "$ brew install iterm2" }, { "code": null, "e": 2152, "s": 2062, "text": "Zsh is a shell designed for interactive use and it is also a powerful scripting language." }, { "code": null, "e": 2177, "s": 2152, "text": "You can find your shell." }, { "code": null, "e": 2199, "s": 2177, "text": "$ echo $SHELL/bin/zsh" }, { "code": null, "e": 2226, "s": 2199, "text": "And find your zsh version." }, { "code": null, "e": 2275, "s": 2226, "text": "$ zsh --versionzsh 5.8 (x86_64-apple-darwin20.0)" }, { "code": null, "e": 2327, "s": 2275, "text": "If you don’t have it then install it with Homebrew." }, { "code": null, "e": 2346, "s": 2327, "text": "$ brew install zsh" }, { "code": null, "e": 2391, "s": 2346, "text": "If your shell is not zsh, run the following." }, { "code": null, "e": 2410, "s": 2391, "text": "$ chsh -s /bin/zsh" }, { "code": null, "e": 2464, "s": 2410, "text": "Then restart your iTerm2 or open a new tab in iTerm2." }, { "code": null, "e": 2478, "s": 2464, "text": "$ echo $SHELL" }, { "code": null, "e": 2647, "s": 2478, "text": "Oh-My-Zsh is an open-source, community-driven framework for managing your ZSH configuration. It comes bundled with a ton of helpful functions, helpers, plugins, themes." }, { "code": null, "e": 2794, "s": 2647, "text": "You can install Oh-My-Zsh with running one of the following commands in iTerm. You can install this via the command-line with either curl or wget." }, { "code": null, "e": 2803, "s": 2794, "text": "via curl" }, { "code": null, "e": 2901, "s": 2803, "text": "$ sh -c \"$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)\"" }, { "code": null, "e": 2910, "s": 2901, "text": "via wget" }, { "code": null, "e": 3006, "s": 2910, "text": "$ sh -c \"$(wget -O- https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)\"" }, { "code": null, "e": 3051, "s": 3006, "text": "You can see the terminal prompt change to ~." }, { "code": null, "e": 3069, "s": 3051, "text": "Update Oh-My-Zsh:" }, { "code": null, "e": 3082, "s": 3069, "text": "$ omz update" }, { "code": null, "e": 3196, "s": 3082, "text": "Oh-My-Zsh may overwrites ~/.zshrc, you need to add the path to brew. This time you need to add it before plugins." }, { "code": null, "e": 3239, "s": 3196, "text": "Using a text editor (Vim/VSCode/TextEdit):" }, { "code": null, "e": 3303, "s": 3239, "text": "# ~/.zshrc export PATH=$(brew --prefix)/bin:$PATH plugins=(git)" }, { "code": null, "e": 3337, "s": 3303, "text": "Do you have the following errors?" }, { "code": null, "e": 3340, "s": 3337, "text": "Or" }, { "code": null, "e": 3427, "s": 3340, "text": "You need to change the access permission to these files. These commands will fix them." }, { "code": null, "e": 3464, "s": 3427, "text": "Run the followings on your terminal:" }, { "code": null, "e": 3556, "s": 3464, "text": "$ chmod 755 $(brew --prefix)/share/zsh$ chmod 755 $(brew --prefix)/share/zsh/site-functions" }, { "code": null, "e": 3578, "s": 3556, "text": "And open another tab." }, { "code": null, "e": 3653, "s": 3578, "text": "You can toggle showing hidden files in Finder by Command + Shift + Period." }, { "code": null, "e": 3675, "s": 3653, "text": "betterprogramming.pub" }, { "code": null, "e": 3697, "s": 3675, "text": "betterprogramming.pub" }, { "code": null, "e": 3841, "s": 3697, "text": "In this section, you will find Starship and iTem2 themes. You just need to use one of them. I used to use iTerm2 theme, but now I use Starship." }, { "code": null, "e": 3968, "s": 3841, "text": "I started using the Starship and I quite like it. The Starship is a minimal, blazing-fast, and infinitely customizable prompt." }, { "code": null, "e": 4056, "s": 3968, "text": "After installing iTerm2, Zsh, Oh-My-Zsh as I explained before you install the Starship." }, { "code": null, "e": 4097, "s": 4056, "text": "For example, if you are a Homebrew user:" }, { "code": null, "e": 4121, "s": 4097, "text": "$ brew install starship" }, { "code": null, "e": 4163, "s": 4121, "text": "Add the following to the end of ~/.zshrc:" }, { "code": null, "e": 4183, "s": 4163, "text": "From your terminal:" }, { "code": null, "e": 4232, "s": 4183, "text": "$ echo 'eval \"$(starship init zsh)\"' >> ~/.zshrc" }, { "code": null, "e": 4280, "s": 4232, "text": "Or if you know Vim (or TextEdit for beginners):" }, { "code": null, "e": 4308, "s": 4280, "text": "eval \"$(starship init zsh)\"" }, { "code": null, "e": 4347, "s": 4308, "text": "We change the iTerm2 theme to Minimal." }, { "code": null, "e": 4386, "s": 4347, "text": "We change the color presets to Snazzy:" }, { "code": null, "e": 4453, "s": 4386, "text": "Starship recommends using Nerd-font. You can install it with brew:" }, { "code": null, "e": 4525, "s": 4453, "text": "$ brew tap homebrew/cask-fonts$ brew install --cask font-hack-nerd-font" }, { "code": null, "e": 4566, "s": 4525, "text": "Or you can install Fira Code using brew:" }, { "code": null, "e": 4645, "s": 4566, "text": "$ brew tap homebrew/cask-fonts && brew install --cask font-fira-code-nerd-font" }, { "code": null, "e": 4714, "s": 4645, "text": "Select Hack Nerd Font Mono under iTerm2 Preference > Profile > Text:" }, { "code": null, "e": 4749, "s": 4714, "text": "Or select FiraCode Nerd Font Mono:" }, { "code": null, "e": 4851, "s": 4749, "text": "In one of my npm package directories, it shows Git status, repo version, and Node version with icons." }, { "code": null, "e": 4951, "s": 4851, "text": "The [!] is one of Starship Git status options and it is telling you that the directory is modified." }, { "code": null, "e": 5037, "s": 4951, "text": "If you want to know what’s going in the status bar, use the starship explain command:" }, { "code": null, "e": 5056, "s": 5037, "text": "$ starship explain" }, { "code": null, "e": 5116, "s": 5056, "text": "You can change the prompt using the Starship configuration." }, { "code": null, "e": 5126, "s": 5116, "text": "Powerline" }, { "code": null, "e": 5207, "s": 5126, "text": "iTerm has more than 200 themes. My favorite themes are Cobalt2 and Oceanic next." }, { "code": null, "e": 5230, "s": 5207, "text": "Let’s install Cobalt2." }, { "code": null, "e": 5487, "s": 5230, "text": "Download this repo and drop the cobalt2.zsh-theme file in to the ~/.oh-my-zsh/themes/ directory. Command + C to copy the file and Command + Option + V to cut-paste.Open up your ZSH preferences at ~/.zshrc and change the theme variable to ZSH_THEME=cobalt2." }, { "code": null, "e": 5652, "s": 5487, "text": "Download this repo and drop the cobalt2.zsh-theme file in to the ~/.oh-my-zsh/themes/ directory. Command + C to copy the file and Command + Option + V to cut-paste." }, { "code": null, "e": 5745, "s": 5652, "text": "Open up your ZSH preferences at ~/.zshrc and change the theme variable to ZSH_THEME=cobalt2." }, { "code": null, "e": 5809, "s": 5745, "text": "3. Install Powerline and necessary fonts - one way is using PIP" }, { "code": null, "e": 5848, "s": 5809, "text": "$ pip3 install --user powerline-status" }, { "code": null, "e": 5877, "s": 5848, "text": "You may need to upgrade PIP." }, { "code": null, "e": 5906, "s": 5877, "text": "$ pip3 install --upgrade pip" }, { "code": null, "e": 5983, "s": 5906, "text": "4. Install all necessary fonts by downloading or cloning the git repository." }, { "code": null, "e": 6054, "s": 5983, "text": "$ git clone https://github.com/powerline/fonts$ cd fonts$ ./install.sh" }, { "code": null, "e": 6097, "s": 6054, "text": "If you wish to remove the fonts directory." }, { "code": null, "e": 6116, "s": 6097, "text": "$ ..$ rm -rf fonts" }, { "code": null, "e": 6178, "s": 6116, "text": "5. In iTerm2 access the Preferences pane on the Profiles tab." }, { "code": null, "e": 6271, "s": 6178, "text": "6. Under the Colors tab import the cobalt2.itermcolors file via the Color Presets drop-down." }, { "code": null, "e": 6379, "s": 6271, "text": "7. Under the Text tab change the font for each type (Regular and Non-ASCII) to ‘Inconsolata for Powerline’." }, { "code": null, "e": 6441, "s": 6379, "text": "8. Refresh ZSH by typing source ~/.zshrc on the command line." }, { "code": null, "e": 6458, "s": 6441, "text": "VS Code terminal" }, { "code": null, "e": 6533, "s": 6458, "text": "For your VS Code terminal, you need to add the following to Setting(JSON)." }, { "code": null, "e": 6601, "s": 6533, "text": "{ \"terminal.integrated.fontFamily\":\"Inconsolata for Powerline\",}" }, { "code": null, "e": 6657, "s": 6601, "text": "If you feel a bit adventurous, try powerlevel10k theme." }, { "code": null, "e": 6690, "s": 6657, "text": "Oh-My-Zsh has built-in commands." }, { "code": null, "e": 6779, "s": 6690, "text": "Oh-My-Zsh’s power comes with its plugins. There are more than 260 plugins are available." }, { "code": null, "e": 6948, "s": 6779, "text": "The zsh git plugin provides many aliases and a few useful functions. To install it, add git to the plugins array in your .zshrc file. Open .zshrc with your text editor:" }, { "code": null, "e": 6962, "s": 6948, "text": "plugins=(git)" }, { "code": null, "e": 7021, "s": 6962, "text": "The following is an example workflow using the git plugin." }, { "code": null, "e": 7510, "s": 7021, "text": "# make a directory and cd into it$ mkdir -p Datascience/terminal-article && cd $_# create a new git repo$ git initInitialized empty Git repository in /Users/shinokada/DataScience/terminal-article/.git/# Add a README.md$ echo \"# Terminal-article\" >> README.md# git add .$ ga .# git commit -m $ gcmsg \"First commit\"[master (root-commit) 128f2b9] First commit1 file changed, 1 insertion(+)create mode 100644 README.md# git remote add$ gra origin git@github.com:shinokada/terminal-article.git" }, { "code": null, "e": 7652, "s": 7510, "text": "# modify a file$ echo \"more fix\" >> README.md# git status$ gst# git add .$ ga .# git commit and message$ gcmsg \"Update\"# git push origin$ ggp" }, { "code": null, "e": 7741, "s": 7652, "text": "You can use alias to see all your alias commands. Please see this page for more aliases." }, { "code": null, "e": 8015, "s": 7741, "text": "You use aliases cd -, cd -2, etc. with the dirs command as you can see in the above image. The dirs displays the contents of the directory stack. The current directory is always the \"top\" of the directory stack. cd -2 changes directory to the second in the directory stack." }, { "code": null, "e": 8215, "s": 8015, "text": "autojump plugin loads the autojump navigation tool. autojump is a faster way to navigate your filesystem. It works by maintaining a database of the directories you use the most from the command line." }, { "code": null, "e": 8249, "s": 8215, "text": "First, install it on your Mac OS." }, { "code": null, "e": 8314, "s": 8249, "text": "$ brew install autojump# or for port user$ port install autojump" }, { "code": null, "e": 8380, "s": 8314, "text": "To use it, add autojump to the plugins array in your .zshrc file:" }, { "code": null, "e": 8439, "s": 8380, "text": "# no comma between plugins required plugins=(git autojump)" }, { "code": null, "e": 8505, "s": 8439, "text": "Add the following to the end of ~/.zshrc (Intel x86_64 or arm64):" }, { "code": null, "e": 8603, "s": 8505, "text": "[ -f $(brew --prefix)/etc/profile.d/autojump.sh ] && . $(brew --prefix)/etc/profile.d/autojump.sh" }, { "code": null, "e": 8666, "s": 8603, "text": "Reload .zshrc by so .zshrc on your terminal or open a new tab." }, { "code": null, "e": 8783, "s": 8666, "text": "By changing your directory, autojump records directories. You type j + first few letters of a directory. e.g j Data." }, { "code": null, "e": 8846, "s": 8783, "text": "The brew plugin adds several aliases for common brew commands." }, { "code": null, "e": 8908, "s": 8846, "text": "To use it, add brew to the plugins array of your .zshrc file:" }, { "code": null, "e": 8936, "s": 8908, "text": "plugins=(git autojump brew)" }, { "code": null, "e": 8999, "s": 8936, "text": "After adding brew to plugins, the following message will come." }, { "code": null, "e": 9023, "s": 8999, "text": "You can start using it." }, { "code": null, "e": 9045, "s": 9023, "text": "Create your own alias" }, { "code": null, "e": 9119, "s": 9045, "text": "In .zshrc add the following. buou will update, show outdated and upgrade." }, { "code": null, "e": 9248, "s": 9119, "text": "# brew update && brew outdated && brew upgrade ➡️ buoualias buou=\"brew update && brew outdated && brew upgrade && brew cleanup\"" }, { "code": null, "e": 9340, "s": 9248, "text": "Install zsh-syntax-highlighting by cloning the repository in oh-my-zsh’s plugins directory:" }, { "code": null, "e": 9476, "s": 9340, "text": "$ git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting" }, { "code": null, "e": 9576, "s": 9476, "text": "Note that zsh-syntax-highlighting must be the last plugin sourced. Activate the plugin in ~/.zshrc:" }, { "code": null, "e": 9629, "s": 9576, "text": "plugins=(some other plugins zsh-syntax-highlighting)" }, { "code": null, "e": 9683, "s": 9629, "text": "Restart iTerm2, open a new tab, or run source .zshrc." }, { "code": null, "e": 9691, "s": 9683, "text": "Before:" }, { "code": null, "e": 9698, "s": 9691, "text": "After:" }, { "code": null, "e": 9759, "s": 9698, "text": "The zsh-autosuggestions is fish-like autosuggestion for zsh." }, { "code": null, "e": 9847, "s": 9759, "text": "Clone the repository into $ZSH_CUSTOM/plugins (by default ~/.oh-my-zsh/custom/plugins):" }, { "code": null, "e": 9935, "s": 9847, "text": "Clone the repository into $ZSH_CUSTOM/plugins (by default ~/.oh-my-zsh/custom/plugins):" }, { "code": null, "e": 10059, "s": 9935, "text": "$ git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions" }, { "code": null, "e": 10113, "s": 10059, "text": "2. Add the plugin to the list of plugins in ~/.zshrc:" }, { "code": null, "e": 10176, "s": 10113, "text": "plugins=(git brew zsh-syntax-highlighting zsh-autosuggestions)" }, { "code": null, "e": 10236, "s": 10176, "text": "3. Start a new terminal session or open a new terminal tab." }, { "code": null, "e": 10254, "s": 10236, "text": "$ source ~/.zshrc" }, { "code": null, "e": 10400, "s": 10254, "text": "When you press CMD+T, iTerm will open a new tab and the location is the ~ or home directory. I’d like to duplicate a tab with the same directory." }, { "code": null, "e": 10602, "s": 10400, "text": "On your iTerm, press CMD+, to open settings. Press Keys and select Key Bindings. Click + sign at the bottom left and choose your keyboard shortcut, like Shift+CMD+T. Select Duplicate Tab in the action." }, { "code": null, "e": 10799, "s": 10602, "text": "History is stored in ~/.zsh_history or ~/.bash_history or ~/.history depending on your shell. History is stored for 1000 or 2000 lines depending on your system. You can find the number of history:" }, { "code": null, "e": 10888, "s": 10799, "text": "$ echo $HISTSIZE 50000$ echo $HISTFILE/Users/shinokada/.zsh_history$ echo $SAVEHIST10000" }, { "code": null, "e": 11097, "s": 10888, "text": "HISTSIZE is the maximum number of lines that are kept in a session and SAVEHIST is the maximum number of lines that are kept in the history file. HISTFILE is the file name where your system is saving history." }, { "code": null, "e": 11161, "s": 11097, "text": "You can change these numbers by adding the following to .zshrc." }, { "code": null, "e": 11188, "s": 11161, "text": "HISTSIZE=5000SAVEHIST=5000" }, { "code": null, "e": 11419, "s": 11188, "text": "reverse-i-search allows you to search for a command from the history file. Press CTRL+r to start it and type whatever you remember to search. If you keep pressing CTRL+r, the terminal searches the next command in the history file." }, { "code": null, "e": 11486, "s": 11419, "text": "You can see all your command history using a bash command history." }, { "code": null, "e": 11806, "s": 11486, "text": "# shows all command history$ history# shows first 10 commands$ history | head# shows last 10 commands$ hisotry | tail# shows less history$ history | less# Use grep to search your command history$ history | grep Search-word# Use grep to do a case-insensitive search of your command history$ hisotry | grep -i search-word" }, { "code": null, "e": 11897, "s": 11806, "text": "In order to remove commands from your history list, you add the following to your .zshrc :" }, { "code": null, "e": 11922, "s": 11897, "text": "setopt HIST_IGNORE_SPACE" }, { "code": null, "e": 12020, "s": 11922, "text": "This removes command lines from the history list when the first character on the line is a space." }, { "code": null, "e": 12111, "s": 12020, "text": "# This won't work$ cd ~# This will work because there is a space before the command$ cd ~" }, { "code": null, "e": 12330, "s": 12111, "text": "You may not want common commands in the command history. Adding the following to zshrc prevent ll ls la cd man scp vim nvim less ping open file which whois drill uname md5sum traceroute commands in the command history." }, { "code": null, "e": 13046, "s": 12330, "text": "zshaddhistory() { local line=${1%%$'\\n'} local cmd=${line%% *} # Only those that satisfy all of the following conditions are added to the history [[ ${#line} -ge 5 && ${cmd} != ll && ${cmd} != ls && ${cmd} != la && ${cmd} != cd && ${cmd} != man && ${cmd} != scp && ${cmd} != vim && ${cmd} != nvim && ${cmd} != less && ${cmd} != ping && ${cmd} != open && ${cmd} != file && ${cmd} != which && ${cmd} != whois && ${cmd} != drill && ${cmd} != uname && ${cmd} != md5sum && ${cmd} != pacman && ${cmd} != xdg-open && ${cmd} != traceroute && ${cmd} != speedtest-cli ]]}zshaddhistory" }, { "code": null, "e": 13118, "s": 13046, "text": "As I showed before withbuou, you can add your own alias to .zshrc file." }, { "code": null, "e": 13338, "s": 13118, "text": "# brew update && brew outdated && brew upgradealias buou=\"brew update && brew outdated && brew upgrade && brew cleanup\"# npm outdated -g --depth=0 && npm update -galias npmou=\"npm outdated -g --depth=0 && npm update -g\"" }, { "code": null, "e": 13535, "s": 13338, "text": "I havevirtualenv and virtualenvwrapper installed. And the following aliases allow me to use note to start a Jupyter environment and Jupyter notebook. lab will start the environment and Jupyterlab." }, { "code": null, "e": 13718, "s": 13535, "text": "# start jupyter environmentalias wj='workon jupyter'# start jupyter notebookalias note='workon jupyter && jupyter notebook'# start jupyterlabalias lab='workon jupyter && jupyter lab'" }, { "code": null, "e": 13824, "s": 13718, "text": "# Repeat the last command$ !!# Clear the screen$ clear # Or you can clear the screen with CTRL+l, as well" }, { "code": null, "e": 13985, "s": 13824, "text": "Instead of using the rm command, I suggest using rmtrash. It will move the file to OS X’s Trash rather than removing permanently. You can install it using brew:" }, { "code": null, "e": 14008, "s": 13985, "text": "$ brew install rmtrash" }, { "code": null, "e": 14051, "s": 14008, "text": "And create an alias in your ~/.zshrc file:" }, { "code": null, "e": 14073, "s": 14051, "text": "alias del=\"rmtrash\"" }, { "code": null, "e": 14111, "s": 14073, "text": "Removing files in Download directory:" }, { "code": null, "e": 14145, "s": 14111, "text": "# Using autojump$ j Down$ del ./*" }, { "code": null, "e": 14196, "s": 14145, "text": "You can find more keyboard shortcuts for Mac here." }, { "code": null, "e": 14268, "s": 14196, "text": "You can use taskworrior to manage your todo-list from the command line." }, { "code": null, "e": 14294, "s": 14268, "text": "If you are Homebrew user:" }, { "code": null, "e": 14314, "s": 14294, "text": "$ brew install task" }, { "code": null, "e": 14366, "s": 14314, "text": "You can find other OS installations from this page." }, { "code": null, "e": 14450, "s": 14366, "text": "You can find a quick demonstration, best practices and example commands in the doc." }, { "code": null, "e": 14535, "s": 14450, "text": "$ task add Buy milkCreated task 1.$ task listID Description-- -----------1 Buy milk" }, { "code": null, "e": 14564, "s": 14535, "text": "Use +/ - to add/delete tags." }, { "code": null, "e": 14601, "s": 14564, "text": "$ task add Buy cake +shopping -lunch" }, { "code": null, "e": 14630, "s": 14601, "text": "Use project: to add Project." }, { "code": null, "e": 14683, "s": 14630, "text": "$ task add Update a file project: 'Medium article A'" }, { "code": null, "e": 14720, "s": 14683, "text": "Use task ID modify to modify a list." }, { "code": null, "e": 14755, "s": 14720, "text": "$ task modify 1 Buy milk and bread" }, { "code": null, "e": 14798, "s": 14755, "text": "Use task ID done when you complete a task." }, { "code": null, "e": 14812, "s": 14798, "text": "$ task 1 done" }, { "code": null, "e": 14893, "s": 14812, "text": "pipes.sh is an animated terminal screensaver. You can install it using Homebrew:" }, { "code": null, "e": 14917, "s": 14893, "text": "$ brew install pipes-sh" }, { "code": null, "e": 14939, "s": 14917, "text": "Find out the options:" }, { "code": null, "e": 15557, "s": 14939, "text": "$ pipes.sh -hUsage: pipes.sh [OPTION]...Animated pipes terminal screensaver. -p [1-] number of pipes (D=1). -t [0-9] type of pipes, can be used more than once (D=0). -c [0-7] color of pipes, can be used more than once (D=1 2 3 4 5 6 7 0). -t c[16 chars] custom type of pipes. -f [20-100] framerate (D=75). -s [5-15] probability of a straight fitting (D=13). -r LIMIT reset after x characters, 0 if no limit (D=2000). -R randomize starting position and direction. -B no bold effect. -C no color. -K pipes keep their color and type when hitting the screen edge. -h help (this screen). -v print version number." }, { "code": null, "e": 15660, "s": 15557, "text": "You can change the number of pipes using the -p option and the type of pipes using the -t option, etc." }, { "code": null, "e": 15679, "s": 15660, "text": "$ pipes.sh -p4 -t2" }, { "code": null, "e": 15713, "s": 15679, "text": "When you press any key, it stops." }, { "code": null, "e": 15770, "s": 15713, "text": "You can install cmatrix if you are fun of Matrix movies." }, { "code": null, "e": 15815, "s": 15770, "text": "$ brew install cmatrix# run cmatrix$ cmatrix" }, { "code": null, "e": 15866, "s": 15815, "text": "You need to press Ctrl-c to stop the screen saver." }, { "code": null, "e": 15973, "s": 15866, "text": "I created the title image with FIGlet. FIGlet is a program for making large letters out of ordinary texts." }, { "code": null, "e": 16050, "s": 15973, "text": "$ brew install figlet$ printf \"\\e[92m\" && figlet -f standard \"Terminal Tips\"" }, { "code": null, "e": 16129, "s": 16050, "text": "printf \"\\e[92m\" sets the output color. You can print your terminal color code." }, { "code": null, "e": 16427, "s": 16129, "text": "$ for code in {30..37}; do \\echo -en \"\\e[${code}m\"'\\\\e['\"$code\"'m'\"\\e[0m\"; \\echo -en \" \\e[$code;1m\"'\\\\e['\"$code\"';1m'\"\\e[0m\"; \\echo -en \" \\e[$code;3m\"'\\\\e['\"$code\"';3m'\"\\e[0m\"; \\echo -en \" \\e[$code;4m\"'\\\\e['\"$code\"';4m'\"\\e[0m\"; \\echo -e \" \\e[$((code+60))m\"'\\\\e['\"$((code+60))\"'m'\"\\e[0m\"; \\done" }, { "code": null, "e": 16481, "s": 16427, "text": "Now you can change the color using one of the colors." }, { "code": null, "e": 16548, "s": 16481, "text": "-f standard sets the font. You can select a wide variety of fonts." }, { "code": null, "e": 16613, "s": 16548, "text": "You can print the weather report on your terminal using wttr.in." }, { "code": null, "e": 16637, "s": 16613, "text": "$ curl wttr.in/CityName" }, { "code": null, "e": 16714, "s": 16637, "text": "If you want to find the weather for your current location, run curl wttr.in." }, { "code": null, "e": 16741, "s": 16714, "text": "You can find more options:" }, { "code": null, "e": 16762, "s": 16741, "text": "$ curl wttr.in/:help" }, { "code": null, "e": 16864, "s": 16762, "text": "You can add an alias to your .zshrc. For ZSH, you need to add \\ to escape a special character like ?." }, { "code": null, "e": 17066, "s": 16864, "text": "# weatheralias we='curl wttr.in/Tokyo' #current, narrow, quiet, no Followalias we1='curl wttr.in/Tokyo\\?1nqF' #+1day, narrow, quiet, no Followalias we2='curl wttr.in/Tokyo\\?2nqF' #+2days, same as above" }, { "code": null, "e": 17248, "s": 17066, "text": "macOS is based on the Unix operating system and has almost the same commands as Linux. I already mentioned the dir command before. Let me list more commands which you use regularly." }, { "code": null, "e": 17293, "s": 17248, "text": "You can display a calendar on your terminal." }, { "code": null, "e": 17386, "s": 17293, "text": "# Current month calendar$ cal# Yearly calendar$ cal 2020# Current month + 2 months$ cal -A 2" }, { "code": null, "e": 17412, "s": 17386, "text": "Try date to display time." }, { "code": null, "e": 17444, "s": 17412, "text": "ditto copies files and folders." }, { "code": null, "e": 17655, "s": 17444, "text": "Now, you know how to beef up your terminal. I hope this article will boost your productivity when working in your terminal. And you can have some fun with your terminal or check the weather report and calendar." }, { "code": null, "e": 17717, "s": 17655, "text": "Find out your favorite themes and plugins to suit your needs." }, { "code": null, "e": 17786, "s": 17717, "text": "What do you have in your .zshrc file? Please share your GitHub link." }, { "code": null, "e": 17823, "s": 17786, "text": "2021–12–17, Starship and Nerd Fonts." }, { "code": null, "e": 17872, "s": 17823, "text": "2021–011–20, M1 Pro chip and fira-code-nerd-font" }, { "code": null, "e": 17902, "s": 17872, "text": "2021–06–11, M1 chip, autojump" }, { "code": null, "e": 17957, "s": 17902, "text": "2021–5–23, oh-my-zsh error, for M1 chip, Duplicate Tab" }, { "code": null, "e": 17982, "s": 17957, "text": "2021–03–30, 2021 version" }, { "code": null, "e": 18012, "s": 17982, "text": "2021–02–22, Fun with Terminal" }, { "code": null, "e": 18032, "s": 18012, "text": "2021–02–15, Weather" } ]
How to Use Pyspark For Your Machine Learning Project | by François St-Amant | Towards Data Science
Pyspark is a Python API that supports Apache Spark, a distributed framework made for handling big data analysis. It’s an amazing framework to use when you are working with huge datasets, and it’s becoming a must-have skill for any data scientist. In this tutorial, I will present how to use Pyspark to do exactly what you are used to see in a Kaggle notebook (cleaning, EDA, feature engineering and building models). I used a database containing information about customers for a telecom company. The objective is to predict which clients will leave (Churn) in the upcoming three months. The CSV file with the data contains more than 800,000 rows and 8 features, as well as a binary Churn variable. The goal here is not to find the best solution. It’s rather to show you how to work with Pyspark. Along the way I will try to present many functions that can be used for all stages of your machine learning project! Let’s begin by creating a SparkSession, which is the entry point to any Spark functionality. import pysparkfrom pyspark.sql import SparkSessionspark = SparkSession.builder.master("local[4]")\ .appName("test").getOrCreate() Here is how to read a CSV using Pyspark. df=spark.read.csv('train.csv',header=True,sep= ",",inferSchema=True) Here is what the dataframe looks like. The Pyspark.sql module allows you to do in Pyspark pretty much anything that can be done with SQL. For instance, let’s begin by cleaning the data a bit. First, as you can see in the image above, we have some Null values. I will drop all rows that contain a null value. df = df.na.drop() Then, thewhen/otherwise functions allow you to filter a column and assign a new value based on what is found in each row. Here for instance, I replace Male and Female with 0 and 1 for the Sex variable. from pyspark.sql.functions import whendf = df.withColumn("gender",when(df["gender"]=='M',0).otherwise(1)) Once the data is all cleaned up, many SQL-like functions can help analyze it. For instance, the groupBy function allows you to group values and return count, sum or whatever for each category. Let’s see how many data points belong to each class for the churn variable. df.groupBy('churnIn3Month').count().show() We have imbalanced classes here. While I will not do anything about it in this tutorial, in an upcoming one, I will show you how to deal with imbalanced classes using Pyspark, doing things like undersampling, oversampling and SMOTE. Another interesting thing to do is to look at how certain features vary between the two groups (clients that left and the ones that did not). Here is one interesting result I found. from pyspark.sql.functions import avgdf.select("phoneBalance","churnIn3Month").\ groupBy("ChurnIn3Month").agg(avg("phoneBalance")) We see that customers that left had on average a much smaller phone balance, which means their phone was much closer to being paid entirely (which makes it easier to leave a phone company of course). Now, let’s look at a correlation matrix. I created it using the correlation function in Pyspark. I also cheated a bit and used Pandas here, just to easily create something much more visual. from pyspark.ml.stat import Correlationx=df.columns[2:11]corr_plot = pd.DataFrame()for i in x: corr=[] for j in x: corr.append(round(df.stat.corr(i,j),2)) corr_plot = pd.concat([corr_plot,pd.Series(corr)],axis=1)corr_plot.columns=xcorr_plot.insert(0,'',x)corr_plot.set_index('') Again, phoneBalance has the strongest correlation with the churn variable. Considering the results from above, I decided to create a new variable, which will be the square of thephoneBalance variable. Here is how to do that with Pyspark. from pyspark.sql.functions import col, powdf = df.withColumn('phoneBalance2',pow(col('phoneBalance'),2)) The withColumn function allows you to add columns to your pyspark dataframe. Super useful! The Machine Learning library in Pyspark certainly is not yet to the standard of Scikit Learn. With that being said, you can still do a lot of stuff with it. The first thing you have to do however is to create a vector containing all your features. All the methods we will use require it. from pyspark.ml.feature import VectorAssemblerignore=['churnIn3Month', 'ID','_c0']vectorAssembler = VectorAssembler(inputCols=[x for x in df.columns if x not in ignore], outputCol = 'features')new_df = vectorAssembler.transform(df)new_df = new_df.select(['features', 'churnIn3Month']) Then, let’s split the data into a training and validation set. train, test = new_df.randomSplit([0.75, 0.25], seed = 12345) Alright, now let’s build some models. I will only show a couple models, just to give you an idea of how to do it with Pyspark. from pyspark.ml.classification import LogisticRegressionlr = LogisticRegression(featuresCol = 'features', labelCol='churnIn3Month')lr_model = lr.fit(train) We can look at the ROC curve for the model. As a reminder, the closer the AUC (area under the curve) is to 1, the better the model is at distinguishing between classes. import matplotlib.pyplot as pltplt.plot(lr_model.summary.roc.select('FPR').collect(), lr_model.summary.roc.select('TPR').collect())plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.show()lr_model.summary.areaUnderROC Let’s do one more model, to showcase how easy it can be to fit models once the data is put in the right format for Pyspark, i.e. vectors. Here is how to create a random forest model. from pyspark.ml.classification import RandomForestClassifierrf = RandomForestClassifier(featuresCol = 'features', labelCol = 'churnIn3Month')rf_model = rf.fit(train) And here is how to get the AUC for the model: from pyspark.ml.evaluation import BinaryClassificationEvaluatorpredictions = rf_model.transform(test)auc = BinaryClassificationEvaluator().setLabelCol('churnIn3Month')print('AUC of the model:' + str(auc.evaluate(predictions))) Both models are very similiar, but the results suggest that the logistic regression model is slightly better in our case. Scikit Learn is fantastic and will perform admirably, for as long as you are not working with too much data. Sadly, the bigger your projects, the more likely it is that you will need Spark. Thankfully, as you have seen here, the learning curve to start using Pyspark really isn’t that steep, especially if you are familiar with Python and SQL. In my mind, the main weakness of Pyspark is data visualization, but hopefully with time that will change! There you have it. This article should serve as a great starting point for anyone that wants to do Machine Learning with Pyspark. I hope you liked it and thanks for reading!
[ { "code": null, "e": 418, "s": 171, "text": "Pyspark is a Python API that supports Apache Spark, a distributed framework made for handling big data analysis. It’s an amazing framework to use when you are working with huge datasets, and it’s becoming a must-have skill for any data scientist." }, { "code": null, "e": 588, "s": 418, "text": "In this tutorial, I will present how to use Pyspark to do exactly what you are used to see in a Kaggle notebook (cleaning, EDA, feature engineering and building models)." }, { "code": null, "e": 870, "s": 588, "text": "I used a database containing information about customers for a telecom company. The objective is to predict which clients will leave (Churn) in the upcoming three months. The CSV file with the data contains more than 800,000 rows and 8 features, as well as a binary Churn variable." }, { "code": null, "e": 1085, "s": 870, "text": "The goal here is not to find the best solution. It’s rather to show you how to work with Pyspark. Along the way I will try to present many functions that can be used for all stages of your machine learning project!" }, { "code": null, "e": 1178, "s": 1085, "text": "Let’s begin by creating a SparkSession, which is the entry point to any Spark functionality." }, { "code": null, "e": 1314, "s": 1178, "text": "import pysparkfrom pyspark.sql import SparkSessionspark = SparkSession.builder.master(\"local[4]\")\\ .appName(\"test\").getOrCreate()" }, { "code": null, "e": 1355, "s": 1314, "text": "Here is how to read a CSV using Pyspark." }, { "code": null, "e": 1424, "s": 1355, "text": "df=spark.read.csv('train.csv',header=True,sep= \",\",inferSchema=True)" }, { "code": null, "e": 1463, "s": 1424, "text": "Here is what the dataframe looks like." }, { "code": null, "e": 1562, "s": 1463, "text": "The Pyspark.sql module allows you to do in Pyspark pretty much anything that can be done with SQL." }, { "code": null, "e": 1732, "s": 1562, "text": "For instance, let’s begin by cleaning the data a bit. First, as you can see in the image above, we have some Null values. I will drop all rows that contain a null value." }, { "code": null, "e": 1750, "s": 1732, "text": "df = df.na.drop()" }, { "code": null, "e": 1952, "s": 1750, "text": "Then, thewhen/otherwise functions allow you to filter a column and assign a new value based on what is found in each row. Here for instance, I replace Male and Female with 0 and 1 for the Sex variable." }, { "code": null, "e": 2058, "s": 1952, "text": "from pyspark.sql.functions import whendf = df.withColumn(\"gender\",when(df[\"gender\"]=='M',0).otherwise(1))" }, { "code": null, "e": 2136, "s": 2058, "text": "Once the data is all cleaned up, many SQL-like functions can help analyze it." }, { "code": null, "e": 2327, "s": 2136, "text": "For instance, the groupBy function allows you to group values and return count, sum or whatever for each category. Let’s see how many data points belong to each class for the churn variable." }, { "code": null, "e": 2370, "s": 2327, "text": "df.groupBy('churnIn3Month').count().show()" }, { "code": null, "e": 2603, "s": 2370, "text": "We have imbalanced classes here. While I will not do anything about it in this tutorial, in an upcoming one, I will show you how to deal with imbalanced classes using Pyspark, doing things like undersampling, oversampling and SMOTE." }, { "code": null, "e": 2785, "s": 2603, "text": "Another interesting thing to do is to look at how certain features vary between the two groups (clients that left and the ones that did not). Here is one interesting result I found." }, { "code": null, "e": 2925, "s": 2785, "text": "from pyspark.sql.functions import avgdf.select(\"phoneBalance\",\"churnIn3Month\").\\ groupBy(\"ChurnIn3Month\").agg(avg(\"phoneBalance\"))" }, { "code": null, "e": 3125, "s": 2925, "text": "We see that customers that left had on average a much smaller phone balance, which means their phone was much closer to being paid entirely (which makes it easier to leave a phone company of course)." }, { "code": null, "e": 3315, "s": 3125, "text": "Now, let’s look at a correlation matrix. I created it using the correlation function in Pyspark. I also cheated a bit and used Pandas here, just to easily create something much more visual." }, { "code": null, "e": 3610, "s": 3315, "text": "from pyspark.ml.stat import Correlationx=df.columns[2:11]corr_plot = pd.DataFrame()for i in x: corr=[] for j in x: corr.append(round(df.stat.corr(i,j),2)) corr_plot = pd.concat([corr_plot,pd.Series(corr)],axis=1)corr_plot.columns=xcorr_plot.insert(0,'',x)corr_plot.set_index('')" }, { "code": null, "e": 3685, "s": 3610, "text": "Again, phoneBalance has the strongest correlation with the churn variable." }, { "code": null, "e": 3848, "s": 3685, "text": "Considering the results from above, I decided to create a new variable, which will be the square of thephoneBalance variable. Here is how to do that with Pyspark." }, { "code": null, "e": 3953, "s": 3848, "text": "from pyspark.sql.functions import col, powdf = df.withColumn('phoneBalance2',pow(col('phoneBalance'),2))" }, { "code": null, "e": 4044, "s": 3953, "text": "The withColumn function allows you to add columns to your pyspark dataframe. Super useful!" }, { "code": null, "e": 4201, "s": 4044, "text": "The Machine Learning library in Pyspark certainly is not yet to the standard of Scikit Learn. With that being said, you can still do a lot of stuff with it." }, { "code": null, "e": 4332, "s": 4201, "text": "The first thing you have to do however is to create a vector containing all your features. All the methods we will use require it." }, { "code": null, "e": 4636, "s": 4332, "text": "from pyspark.ml.feature import VectorAssemblerignore=['churnIn3Month', 'ID','_c0']vectorAssembler = VectorAssembler(inputCols=[x for x in df.columns if x not in ignore], outputCol = 'features')new_df = vectorAssembler.transform(df)new_df = new_df.select(['features', 'churnIn3Month'])" }, { "code": null, "e": 4699, "s": 4636, "text": "Then, let’s split the data into a training and validation set." }, { "code": null, "e": 4760, "s": 4699, "text": "train, test = new_df.randomSplit([0.75, 0.25], seed = 12345)" }, { "code": null, "e": 4887, "s": 4760, "text": "Alright, now let’s build some models. I will only show a couple models, just to give you an idea of how to do it with Pyspark." }, { "code": null, "e": 5068, "s": 4887, "text": "from pyspark.ml.classification import LogisticRegressionlr = LogisticRegression(featuresCol = 'features', labelCol='churnIn3Month')lr_model = lr.fit(train)" }, { "code": null, "e": 5237, "s": 5068, "text": "We can look at the ROC curve for the model. As a reminder, the closer the AUC (area under the curve) is to 1, the better the model is at distinguishing between classes." }, { "code": null, "e": 5481, "s": 5237, "text": "import matplotlib.pyplot as pltplt.plot(lr_model.summary.roc.select('FPR').collect(), lr_model.summary.roc.select('TPR').collect())plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.show()lr_model.summary.areaUnderROC" }, { "code": null, "e": 5664, "s": 5481, "text": "Let’s do one more model, to showcase how easy it can be to fit models once the data is put in the right format for Pyspark, i.e. vectors. Here is how to create a random forest model." }, { "code": null, "e": 5858, "s": 5664, "text": "from pyspark.ml.classification import RandomForestClassifierrf = RandomForestClassifier(featuresCol = 'features', labelCol = 'churnIn3Month')rf_model = rf.fit(train)" }, { "code": null, "e": 5904, "s": 5858, "text": "And here is how to get the AUC for the model:" }, { "code": null, "e": 6131, "s": 5904, "text": "from pyspark.ml.evaluation import BinaryClassificationEvaluatorpredictions = rf_model.transform(test)auc = BinaryClassificationEvaluator().setLabelCol('churnIn3Month')print('AUC of the model:' + str(auc.evaluate(predictions)))" }, { "code": null, "e": 6253, "s": 6131, "text": "Both models are very similiar, but the results suggest that the logistic regression model is slightly better in our case." }, { "code": null, "e": 6703, "s": 6253, "text": "Scikit Learn is fantastic and will perform admirably, for as long as you are not working with too much data. Sadly, the bigger your projects, the more likely it is that you will need Spark. Thankfully, as you have seen here, the learning curve to start using Pyspark really isn’t that steep, especially if you are familiar with Python and SQL. In my mind, the main weakness of Pyspark is data visualization, but hopefully with time that will change!" } ]
Code Generation and Optimization - GeeksforGeeks
21 Jan, 2014 In the following code: a = b * c + g; d = b * c * e; it may be worth transforming the code to: tmp = b * c; a = tmp + g; d = tmp * e; 4*j is common subexpression elimination so B is true. 5*i can be moved out of inner loop so can be i%2. Means, A is true as we have loop invariant computation. Next, 4*j as well as 5*i can be replaced with a = - 4; before j loop then a = a + 4; where 4*j is computed, likewise for 5*i. C is true as there is scope of strength reduction. By choice elimination, we have D. 1. i = 1 2. j = 1 3. t1 = 5 * i 4. t2 = t1 + j 5. t3 = 4 * t2 6. t4 = t3 7. a[t4] = –1 8. j = j + 1 9. if j <= 5 goto(3) 10. i = i + 1 11. if i < 5 goto(2) x = u - t; y = x * v; x = y + w; y = t - z; y = x * y; x = u - t; x = y + w; y = x * v; y = t - z; y = x * y x1 = u - t; y1 = x1 * v; x2 = y1 + w; y2 = t - z; y3 = x2 * y2; S → n B → BbB S → L.L { S.val=L1.val + L2.val / 2^L2.nb } S → L { S.val = L.val } L → LB { L.val = 2 * L.val + B.val , L.nb = L.nb + B.nb } L → B { L.val = B.val , L.nb = B.nb } B → 0 { B.val = 0 , B.nb = 1 } B → 1 { B.val = 1 , B.nb = 1 } Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Product Based Companies Axios in React: A Guide for Beginners How to set background images in ReactJS ? How to Install Flutter on Visual Studio Code? How to calculate MOVING AVERAGE in a Pandas DataFrame? How to Show Images on Click using HTML ? What is the difference between position:sticky and position:fixed in CSS ? Microsoft Interview Experience for Internship (Via Engage) Retrofit with Kotlin Coroutine in Android Difference between sh and bash
[ { "code": null, "e": 25218, "s": 25190, "text": "\n21 Jan, 2014" }, { "code": null, "e": 25355, "s": 25218, "text": "In the following code:\n\na = b * c + g;\nd = b * c * e;\n\nit may be worth transforming the code to:\n\ntmp = b * c;\na = tmp + g;\nd = tmp * e;" }, { "code": null, "e": 25733, "s": 25355, "text": "\n4*j is common subexpression elimination so B is true.\n\n5*i can be moved out of inner loop so can be i%2. \nMeans, A is true as we have loop invariant computation.\n\nNext, 4*j as well as 5*i can be replaced with a = - 4;\nbefore j loop then a = a + 4; where 4*j is computed,\nlikewise for 5*i. C is true as there is scope of strength \nreduction. \n\nBy choice elimination, we have D." }, { "code": null, "e": 25890, "s": 25733, "text": "1. i = 1\n2. j = 1\n3. t1 = 5 * i\n4. t2 = t1 + j\n5. t3 = 4 * t2\n6. t4 = t3\n7. a[t4] = –1\n8. j = j + 1\n9. if j <= 5 goto(3)\n10. i = i + 1\n11. if i < 5 goto(2) " }, { "code": null, "e": 25946, "s": 25890, "text": "x = u - t;\ny = x * v;\nx = y + w;\ny = t - z;\ny = x * y; " }, { "code": null, "e": 25969, "s": 25946, "text": "x = u - t;\nx = y + w;\n" }, { "code": null, "e": 26002, "s": 25969, "text": "y = x * v;\ny = t - z;\ny = x * y " }, { "code": null, "e": 26066, "s": 26002, "text": "x1 = u - t;\ny1 = x1 * v;\nx2 = y1 + w;\ny2 = t - z;\ny3 = x2 * y2;" }, { "code": null, "e": 26081, "s": 26066, "text": "S → n\nB → BbB " }, { "code": null, "e": 26358, "s": 26081, "text": "S → L.L { S.val=L1.val + L2.val / 2^L2.nb }\nS → L { S.val = L.val } \nL → LB { L.val = 2 * L.val + B.val , L.nb = L.nb + B.nb } \nL → B { L.val = B.val , L.nb = B.nb } \nB → 0 { B.val = 0 , B.nb = 1 } \nB → 1 { B.val = 1 , B.nb = 1 } " }, { "code": null, "e": 26456, "s": 26358, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 26509, "s": 26456, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 26547, "s": 26509, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 26589, "s": 26547, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 26635, "s": 26589, "text": "How to Install Flutter on Visual Studio Code?" }, { "code": null, "e": 26690, "s": 26635, "text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?" }, { "code": null, "e": 26731, "s": 26690, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 26806, "s": 26731, "text": "What is the difference between position:sticky and position:fixed in CSS ?" }, { "code": null, "e": 26865, "s": 26806, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 26907, "s": 26865, "text": "Retrofit with Kotlin Coroutine in Android" } ]
Spring JDBC - SimpleJdbcCall Class
The org.springframework.jdbc.core.SimpleJdbcCall class is a multi-threaded, reusable object representing a call to a stored procedure or a stored function. It provides meta data processing to simplify the code needed to access basic stored procedures/functions. All you need to provide is the name of the procedure/function and a map containing the parameters when you execute the call. The names of the supplied parameters will be matched up with in and out parameters declared when the stored procedure was created. Following is the declaration for org.springframework.jdbc.core.SimpleJdbcCall class − public class SimpleJdbcCall extends AbstractJdbcCall implements SimpleJdbcCallOperations Following example will demonstrate how to call a stored procedure using Spring SimpleJdbcCall. We'll read one of the available records in Student Table by calling a stored procedure. We'll pass an id and receive a student record. SimpleJdbcCall jdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("getRecord"); SqlParameterSource in = new MapSqlParameterSource().addValue("in_id", id); Map<String, Object> out = jdbcCall.execute(in); Student student = new Student(); student.setId(id); student.setName((String) out.get("out_name")); student.setAge((Integer) out.get("out_age")); Where, jdbcCall − SimpleJdbcCall object to represent a stored procedure. jdbcCall − SimpleJdbcCall object to represent a stored procedure. in − SqlParameterSource object to pass a parameter to a stored procedure. in − SqlParameterSource object to pass a parameter to a stored procedure. student − Student object. student − Student object. out − Map object to represent output of stored procedure call result. out − Map object to represent output of stored procedure call result. To understand the above-mentioned concepts related to Spring JDBC, let us write an example which will call a stored procedure. To write our example, let us have a working Eclipse IDE in place and use the following steps to create a Spring application. Following is the content of the Data Access Object interface file StudentDAO.java. package com.tutorialspoint; import java.util.List; import javax.sql.DataSource; public interface StudentDAO { /** * This is the method to be used to initialize * database resources ie. connection. */ public void setDataSource(DataSource ds); /** * This is the method to be used to list down * a record from the Student table corresponding * to a passed student id. */ public Student getStudent(Integer id); } Following is the content of the Student.java file. package com.tutorialspoint; public class Student { private Integer age; private String name; private Integer id; public void setAge(Integer age) { this.age = age; } public Integer getAge() { return age; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setId(Integer id) { this.id = id; } public Integer getId() { return id; } } Following is the content of the StudentMapper.java file. package com.tutorialspoint; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; public class StudentMapper implements RowMapper<Student> { public Student mapRow(ResultSet rs, int rowNum) throws SQLException { Student student = new Student(); student.setId(rs.getInt("id")); student.setName(rs.getString("name")); student.setAge(rs.getInt("age")); return student; } } Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO. package com.tutorialspoint; import java.util.List; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcCall; public class StudentJDBCTemplate implements StudentDAO { private DataSource dataSource; private JdbcTemplate jdbcTemplateObject; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; this.jdbcTemplateObject = new JdbcTemplate(dataSource); } public Student getStudent(Integer id) { SimpleJdbcCall jdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("getRecord"); SqlParameterSource in = new MapSqlParameterSource().addValue("in_id", id); Map<String, Object> out = jdbcCall.execute(in); Student student = new Student(); student.setId(id); student.setName((String) out.get("out_name")); student.setAge((Integer) out.get("out_age")); return student; } } The code you write for the execution of the call involves creating an SqlParameterSource containing the IN parameter. It's important to match the name provided for the input value with that of the parameter name declared in the stored procedure. The execute method takes the IN parameters and returns a Map containing any out parameters keyed by the name as specified in the stored procedure. Following is the content of the MainApp.java file. package com.tutorialspoint; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.tutorialspoint.StudentJDBCTemplate; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean("studentJDBCTemplate"); Student student = studentJDBCTemplate.getStudent(1); System.out.print("ID : " + student.getId() ); System.out.print(", Name : " + student.getName() ); System.out.println(", Age : " + student.getAge()); } } Following is the configuration file Beans.xml. <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd "> <!-- Initialization for data source --> <bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name = "driverClassName" value = "com.mysql.cj.jdbc.Driver"/> <property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/> <property name = "username" value = "root"/> <property name = "password" value = "admin"/> </bean> <!-- Definition for studentJDBCTemplate bean --> <bean id = "studentJDBCTemplate" class = "com.tutorialspoint.StudentJDBCTemplate"> <property name = "dataSource" ref = "dataSource" /> </bean> </beans> Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message. ID : 1, Name : Zara, Age : 11 Print Add Notes Bookmark this page
[ { "code": null, "e": 2658, "s": 2396, "text": "The org.springframework.jdbc.core.SimpleJdbcCall class is a multi-threaded, reusable object representing a call to a stored procedure or a stored function. It provides meta data processing to simplify the code needed to access basic stored procedures/functions." }, { "code": null, "e": 2914, "s": 2658, "text": "All you need to provide is the name of the procedure/function and a map containing the parameters when you execute the call. The names of the supplied parameters will be matched up with in and out parameters declared when the stored procedure was created." }, { "code": null, "e": 3000, "s": 2914, "text": "Following is the declaration for org.springframework.jdbc.core.SimpleJdbcCall class −" }, { "code": null, "e": 3099, "s": 3000, "text": "public class SimpleJdbcCall\n extends AbstractJdbcCall\n implements SimpleJdbcCallOperations\n" }, { "code": null, "e": 3329, "s": 3099, "text": "Following example will demonstrate how to call a stored procedure using Spring SimpleJdbcCall. We'll read one of the available records in Student Table by calling a stored procedure. We'll pass an id and receive a student record." }, { "code": null, "e": 3687, "s": 3329, "text": "SimpleJdbcCall jdbcCall = new SimpleJdbcCall(dataSource).withProcedureName(\"getRecord\");\nSqlParameterSource in = new MapSqlParameterSource().addValue(\"in_id\", id);\nMap<String, Object> out = jdbcCall.execute(in);\n\nStudent student = new Student();\nstudent.setId(id);\nstudent.setName((String) out.get(\"out_name\"));\nstudent.setAge((Integer) out.get(\"out_age\"));" }, { "code": null, "e": 3694, "s": 3687, "text": "Where," }, { "code": null, "e": 3760, "s": 3694, "text": "jdbcCall − SimpleJdbcCall object to represent a stored procedure." }, { "code": null, "e": 3826, "s": 3760, "text": "jdbcCall − SimpleJdbcCall object to represent a stored procedure." }, { "code": null, "e": 3900, "s": 3826, "text": "in − SqlParameterSource object to pass a parameter to a stored procedure." }, { "code": null, "e": 3974, "s": 3900, "text": "in − SqlParameterSource object to pass a parameter to a stored procedure." }, { "code": null, "e": 4000, "s": 3974, "text": "student − Student object." }, { "code": null, "e": 4026, "s": 4000, "text": "student − Student object." }, { "code": null, "e": 4096, "s": 4026, "text": "out − Map object to represent output of stored procedure call result." }, { "code": null, "e": 4166, "s": 4096, "text": "out − Map object to represent output of stored procedure call result." }, { "code": null, "e": 4418, "s": 4166, "text": "To understand the above-mentioned concepts related to Spring JDBC, let us write an example which will call a stored procedure. To write our example, let us have a working Eclipse IDE in place and use the following steps to create a Spring application." }, { "code": null, "e": 4501, "s": 4418, "text": "Following is the content of the Data Access Object interface file StudentDAO.java." }, { "code": null, "e": 4968, "s": 4501, "text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport javax.sql.DataSource;\n\npublic interface StudentDAO {\n /** \n * This is the method to be used to initialize\n * database resources ie. connection.\n */\n public void setDataSource(DataSource ds);\n \n /** \n * This is the method to be used to list down\n * a record from the Student table corresponding\n * to a passed student id.\n */\n public Student getStudent(Integer id); \n}" }, { "code": null, "e": 5019, "s": 4968, "text": "Following is the content of the Student.java file." }, { "code": null, "e": 5491, "s": 5019, "text": "package com.tutorialspoint;\n\npublic class Student {\n private Integer age;\n private String name;\n private Integer id;\n\n public void setAge(Integer age) {\n this.age = age;\n }\n public Integer getAge() {\n return age;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getName() {\n return name;\n }\n public void setId(Integer id) {\n this.id = id;\n }\n public Integer getId() {\n return id;\n }\n}" }, { "code": null, "e": 5548, "s": 5491, "text": "Following is the content of the StudentMapper.java file." }, { "code": null, "e": 6006, "s": 5548, "text": "package com.tutorialspoint;\n\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.springframework.jdbc.core.RowMapper;\n\npublic class StudentMapper implements RowMapper<Student> {\n public Student mapRow(ResultSet rs, int rowNum) throws SQLException {\n Student student = new Student();\n student.setId(rs.getInt(\"id\"));\n student.setName(rs.getString(\"name\"));\n student.setAge(rs.getInt(\"age\"));\n return student;\n }\n}" }, { "code": null, "e": 6116, "s": 6006, "text": "Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO." }, { "code": null, "e": 7223, "s": 6116, "text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport javax.sql.DataSource;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.jdbc.core.namedparam.MapSqlParameterSource;\nimport org.springframework.jdbc.core.namedparam.SqlParameterSource;\nimport org.springframework.jdbc.core.simple.SimpleJdbcCall;\n\npublic class StudentJDBCTemplate implements StudentDAO {\n private DataSource dataSource;\n private JdbcTemplate jdbcTemplateObject;\n \n public void setDataSource(DataSource dataSource) {\n this.dataSource = dataSource;\n this.jdbcTemplateObject = new JdbcTemplate(dataSource);\n }\n public Student getStudent(Integer id) {\n SimpleJdbcCall jdbcCall = new SimpleJdbcCall(dataSource).withProcedureName(\"getRecord\");\n\n SqlParameterSource in = new MapSqlParameterSource().addValue(\"in_id\", id);\n Map<String, Object> out = jdbcCall.execute(in);\n\n Student student = new Student();\n student.setId(id);\n student.setName((String) out.get(\"out_name\"));\n student.setAge((Integer) out.get(\"out_age\"));\n return student; \n }\n}" }, { "code": null, "e": 7616, "s": 7223, "text": "The code you write for the execution of the call involves creating an SqlParameterSource containing the IN parameter. It's important to match the name provided for the input value with that of the parameter name declared in the stored procedure. The execute method takes the IN parameters and returns a Map containing any out parameters keyed by the name as specified in the stored procedure." }, { "code": null, "e": 7667, "s": 7616, "text": "Following is the content of the MainApp.java file." }, { "code": null, "e": 8391, "s": 7667, "text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\nimport com.tutorialspoint.StudentJDBCTemplate;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean(\"studentJDBCTemplate\");\n Student student = studentJDBCTemplate.getStudent(1);\n System.out.print(\"ID : \" + student.getId() );\n System.out.print(\", Name : \" + student.getName() );\n System.out.println(\", Age : \" + student.getAge()); \n }\n}" }, { "code": null, "e": 8438, "s": 8391, "text": "Following is the configuration file Beans.xml." }, { "code": null, "e": 9383, "s": 8438, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd \">\n\n <!-- Initialization for data source -->\n <bean id = \"dataSource\" \n class = \"org.springframework.jdbc.datasource.DriverManagerDataSource\">\n <property name = \"driverClassName\" value = \"com.mysql.cj.jdbc.Driver\"/>\n <property name = \"url\" value = \"jdbc:mysql://localhost:3306/TEST\"/>\n <property name = \"username\" value = \"root\"/>\n <property name = \"password\" value = \"admin\"/>\n </bean>\n\n <!-- Definition for studentJDBCTemplate bean -->\n <bean id = \"studentJDBCTemplate\" \n class = \"com.tutorialspoint.StudentJDBCTemplate\">\n <property name = \"dataSource\" ref = \"dataSource\" /> \n </bean>\n</beans>" }, { "code": null, "e": 9561, "s": 9383, "text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message." }, { "code": null, "e": 9592, "s": 9561, "text": "ID : 1, Name : Zara, Age : 11\n" }, { "code": null, "e": 9599, "s": 9592, "text": " Print" }, { "code": null, "e": 9610, "s": 9599, "text": " Add Notes" } ]
Plot a lineplot with Seaborn – Python Pandas
Lineplot in Seaborn is used to draw a line plot with possibility of several semantic groupings. The seaborn.lineplot() is used for this. Let’s say the following is our dataset in the form of a CSV file − Cricketers.csv At first, import the required 3 libraries − import seaborn as sb import pandas as pd import matplotlib.pyplot as plt Load data from a CSV file into a Pandas DataFrame − dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\Cricketers.csv") Following is the code − import seaborn as sb import pandas as pd import matplotlib.pyplot as plt # Load data from a CSV file into a Pandas DataFrame dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\Cricketers.csv") print("\nReading the CSV file...\n",dataFrame) # Age in kgs x = dataFrame['Age'] # Height in Inches y = dataFrame['Height'] # plot lineplot with Age and Height sb.lineplot(x,y) plt.ylabel("Height (inches)") plt.show() This will produce the following output −
[ { "code": null, "e": 1199, "s": 1062, "text": "Lineplot in Seaborn is used to draw a line plot with possibility of several semantic groupings. The seaborn.lineplot() is used for this." }, { "code": null, "e": 1281, "s": 1199, "text": "Let’s say the following is our dataset in the form of a CSV file − Cricketers.csv" }, { "code": null, "e": 1325, "s": 1281, "text": "At first, import the required 3 libraries −" }, { "code": null, "e": 1398, "s": 1325, "text": "import seaborn as sb\nimport pandas as pd\nimport matplotlib.pyplot as plt" }, { "code": null, "e": 1450, "s": 1398, "text": "Load data from a CSV file into a Pandas DataFrame −" }, { "code": null, "e": 1520, "s": 1450, "text": "dataFrame = pd.read_csv(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\Cricketers.csv\")\n" }, { "code": null, "e": 1544, "s": 1520, "text": "Following is the code −" }, { "code": null, "e": 1960, "s": 1544, "text": "import seaborn as sb\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Load data from a CSV file into a Pandas DataFrame\ndataFrame = pd.read_csv(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\Cricketers.csv\")\nprint(\"\\nReading the CSV file...\\n\",dataFrame)\n\n# Age in kgs\nx = dataFrame['Age']\n\n# Height in Inches\ny = dataFrame['Height']\n\n# plot lineplot with Age and Height\nsb.lineplot(x,y)\nplt.ylabel(\"Height (inches)\")\nplt.show()" }, { "code": null, "e": 2001, "s": 1960, "text": "This will produce the following output −" } ]
AWK - Assignment Operators
AWK supports the following assignment operators − It is represented by =. The following example demonstrates this − [jerry]$ awk 'BEGIN { name = "Jerry"; print "My name is", name }' On executing this code, you get the following result − My name is Jerry It is represented by +=. The following example demonstrates this − [jerry]$ awk 'BEGIN { cnt = 10; cnt += 10; print "Counter =", cnt }' On executing this code, you get the following result − Counter = 20 In the above example, the first statement assigns value 10 to the variable cnt. In the next statement, the shorthand operator increments its value by 10. It is represented by -=. The following example demonstrates this − [jerry]$ awk 'BEGIN { cnt = 100; cnt -= 10; print "Counter =", cnt }' On executing this code, you get the following result − Counter = 90 In the above example, the first statement assigns value 100 to the variable cnt. In the next statement, the shorthand operator decrements its value by 10. It is represented by *=. The following example demonstrates this − [jerry]$ awk 'BEGIN { cnt = 10; cnt *= 10; print "Counter =", cnt }' On executing this code, you get the following result − Counter = 100 In the above example, the first statement assigns value 10 to the variable cnt. In the next statement, the shorthand operator multiplies its value by 10. It is represented by /=. The following example demonstrates this − [jerry]$ awk 'BEGIN { cnt = 100; cnt /= 5; print "Counter =", cnt }' On executing this code, you get the following result − Counter = 20 In the above example, the first statement assigns value 100 to the variable cnt. In the next statement, the shorthand operator divides it by 5. It is represented by %=. The following example demonstrates this − [jerry]$ awk 'BEGIN { cnt = 100; cnt %= 8; print "Counter =", cnt }' On executing this code, you get the following result − Counter = 4 It is represented by ^=. The following example demonstrates this − [jerry]$ awk 'BEGIN { cnt = 2; cnt ^= 4; print "Counter =", cnt }' On executing this code, you get the following result − Counter = 16 The above example raises the value of cnt by 4. It is represented by **=. The following example demonstrates this − [jerry]$ awk 'BEGIN { cnt = 2; cnt **= 4; print "Counter =", cnt }' On executing this code, you get the following result − Counter = 16 This example also raises the value of cnt by 4. Print Add Notes Bookmark this page
[ { "code": null, "e": 1907, "s": 1857, "text": "AWK supports the following assignment operators −" }, { "code": null, "e": 1973, "s": 1907, "text": "It is represented by =. The following example demonstrates this −" }, { "code": null, "e": 2039, "s": 1973, "text": "[jerry]$ awk 'BEGIN { name = \"Jerry\"; print \"My name is\", name }'" }, { "code": null, "e": 2094, "s": 2039, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 2112, "s": 2094, "text": "My name is Jerry\n" }, { "code": null, "e": 2179, "s": 2112, "text": "It is represented by +=. The following example demonstrates this −" }, { "code": null, "e": 2248, "s": 2179, "text": "[jerry]$ awk 'BEGIN { cnt = 10; cnt += 10; print \"Counter =\", cnt }'" }, { "code": null, "e": 2303, "s": 2248, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 2317, "s": 2303, "text": "Counter = 20\n" }, { "code": null, "e": 2471, "s": 2317, "text": "In the above example, the first statement assigns value 10 to the variable cnt. In the next statement, the shorthand operator increments its value by 10." }, { "code": null, "e": 2538, "s": 2471, "text": "It is represented by -=. The following example demonstrates this −" }, { "code": null, "e": 2608, "s": 2538, "text": "[jerry]$ awk 'BEGIN { cnt = 100; cnt -= 10; print \"Counter =\", cnt }'" }, { "code": null, "e": 2663, "s": 2608, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 2677, "s": 2663, "text": "Counter = 90\n" }, { "code": null, "e": 2832, "s": 2677, "text": "In the above example, the first statement assigns value 100 to the variable cnt. In the next statement, the shorthand operator decrements its value by 10." }, { "code": null, "e": 2899, "s": 2832, "text": "It is represented by *=. The following example demonstrates this −" }, { "code": null, "e": 2968, "s": 2899, "text": "[jerry]$ awk 'BEGIN { cnt = 10; cnt *= 10; print \"Counter =\", cnt }'" }, { "code": null, "e": 3023, "s": 2968, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 3038, "s": 3023, "text": "Counter = 100\n" }, { "code": null, "e": 3192, "s": 3038, "text": "In the above example, the first statement assigns value 10 to the variable cnt. In the next statement, the shorthand operator multiplies its value by 10." }, { "code": null, "e": 3259, "s": 3192, "text": "It is represented by /=. The following example demonstrates this −" }, { "code": null, "e": 3328, "s": 3259, "text": "[jerry]$ awk 'BEGIN { cnt = 100; cnt /= 5; print \"Counter =\", cnt }'" }, { "code": null, "e": 3383, "s": 3328, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 3397, "s": 3383, "text": "Counter = 20\n" }, { "code": null, "e": 3541, "s": 3397, "text": "In the above example, the first statement assigns value 100 to the variable cnt. In the next statement, the shorthand operator divides it by 5." }, { "code": null, "e": 3608, "s": 3541, "text": "It is represented by %=. The following example demonstrates this −" }, { "code": null, "e": 3677, "s": 3608, "text": "[jerry]$ awk 'BEGIN { cnt = 100; cnt %= 8; print \"Counter =\", cnt }'" }, { "code": null, "e": 3732, "s": 3677, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 3745, "s": 3732, "text": "Counter = 4\n" }, { "code": null, "e": 3812, "s": 3745, "text": "It is represented by ^=. The following example demonstrates this −" }, { "code": null, "e": 3879, "s": 3812, "text": "[jerry]$ awk 'BEGIN { cnt = 2; cnt ^= 4; print \"Counter =\", cnt }'" }, { "code": null, "e": 3934, "s": 3879, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 3948, "s": 3934, "text": "Counter = 16\n" }, { "code": null, "e": 3996, "s": 3948, "text": "The above example raises the value of cnt by 4." }, { "code": null, "e": 4064, "s": 3996, "text": "It is represented by **=. The following example demonstrates this −" }, { "code": null, "e": 4132, "s": 4064, "text": "[jerry]$ awk 'BEGIN { cnt = 2; cnt **= 4; print \"Counter =\", cnt }'" }, { "code": null, "e": 4187, "s": 4132, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 4201, "s": 4187, "text": "Counter = 16\n" }, { "code": null, "e": 4249, "s": 4201, "text": "This example also raises the value of cnt by 4." }, { "code": null, "e": 4256, "s": 4249, "text": " Print" }, { "code": null, "e": 4267, "s": 4256, "text": " Add Notes" } ]
Monitor and Improve GPU Usage for Training Deep Learning Models | by Lukas Biewald | Towards Data Science
One of the exciting things about running Weights and Biases is that we can research how models are actually using their computational resources in real world scenarios and, since we are making monitoring GPU and memory easy, we wanted to help our users by taking a look at how well folks utilize their computational resources. For users training on GPUs, I looked at their average utilization across all runs. Since launch, we’ve tracked hundreds of thousands of runs across a wide variety of use cases, techniques and frameworks. Nearly a third of our users are averaging less than 15% utilization. Average GPU memory usage is quite similar. Our users tend to be experienced deep learning practitioners and GPUs are an expensive resource so I was surprised to see such low average usage. Here’s a few easy, concrete suggestions for improving GPU usage that apply to almost everyone: Measure your GPU usage consistently over your entire training runs Measure your GPU usage consistently over your entire training runs You can’t improve GPU usage without measuring it. It’s not hard to take a snapshot of your usage with useful tools like nvidia-smi, but a simple way to find issues is to track usage over time. Anyone can use the wandb python package we built to track GPU, CPU, memory usage and other metrics over time by adding two lines of code import wandbwandb.init() The wandb.init() function will create a lightweight child process that will collect system metrics and send them to a wandb server where you can look at them and compare across runs with graphs like these: The danger of taking a single measurement is that GPU usage can change over time. This is a common pattern we see where our user Boris is training an RNN; mid-training, his usage plummets from 80 percent to around 25 percent. You can see his complete set of stats and training log at https://app.wandb.ai/borisd13/char-RNN/runs/cw9gnx9z/system. A related case we commonly see with multiple GPUs is that mid-training, some of the GPUs stop handling any load. In this example both GPUs started off doing computations, but a few minutes in, all the load is sent to a single GPU. This could be intentional but this is often the sign of a hard to catch bug in the code. Another common issue we see is that there are long periods of not using the GPUs — often corresponding with a testing or validation phases in training or bottlenecked on some data preprocessing. Here is a typical graph, training on 8 GPUs where all of them turn off and wait for some time at a regular interval. 2) Make sure your GPU is the bottleneck This is a common situation we see — here the system memory is significantly used and the memory usage seems to be gradually increasing. As the memory usage goes up the GPU usage goes down. We also often see network being the bottleneck when people try to train on datasets that aren’t available locally. 3) Try increasing your batch size It doesn’t work in every case, but one simple way to possibly increase GPU utilization is to increase batch size. Gradients for a batch are generally calculated in parallel on a GPU, so as long as there is enough memory to fit the full batch and multiple copies of the neural network into GPU memory, increasing the batch size should increase the speed of calculation. If I increase the batch size and change nothing else, I might conclude that increasing the batch size speeds up computation but reduces model performance. Here are my results training CIFAR with batch sizes 32, 64 and 128. Indeed, there are many papers and a top post on StackOverflow warning about large batch sizes. There is a simple way to make larger batch sizes work reasonably well. Increase the learning rate along with batch size. Intuitively, this makes sense, batch sizes are how many examples a training algorithm looks at before making a step and learning rate is roughly the size of the step. So if the model looks at more examples it should probably be comfortable taking a larger step. This is recommended in the paper One weird trick for parallelizing convolutional neural networks and later in Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour where the authors managed to increase the batch size to 8000 before they saw a loss in performance. I tried increasing the learning rate with the batch size on my own model and reached the same conclusion. When I multiply the learning rate by 4 and increase the batch size by 4, my model trains faster and learns faster at each step. The Facebook paper does some fancy things to make the model work well at very large batch sizes and they are able to get the same performance but at much higher speeds up to 8000 samples per batch. These huge batch sizes make sense for distributed training, and the paper’s scheme of starting with a lower learning rate and then ramping it up looks very valuable in that context. If you’re training on one GPU and not maxing out your utilization, I have a quick recommendation: double your batch size and double your learning rate. You can dive into more data from my runs in the Batch Size Report. Conclusion GPUs are getting faster and faster but it doesn’t matter if the training code doesn’t completely use them. The good news is that for most people training machine learning models there is still a lot of simple things to do that will significantly improve efficiency. There’s another, probably larger, waste of resources: GPUs that sit unused. We don’t measure this, but I’ve heard it anecdotally from many of the companies we work with. It’s hard to queue up work efficiently for GPUs, in a typical workflow a researcher will set up a large number of experiments, wait for them to finish and then spend quite a lot of time digesting the results while the GPUs sit idle. This is outside the scope of wandb, but tools like Paperspace and Amazon’s Sagemaker make it easy to spin up and down resources as needed. Thanks Thanks Sam Pottinger, Carey Phelps, James Cham, Yanda Erlich, Stephanie Sher for edits and feedback.
[ { "code": null, "e": 499, "s": 172, "text": "One of the exciting things about running Weights and Biases is that we can research how models are actually using their computational resources in real world scenarios and, since we are making monitoring GPU and memory easy, we wanted to help our users by taking a look at how well folks utilize their computational resources." }, { "code": null, "e": 961, "s": 499, "text": "For users training on GPUs, I looked at their average utilization across all runs. Since launch, we’ve tracked hundreds of thousands of runs across a wide variety of use cases, techniques and frameworks. Nearly a third of our users are averaging less than 15% utilization. Average GPU memory usage is quite similar. Our users tend to be experienced deep learning practitioners and GPUs are an expensive resource so I was surprised to see such low average usage." }, { "code": null, "e": 1056, "s": 961, "text": "Here’s a few easy, concrete suggestions for improving GPU usage that apply to almost everyone:" }, { "code": null, "e": 1123, "s": 1056, "text": "Measure your GPU usage consistently over your entire training runs" }, { "code": null, "e": 1190, "s": 1123, "text": "Measure your GPU usage consistently over your entire training runs" }, { "code": null, "e": 1520, "s": 1190, "text": "You can’t improve GPU usage without measuring it. It’s not hard to take a snapshot of your usage with useful tools like nvidia-smi, but a simple way to find issues is to track usage over time. Anyone can use the wandb python package we built to track GPU, CPU, memory usage and other metrics over time by adding two lines of code" }, { "code": null, "e": 1545, "s": 1520, "text": "import wandbwandb.init()" }, { "code": null, "e": 1751, "s": 1545, "text": "The wandb.init() function will create a lightweight child process that will collect system metrics and send them to a wandb server where you can look at them and compare across runs with graphs like these:" }, { "code": null, "e": 1977, "s": 1751, "text": "The danger of taking a single measurement is that GPU usage can change over time. This is a common pattern we see where our user Boris is training an RNN; mid-training, his usage plummets from 80 percent to around 25 percent." }, { "code": null, "e": 2096, "s": 1977, "text": "You can see his complete set of stats and training log at https://app.wandb.ai/borisd13/char-RNN/runs/cw9gnx9z/system." }, { "code": null, "e": 2416, "s": 2096, "text": "A related case we commonly see with multiple GPUs is that mid-training, some of the GPUs stop handling any load. In this example both GPUs started off doing computations, but a few minutes in, all the load is sent to a single GPU. This could be intentional but this is often the sign of a hard to catch bug in the code." }, { "code": null, "e": 2728, "s": 2416, "text": "Another common issue we see is that there are long periods of not using the GPUs — often corresponding with a testing or validation phases in training or bottlenecked on some data preprocessing. Here is a typical graph, training on 8 GPUs where all of them turn off and wait for some time at a regular interval." }, { "code": null, "e": 2768, "s": 2728, "text": "2) Make sure your GPU is the bottleneck" }, { "code": null, "e": 3072, "s": 2768, "text": "This is a common situation we see — here the system memory is significantly used and the memory usage seems to be gradually increasing. As the memory usage goes up the GPU usage goes down. We also often see network being the bottleneck when people try to train on datasets that aren’t available locally." }, { "code": null, "e": 3106, "s": 3072, "text": "3) Try increasing your batch size" }, { "code": null, "e": 3475, "s": 3106, "text": "It doesn’t work in every case, but one simple way to possibly increase GPU utilization is to increase batch size. Gradients for a batch are generally calculated in parallel on a GPU, so as long as there is enough memory to fit the full batch and multiple copies of the neural network into GPU memory, increasing the batch size should increase the speed of calculation." }, { "code": null, "e": 3698, "s": 3475, "text": "If I increase the batch size and change nothing else, I might conclude that increasing the batch size speeds up computation but reduces model performance. Here are my results training CIFAR with batch sizes 32, 64 and 128." }, { "code": null, "e": 4445, "s": 3698, "text": "Indeed, there are many papers and a top post on StackOverflow warning about large batch sizes. There is a simple way to make larger batch sizes work reasonably well. Increase the learning rate along with batch size. Intuitively, this makes sense, batch sizes are how many examples a training algorithm looks at before making a step and learning rate is roughly the size of the step. So if the model looks at more examples it should probably be comfortable taking a larger step. This is recommended in the paper One weird trick for parallelizing convolutional neural networks and later in Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour where the authors managed to increase the batch size to 8000 before they saw a loss in performance." }, { "code": null, "e": 4679, "s": 4445, "text": "I tried increasing the learning rate with the batch size on my own model and reached the same conclusion. When I multiply the learning rate by 4 and increase the batch size by 4, my model trains faster and learns faster at each step." }, { "code": null, "e": 4877, "s": 4679, "text": "The Facebook paper does some fancy things to make the model work well at very large batch sizes and they are able to get the same performance but at much higher speeds up to 8000 samples per batch." }, { "code": null, "e": 5211, "s": 4877, "text": "These huge batch sizes make sense for distributed training, and the paper’s scheme of starting with a lower learning rate and then ramping it up looks very valuable in that context. If you’re training on one GPU and not maxing out your utilization, I have a quick recommendation: double your batch size and double your learning rate." }, { "code": null, "e": 5278, "s": 5211, "text": "You can dive into more data from my runs in the Batch Size Report." }, { "code": null, "e": 5289, "s": 5278, "text": "Conclusion" }, { "code": null, "e": 5555, "s": 5289, "text": "GPUs are getting faster and faster but it doesn’t matter if the training code doesn’t completely use them. The good news is that for most people training machine learning models there is still a lot of simple things to do that will significantly improve efficiency." }, { "code": null, "e": 6097, "s": 5555, "text": "There’s another, probably larger, waste of resources: GPUs that sit unused. We don’t measure this, but I’ve heard it anecdotally from many of the companies we work with. It’s hard to queue up work efficiently for GPUs, in a typical workflow a researcher will set up a large number of experiments, wait for them to finish and then spend quite a lot of time digesting the results while the GPUs sit idle. This is outside the scope of wandb, but tools like Paperspace and Amazon’s Sagemaker make it easy to spin up and down resources as needed." }, { "code": null, "e": 6104, "s": 6097, "text": "Thanks" } ]
Add two numbers represented by two arrays - GeeksforGeeks
19 Mar, 2021 Given two array A[0....n-1] and B[0....m-1] of size n and m respectively, representing two numbers such that every element of arrays represent a digit. For example, A[] = { 1, 2, 3} and B[] = { 2, 1, 4 } represent 123 and 214 respectively. The task is to find the sum of both the number. In above case, answer is 337. Examples : Input : n = 3, m = 3 a[] = { 1, 2, 3 } b[] = { 2, 1, 4 } Output : 337 123 + 214 = 337 Input : n = 4, m = 3 a[] = { 9, 5, 4, 9 } b[] = { 2, 1, 4 } Output : 9763 The idea is to start traversing both the array simultaneously from the end until we reach the 0th index of either of the array. While traversing each elements of array, add element of both the array and carry from the previous sum. Now store the unit digit of the sum and forward carry for the next index sum. While adding 0th index element if the carry left, then append it to beginning of the number. Below is the illustration of approach: Below is the implementation of this approach: C++ Java Python3 C# PHP Javascript // CPP program to sum two numbers represented two// arrays.#include <bits/stdc++.h>using namespace std; // Return sum of two number represented by the arrays.// Size of a[] is greater than b[]. It is made sure// be the wrapper functionint calSumUtil(int a[], int b[], int n, int m){ // array to store sum. int sum[n]; int i = n - 1, j = m - 1, k = n - 1; int carry = 0, s = 0; // Until we reach beginning of array. // we are comparing only for second array // because we have already compare the size // of array in wrapper function. while (j >= 0) { // find sum of corresponding element // of both arrays. s = a[i] + b[j] + carry; sum[k] = (s % 10); // Finding carry for next sum. carry = s / 10; k--; i--; j--; } // If second array size is less the first // array size. while (i >= 0) { // Add carry to first array elements. s = a[i] + carry; sum[k] = (s % 10); carry = s / 10; i--; k--; } int ans = 0; // If there is carry on adding 0 index elements. // append 1 to total sum. if (carry) ans = 10; // Converting array into number. for (int i = 0; i <= n - 1; i++) { ans += sum[i]; ans *= 10; } return ans / 10;} // Wrapper Functionint calSum(int a[], int b[], int n, int m){ // Making first array which have // greater number of element if (n >= m) return calSumUtil(a, b, n, m); else return calSumUtil(b, a, m, n);} // Driven Programint main(){ int a[] = { 9, 3, 9 }; int b[] = { 6, 1 }; int n = sizeof(a) / sizeof(a[0]); int m = sizeof(b) / sizeof(b[0]); cout << calSum(a, b, n, m) << endl; return 0;} // Java program to sum two numbers // represented two arrays.import java.io.*; class GFG { // Return sum of two number represented by // the arrays. Size of a[] is greater than // b[]. It is made sure be the wrapper // function static int calSumUtil(int a[], int b[], int n, int m) { // array to store sum. int[] sum= new int[n]; int i = n - 1, j = m - 1, k = n - 1; int carry = 0, s = 0; // Until we reach beginning of array. // we are comparing only for second // array because we have already compare // the size of array in wrapper function. while (j >= 0) { // find sum of corresponding element // of both array. s = a[i] + b[j] + carry; sum[k] = (s % 10); // Finding carry for next sum. carry = s / 10; k--; i--; j--; } // If second array size is less // the first array size. while (i >= 0) { // Add carry to first array elements. s = a[i] + carry; sum[k] = (s % 10); carry = s / 10; i--; k--; } int ans = 0; // If there is carry on adding 0 index // elements append 1 to total sum. if (carry == 1) ans = 10; // Converting array into number. for ( i = 0; i <= n - 1; i++) { ans += sum[i]; ans *= 10; } return ans / 10; } // Wrapper Function static int calSum(int a[], int b[], int n, int m) { // Making first array which have // greater number of element if (n >= m) return calSumUtil(a, b, n, m); else return calSumUtil(b, a, m, n); } /* Driver program to test above function */ public static void main(String[] args) { int a[] = { 9, 3, 9 }; int b[] = { 6, 1 }; int n = a.length; int m = b.length; System.out.println(calSum(a, b, n, m)); }} // This article is contributed by Gitanjali. # Python3 code to sum two numbers# representer two arrays. # Return sum of two number represented# by the arrays. Size of a[] is greater# than b[]. It is made sure be the# wrapper functiondef calSumUtil( a , b , n , m ): # array to store sum. sum = [0] * n i = n - 1 j = m - 1 k = n - 1 carry = 0 s = 0 # Until we reach beginning of array. # we are comparing only for second array # because we have already compare the size # of array in wrapper function. while j >= 0: # find sum of corresponding element # of both array. s = a[i] + b[j] + carry sum[k] = (s % 10) # Finding carry for next sum. carry = s // 10 k-=1 i-=1 j-=1 # If second array size is less the first # array size. while i >= 0: # Add carry to first array elements. s = a[i] + carry sum[k] = (s % 10) carry = s // 10 i-=1 k-=1 ans = 0 # If there is carry on adding 0 index elements. # append 1 to total sum. if carry: ans = 10 # Converting array into number. for i in range(n): ans += sum[i] ans *= 10 return ans // 10 # Wrapper Functiondef calSum(a, b, n, m ): # Making first array which have # greater number of element if n >= m: return calSumUtil(a, b, n, m) else: return calSumUtil(b, a, m, n) # Driven Codea = [ 9, 3, 9 ]b = [ 6, 1 ]n = len(a)m = len(b)print(calSum(a, b, n, m)) # This code is contributed by "Sharad_Bhardwaj". // C# program to sum two numbers// represented two arrays.using System; class GFG { // Return sum of two number represented by // the arrays. Size of a[] is greater than // b[]. It is made sure be the wrapper // function static int calSumUtil(int []a, int []b, int n, int m) { // array to store sum. int[] sum= new int[n]; int i = n - 1, j = m - 1, k = n - 1; int carry = 0, s = 0; // Until we reach beginning of array. // we are comparing only for second // array because we have already compare // the size of array in wrapper function. while (j >= 0) { // find sum of corresponding element // of both array. s = a[i] + b[j] + carry; sum[k] = (s % 10); // Finding carry for next sum. carry = s / 10; k--; i--; j--; } // If second array size is less // the first array size. while (i >= 0) { // Add carry to first array elements. s = a[i] + carry; sum[k] = (s % 10); carry = s / 10; i--; k--; } int ans = 0; // If there is carry on adding 0 index // elements append 1 to total sum. if (carry == 1) ans = 10; // Converting array into number. for ( i = 0; i <= n - 1; i++) { ans += sum[i]; ans *= 10; } return ans / 10; } // Wrapper Function static int calSum(int []a, int []b, int n, int m) { // Making first array which have // greater number of element if (n >= m) return calSumUtil(a, b, n, m); else return calSumUtil(b, a, m, n); } // Driver program public static void Main() { int []a = { 9, 3, 9 }; int []b = { 6, 1 }; int n = a.Length; int m = b.Length; Console.WriteLine(calSum(a, b, n, m)); }} // This article is contributed by vt_m. <?php// PHP program to sum two numbers// represented two arrays. // Return sum of two number represented// by the arrays. Size of a[] is greater// than b[]. It is made sure be the// wrapper functionfunction calSumUtil($a, $b, $n, $m){ // array to store sum. $sum = array(); $i = $n - 1; $j = $m - 1; $k = $n - 1; $carry = 0; $s = 0; // Until we reach beginning of array. // we are comparing only for second array // because we have already compare the size // of array in wrapper function. while ($j >= 0) { // find sum of corresponding // element of both array. $s = $a[$i] + $b[$j] + $carry; $sum[$k] = ($s % 10); // Finding carry for next sum. $carry = $s / 10; $k--; $i--; $j--; } // If second array size is less // than the first array size. while ($i >= 0) { // Add carry to first array elements. $s = $a[$i] + $carry; $sum[$k] = ($s % 10); $carry = $s / 10; $i--; $k--; } $ans = 0; // If there is carry on // adding 0 index elements. // append 1 to total sum. if ($carry) $ans = 10; // Converting array into number. for ( $i = 0; $i <= $n - 1; $i++) { $ans += $sum[$i]; $ans *= 10; } return $ans / 10;} // Wrapper Functionfunction calSum( $a, $b, $n, $m){ // Making first array which have // greater number of element if ($n >= $m) return calSumUtil($a, $b, $n, $m); else return calSumUtil($b, $a, $m, $n);} // Driven Code$a = array( 9, 3, 9 );$b = array( 6, 1 ); $n = count($a);$m = count($b); echo calSum($a, $b, $n, $m); // This article is contributed by anuj_67.?> <script> // Javascript program to sum two numbers represented two// arrays. // Return sum of two number represented by the arrays.// Size of a[] is greater than b[]. It is made sure// be the wrapper functionfunction calSumUtil(a, b, n, m){ // array to store sum. let sum = new Array(n); let i = n - 1, j = m - 1, k = n - 1; let carry = 0, s = 0; // Until we reach beginning of array. // we are comparing only for second array // because we have already compare the size // of array in wrapper function. while (j >= 0) { // find sum of corresponding element // of both arrays. s = a[i] + b[j] + carry; sum[k] = (s % 10); // Finding carry for next sum. carry = Math.floor(s / 10); k--; i--; j--; } // If second array size is less the first // array size. while (i >= 0) { // Add carry to first array elements. s = a[i] + carry; sum[k] = (s % 10); carry = Math.floor(s / 10); i--; k--; } let ans = 0; // If there is carry on adding 0 index elements. // append 1 to total sum. if (carry) ans = 10; // Converting array into number. for (let i = 0; i <= n - 1; i++) { ans += sum[i]; ans *= 10; } return ans / 10;} // Wrapper Functionfunction calSum(a, b, n, m){ // Making first array which have // greater number of element if (n >= m) return calSumUtil(a, b, n, m); else return calSumUtil(b, a, m, n);} // Driven Program let a = [ 9, 3, 9 ]; let b = [ 6, 1 ]; let n = a.length; let m = b.length; document.write(calSum(a, b, n, m) + "<br>"); // This code is contributed by Mayank Tyagi </script> Output : 1000 Time Complexity: O(n + m) Auxiliary Space: O(max(n, m)) gautamkumar vt_m SonamKumari subhammahato348 mayanktyagi1709 large-numbers Arrays Strings Arrays Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Linear Search Reverse a string in Java Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 25114, "s": 25086, "text": "\n19 Mar, 2021" }, { "code": null, "e": 25444, "s": 25114, "text": "Given two array A[0....n-1] and B[0....m-1] of size n and m respectively, representing two numbers such that every element of arrays represent a digit. For example, A[] = { 1, 2, 3} and B[] = { 2, 1, 4 } represent 123 and 214 respectively. The task is to find the sum of both the number. In above case, answer is 337. Examples : " }, { "code": null, "e": 25637, "s": 25444, "text": "Input : n = 3, m = 3\n a[] = { 1, 2, 3 }\n b[] = { 2, 1, 4 }\nOutput : 337\n123 + 214 = 337\n\nInput : n = 4, m = 3\n a[] = { 9, 5, 4, 9 }\n b[] = { 2, 1, 4 }\nOutput : 9763" }, { "code": null, "e": 26081, "s": 25637, "text": "The idea is to start traversing both the array simultaneously from the end until we reach the 0th index of either of the array. While traversing each elements of array, add element of both the array and carry from the previous sum. Now store the unit digit of the sum and forward carry for the next index sum. While adding 0th index element if the carry left, then append it to beginning of the number. Below is the illustration of approach: " }, { "code": null, "e": 26129, "s": 26081, "text": "Below is the implementation of this approach: " }, { "code": null, "e": 26133, "s": 26129, "text": "C++" }, { "code": null, "e": 26138, "s": 26133, "text": "Java" }, { "code": null, "e": 26146, "s": 26138, "text": "Python3" }, { "code": null, "e": 26149, "s": 26146, "text": "C#" }, { "code": null, "e": 26153, "s": 26149, "text": "PHP" }, { "code": null, "e": 26164, "s": 26153, "text": "Javascript" }, { "code": "// CPP program to sum two numbers represented two// arrays.#include <bits/stdc++.h>using namespace std; // Return sum of two number represented by the arrays.// Size of a[] is greater than b[]. It is made sure// be the wrapper functionint calSumUtil(int a[], int b[], int n, int m){ // array to store sum. int sum[n]; int i = n - 1, j = m - 1, k = n - 1; int carry = 0, s = 0; // Until we reach beginning of array. // we are comparing only for second array // because we have already compare the size // of array in wrapper function. while (j >= 0) { // find sum of corresponding element // of both arrays. s = a[i] + b[j] + carry; sum[k] = (s % 10); // Finding carry for next sum. carry = s / 10; k--; i--; j--; } // If second array size is less the first // array size. while (i >= 0) { // Add carry to first array elements. s = a[i] + carry; sum[k] = (s % 10); carry = s / 10; i--; k--; } int ans = 0; // If there is carry on adding 0 index elements. // append 1 to total sum. if (carry) ans = 10; // Converting array into number. for (int i = 0; i <= n - 1; i++) { ans += sum[i]; ans *= 10; } return ans / 10;} // Wrapper Functionint calSum(int a[], int b[], int n, int m){ // Making first array which have // greater number of element if (n >= m) return calSumUtil(a, b, n, m); else return calSumUtil(b, a, m, n);} // Driven Programint main(){ int a[] = { 9, 3, 9 }; int b[] = { 6, 1 }; int n = sizeof(a) / sizeof(a[0]); int m = sizeof(b) / sizeof(b[0]); cout << calSum(a, b, n, m) << endl; return 0;}", "e": 27924, "s": 26164, "text": null }, { "code": "// Java program to sum two numbers // represented two arrays.import java.io.*; class GFG { // Return sum of two number represented by // the arrays. Size of a[] is greater than // b[]. It is made sure be the wrapper // function static int calSumUtil(int a[], int b[], int n, int m) { // array to store sum. int[] sum= new int[n]; int i = n - 1, j = m - 1, k = n - 1; int carry = 0, s = 0; // Until we reach beginning of array. // we are comparing only for second // array because we have already compare // the size of array in wrapper function. while (j >= 0) { // find sum of corresponding element // of both array. s = a[i] + b[j] + carry; sum[k] = (s % 10); // Finding carry for next sum. carry = s / 10; k--; i--; j--; } // If second array size is less // the first array size. while (i >= 0) { // Add carry to first array elements. s = a[i] + carry; sum[k] = (s % 10); carry = s / 10; i--; k--; } int ans = 0; // If there is carry on adding 0 index // elements append 1 to total sum. if (carry == 1) ans = 10; // Converting array into number. for ( i = 0; i <= n - 1; i++) { ans += sum[i]; ans *= 10; } return ans / 10; } // Wrapper Function static int calSum(int a[], int b[], int n, int m) { // Making first array which have // greater number of element if (n >= m) return calSumUtil(a, b, n, m); else return calSumUtil(b, a, m, n); } /* Driver program to test above function */ public static void main(String[] args) { int a[] = { 9, 3, 9 }; int b[] = { 6, 1 }; int n = a.length; int m = b.length; System.out.println(calSum(a, b, n, m)); }} // This article is contributed by Gitanjali.", "e": 30191, "s": 27924, "text": null }, { "code": "# Python3 code to sum two numbers# representer two arrays. # Return sum of two number represented# by the arrays. Size of a[] is greater# than b[]. It is made sure be the# wrapper functiondef calSumUtil( a , b , n , m ): # array to store sum. sum = [0] * n i = n - 1 j = m - 1 k = n - 1 carry = 0 s = 0 # Until we reach beginning of array. # we are comparing only for second array # because we have already compare the size # of array in wrapper function. while j >= 0: # find sum of corresponding element # of both array. s = a[i] + b[j] + carry sum[k] = (s % 10) # Finding carry for next sum. carry = s // 10 k-=1 i-=1 j-=1 # If second array size is less the first # array size. while i >= 0: # Add carry to first array elements. s = a[i] + carry sum[k] = (s % 10) carry = s // 10 i-=1 k-=1 ans = 0 # If there is carry on adding 0 index elements. # append 1 to total sum. if carry: ans = 10 # Converting array into number. for i in range(n): ans += sum[i] ans *= 10 return ans // 10 # Wrapper Functiondef calSum(a, b, n, m ): # Making first array which have # greater number of element if n >= m: return calSumUtil(a, b, n, m) else: return calSumUtil(b, a, m, n) # Driven Codea = [ 9, 3, 9 ]b = [ 6, 1 ]n = len(a)m = len(b)print(calSum(a, b, n, m)) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 31769, "s": 30191, "text": null }, { "code": "// C# program to sum two numbers// represented two arrays.using System; class GFG { // Return sum of two number represented by // the arrays. Size of a[] is greater than // b[]. It is made sure be the wrapper // function static int calSumUtil(int []a, int []b, int n, int m) { // array to store sum. int[] sum= new int[n]; int i = n - 1, j = m - 1, k = n - 1; int carry = 0, s = 0; // Until we reach beginning of array. // we are comparing only for second // array because we have already compare // the size of array in wrapper function. while (j >= 0) { // find sum of corresponding element // of both array. s = a[i] + b[j] + carry; sum[k] = (s % 10); // Finding carry for next sum. carry = s / 10; k--; i--; j--; } // If second array size is less // the first array size. while (i >= 0) { // Add carry to first array elements. s = a[i] + carry; sum[k] = (s % 10); carry = s / 10; i--; k--; } int ans = 0; // If there is carry on adding 0 index // elements append 1 to total sum. if (carry == 1) ans = 10; // Converting array into number. for ( i = 0; i <= n - 1; i++) { ans += sum[i]; ans *= 10; } return ans / 10; } // Wrapper Function static int calSum(int []a, int []b, int n, int m) { // Making first array which have // greater number of element if (n >= m) return calSumUtil(a, b, n, m); else return calSumUtil(b, a, m, n); } // Driver program public static void Main() { int []a = { 9, 3, 9 }; int []b = { 6, 1 }; int n = a.Length; int m = b.Length; Console.WriteLine(calSum(a, b, n, m)); }} // This article is contributed by vt_m.", "e": 33976, "s": 31769, "text": null }, { "code": "<?php// PHP program to sum two numbers// represented two arrays. // Return sum of two number represented// by the arrays. Size of a[] is greater// than b[]. It is made sure be the// wrapper functionfunction calSumUtil($a, $b, $n, $m){ // array to store sum. $sum = array(); $i = $n - 1; $j = $m - 1; $k = $n - 1; $carry = 0; $s = 0; // Until we reach beginning of array. // we are comparing only for second array // because we have already compare the size // of array in wrapper function. while ($j >= 0) { // find sum of corresponding // element of both array. $s = $a[$i] + $b[$j] + $carry; $sum[$k] = ($s % 10); // Finding carry for next sum. $carry = $s / 10; $k--; $i--; $j--; } // If second array size is less // than the first array size. while ($i >= 0) { // Add carry to first array elements. $s = $a[$i] + $carry; $sum[$k] = ($s % 10); $carry = $s / 10; $i--; $k--; } $ans = 0; // If there is carry on // adding 0 index elements. // append 1 to total sum. if ($carry) $ans = 10; // Converting array into number. for ( $i = 0; $i <= $n - 1; $i++) { $ans += $sum[$i]; $ans *= 10; } return $ans / 10;} // Wrapper Functionfunction calSum( $a, $b, $n, $m){ // Making first array which have // greater number of element if ($n >= $m) return calSumUtil($a, $b, $n, $m); else return calSumUtil($b, $a, $m, $n);} // Driven Code$a = array( 9, 3, 9 );$b = array( 6, 1 ); $n = count($a);$m = count($b); echo calSum($a, $b, $n, $m); // This article is contributed by anuj_67.?>", "e": 35695, "s": 33976, "text": null }, { "code": "<script> // Javascript program to sum two numbers represented two// arrays. // Return sum of two number represented by the arrays.// Size of a[] is greater than b[]. It is made sure// be the wrapper functionfunction calSumUtil(a, b, n, m){ // array to store sum. let sum = new Array(n); let i = n - 1, j = m - 1, k = n - 1; let carry = 0, s = 0; // Until we reach beginning of array. // we are comparing only for second array // because we have already compare the size // of array in wrapper function. while (j >= 0) { // find sum of corresponding element // of both arrays. s = a[i] + b[j] + carry; sum[k] = (s % 10); // Finding carry for next sum. carry = Math.floor(s / 10); k--; i--; j--; } // If second array size is less the first // array size. while (i >= 0) { // Add carry to first array elements. s = a[i] + carry; sum[k] = (s % 10); carry = Math.floor(s / 10); i--; k--; } let ans = 0; // If there is carry on adding 0 index elements. // append 1 to total sum. if (carry) ans = 10; // Converting array into number. for (let i = 0; i <= n - 1; i++) { ans += sum[i]; ans *= 10; } return ans / 10;} // Wrapper Functionfunction calSum(a, b, n, m){ // Making first array which have // greater number of element if (n >= m) return calSumUtil(a, b, n, m); else return calSumUtil(b, a, m, n);} // Driven Program let a = [ 9, 3, 9 ]; let b = [ 6, 1 ]; let n = a.length; let m = b.length; document.write(calSum(a, b, n, m) + \"<br>\"); // This code is contributed by Mayank Tyagi </script>", "e": 37438, "s": 35695, "text": null }, { "code": null, "e": 37449, "s": 37438, "text": "Output : " }, { "code": null, "e": 37454, "s": 37449, "text": "1000" }, { "code": null, "e": 37480, "s": 37454, "text": "Time Complexity: O(n + m)" }, { "code": null, "e": 37511, "s": 37480, "text": "Auxiliary Space: O(max(n, m)) " }, { "code": null, "e": 37523, "s": 37511, "text": "gautamkumar" }, { "code": null, "e": 37528, "s": 37523, "text": "vt_m" }, { "code": null, "e": 37540, "s": 37528, "text": "SonamKumari" }, { "code": null, "e": 37556, "s": 37540, "text": "subhammahato348" }, { "code": null, "e": 37572, "s": 37556, "text": "mayanktyagi1709" }, { "code": null, "e": 37586, "s": 37572, "text": "large-numbers" }, { "code": null, "e": 37593, "s": 37586, "text": "Arrays" }, { "code": null, "e": 37601, "s": 37593, "text": "Strings" }, { "code": null, "e": 37608, "s": 37601, "text": "Arrays" }, { "code": null, "e": 37616, "s": 37608, "text": "Strings" }, { "code": null, "e": 37714, "s": 37616, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37762, "s": 37714, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 37806, "s": 37762, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 37838, "s": 37806, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 37861, "s": 37838, "text": "Introduction to Arrays" }, { "code": null, "e": 37875, "s": 37861, "text": "Linear Search" }, { "code": null, "e": 37900, "s": 37875, "text": "Reverse a string in Java" }, { "code": null, "e": 37934, "s": 37900, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 37994, "s": 37934, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 38009, "s": 37994, "text": "C++ Data Types" } ]
Prime Factors | Practice | GeeksforGeeks
Given a number N. Find its unique prime factors in increasing order. Example 1: Input: N = 100 Output: 2 5 Explanation: 2 and 5 are the unique prime factors of 100. Example 2: Input: N = 35 Output: 5 7 Explanation: 5 and 7 are the unique prime factors of 35. Your Task: You don't need to read or print anything. Your task is to complete the function AllPrimeFactors() which takes N as input parameter and returns a list of all unique prime factors of N in increasing order. Expected Time Complexity: O(N) Expected Space Complexity: O(N) Constraints: 1 <= N <= 106 0 pruthvibelgaonkar4692 months ago SIMPLEST SOLUTION vector<int>AllPrimeFactors(int n) { vector<int>v; set<int>s; if(n==2) { s.insert(n); } for(int i=2;i<=n;i++) { while(n%i==0) { s.insert(i); n/=i; } } for(auto it:s) { v.push_back(it); } return v;} 0 shreyash9779662 months ago vector<int>AllPrimeFactors(int n) { // Code here set<int>s; vector<int>v; if(n==2) s.insert(n); for(int i=2;i<=n;i++){ while(n%i==0){ s.insert(i); n/=i; } } for(auto it:s){ v.push_back(it); } return v; } 0 ayazmrz982 months ago static boolean isprime(int n) { if(n<=1) { return false; } for(int i=2;i<=Math.sqrt(n);i++) { if(n%i==0) { return false; } } return true; } public int[] AllPrimeFactors(int N) { ArrayList<Integer> arr = new ArrayList<Integer>(); for(int i=2;i<=N;i++) { int m=0; if(N%i==0) { m=i; if(isprime(m)) { arr.add(m); } } } int[] result = new int[arr.size()]; for(int i=0;i<arr.size();i++) { result[i]=arr.get(i); } return result; } +1 shubhamkhavare2 months ago Simple Java Code: class Solution{ public Boolean isPrime(int n){ if(n <= 1) { return false; } for(int i = 2 ; i <= Math.sqrt(n) ; i++) { if(n%i == 0) { return false; } } return true; } public int[] AllPrimeFactors(int N) { ArrayList<Integer> al = new ArrayList<Integer>(); for(int i = 1 ; i <= N ; i++) { int m = 0; if(N%i == 0) { m = i; } if(isPrime(m)) { al.add(i); } } int[] arr = new int[al.size()]; for(int i = 0 ; i < al.size(); i++) { arr[i] = al.get(i); } return arr; }} 0 snehads26133 months ago vector<int>AllPrimeFactors(int n) { // Code here set<int> st; vector<int> v; for(int i=2;i*i<=n;i++){ while(n%i==0){ st.insert(i); n/=i; } } if(n>1){ st.insert(n); } for(auto it: st){ v.push_back(it); } return v;} 0 sahibealam293 months ago class Solution{ public int[] AllPrimeFactors(int N) { ArrayList<Integer> arrLi = new ArrayList<>(); if(N%2==0){ arrLi.add(2); while(N%2==0) N/=2; } for(int i=3;i<=Math.sqrt(N);i+=2){ if(N%i==0) arrLi.add(i); while(N%i==0) N/=i; } if(N!=1) arrLi.add(N); int[] arr = arrLi.stream().mapToInt(index -> index).toArray(); return arr; // code here }} 0 sahibealam293 months ago class Solution{public:vector<int> AllPrimeFactors(int N) { vector<int> vi; if(N%2==0){ vi.push_back(2); while(N%2==0) N/=2; } for(int i=3;i<=sqrt(N);i+=2){ if(N%i==0) vi.push_back(i); while(N%i==0) N/=i; } if(N!=1) vi.push_back(N); return vi; // Code here}}; 0 abhishekguptaaa3 months ago class Solution{public:vector<int>AllPrimeFactors(int N) { vector<int> v; for(int i=2;i*i<=N;i++) { if(N%i==0) { while(N%i==0) { N=N/i; v.push_back(i); } } } if(N>1) { v.push_back(N); } //for deleting the duplicate elements in the vector v.erase(unique(v.begin(),v.end()),v.end()); return v; }}; 0 akashdeepchauhan19994 months ago class Solution{ public int[] AllPrimeFactors(int n) { ArrayList<Integer>al = new ArrayList<>(); int j = 0; for(int i =2; i*i <= n; i++) { if(n % i == 0) { al.add(i); while(n%i == 0) { n = n/i; } } } if(n!= 1) { al.add(n); } int l = al.size(); int [] ans = new int[l]; for(Integer p : al) { ans[j++] = p; } return ans; }} -1 Brijesh Yadav10 months ago Brijesh Yadav class Solution{public: bool isprime(int n1){ for(int i=2;i*i<=n1;i++) { if(n1%i==0) { return false; } } return true;} vector<int>AllPrimeFactors(int n) { // Code here vector<int>v; for(int i=2;i<=n;i++) { if(n%i==0) { if(isprime(i)) { v.push_back(i); } } } return v; }}; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 309, "s": 238, "text": "Given a number N. Find its unique prime factors in increasing order.\n " }, { "code": null, "e": 320, "s": 309, "text": "Example 1:" }, { "code": null, "e": 406, "s": 320, "text": "Input: N = 100\nOutput: 2 5\nExplanation: 2 and 5 are the unique prime\nfactors of 100.\n" }, { "code": null, "e": 417, "s": 406, "text": "Example 2:" }, { "code": null, "e": 501, "s": 417, "text": "Input: N = 35\nOutput: 5 7\nExplanation: 5 and 7 are the unique prime\nfactors of 35.\n" }, { "code": null, "e": 718, "s": 503, "text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function AllPrimeFactors() which takes N as input parameter and returns a list of all unique prime factors of N in increasing order." }, { "code": null, "e": 785, "s": 720, "text": "Expected Time Complexity: O(N)\nExpected Space Complexity: O(N)\n " }, { "code": null, "e": 813, "s": 785, "text": "Constraints:\n1 <= N <= 106" }, { "code": null, "e": 815, "s": 813, "text": "0" }, { "code": null, "e": 848, "s": 815, "text": "pruthvibelgaonkar4692 months ago" }, { "code": null, "e": 866, "s": 848, "text": "SIMPLEST SOLUTION" }, { "code": null, "e": 1163, "s": 868, "text": "vector<int>AllPrimeFactors(int n) { vector<int>v; set<int>s; if(n==2) { s.insert(n); } for(int i=2;i<=n;i++) { while(n%i==0) { s.insert(i); n/=i; } } for(auto it:s) { v.push_back(it); } return v;}" }, { "code": null, "e": 1165, "s": 1163, "text": "0" }, { "code": null, "e": 1192, "s": 1165, "text": "shreyash9779662 months ago" }, { "code": null, "e": 1504, "s": 1192, "text": "\tvector<int>AllPrimeFactors(int n) {\n\t // Code here\n\t set<int>s;\n\t vector<int>v;\n\t if(n==2) s.insert(n);\n\t for(int i=2;i<=n;i++){\n\t while(n%i==0){\n\t s.insert(i);\n\t n/=i;\n\t }\n\t }\n\t \n\t for(auto it:s){\n\t v.push_back(it);\n\t }\n\t return v;\n\t \n\t}" }, { "code": null, "e": 1506, "s": 1504, "text": "0" }, { "code": null, "e": 1528, "s": 1506, "text": "ayazmrz982 months ago" }, { "code": null, "e": 2094, "s": 1528, "text": "static boolean isprime(int n)\n {\n if(n<=1)\n {\n return false;\n }\n for(int i=2;i<=Math.sqrt(n);i++)\n {\n if(n%i==0)\n {\n return false;\n }\n }\n return true;\n }\n public int[] AllPrimeFactors(int N)\n {\n ArrayList<Integer> arr = new ArrayList<Integer>();\n for(int i=2;i<=N;i++)\n {\n int m=0;\n if(N%i==0)\n {\n m=i; \n if(isprime(m))\n {\n arr.add(m);\n }\n }" }, { "code": null, "e": 2261, "s": 2094, "text": " }\n int[] result = new int[arr.size()];\n for(int i=0;i<arr.size();i++)\n {\n result[i]=arr.get(i);\n }\n return result;\n }" }, { "code": null, "e": 2264, "s": 2261, "text": "+1" }, { "code": null, "e": 2291, "s": 2264, "text": "shubhamkhavare2 months ago" }, { "code": null, "e": 2309, "s": 2291, "text": "Simple Java Code:" }, { "code": null, "e": 3037, "s": 2309, "text": "class Solution{ public Boolean isPrime(int n){ if(n <= 1) { return false; } for(int i = 2 ; i <= Math.sqrt(n) ; i++) { if(n%i == 0) { return false; } } return true; } public int[] AllPrimeFactors(int N) { ArrayList<Integer> al = new ArrayList<Integer>(); for(int i = 1 ; i <= N ; i++) { int m = 0; if(N%i == 0) { m = i; } if(isPrime(m)) { al.add(i); } } int[] arr = new int[al.size()]; for(int i = 0 ; i < al.size(); i++) { arr[i] = al.get(i); } return arr; }}" }, { "code": null, "e": 3039, "s": 3037, "text": "0" }, { "code": null, "e": 3063, "s": 3039, "text": "snehads26133 months ago" }, { "code": null, "e": 3361, "s": 3063, "text": "vector<int>AllPrimeFactors(int n) { // Code here set<int> st; vector<int> v; for(int i=2;i*i<=n;i++){ while(n%i==0){ st.insert(i); n/=i; } } if(n>1){ st.insert(n); } for(auto it: st){ v.push_back(it); } return v;}" }, { "code": null, "e": 3363, "s": 3361, "text": "0" }, { "code": null, "e": 3388, "s": 3363, "text": "sahibealam293 months ago" }, { "code": null, "e": 3842, "s": 3388, "text": "class Solution{ public int[] AllPrimeFactors(int N) { ArrayList<Integer> arrLi = new ArrayList<>(); if(N%2==0){ arrLi.add(2); while(N%2==0) N/=2; } for(int i=3;i<=Math.sqrt(N);i+=2){ if(N%i==0) arrLi.add(i); while(N%i==0) N/=i; } if(N!=1) arrLi.add(N); int[] arr = arrLi.stream().mapToInt(index -> index).toArray(); return arr; // code here }}" }, { "code": null, "e": 3844, "s": 3842, "text": "0" }, { "code": null, "e": 3869, "s": 3844, "text": "sahibealam293 months ago" }, { "code": null, "e": 4220, "s": 3869, "text": "class Solution{public:vector<int> AllPrimeFactors(int N) { vector<int> vi; if(N%2==0){ vi.push_back(2); while(N%2==0) N/=2; } for(int i=3;i<=sqrt(N);i+=2){ if(N%i==0) vi.push_back(i); while(N%i==0) N/=i; } if(N!=1) vi.push_back(N); return vi; // Code here}};" }, { "code": null, "e": 4222, "s": 4220, "text": "0" }, { "code": null, "e": 4250, "s": 4222, "text": "abhishekguptaaa3 months ago" }, { "code": null, "e": 4699, "s": 4250, "text": "class Solution{public:vector<int>AllPrimeFactors(int N) { vector<int> v; for(int i=2;i*i<=N;i++) { if(N%i==0) { while(N%i==0) { N=N/i; v.push_back(i); } } } if(N>1) { v.push_back(N); } //for deleting the duplicate elements in the vector v.erase(unique(v.begin(),v.end()),v.end()); return v; }};" }, { "code": null, "e": 4701, "s": 4699, "text": "0" }, { "code": null, "e": 4734, "s": 4701, "text": "akashdeepchauhan19994 months ago" }, { "code": null, "e": 5288, "s": 4734, "text": "class Solution{ public int[] AllPrimeFactors(int n) { ArrayList<Integer>al = new ArrayList<>(); int j = 0; for(int i =2; i*i <= n; i++) { if(n % i == 0) { al.add(i); while(n%i == 0) { n = n/i; } } } if(n!= 1) { al.add(n); } int l = al.size(); int [] ans = new int[l]; for(Integer p : al) { ans[j++] = p; } return ans; }}" }, { "code": null, "e": 5291, "s": 5288, "text": "-1" }, { "code": null, "e": 5318, "s": 5291, "text": "Brijesh Yadav10 months ago" }, { "code": null, "e": 5332, "s": 5318, "text": "Brijesh Yadav" }, { "code": null, "e": 5355, "s": 5332, "text": "class Solution{public:" }, { "code": null, "e": 5494, "s": 5355, "text": "bool isprime(int n1){ for(int i=2;i*i<=n1;i++) { if(n1%i==0) { return false; } } return true;}" }, { "code": null, "e": 5546, "s": 5494, "text": "vector<int>AllPrimeFactors(int n) { // Code here" }, { "code": null, "e": 5564, "s": 5546, "text": " vector<int>v;" }, { "code": null, "e": 5732, "s": 5564, "text": " for(int i=2;i<=n;i++) { if(n%i==0) { if(isprime(i)) { v.push_back(i); } } } return v;" }, { "code": null, "e": 5736, "s": 5732, "text": "}};" }, { "code": null, "e": 5882, "s": 5736, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5918, "s": 5882, "text": " Login to access your submissions. " }, { "code": null, "e": 5928, "s": 5918, "text": "\nProblem\n" }, { "code": null, "e": 5938, "s": 5928, "text": "\nContest\n" }, { "code": null, "e": 6001, "s": 5938, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6149, "s": 6001, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6357, "s": 6149, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6463, "s": 6357, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Print lists in Python (4 Different Ways) - GeeksforGeeks
27 Aug, 2021 Printing a list in python can be done is following ways: Using for loop : Traverse from 0 to len(list) and print all elements of the list one by one using a for loop, this is the standard practice of doing it.PythonPython# Python program to print list# using for loopa = [1, 2, 3, 4, 5] # printing the list using loopfor x in range(len(a)): print a[x],Output:1 2 3 4 5 Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively.PythonPython# Python program to print list# without using loop a = [1, 2, 3, 4, 5] # printing the list using * operator separated # by space print(*a) # printing the list using * and sep operatorprint("printing lists separated by commas") print(*a, sep = ", ") # print in new lineprint("printing lists in new line") print(*a, sep = "\n")Output:1 2 3 4 5 printing lists separated by commas 1, 2, 3, 4, 5 printing lists in new line 1 2 3 4 5 Convert a list to a string for display : If it is a list of strings we can simply join them using join() function, but if the list contains integers then convert it into string and then use join() function to join them to a string and print the string.PythonPython# Python program to print list# by Converting a list to a # string for displaya =["Geeks", "for", "Geeks"] # print the list using join function()print(' '.join(a)) # print the list by converting a list of # integers to string a = [1, 2, 3, 4, 5] print str(a)[1:-1] Output:Geeks for Geeks 1, 2, 3, 4, 5 Using map : Use map() to convert each item in the list to a string if list is not a string, and then join them:PythonPython# Python program to print list# print the list by converting a list of # integers to string using map a = [1, 2, 3, 4, 5]print(' '.join(map(str, a))) print"in new line"print('\n'.join(map(str, a)))Output:1 2 3 4 5 in new line 1 2 3 4 5 Using for loop : Traverse from 0 to len(list) and print all elements of the list one by one using a for loop, this is the standard practice of doing it.PythonPython# Python program to print list# using for loopa = [1, 2, 3, 4, 5] # printing the list using loopfor x in range(len(a)): print a[x],Output:1 2 3 4 5 Python # Python program to print list# using for loopa = [1, 2, 3, 4, 5] # printing the list using loopfor x in range(len(a)): print a[x], 1 2 3 4 5 Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively.PythonPython# Python program to print list# without using loop a = [1, 2, 3, 4, 5] # printing the list using * operator separated # by space print(*a) # printing the list using * and sep operatorprint("printing lists separated by commas") print(*a, sep = ", ") # print in new lineprint("printing lists in new line") print(*a, sep = "\n")Output:1 2 3 4 5 printing lists separated by commas 1, 2, 3, 4, 5 printing lists in new line 1 2 3 4 5 Python # Python program to print list# without using loop a = [1, 2, 3, 4, 5] # printing the list using * operator separated # by space print(*a) # printing the list using * and sep operatorprint("printing lists separated by commas") print(*a, sep = ", ") # print in new lineprint("printing lists in new line") print(*a, sep = "\n") 1 2 3 4 5 printing lists separated by commas 1, 2, 3, 4, 5 printing lists in new line 1 2 3 4 5 Convert a list to a string for display : If it is a list of strings we can simply join them using join() function, but if the list contains integers then convert it into string and then use join() function to join them to a string and print the string.PythonPython# Python program to print list# by Converting a list to a # string for displaya =["Geeks", "for", "Geeks"] # print the list using join function()print(' '.join(a)) # print the list by converting a list of # integers to string a = [1, 2, 3, 4, 5] print str(a)[1:-1] Output:Geeks for Geeks 1, 2, 3, 4, 5 Python # Python program to print list# by Converting a list to a # string for displaya =["Geeks", "for", "Geeks"] # print the list using join function()print(' '.join(a)) # print the list by converting a list of # integers to string a = [1, 2, 3, 4, 5] print str(a)[1:-1] Geeks for Geeks 1, 2, 3, 4, 5 Using map : Use map() to convert each item in the list to a string if list is not a string, and then join them:PythonPython# Python program to print list# print the list by converting a list of # integers to string using map a = [1, 2, 3, 4, 5]print(' '.join(map(str, a))) print"in new line"print('\n'.join(map(str, a)))Output:1 2 3 4 5 in new line 1 2 3 4 5 Python # Python program to print list# print the list by converting a list of # integers to string using map a = [1, 2, 3, 4, 5]print(' '.join(map(str, a))) print"in new line"print('\n'.join(map(str, a))) 1 2 3 4 5 in new line 1 2 3 4 5 sumitgumber28 python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe *args and **kwargs in Python Graph Plotting in Python | Set 1 How To Convert Python Dictionary To JSON? Check if element exists in list in Python Convert integer to string in Python Python | Program to convert String to a List Python | Pandas dataframe.groupby()
[ { "code": null, "e": 23761, "s": 23733, "text": "\n27 Aug, 2021" }, { "code": null, "e": 23818, "s": 23761, "text": "Printing a list in python can be done is following ways:" }, { "code": null, "e": 25701, "s": 23818, "text": "Using for loop : Traverse from 0 to len(list) and print all elements of the list one by one using a for loop, this is the standard practice of doing it.PythonPython# Python program to print list# using for loopa = [1, 2, 3, 4, 5] # printing the list using loopfor x in range(len(a)): print a[x],Output:1 2 3 4 5\nWithout using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\\n” or sep=”, ” respectively.PythonPython# Python program to print list# without using loop a = [1, 2, 3, 4, 5] # printing the list using * operator separated # by space print(*a) # printing the list using * and sep operatorprint(\"printing lists separated by commas\") print(*a, sep = \", \") # print in new lineprint(\"printing lists in new line\") print(*a, sep = \"\\n\")Output:1 2 3 4 5\nprinting lists separated by commas\n1, 2, 3, 4, 5\nprinting lists in new line\n1\n2\n3\n4\n5\nConvert a list to a string for display : If it is a list of strings we can simply join them using join() function, but if the list contains integers then convert it into string and then use join() function to join them to a string and print the string.PythonPython# Python program to print list# by Converting a list to a # string for displaya =[\"Geeks\", \"for\", \"Geeks\"] # print the list using join function()print(' '.join(a)) # print the list by converting a list of # integers to string a = [1, 2, 3, 4, 5] print str(a)[1:-1] Output:Geeks for Geeks\n1, 2, 3, 4, 5\nUsing map : Use map() to convert each item in the list to a string if list is not a string, and then join them:PythonPython# Python program to print list# print the list by converting a list of # integers to string using map a = [1, 2, 3, 4, 5]print(' '.join(map(str, a))) print\"in new line\"print('\\n'.join(map(str, a)))Output:1 2 3 4 5\nin new line\n1\n2\n3\n4\n5\n" }, { "code": null, "e": 26018, "s": 25701, "text": "Using for loop : Traverse from 0 to len(list) and print all elements of the list one by one using a for loop, this is the standard practice of doing it.PythonPython# Python program to print list# using for loopa = [1, 2, 3, 4, 5] # printing the list using loopfor x in range(len(a)): print a[x],Output:1 2 3 4 5\n" }, { "code": null, "e": 26025, "s": 26018, "text": "Python" }, { "code": "# Python program to print list# using for loopa = [1, 2, 3, 4, 5] # printing the list using loopfor x in range(len(a)): print a[x],", "e": 26161, "s": 26025, "text": null }, { "code": null, "e": 26172, "s": 26161, "text": "1 2 3 4 5\n" }, { "code": null, "e": 26808, "s": 26172, "text": "Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\\n” or sep=”, ” respectively.PythonPython# Python program to print list# without using loop a = [1, 2, 3, 4, 5] # printing the list using * operator separated # by space print(*a) # printing the list using * and sep operatorprint(\"printing lists separated by commas\") print(*a, sep = \", \") # print in new lineprint(\"printing lists in new line\") print(*a, sep = \"\\n\")Output:1 2 3 4 5\nprinting lists separated by commas\n1, 2, 3, 4, 5\nprinting lists in new line\n1\n2\n3\n4\n5\n" }, { "code": null, "e": 26815, "s": 26808, "text": "Python" }, { "code": "# Python program to print list# without using loop a = [1, 2, 3, 4, 5] # printing the list using * operator separated # by space print(*a) # printing the list using * and sep operatorprint(\"printing lists separated by commas\") print(*a, sep = \", \") # print in new lineprint(\"printing lists in new line\") print(*a, sep = \"\\n\")", "e": 27148, "s": 26815, "text": null }, { "code": null, "e": 27245, "s": 27148, "text": "1 2 3 4 5\nprinting lists separated by commas\n1, 2, 3, 4, 5\nprinting lists in new line\n1\n2\n3\n4\n5\n" }, { "code": null, "e": 27815, "s": 27245, "text": "Convert a list to a string for display : If it is a list of strings we can simply join them using join() function, but if the list contains integers then convert it into string and then use join() function to join them to a string and print the string.PythonPython# Python program to print list# by Converting a list to a # string for displaya =[\"Geeks\", \"for\", \"Geeks\"] # print the list using join function()print(' '.join(a)) # print the list by converting a list of # integers to string a = [1, 2, 3, 4, 5] print str(a)[1:-1] Output:Geeks for Geeks\n1, 2, 3, 4, 5\n" }, { "code": null, "e": 27822, "s": 27815, "text": "Python" }, { "code": "# Python program to print list# by Converting a list to a # string for displaya =[\"Geeks\", \"for\", \"Geeks\"] # print the list using join function()print(' '.join(a)) # print the list by converting a list of # integers to string a = [1, 2, 3, 4, 5] print str(a)[1:-1] ", "e": 28091, "s": 27822, "text": null }, { "code": null, "e": 28122, "s": 28091, "text": "Geeks for Geeks\n1, 2, 3, 4, 5\n" }, { "code": null, "e": 28485, "s": 28122, "text": "Using map : Use map() to convert each item in the list to a string if list is not a string, and then join them:PythonPython# Python program to print list# print the list by converting a list of # integers to string using map a = [1, 2, 3, 4, 5]print(' '.join(map(str, a))) print\"in new line\"print('\\n'.join(map(str, a)))Output:1 2 3 4 5\nin new line\n1\n2\n3\n4\n5\n" }, { "code": null, "e": 28492, "s": 28485, "text": "Python" }, { "code": "# Python program to print list# print the list by converting a list of # integers to string using map a = [1, 2, 3, 4, 5]print(' '.join(map(str, a))) print\"in new line\"print('\\n'.join(map(str, a)))", "e": 28693, "s": 28492, "text": null }, { "code": null, "e": 28726, "s": 28693, "text": "1 2 3 4 5\nin new line\n1\n2\n3\n4\n5\n" }, { "code": null, "e": 28740, "s": 28726, "text": "sumitgumber28" }, { "code": null, "e": 28752, "s": 28740, "text": "python-list" }, { "code": null, "e": 28759, "s": 28752, "text": "Python" }, { "code": null, "e": 28771, "s": 28759, "text": "python-list" }, { "code": null, "e": 28869, "s": 28771, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28878, "s": 28869, "text": "Comments" }, { "code": null, "e": 28891, "s": 28878, "text": "Old Comments" }, { "code": null, "e": 28923, "s": 28891, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28960, "s": 28923, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29016, "s": 28960, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29045, "s": 29016, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29078, "s": 29045, "text": "Graph Plotting in Python | Set 1" }, { "code": null, "e": 29120, "s": 29078, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29162, "s": 29120, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29198, "s": 29162, "text": "Convert integer to string in Python" }, { "code": null, "e": 29243, "s": 29198, "text": "Python | Program to convert String to a List" } ]
Python 3 - Number abs() Method
The abs() method returns the absolute value of x i.e. the positive distance between x and zero. Following is the syntax for abs() method − abs( x ) x − This is a numeric expression. This method returns the absolute value of x. The following example shows the usage of the abs() method. #!/usr/bin/python3 print ("abs(-45) : ", abs(-45)) print ("abs(100.12) : ", abs(100.12)) When we run the above program, it produces the following result − abs(-45) : 45 abs(100.12) : 100.12 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": 2436, "s": 2340, "text": "The abs() method returns the absolute value of x i.e. the positive distance between x and zero." }, { "code": null, "e": 2479, "s": 2436, "text": "Following is the syntax for abs() method −" }, { "code": null, "e": 2489, "s": 2479, "text": "abs( x )\n" }, { "code": null, "e": 2523, "s": 2489, "text": "x − This is a numeric expression." }, { "code": null, "e": 2568, "s": 2523, "text": "This method returns the absolute value of x." }, { "code": null, "e": 2627, "s": 2568, "text": "The following example shows the usage of the abs() method." }, { "code": null, "e": 2717, "s": 2627, "text": "#!/usr/bin/python3\n\nprint (\"abs(-45) : \", abs(-45))\nprint (\"abs(100.12) : \", abs(100.12))" }, { "code": null, "e": 2783, "s": 2717, "text": "When we run the above program, it produces the following result −" }, { "code": null, "e": 2821, "s": 2783, "text": "abs(-45) : 45\nabs(100.12) : 100.12\n" }, { "code": null, "e": 2858, "s": 2821, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 2874, "s": 2858, "text": " Malhar Lathkar" }, { "code": null, "e": 2907, "s": 2874, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 2926, "s": 2907, "text": " Arnab Chakraborty" }, { "code": null, "e": 2961, "s": 2926, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 2983, "s": 2961, "text": " In28Minutes Official" }, { "code": null, "e": 3017, "s": 2983, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3045, "s": 3017, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3080, "s": 3045, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3094, "s": 3080, "text": " Lets Kode It" }, { "code": null, "e": 3127, "s": 3094, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3144, "s": 3127, "text": " Abhilash Nelson" }, { "code": null, "e": 3151, "s": 3144, "text": " Print" }, { "code": null, "e": 3162, "s": 3151, "text": " Add Notes" } ]
Amazon WOW Interview Experience - GeeksforGeeks
04 Mar, 2022 I applied for the role of SDE I through Amazon WOW drive 2020. There were a total of 5 rounds (1 coding test + 4 interviews). Originally interviews were supposed to be offline but because of the coronavirus pandemic, I gave my interviews online. Round 1: Round 1 was an online coding round consisting of 2 coding questions and 28 MCQs based on C, C++, Java, data structures, algorithms, and core subjects. The first coding question was to convert the infix expression to postfix https://www.geeksforgeeks.org/stack-set-2-infix-to-postfix and the second was to find the mean, median, and mode of the given array. This round was for 1 hour 30 minutes. I solved both the coding questions completely. After getting shortlisted, a total of 4 interviews were to take place, each being eliminative in nature. The time for each was fixed to 60 minutes each and each of them involved writing the complete code on an IDE link shared by the interviewer. For each question, time complexity has to be told. Interviews: Interview 1: The interviewer started directly by giving coding questions. Alternate reversal of linked list in a group of size k. Like the first group should be reversed, the second group should be the same, the third should be reversed, the fourth should be the same, etc.Example : Input : 1->2->3->4->5->6->7->8, k=2 Output : 2->1->3->4->6->5->7->8There are two strings given to find the matching and non-matching characters.Example :Input : s1 = abc s2 = abd Output : matching = 2 non-matching = 1 Alternate reversal of linked list in a group of size k. Like the first group should be reversed, the second group should be the same, the third should be reversed, the fourth should be the same, etc.Example : Input : 1->2->3->4->5->6->7->8, k=2 Output : 2->1->3->4->6->5->7->8 Alternate reversal of linked list in a group of size k. Like the first group should be reversed, the second group should be the same, the third should be reversed, the fourth should be the same, etc. Example : Input : 1->2->3->4->5->6->7->8, k=2 Output : 2->1->3->4->6->5->7->8 There are two strings given to find the matching and non-matching characters.Example :Input : s1 = abc s2 = abd Output : matching = 2 non-matching = 1 There are two strings given to find the matching and non-matching characters. Example : Input : s1 = abc s2 = abd Output : matching = 2 non-matching = 1 I was able to solve both the questions in around 55 minutes. The interviewer seemed satisfied. I got a mail for the second interview after 2 days and the interview was scheduled after 2 days. Interview 2: Started with the interviewer’s introduction and then my introduction and then 2 coding questions. Reach from one start string to the destination string in a minimum number of steps provided some set of intermediate strings cannot be reached. The string consists of numbers starting from 0 to 9 and it works like a suitcase lock where from 0 there can be two options 1 or 9, similarly, from 1 we can go to 2 or 0. Hint: Use BFS constructing graphs of strings.Example: Input : Source = 123 Destination = 456 steps = 9Find a maximum of the difference between maximum and minimum of all subarrays of size k. In this interview, I was able to write code for both questions in just 25 minutes(Good luck maybe :-). Got mail for the third round the same day and the interview was on the next day. Reach from one start string to the destination string in a minimum number of steps provided some set of intermediate strings cannot be reached. The string consists of numbers starting from 0 to 9 and it works like a suitcase lock where from 0 there can be two options 1 or 9, similarly, from 1 we can go to 2 or 0. Hint: Use BFS constructing graphs of strings.Example: Input : Source = 123 Destination = 456 steps = 9 Reach from one start string to the destination string in a minimum number of steps provided some set of intermediate strings cannot be reached. The string consists of numbers starting from 0 to 9 and it works like a suitcase lock where from 0 there can be two options 1 or 9, similarly, from 1 we can go to 2 or 0. Hint: Use BFS constructing graphs of strings. Example: Input : Source = 123 Destination = 456 steps = 9 Find a maximum of the difference between maximum and minimum of all subarrays of size k. In this interview, I was able to write code for both questions in just 25 minutes(Good luck maybe :-). Got mail for the third round the same day and the interview was on the next day. Find a maximum of the difference between maximum and minimum of all subarrays of size k. In this interview, I was able to write code for both questions in just 25 minutes(Good luck maybe :-). Got mail for the third round the same day and the interview was on the next day. Interview 3: Given a family of ants, in which female and male ants are there, interactions b/w family members are given i.e., it is given who interacts with whom, find if it is a good family and a family is good if only two different genders interact. Example : Input: number of ants = 6, Interactions = { 1-2, 3-4, 5-6} Output - Good family Input : number of ants = 6 Interaction = {1-3, 3-5, 1-5} Output - Bad familyNext greater elementAnd questions on os(Explain Banker’s algorithm with an example, Thrashing, Deadlock, Semaphore, etc), DBMS(ACID properties), oops, and projects. Given a family of ants, in which female and male ants are there, interactions b/w family members are given i.e., it is given who interacts with whom, find if it is a good family and a family is good if only two different genders interact. Example : Input: number of ants = 6, Interactions = { 1-2, 3-4, 5-6} Output - Good family Input : number of ants = 6 Interaction = {1-3, 3-5, 1-5} Output - Bad family Given a family of ants, in which female and male ants are there, interactions b/w family members are given i.e., it is given who interacts with whom, find if it is a good family and a family is good if only two different genders interact. Example : Input: number of ants = 6, Interactions = { 1-2, 3-4, 5-6} Output - Good family Input : number of ants = 6 Interaction = {1-3, 3-5, 1-5} Output - Bad family Next greater elementAnd questions on os(Explain Banker’s algorithm with an example, Thrashing, Deadlock, Semaphore, etc), DBMS(ACID properties), oops, and projects. Next greater element And questions on os(Explain Banker’s algorithm with an example, Thrashing, Deadlock, Semaphore, etc), DBMS(ACID properties), oops, and projects. The first question seemed very new to me. After thinking a lot I was able to get that there shouldn’t be any odd cycle in the graph formed from interactions. I tried writing code but the interview wasn’t very much satisfactory. Then he moved to the next question. As the second question is a very common question, I instantly started telling the solution, by which the interviewer asked do you know this question and I said yes. He asked me to write code in just 2 minutes without any bugs, And I wrote it, but he could find one bug out of it After this interview, I didn’t expect a call for the next interview. But luckily I got the mail after 6 days for the next round to be scheduled the next day. Final Interview: Started with the introduction, project questions, and behavioural questions. Like, Give an example where you spent some time and figured out something on your own. Given two arrays move an element from one array to another only if the average of both the arrays become greater than the previous average find which element can be movedSome BFS related questions don’t remember exactlyMinimum element in the stack without using another stack Given two arrays move an element from one array to another only if the average of both the arrays become greater than the previous average find which element can be moved Some BFS related questions don’t remember exactly Minimum element in the stack without using another stack In the first question, I got nervous and couldn’t come up with an approach. The interviewer was very friendly and helped me to understand the approach and then asked me to write the code. The next two questions I was able to solve. After around 15-20 days, I got mail that I have been selected as a SIDE at Amazon. I would suggest being patient and calm during the interview. Think out loud. The interviewer is there to help you out. Best of luck!! Amazon Amazon-WoW Marketing Interview Experiences Amazon Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Difference between ANN, CNN and RNN Amazon Interview Experience Amazon Interview Experience for SDE-1 JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 Amazon Interview Experience (Off-Campus) 2022 Infosys Interview Experience for DSE 2022 Amazon Interview Experience for SDE-1 (On-Campus) Infosys Interview Experience for Digital Specialist Engineer Through InfyTQ
[ { "code": null, "e": 26393, "s": 26365, "text": "\n04 Mar, 2022" }, { "code": null, "e": 26639, "s": 26393, "text": "I applied for the role of SDE I through Amazon WOW drive 2020. There were a total of 5 rounds (1 coding test + 4 interviews). Originally interviews were supposed to be offline but because of the coronavirus pandemic, I gave my interviews online." }, { "code": null, "e": 27043, "s": 26639, "text": "Round 1: Round 1 was an online coding round consisting of 2 coding questions and 28 MCQs based on C, C++, Java, data structures, algorithms, and core subjects. The first coding question was to convert the infix expression to postfix https://www.geeksforgeeks.org/stack-set-2-infix-to-postfix and the second was to find the mean, median, and mode of the given array. This round was for 1 hour 30 minutes." }, { "code": null, "e": 27387, "s": 27043, "text": "I solved both the coding questions completely. After getting shortlisted, a total of 4 interviews were to take place, each being eliminative in nature. The time for each was fixed to 60 minutes each and each of them involved writing the complete code on an IDE link shared by the interviewer. For each question, time complexity has to be told." }, { "code": null, "e": 27399, "s": 27387, "text": "Interviews:" }, { "code": null, "e": 27473, "s": 27399, "text": "Interview 1: The interviewer started directly by giving coding questions." }, { "code": null, "e": 27902, "s": 27473, "text": "Alternate reversal of linked list in a group of size k. Like the first group should be reversed, the second group should be the same, the third should be reversed, the fourth should be the same, etc.Example : Input : 1->2->3->4->5->6->7->8, k=2\nOutput : 2->1->3->4->6->5->7->8There are two strings given to find the matching and non-matching characters.Example :Input : s1 = abc s2 = abd \nOutput : matching = 2 non-matching = 1" }, { "code": null, "e": 28180, "s": 27902, "text": "Alternate reversal of linked list in a group of size k. Like the first group should be reversed, the second group should be the same, the third should be reversed, the fourth should be the same, etc.Example : Input : 1->2->3->4->5->6->7->8, k=2\nOutput : 2->1->3->4->6->5->7->8" }, { "code": null, "e": 28380, "s": 28180, "text": "Alternate reversal of linked list in a group of size k. Like the first group should be reversed, the second group should be the same, the third should be reversed, the fourth should be the same, etc." }, { "code": null, "e": 28391, "s": 28380, "text": "Example : " }, { "code": null, "e": 28460, "s": 28391, "text": "Input : 1->2->3->4->5->6->7->8, k=2\nOutput : 2->1->3->4->6->5->7->8" }, { "code": null, "e": 28612, "s": 28460, "text": "There are two strings given to find the matching and non-matching characters.Example :Input : s1 = abc s2 = abd \nOutput : matching = 2 non-matching = 1" }, { "code": null, "e": 28690, "s": 28612, "text": "There are two strings given to find the matching and non-matching characters." }, { "code": null, "e": 28700, "s": 28690, "text": "Example :" }, { "code": null, "e": 28766, "s": 28700, "text": "Input : s1 = abc s2 = abd \nOutput : matching = 2 non-matching = 1" }, { "code": null, "e": 28958, "s": 28766, "text": "I was able to solve both the questions in around 55 minutes. The interviewer seemed satisfied. I got a mail for the second interview after 2 days and the interview was scheduled after 2 days." }, { "code": null, "e": 29069, "s": 28958, "text": "Interview 2: Started with the interviewer’s introduction and then my introduction and then 2 coding questions." }, { "code": null, "e": 29760, "s": 29069, "text": "Reach from one start string to the destination string in a minimum number of steps provided some set of intermediate strings cannot be reached. The string consists of numbers starting from 0 to 9 and it works like a suitcase lock where from 0 there can be two options 1 or 9, similarly, from 1 we can go to 2 or 0. Hint: Use BFS constructing graphs of strings.Example: Input : \nSource = 123\nDestination = 456\nsteps = 9Find a maximum of the difference between maximum and minimum of all subarrays of size k. In this interview, I was able to write code for both questions in just 25 minutes(Good luck maybe :-). Got mail for the third round the same day and the interview was on the next day." }, { "code": null, "e": 30179, "s": 29760, "text": "Reach from one start string to the destination string in a minimum number of steps provided some set of intermediate strings cannot be reached. The string consists of numbers starting from 0 to 9 and it works like a suitcase lock where from 0 there can be two options 1 or 9, similarly, from 1 we can go to 2 or 0. Hint: Use BFS constructing graphs of strings.Example: Input : \nSource = 123\nDestination = 456\nsteps = 9" }, { "code": null, "e": 30495, "s": 30179, "text": "Reach from one start string to the destination string in a minimum number of steps provided some set of intermediate strings cannot be reached. The string consists of numbers starting from 0 to 9 and it works like a suitcase lock where from 0 there can be two options 1 or 9, similarly, from 1 we can go to 2 or 0. " }, { "code": null, "e": 30541, "s": 30495, "text": "Hint: Use BFS constructing graphs of strings." }, { "code": null, "e": 30551, "s": 30541, "text": "Example: " }, { "code": null, "e": 30601, "s": 30551, "text": "Input : \nSource = 123\nDestination = 456\nsteps = 9" }, { "code": null, "e": 30874, "s": 30601, "text": "Find a maximum of the difference between maximum and minimum of all subarrays of size k. In this interview, I was able to write code for both questions in just 25 minutes(Good luck maybe :-). Got mail for the third round the same day and the interview was on the next day." }, { "code": null, "e": 31147, "s": 30874, "text": "Find a maximum of the difference between maximum and minimum of all subarrays of size k. In this interview, I was able to write code for both questions in just 25 minutes(Good luck maybe :-). Got mail for the third round the same day and the interview was on the next day." }, { "code": null, "e": 31161, "s": 31147, "text": "Interview 3: " }, { "code": null, "e": 31731, "s": 31161, "text": "Given a family of ants, in which female and male ants are there, interactions b/w family members are given i.e., it is given who interacts with whom, find if it is a good family and a family is good if only two different genders interact. Example : Input: number of ants = 6, Interactions = { 1-2, 3-4, 5-6}\nOutput - Good family\nInput : number of ants = 6 Interaction = {1-3, 3-5, 1-5}\nOutput - Bad familyNext greater elementAnd questions on os(Explain Banker’s algorithm with an example, Thrashing, Deadlock, Semaphore, etc), DBMS(ACID properties), oops, and projects." }, { "code": null, "e": 32137, "s": 31731, "text": "Given a family of ants, in which female and male ants are there, interactions b/w family members are given i.e., it is given who interacts with whom, find if it is a good family and a family is good if only two different genders interact. Example : Input: number of ants = 6, Interactions = { 1-2, 3-4, 5-6}\nOutput - Good family\nInput : number of ants = 6 Interaction = {1-3, 3-5, 1-5}\nOutput - Bad family" }, { "code": null, "e": 32377, "s": 32137, "text": "Given a family of ants, in which female and male ants are there, interactions b/w family members are given i.e., it is given who interacts with whom, find if it is a good family and a family is good if only two different genders interact. " }, { "code": null, "e": 32388, "s": 32377, "text": "Example : " }, { "code": null, "e": 32545, "s": 32388, "text": "Input: number of ants = 6, Interactions = { 1-2, 3-4, 5-6}\nOutput - Good family\nInput : number of ants = 6 Interaction = {1-3, 3-5, 1-5}\nOutput - Bad family" }, { "code": null, "e": 32710, "s": 32545, "text": "Next greater elementAnd questions on os(Explain Banker’s algorithm with an example, Thrashing, Deadlock, Semaphore, etc), DBMS(ACID properties), oops, and projects." }, { "code": null, "e": 32731, "s": 32710, "text": "Next greater element" }, { "code": null, "e": 32876, "s": 32731, "text": "And questions on os(Explain Banker’s algorithm with an example, Thrashing, Deadlock, Semaphore, etc), DBMS(ACID properties), oops, and projects." }, { "code": null, "e": 33420, "s": 32876, "text": "The first question seemed very new to me. After thinking a lot I was able to get that there shouldn’t be any odd cycle in the graph formed from interactions. I tried writing code but the interview wasn’t very much satisfactory. Then he moved to the next question. As the second question is a very common question, I instantly started telling the solution, by which the interviewer asked do you know this question and I said yes. He asked me to write code in just 2 minutes without any bugs, And I wrote it, but he could find one bug out of it " }, { "code": null, "e": 33578, "s": 33420, "text": "After this interview, I didn’t expect a call for the next interview. But luckily I got the mail after 6 days for the next round to be scheduled the next day." }, { "code": null, "e": 33759, "s": 33578, "text": "Final Interview: Started with the introduction, project questions, and behavioural questions. Like, Give an example where you spent some time and figured out something on your own." }, { "code": null, "e": 34035, "s": 33759, "text": "Given two arrays move an element from one array to another only if the average of both the arrays become greater than the previous average find which element can be movedSome BFS related questions don’t remember exactlyMinimum element in the stack without using another stack" }, { "code": null, "e": 34206, "s": 34035, "text": "Given two arrays move an element from one array to another only if the average of both the arrays become greater than the previous average find which element can be moved" }, { "code": null, "e": 34256, "s": 34206, "text": "Some BFS related questions don’t remember exactly" }, { "code": null, "e": 34313, "s": 34256, "text": "Minimum element in the stack without using another stack" }, { "code": null, "e": 34545, "s": 34313, "text": "In the first question, I got nervous and couldn’t come up with an approach. The interviewer was very friendly and helped me to understand the approach and then asked me to write the code. The next two questions I was able to solve." }, { "code": null, "e": 34747, "s": 34545, "text": "After around 15-20 days, I got mail that I have been selected as a SIDE at Amazon. I would suggest being patient and calm during the interview. Think out loud. The interviewer is there to help you out." }, { "code": null, "e": 34762, "s": 34747, "text": "Best of luck!!" }, { "code": null, "e": 34769, "s": 34762, "text": "Amazon" }, { "code": null, "e": 34780, "s": 34769, "text": "Amazon-WoW" }, { "code": null, "e": 34790, "s": 34780, "text": "Marketing" }, { "code": null, "e": 34812, "s": 34790, "text": "Interview Experiences" }, { "code": null, "e": 34819, "s": 34812, "text": "Amazon" }, { "code": null, "e": 34917, "s": 34819, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34968, "s": 34917, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 35010, "s": 34968, "text": "Amazon AWS Interview Experience for SDE-1" }, { "code": null, "e": 35046, "s": 35010, "text": "Difference between ANN, CNN and RNN" }, { "code": null, "e": 35074, "s": 35046, "text": "Amazon Interview Experience" }, { "code": null, "e": 35112, "s": 35074, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 35184, "s": 35112, "text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021" }, { "code": null, "e": 35230, "s": 35184, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 35272, "s": 35230, "text": "Infosys Interview Experience for DSE 2022" }, { "code": null, "e": 35322, "s": 35272, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" } ]
AVL with duplicate keys - GeeksforGeeks
28 Feb, 2022 Please refer below post before reading about AVL tree handling of duplicates.How to handle duplicates in Binary Search Tree?This is to augment AVL tree node to store count together with regular fields like key, left and right pointers. Insertion of keys 12, 10, 20, 9, 11, 10, 12, 12 in an empty Binary Search Tree would create following. 12(3) / \ 10(2) 20(1) / \ 9(1) 11(1) Count of a key is shown in bracketBelow is implementation of normal AVL Tree with count with every key. This code basically is taken from code for insert and delete in AVL tree. The changes made for handling duplicates are highlighted, rest of the code is same.The important thing to note is changes are very similar to simple Binary Search Tree changes. C++ C Java C# Python3 Javascript // C++ program of AVL tree that// handles duplicates#include <bits/stdc++.h>using namespace std; // An AVL tree nodestruct node { int key; struct node* left; struct node* right; int height; int count;}; // A utility function to get maximum of two integersint max(int a, int b); // A utility function to get height of the treeint height(struct node* N){ if (N == NULL) return 0; return N->height;} // A utility function to get maximum of two integersint max(int a, int b){ return (a > b) ? a : b;} /* Helper function that allocates a new node with the given key and NULL left and right pointers. */struct node* newNode(int key){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->key = key; node->left = NULL; node->right = NULL; node->height = 1; // new node is initially added at leaf node->count = 1; return (node);} // A utility function to right rotate subtree rooted with y// See the diagram given above.struct node* rightRotate(struct node* y){ struct node* x = y->left; struct node* T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right)) + 1; x->height = max(height(x->left), height(x->right)) + 1; // Return new root return x;} // A utility function to left rotate subtree rooted with x// See the diagram given above.struct node* leftRotate(struct node* x){ struct node* y = x->right; struct node* T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right)) + 1; y->height = max(height(y->left), height(y->right)) + 1; // Return new root return y;} // Get Balance factor of node Nint getBalance(struct node* N){ if (N == NULL) return 0; return height(N->left) - height(N->right);} struct node* insert(struct node* node, int key){ /* 1. Perform the normal BST rotation */ if (node == NULL) return (newNode(key)); // If key already exists in BST, increment count and return if (key == node->key) { (node->count)++; return node; } /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); /* 2. Update height of this ancestor node */ node->height = max(height(node->left), height(node->right)) + 1; /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */struct node* minValueNode(struct node* node){ struct node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) current = current->left; return current;} struct node* deleteNode(struct node* root, int key){ // STEP 1: PERFORM STANDARD BST DELETE if (root == NULL) return root; // If the key to be deleted is smaller than the root's key, // then it lies in left subtree if (key < root->key) root->left = deleteNode(root->left, key); // If the key to be deleted is greater than the root's key, // then it lies in right subtree else if (key > root->key) root->right = deleteNode(root->right, key); // if key is same as root's key, then This is the node // to be deleted else { // If key is present more than once, simply decrement // count and return if (root->count > 1) { (root->count)--; return NULL; } // Else, delete the node // node with only one child or no child if ((root->left == NULL) || (root->right == NULL)) { struct node* temp = root->left ? root->left : root->right; // No child case if (temp == NULL) { temp = root; root = NULL; } else // One child case *root = *temp; // Copy the contents of the non-empty child free(temp); } else { // node with two children: Get the inorder successor (smallest // in the right subtree) struct node* temp = minValueNode(root->right); // Copy the inorder successor's data to this node and update the count root->key = temp->key; root->count = temp->count; temp->count = 1; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } } // If the tree had only one node then return if (root == NULL) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root->height = max(height(root->left), height(root->right)) + 1; // STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether // this node became unbalanced) int balance = getBalance(root); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root->left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root->left) < 0) { root->left = leftRotate(root->left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root->right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root->right) > 0) { root->right = rightRotate(root->right); return leftRotate(root); } return root;} // A utility function to print preorder traversal of the tree.// The function also prints height of every nodevoid preOrder(struct node* root){ if (root != NULL) { cout << root->key << "("<<root->count << ")"<< " "; preOrder(root->left); preOrder(root->right); }} /* Driver program to test above function*/int main(){ struct node* root = NULL; /* Constructing tree given in the above figure */ root = insert(root, 9); root = insert(root, 5); root = insert(root, 10); root = insert(root, 5); root = insert(root, 9); root = insert(root, 7); root = insert(root, 17); cout <<"Pre order traversal of the constructed AVL tree is \n"; preOrder(root); cout <<"\nPre order traversal after deletion of 9 \n"; preOrder(root); return 0;} // this code is contributed by shivanisinghss2110 // C++ program of AVL tree that// handles duplicates#include <stdio.h>#include <stdlib.h> // An AVL tree nodestruct node { int key; struct node* left; struct node* right; int height; int count;}; // A utility function to get maximum of two integersint max(int a, int b); // A utility function to get height of the treeint height(struct node* N){ if (N == NULL) return 0; return N->height;} // A utility function to get maximum of two integersint max(int a, int b){ return (a > b) ? a : b;} /* Helper function that allocates a new node with the given key and NULL left and right pointers. */struct node* newNode(int key){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->key = key; node->left = NULL; node->right = NULL; node->height = 1; // new node is initially added at leaf node->count = 1; return (node);} // A utility function to right rotate subtree rooted with y// See the diagram given above.struct node* rightRotate(struct node* y){ struct node* x = y->left; struct node* T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right)) + 1; x->height = max(height(x->left), height(x->right)) + 1; // Return new root return x;} // A utility function to left rotate subtree rooted with x// See the diagram given above.struct node* leftRotate(struct node* x){ struct node* y = x->right; struct node* T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right)) + 1; y->height = max(height(y->left), height(y->right)) + 1; // Return new root return y;} // Get Balance factor of node Nint getBalance(struct node* N){ if (N == NULL) return 0; return height(N->left) - height(N->right);} struct node* insert(struct node* node, int key){ /* 1. Perform the normal BST rotation */ if (node == NULL) return (newNode(key)); // If key already exists in BST, increment count and return if (key == node->key) { (node->count)++; return node; } /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); /* 2. Update height of this ancestor node */ node->height = max(height(node->left), height(node->right)) + 1; /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */struct node* minValueNode(struct node* node){ struct node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) current = current->left; return current;} struct node* deleteNode(struct node* root, int key){ // STEP 1: PERFORM STANDARD BST DELETE if (root == NULL) return root; // If the key to be deleted is smaller than the root's key, // then it lies in left subtree if (key < root->key) root->left = deleteNode(root->left, key); // If the key to be deleted is greater than the root's key, // then it lies in right subtree else if (key > root->key) root->right = deleteNode(root->right, key); // if key is same as root's key, then This is the node // to be deleted else { // If key is present more than once, simply decrement // count and return if (root->count > 1) { (root->count)--; return NULL; } // Else, delete the node // node with only one child or no child if ((root->left == NULL) || (root->right == NULL)) { struct node* temp = root->left ? root->left : root->right; // No child case if (temp == NULL) { temp = root; root = NULL; } else // One child case *root = *temp; // Copy the contents of the non-empty child free(temp); } else { // node with two children: Get the inorder successor (smallest // in the right subtree) struct node* temp = minValueNode(root->right); // Copy the inorder successor's data to this node and update the count root->key = temp->key; root->count = temp->count; temp->count = 1; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } } // If the tree had only one node then return if (root == NULL) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root->height = max(height(root->left), height(root->right)) + 1; // STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether // this node became unbalanced) int balance = getBalance(root); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root->left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root->left) < 0) { root->left = leftRotate(root->left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root->right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root->right) > 0) { root->right = rightRotate(root->right); return leftRotate(root); } return root;} // A utility function to print preorder traversal of the tree.// The function also prints height of every nodevoid preOrder(struct node* root){ if (root != NULL) { printf("%d(%d) ", root->key, root->count); preOrder(root->left); preOrder(root->right); }} /* Driver program to test above function*/int main(){ struct node* root = NULL; /* Constructing tree given in the above figure */ root = insert(root, 9); root = insert(root, 5); root = insert(root, 10); root = insert(root, 5); root = insert(root, 9); root = insert(root, 7); root = insert(root, 17); printf("Pre order traversal of the constructed AVL tree is \n"); preOrder(root); root = deleteNode(root, 9); printf("\nPre order traversal after deletion of 9 \n"); preOrder(root); return 0;} // Java program of AVL tree that handles duplicatesimport java.util.*; class solution { // An AVL tree node static class node { int key; node left; node right; int height; int count; } // A utility function to get height of the tree static int height(node N) { if (N == null) return 0; return N.height; } // A utility function to get maximum of two integers static int max(int a, int b) { return (a > b) ? a : b; } /* Helper function that allocates a new node with the given key and null left and right pointers. */ static node newNode(int key) { node node = new node(); node.key = key; node.left = null; node.right = null; node.height = 1; // new node is initially added at leaf node.count = 1; return (node); } // A utility function to right rotate subtree rooted with y // See the diagram given above. static node rightRotate(node y) { node x = y.left; node T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left rotate subtree rooted with x // See the diagram given above. static node leftRotate(node x) { node y = x.right; node T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N static int getBalance(node N) { if (N == null) return 0; return height(N.left) - height(N.right); } static node insert(node node, int key) { /*1. Perform the normal BST rotation */ if (node == null) return (newNode(key)); // If key already exists in BST, increment count and return if (key == node.key) { (node.count)++; return node; } /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); /* 2. Update height of this ancestor node */ node.height = max(height(node.left), height(node.right)) + 1; /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */ static node minValueNode(node node) { node current = node; /* loop down to find the leftmost leaf */ while (current.left != null) current = current.left; return current; } static node deleteNode(node root, int key) { // STEP 1: PERFORM STANDARD BST DELETE if (root == null) return root; // If the key to be deleted is smaller than the root's key, // then it lies in left subtree if (key < root.key) root.left = deleteNode(root.left, key); // If the key to be deleted is greater than the root's key, // then it lies in right subtree else if (key > root.key) root.right = deleteNode(root.right, key); // if key is same as root's key, then This is the node // to be deleted else { // If key is present more than once, simply decrement // count and return if (root.count > 1) { (root.count)--; return null; } // ElSE, delete the node // node with only one child or no child if ((root.left == null) || (root.right == null)) { node temp = root.left != null ? root.left : root.right; // No child case if (temp == null) { temp = root; root = null; } else // One child case root = temp; // Copy the contents of the non-empty child } else { // node with two children: Get the inorder successor (smallest // in the right subtree) node temp = minValueNode(root.right); // Copy the inorder successor's data to this node and update the count root.key = temp.key; root.count = temp.count; temp.count = 1; // Delete the inorder successor root.right = deleteNode(root.right, temp.key); } } // If the tree had only one node then return if (root == null) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root.height = max(height(root.left), height(root.right)) + 1; // STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether // this node became unbalanced) int balance = getBalance(root); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root.left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root.left) < 0) { root.left = leftRotate(root.left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root.right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root.right) > 0) { root.right = rightRotate(root.right); return leftRotate(root); } return root; } // A utility function to print preorder traversal of the tree. // The function also prints height of every node static void preOrder(node root) { if (root != null) { System.out.printf("%d(%d) ", root.key, root.count); preOrder(root.left); preOrder(root.right); } } /* Driver program to test above function*/ public static void main(String args[]) { node root = null; /* Constructing tree given in the above figure */ root = insert(root, 9); root = insert(root, 5); root = insert(root, 10); root = insert(root, 5); root = insert(root, 9); root = insert(root, 7); root = insert(root, 17); System.out.printf("Pre order traversal of the constructed AVL tree is \n"); preOrder(root); deleteNode(root, 9); System.out.printf("\nPre order traversal after deletion of 9 \n"); preOrder(root); }}// contributed by Arnab Kundu // C# program of AVL tree that// handles duplicatesusing System; class GFG { // An AVL tree node class node { public int key; public node left; public node right; public int height; public int count; } // A utility function to get // height of the tree static int height(node N) { if (N == null) return 0; return N.height; } // A utility function to get // maximum of two integers static int max(int a, int b) { return (a > b) ? a : b; } /* Helper function that allocates a new node with the given key and null left and right pointers. */ static node newNode(int key) { node node = new node(); node.key = key; node.left = null; node.right = null; node.height = 1; // new node is initially // added at leaf node.count = 1; return (node); } // A utility function to right // rotate subtree rooted with y // See the diagram given above. static node rightRotate(node y) { node x = y.left; node T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left // rotate subtree rooted with x // See the diagram given above. static node leftRotate(node x) { node y = x.right; node T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N static int getBalance(node N) { if (N == null) return 0; return height(N.left) - height(N.right); } static node insert(node node, int key) { /*1. Perform the normal BST rotation */ if (node == null) return (newNode(key)); // If key already exists in BST, // increment count and return if (key == node.key) { (node.count)++; return node; } /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); /* 2. Update height of this ancestor node */ node.height = max(height(node.left), height(node.right)) + 1; /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, // then there are 4 cases // Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */ static node minValueNode(node node) { node current = node; /* loop down to find the leftmost leaf */ while (current.left != null) current = current.left; return current; } static node deleteNode(node root, int key) { // STEP 1: PERFORM STANDARD BST DELETE if (root == null) return root; // If the key to be deleted is // smaller than the root's key, // then it lies in left subtree if (key < root.key) root.left = deleteNode(root.left, key); // If the key to be deleted is // greater than the root's key, // then it lies in right subtree else if (key > root.key) root.right = deleteNode(root.right, key); // if key is same as root's key, // then this is the node to be deleted else { // If key is present more than // once, simply decrement // count and return if (root.count > 1) { (root.count)--; return null; } // ElSE, delete the node // node with only one child // or no child if ((root.left == null) || (root.right == null)) { node temp = root.left != null ? root.left : root.right; // No child case if (temp == null) { temp = root; root = null; } else // One child case root = temp; // Copy the contents of // the non-empty child } else { // node with two children: Get // the inorder successor (smallest // in the right subtree) node temp = minValueNode(root.right); // Copy the inorder successor's // data to this node and update the count root.key = temp.key; root.count = temp.count; temp.count = 1; // Delete the inorder successor root.right = deleteNode(root.right, temp.key); } } // If the tree had only one // node then return if (root == null) return root; // STEP 2: UPDATE HEIGHT OF // THE CURRENT NODE root.height = max(height(root.left), height(root.right)) + 1; // STEP 3: GET THE BALANCE FACTOR // OF THIS NODE (to check whether // this node became unbalanced) int balance = getBalance(root); // If this node becomes unbalanced, // then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root.left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root.left) < 0) { root.left = leftRotate(root.left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root.right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root.right) > 0) { root.right = rightRotate(root.right); return leftRotate(root); } return root; } // A utility function to print // preorder traversal of the tree. // The function also prints height // of every node static void preOrder(node root) { if (root != null) { Console.Write(root.key + "(" + root.count + ") "); preOrder(root.left); preOrder(root.right); } } // Driver Code static public void Main(String[] args) { node root = null; /* Constructing tree given in the above figure */ root = insert(root, 9); root = insert(root, 5); root = insert(root, 10); root = insert(root, 5); root = insert(root, 9); root = insert(root, 7); root = insert(root, 17); Console.Write("Pre order traversal of " + "the constructed AVL tree is \n"); preOrder(root); deleteNode(root, 9); Console.Write("\nPre order traversal after " + "deletion of 9 \n"); preOrder(root); }} // This code is contributed by Arnab Kundu # Python code to delete a node in AVL tree# Generic tree node class class TreeNode(): def __init__(self, val): self.count = 1 # assigning count variable so that during insertion in will be incremented for duplicate values # and during deletion, it will be decremented if has multiple copies. self.height = 1 self.val = val self.left = None self.right = None# only insertion and deletion will be affected. if multiple copies are there, entry(count) will be printed during traversal. # AVL tree class which supports insertion,# deletion operations class AVL_Tree(object): def insert(self, root, key): # Step 1 - Perform normal BST if not root: return TreeNode(key) else if key < root.val: root.left = self.insert(root.left, key) else if key > root.val: root.right = self.insert(root.right, key) else: root.count += 1 # incrementing count if same entry is inserted. # Step 2 - Update the height of the # ancestor node root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right)) # Step 3 - Get the balance factor balance = self.getBalance(root) # Step 4 - If the node is unbalanced, # then try out the 4 cases # Case 1 - Left Left if balance > 1 and key < root.left.val: return self.rightRotate(root) # Case 2 - Right Right if balance < -1 and key > root.right.val: return self.leftRotate(root) # Case 3 - Left Right if balance > 1 and key > root.left.val: root.left = self.leftRotate(root.left) return self.rightRotate(root) # Case 4 - Right Left if balance < -1 and key < root.right.val: root.right = self.rightRotate(root.right) return self.leftRotate(root) return root # Recursive function to delete a node with # given key from subtree with given root. # It returns root of the modified subtree. def delete(self, root, key): # Step 1 - Perform standard BST delete if not root: return root else if key < root.val: root.left = self.delete(root.left, key) else if key > root.val: root.right = self.delete(root.right, key) else: if root.count > 1: # if count is more than one i.e multiple copies are there root.count -= 1 # just decrement count return root # so that one copy will be deleted and return if root.left is None: temp = root.right root = None return temp else if root.right is None: temp = root.left root = None return temp temp = self.getMinValueNode(root.right) root.val = temp.val root.right = self.delete(root.right, temp.val) # If the tree has only one node, # simply return it if root is None: return root # Step 2 - Update the height of the # ancestor node root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right)) # Step 3 - Get the balance factor balance = self.getBalance(root) # Step 4 - If the node is unbalanced, # then try out the 4 cases # Case 1 - Left Left if balance > 1 and self.getBalance(root.left) >= 0: return self.rightRotate(root) # Case 2 - Right Right if balance < -1 and self.getBalance(root.right) <= 0: return self.leftRotate(root) # Case 3 - Left Right if balance > 1 and self.getBalance(root.left) < 0: root.left = self.leftRotate(root.left) return self.rightRotate(root) # Case 4 - Right Left if balance < -1 and self.getBalance(root.right) > 0: root.right = self.rightRotate(root.right) return self.leftRotate(root) return root def leftRotate(self, z): y = z.right T2 = y.left # Perform rotation y.left = z z.right = T2 # Update heights z.height = 1 + max(self.getHeight(z.left), self.getHeight(z.right)) y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right)) # Return the new root return y def rightRotate(self, z): y = z.left T3 = y.right # Perform rotation y.right = z z.left = T3 # Update heights z.height = 1 + max(self.getHeight(z.left), self.getHeight(z.right)) y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right)) # Return the new root return y def getHeight(self, root): if not root: return 0 return root.height def getBalance(self, root): if not root: return 0 return self.getHeight(root.left) - self.getHeight(root.right) def getMinValueNode(self, root): if root is None or root.left is None: return root return self.getMinValueNode(root.left) def preOrder(self, root): if not root: return print("{}({}) ".format(root.val, root.count), end="") self.preOrder(root.left) self.preOrder(root.right) myTree = AVL_Tree()root = Nonenums = [9, 5, 10, 5, 9, 7, 17] for num in nums: root = myTree.insert(root, num) # Preorder Traversalprint("Preorder Traversal after insertion -")myTree.preOrder(root)print() # Deletekey = 10root = myTree.delete(root, key)key = 10root = myTree.delete(root, key)key = -1root = myTree.delete(root, key)key = 0root = myTree.delete(root, key) # Preorder Traversalprint("Preorder Traversal after deletion -")myTree.preOrder(root)print() # This code is contributed by Ajitesh Pathak <script> // JavaScript program of AVL tree that handles duplicates class Node { constructor() { this.left; this.right; this.key; this.height; this.count; } } // A utility function to get height of the tree function height(N) { if (N == null) return 0; return N.height; } // A utility function to get maximum of two integers function max(a, b) { return (a > b) ? a : b; } /* Helper function that allocates a new node with the given key and null left and right pointers. */ function newNode(key) { let node = new Node(); node.key = key; node.left = null; node.right = null; node.height = 1; // new node is initially added at leaf node.count = 1; return (node); } // A utility function to right rotate // subtree rooted with y // See the diagram given above. function rightRotate(y) { let x = y.left; let T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left rotate subtree rooted with x // See the diagram given above. function leftRotate(x) { let y = x.right; let T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N function getBalance(N) { if (N == null) return 0; return height(N.left) - height(N.right); } function insert(node, key) { /*1. Perform the normal BST rotation */ if (node == null) return (newNode(key)); // If key already exists in BST, increment count and return if (key == node.key) { (node.count)++; return node; } /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); /* 2. Update height of this ancestor node */ node.height = max(height(node.left), height(node.right)) + 1; /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ let balance = getBalance(node); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */ function minValueNode(node) { let current = node; /* loop down to find the leftmost leaf */ while (current.left != null) current = current.left; return current; } function deleteNode(root, key) { // STEP 1: PERFORM STANDARD BST DELETE if (root == null) return root; // If the key to be deleted is smaller than the root's key, // then it lies in left subtree if (key < root.key) root.left = deleteNode(root.left, key); // If the key to be deleted is greater than the root's key, // then it lies in right subtree else if (key > root.key) root.right = deleteNode(root.right, key); // if key is same as root's key, then This is the node // to be deleted else { // If key is present more than once, simply decrement // count and return if (root.count > 1) { (root.count)--; return null; } // ElSE, delete the node // node with only one child or no child if ((root.left == null) || (root.right == null)) { let temp = root.left != null ? root.left : root.right; // No child case if (temp == null) { temp = root; root = null; } else // One child case // Copy the contents of the non-empty child root = temp; } else { // node with two children: Get the // inorder successor (smallest // in the right subtree) let temp = minValueNode(root.right); // Copy the inorder successor's data to // this node and update the count root.key = temp.key; root.count = temp.count; temp.count = 1; // Delete the inorder successor root.right = deleteNode(root.right, temp.key); } } // If the tree had only one node then return if (root == null) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root.height = max(height(root.left), height(root.right)) + 1; // STEP 3: GET THE BALANCE FACTOR // OF THIS NODE (to check whether // this node became unbalanced) let balance = getBalance(root); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root.left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root.left) < 0) { root.left = leftRotate(root.left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root.right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root.right) > 0) { root.right = rightRotate(root.right); return leftRotate(root); } return root; } // A utility function to print preorder traversal of the tree. // The function also prints height of every node function preOrder(root) { if (root != null) { document.write(root.key + "(" + root.count + ") "); preOrder(root.left); preOrder(root.right); } } let root = null; /* Constructing tree given in the above figure */ root = insert(root, 9); root = insert(root, 5); root = insert(root, 10); root = insert(root, 5); root = insert(root, 9); root = insert(root, 7); root = insert(root, 17); document.write( "Pre order traversal of the constructed AVL tree is " + "</br>"); preOrder(root); deleteNode(root, 9); document.write( "</br>" + "Pre order traversal after deletion of 9 " + "</br>"); preOrder(root); </script> Output: Pre order traversal of the constructed AVL tree is 9(2) 5(2) 7(1) 10(1) 17(1) Pre order traversal after deletion of 9 9(1) 5(2) 7(1) 10(1) 17(1) Thanks to Rounaq Jhunjhunu Wala for sharing initial code. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above andrew1234 TapanMeena rohitgr7 nidhi_biet 20ajinky mukesh07 shivanisinghss2110 varshagumber28 surindertarika1234 surinderdawra388 AVL-Tree Tree Tree AVL-Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion Binary Tree | Set 3 (Types of Binary Tree) Write a Program to Find the Maximum Depth or Height of a Tree Binary Tree | Set 2 (Properties) Decision Tree A program to check if a binary tree is BST or not
[ { "code": null, "e": 35848, "s": 35820, "text": "\n28 Feb, 2022" }, { "code": null, "e": 36189, "s": 35848, "text": "Please refer below post before reading about AVL tree handling of duplicates.How to handle duplicates in Binary Search Tree?This is to augment AVL tree node to store count together with regular fields like key, left and right pointers. Insertion of keys 12, 10, 20, 9, 11, 10, 12, 12 in an empty Binary Search Tree would create following. " }, { "code": null, "e": 36280, "s": 36189, "text": " 12(3)\n / \\\n 10(2) 20(1)\n / \\ \n 9(1) 11(1) " }, { "code": null, "e": 36637, "s": 36280, "text": "Count of a key is shown in bracketBelow is implementation of normal AVL Tree with count with every key. This code basically is taken from code for insert and delete in AVL tree. The changes made for handling duplicates are highlighted, rest of the code is same.The important thing to note is changes are very similar to simple Binary Search Tree changes. " }, { "code": null, "e": 36641, "s": 36637, "text": "C++" }, { "code": null, "e": 36643, "s": 36641, "text": "C" }, { "code": null, "e": 36648, "s": 36643, "text": "Java" }, { "code": null, "e": 36651, "s": 36648, "text": "C#" }, { "code": null, "e": 36659, "s": 36651, "text": "Python3" }, { "code": null, "e": 36670, "s": 36659, "text": "Javascript" }, { "code": "// C++ program of AVL tree that// handles duplicates#include <bits/stdc++.h>using namespace std; // An AVL tree nodestruct node { int key; struct node* left; struct node* right; int height; int count;}; // A utility function to get maximum of two integersint max(int a, int b); // A utility function to get height of the treeint height(struct node* N){ if (N == NULL) return 0; return N->height;} // A utility function to get maximum of two integersint max(int a, int b){ return (a > b) ? a : b;} /* Helper function that allocates a new node with the given key and NULL left and right pointers. */struct node* newNode(int key){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->key = key; node->left = NULL; node->right = NULL; node->height = 1; // new node is initially added at leaf node->count = 1; return (node);} // A utility function to right rotate subtree rooted with y// See the diagram given above.struct node* rightRotate(struct node* y){ struct node* x = y->left; struct node* T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right)) + 1; x->height = max(height(x->left), height(x->right)) + 1; // Return new root return x;} // A utility function to left rotate subtree rooted with x// See the diagram given above.struct node* leftRotate(struct node* x){ struct node* y = x->right; struct node* T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right)) + 1; y->height = max(height(y->left), height(y->right)) + 1; // Return new root return y;} // Get Balance factor of node Nint getBalance(struct node* N){ if (N == NULL) return 0; return height(N->left) - height(N->right);} struct node* insert(struct node* node, int key){ /* 1. Perform the normal BST rotation */ if (node == NULL) return (newNode(key)); // If key already exists in BST, increment count and return if (key == node->key) { (node->count)++; return node; } /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); /* 2. Update height of this ancestor node */ node->height = max(height(node->left), height(node->right)) + 1; /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */struct node* minValueNode(struct node* node){ struct node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) current = current->left; return current;} struct node* deleteNode(struct node* root, int key){ // STEP 1: PERFORM STANDARD BST DELETE if (root == NULL) return root; // If the key to be deleted is smaller than the root's key, // then it lies in left subtree if (key < root->key) root->left = deleteNode(root->left, key); // If the key to be deleted is greater than the root's key, // then it lies in right subtree else if (key > root->key) root->right = deleteNode(root->right, key); // if key is same as root's key, then This is the node // to be deleted else { // If key is present more than once, simply decrement // count and return if (root->count > 1) { (root->count)--; return NULL; } // Else, delete the node // node with only one child or no child if ((root->left == NULL) || (root->right == NULL)) { struct node* temp = root->left ? root->left : root->right; // No child case if (temp == NULL) { temp = root; root = NULL; } else // One child case *root = *temp; // Copy the contents of the non-empty child free(temp); } else { // node with two children: Get the inorder successor (smallest // in the right subtree) struct node* temp = minValueNode(root->right); // Copy the inorder successor's data to this node and update the count root->key = temp->key; root->count = temp->count; temp->count = 1; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } } // If the tree had only one node then return if (root == NULL) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root->height = max(height(root->left), height(root->right)) + 1; // STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether // this node became unbalanced) int balance = getBalance(root); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root->left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root->left) < 0) { root->left = leftRotate(root->left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root->right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root->right) > 0) { root->right = rightRotate(root->right); return leftRotate(root); } return root;} // A utility function to print preorder traversal of the tree.// The function also prints height of every nodevoid preOrder(struct node* root){ if (root != NULL) { cout << root->key << \"(\"<<root->count << \")\"<< \" \"; preOrder(root->left); preOrder(root->right); }} /* Driver program to test above function*/int main(){ struct node* root = NULL; /* Constructing tree given in the above figure */ root = insert(root, 9); root = insert(root, 5); root = insert(root, 10); root = insert(root, 5); root = insert(root, 9); root = insert(root, 7); root = insert(root, 17); cout <<\"Pre order traversal of the constructed AVL tree is \\n\"; preOrder(root); cout <<\"\\nPre order traversal after deletion of 9 \\n\"; preOrder(root); return 0;} // this code is contributed by shivanisinghss2110", "e": 43827, "s": 36670, "text": null }, { "code": "// C++ program of AVL tree that// handles duplicates#include <stdio.h>#include <stdlib.h> // An AVL tree nodestruct node { int key; struct node* left; struct node* right; int height; int count;}; // A utility function to get maximum of two integersint max(int a, int b); // A utility function to get height of the treeint height(struct node* N){ if (N == NULL) return 0; return N->height;} // A utility function to get maximum of two integersint max(int a, int b){ return (a > b) ? a : b;} /* Helper function that allocates a new node with the given key and NULL left and right pointers. */struct node* newNode(int key){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->key = key; node->left = NULL; node->right = NULL; node->height = 1; // new node is initially added at leaf node->count = 1; return (node);} // A utility function to right rotate subtree rooted with y// See the diagram given above.struct node* rightRotate(struct node* y){ struct node* x = y->left; struct node* T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right)) + 1; x->height = max(height(x->left), height(x->right)) + 1; // Return new root return x;} // A utility function to left rotate subtree rooted with x// See the diagram given above.struct node* leftRotate(struct node* x){ struct node* y = x->right; struct node* T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right)) + 1; y->height = max(height(y->left), height(y->right)) + 1; // Return new root return y;} // Get Balance factor of node Nint getBalance(struct node* N){ if (N == NULL) return 0; return height(N->left) - height(N->right);} struct node* insert(struct node* node, int key){ /* 1. Perform the normal BST rotation */ if (node == NULL) return (newNode(key)); // If key already exists in BST, increment count and return if (key == node->key) { (node->count)++; return node; } /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); /* 2. Update height of this ancestor node */ node->height = max(height(node->left), height(node->right)) + 1; /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */struct node* minValueNode(struct node* node){ struct node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) current = current->left; return current;} struct node* deleteNode(struct node* root, int key){ // STEP 1: PERFORM STANDARD BST DELETE if (root == NULL) return root; // If the key to be deleted is smaller than the root's key, // then it lies in left subtree if (key < root->key) root->left = deleteNode(root->left, key); // If the key to be deleted is greater than the root's key, // then it lies in right subtree else if (key > root->key) root->right = deleteNode(root->right, key); // if key is same as root's key, then This is the node // to be deleted else { // If key is present more than once, simply decrement // count and return if (root->count > 1) { (root->count)--; return NULL; } // Else, delete the node // node with only one child or no child if ((root->left == NULL) || (root->right == NULL)) { struct node* temp = root->left ? root->left : root->right; // No child case if (temp == NULL) { temp = root; root = NULL; } else // One child case *root = *temp; // Copy the contents of the non-empty child free(temp); } else { // node with two children: Get the inorder successor (smallest // in the right subtree) struct node* temp = minValueNode(root->right); // Copy the inorder successor's data to this node and update the count root->key = temp->key; root->count = temp->count; temp->count = 1; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } } // If the tree had only one node then return if (root == NULL) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root->height = max(height(root->left), height(root->right)) + 1; // STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether // this node became unbalanced) int balance = getBalance(root); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root->left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root->left) < 0) { root->left = leftRotate(root->left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root->right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root->right) > 0) { root->right = rightRotate(root->right); return leftRotate(root); } return root;} // A utility function to print preorder traversal of the tree.// The function also prints height of every nodevoid preOrder(struct node* root){ if (root != NULL) { printf(\"%d(%d) \", root->key, root->count); preOrder(root->left); preOrder(root->right); }} /* Driver program to test above function*/int main(){ struct node* root = NULL; /* Constructing tree given in the above figure */ root = insert(root, 9); root = insert(root, 5); root = insert(root, 10); root = insert(root, 5); root = insert(root, 9); root = insert(root, 7); root = insert(root, 17); printf(\"Pre order traversal of the constructed AVL tree is \\n\"); preOrder(root); root = deleteNode(root, 9); printf(\"\\nPre order traversal after deletion of 9 \\n\"); preOrder(root); return 0;}", "e": 50942, "s": 43827, "text": null }, { "code": "// Java program of AVL tree that handles duplicatesimport java.util.*; class solution { // An AVL tree node static class node { int key; node left; node right; int height; int count; } // A utility function to get height of the tree static int height(node N) { if (N == null) return 0; return N.height; } // A utility function to get maximum of two integers static int max(int a, int b) { return (a > b) ? a : b; } /* Helper function that allocates a new node with the given key and null left and right pointers. */ static node newNode(int key) { node node = new node(); node.key = key; node.left = null; node.right = null; node.height = 1; // new node is initially added at leaf node.count = 1; return (node); } // A utility function to right rotate subtree rooted with y // See the diagram given above. static node rightRotate(node y) { node x = y.left; node T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left rotate subtree rooted with x // See the diagram given above. static node leftRotate(node x) { node y = x.right; node T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N static int getBalance(node N) { if (N == null) return 0; return height(N.left) - height(N.right); } static node insert(node node, int key) { /*1. Perform the normal BST rotation */ if (node == null) return (newNode(key)); // If key already exists in BST, increment count and return if (key == node.key) { (node.count)++; return node; } /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); /* 2. Update height of this ancestor node */ node.height = max(height(node.left), height(node.right)) + 1; /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */ static node minValueNode(node node) { node current = node; /* loop down to find the leftmost leaf */ while (current.left != null) current = current.left; return current; } static node deleteNode(node root, int key) { // STEP 1: PERFORM STANDARD BST DELETE if (root == null) return root; // If the key to be deleted is smaller than the root's key, // then it lies in left subtree if (key < root.key) root.left = deleteNode(root.left, key); // If the key to be deleted is greater than the root's key, // then it lies in right subtree else if (key > root.key) root.right = deleteNode(root.right, key); // if key is same as root's key, then This is the node // to be deleted else { // If key is present more than once, simply decrement // count and return if (root.count > 1) { (root.count)--; return null; } // ElSE, delete the node // node with only one child or no child if ((root.left == null) || (root.right == null)) { node temp = root.left != null ? root.left : root.right; // No child case if (temp == null) { temp = root; root = null; } else // One child case root = temp; // Copy the contents of the non-empty child } else { // node with two children: Get the inorder successor (smallest // in the right subtree) node temp = minValueNode(root.right); // Copy the inorder successor's data to this node and update the count root.key = temp.key; root.count = temp.count; temp.count = 1; // Delete the inorder successor root.right = deleteNode(root.right, temp.key); } } // If the tree had only one node then return if (root == null) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root.height = max(height(root.left), height(root.right)) + 1; // STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether // this node became unbalanced) int balance = getBalance(root); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root.left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root.left) < 0) { root.left = leftRotate(root.left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root.right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root.right) > 0) { root.right = rightRotate(root.right); return leftRotate(root); } return root; } // A utility function to print preorder traversal of the tree. // The function also prints height of every node static void preOrder(node root) { if (root != null) { System.out.printf(\"%d(%d) \", root.key, root.count); preOrder(root.left); preOrder(root.right); } } /* Driver program to test above function*/ public static void main(String args[]) { node root = null; /* Constructing tree given in the above figure */ root = insert(root, 9); root = insert(root, 5); root = insert(root, 10); root = insert(root, 5); root = insert(root, 9); root = insert(root, 7); root = insert(root, 17); System.out.printf(\"Pre order traversal of the constructed AVL tree is \\n\"); preOrder(root); deleteNode(root, 9); System.out.printf(\"\\nPre order traversal after deletion of 9 \\n\"); preOrder(root); }}// contributed by Arnab Kundu", "e": 58646, "s": 50942, "text": null }, { "code": "// C# program of AVL tree that// handles duplicatesusing System; class GFG { // An AVL tree node class node { public int key; public node left; public node right; public int height; public int count; } // A utility function to get // height of the tree static int height(node N) { if (N == null) return 0; return N.height; } // A utility function to get // maximum of two integers static int max(int a, int b) { return (a > b) ? a : b; } /* Helper function that allocates a new node with the given key and null left and right pointers. */ static node newNode(int key) { node node = new node(); node.key = key; node.left = null; node.right = null; node.height = 1; // new node is initially // added at leaf node.count = 1; return (node); } // A utility function to right // rotate subtree rooted with y // See the diagram given above. static node rightRotate(node y) { node x = y.left; node T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left // rotate subtree rooted with x // See the diagram given above. static node leftRotate(node x) { node y = x.right; node T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N static int getBalance(node N) { if (N == null) return 0; return height(N.left) - height(N.right); } static node insert(node node, int key) { /*1. Perform the normal BST rotation */ if (node == null) return (newNode(key)); // If key already exists in BST, // increment count and return if (key == node.key) { (node.count)++; return node; } /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); /* 2. Update height of this ancestor node */ node.height = max(height(node.left), height(node.right)) + 1; /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, // then there are 4 cases // Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */ static node minValueNode(node node) { node current = node; /* loop down to find the leftmost leaf */ while (current.left != null) current = current.left; return current; } static node deleteNode(node root, int key) { // STEP 1: PERFORM STANDARD BST DELETE if (root == null) return root; // If the key to be deleted is // smaller than the root's key, // then it lies in left subtree if (key < root.key) root.left = deleteNode(root.left, key); // If the key to be deleted is // greater than the root's key, // then it lies in right subtree else if (key > root.key) root.right = deleteNode(root.right, key); // if key is same as root's key, // then this is the node to be deleted else { // If key is present more than // once, simply decrement // count and return if (root.count > 1) { (root.count)--; return null; } // ElSE, delete the node // node with only one child // or no child if ((root.left == null) || (root.right == null)) { node temp = root.left != null ? root.left : root.right; // No child case if (temp == null) { temp = root; root = null; } else // One child case root = temp; // Copy the contents of // the non-empty child } else { // node with two children: Get // the inorder successor (smallest // in the right subtree) node temp = minValueNode(root.right); // Copy the inorder successor's // data to this node and update the count root.key = temp.key; root.count = temp.count; temp.count = 1; // Delete the inorder successor root.right = deleteNode(root.right, temp.key); } } // If the tree had only one // node then return if (root == null) return root; // STEP 2: UPDATE HEIGHT OF // THE CURRENT NODE root.height = max(height(root.left), height(root.right)) + 1; // STEP 3: GET THE BALANCE FACTOR // OF THIS NODE (to check whether // this node became unbalanced) int balance = getBalance(root); // If this node becomes unbalanced, // then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root.left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root.left) < 0) { root.left = leftRotate(root.left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root.right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root.right) > 0) { root.right = rightRotate(root.right); return leftRotate(root); } return root; } // A utility function to print // preorder traversal of the tree. // The function also prints height // of every node static void preOrder(node root) { if (root != null) { Console.Write(root.key + \"(\" + root.count + \") \"); preOrder(root.left); preOrder(root.right); } } // Driver Code static public void Main(String[] args) { node root = null; /* Constructing tree given in the above figure */ root = insert(root, 9); root = insert(root, 5); root = insert(root, 10); root = insert(root, 5); root = insert(root, 9); root = insert(root, 7); root = insert(root, 17); Console.Write(\"Pre order traversal of \" + \"the constructed AVL tree is \\n\"); preOrder(root); deleteNode(root, 9); Console.Write(\"\\nPre order traversal after \" + \"deletion of 9 \\n\"); preOrder(root); }} // This code is contributed by Arnab Kundu", "e": 66928, "s": 58646, "text": null }, { "code": "# Python code to delete a node in AVL tree# Generic tree node class class TreeNode(): def __init__(self, val): self.count = 1 # assigning count variable so that during insertion in will be incremented for duplicate values # and during deletion, it will be decremented if has multiple copies. self.height = 1 self.val = val self.left = None self.right = None# only insertion and deletion will be affected. if multiple copies are there, entry(count) will be printed during traversal. # AVL tree class which supports insertion,# deletion operations class AVL_Tree(object): def insert(self, root, key): # Step 1 - Perform normal BST if not root: return TreeNode(key) else if key < root.val: root.left = self.insert(root.left, key) else if key > root.val: root.right = self.insert(root.right, key) else: root.count += 1 # incrementing count if same entry is inserted. # Step 2 - Update the height of the # ancestor node root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right)) # Step 3 - Get the balance factor balance = self.getBalance(root) # Step 4 - If the node is unbalanced, # then try out the 4 cases # Case 1 - Left Left if balance > 1 and key < root.left.val: return self.rightRotate(root) # Case 2 - Right Right if balance < -1 and key > root.right.val: return self.leftRotate(root) # Case 3 - Left Right if balance > 1 and key > root.left.val: root.left = self.leftRotate(root.left) return self.rightRotate(root) # Case 4 - Right Left if balance < -1 and key < root.right.val: root.right = self.rightRotate(root.right) return self.leftRotate(root) return root # Recursive function to delete a node with # given key from subtree with given root. # It returns root of the modified subtree. def delete(self, root, key): # Step 1 - Perform standard BST delete if not root: return root else if key < root.val: root.left = self.delete(root.left, key) else if key > root.val: root.right = self.delete(root.right, key) else: if root.count > 1: # if count is more than one i.e multiple copies are there root.count -= 1 # just decrement count return root # so that one copy will be deleted and return if root.left is None: temp = root.right root = None return temp else if root.right is None: temp = root.left root = None return temp temp = self.getMinValueNode(root.right) root.val = temp.val root.right = self.delete(root.right, temp.val) # If the tree has only one node, # simply return it if root is None: return root # Step 2 - Update the height of the # ancestor node root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right)) # Step 3 - Get the balance factor balance = self.getBalance(root) # Step 4 - If the node is unbalanced, # then try out the 4 cases # Case 1 - Left Left if balance > 1 and self.getBalance(root.left) >= 0: return self.rightRotate(root) # Case 2 - Right Right if balance < -1 and self.getBalance(root.right) <= 0: return self.leftRotate(root) # Case 3 - Left Right if balance > 1 and self.getBalance(root.left) < 0: root.left = self.leftRotate(root.left) return self.rightRotate(root) # Case 4 - Right Left if balance < -1 and self.getBalance(root.right) > 0: root.right = self.rightRotate(root.right) return self.leftRotate(root) return root def leftRotate(self, z): y = z.right T2 = y.left # Perform rotation y.left = z z.right = T2 # Update heights z.height = 1 + max(self.getHeight(z.left), self.getHeight(z.right)) y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right)) # Return the new root return y def rightRotate(self, z): y = z.left T3 = y.right # Perform rotation y.right = z z.left = T3 # Update heights z.height = 1 + max(self.getHeight(z.left), self.getHeight(z.right)) y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right)) # Return the new root return y def getHeight(self, root): if not root: return 0 return root.height def getBalance(self, root): if not root: return 0 return self.getHeight(root.left) - self.getHeight(root.right) def getMinValueNode(self, root): if root is None or root.left is None: return root return self.getMinValueNode(root.left) def preOrder(self, root): if not root: return print(\"{}({}) \".format(root.val, root.count), end=\"\") self.preOrder(root.left) self.preOrder(root.right) myTree = AVL_Tree()root = Nonenums = [9, 5, 10, 5, 9, 7, 17] for num in nums: root = myTree.insert(root, num) # Preorder Traversalprint(\"Preorder Traversal after insertion -\")myTree.preOrder(root)print() # Deletekey = 10root = myTree.delete(root, key)key = 10root = myTree.delete(root, key)key = -1root = myTree.delete(root, key)key = 0root = myTree.delete(root, key) # Preorder Traversalprint(\"Preorder Traversal after deletion -\")myTree.preOrder(root)print() # This code is contributed by Ajitesh Pathak", "e": 72956, "s": 66928, "text": null }, { "code": "<script> // JavaScript program of AVL tree that handles duplicates class Node { constructor() { this.left; this.right; this.key; this.height; this.count; } } // A utility function to get height of the tree function height(N) { if (N == null) return 0; return N.height; } // A utility function to get maximum of two integers function max(a, b) { return (a > b) ? a : b; } /* Helper function that allocates a new node with the given key and null left and right pointers. */ function newNode(key) { let node = new Node(); node.key = key; node.left = null; node.right = null; node.height = 1; // new node is initially added at leaf node.count = 1; return (node); } // A utility function to right rotate // subtree rooted with y // See the diagram given above. function rightRotate(y) { let x = y.left; let T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left rotate subtree rooted with x // See the diagram given above. function leftRotate(x) { let y = x.right; let T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N function getBalance(N) { if (N == null) return 0; return height(N.left) - height(N.right); } function insert(node, key) { /*1. Perform the normal BST rotation */ if (node == null) return (newNode(key)); // If key already exists in BST, increment count and return if (key == node.key) { (node.count)++; return node; } /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); /* 2. Update height of this ancestor node */ node.height = max(height(node.left), height(node.right)) + 1; /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ let balance = getBalance(node); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */ function minValueNode(node) { let current = node; /* loop down to find the leftmost leaf */ while (current.left != null) current = current.left; return current; } function deleteNode(root, key) { // STEP 1: PERFORM STANDARD BST DELETE if (root == null) return root; // If the key to be deleted is smaller than the root's key, // then it lies in left subtree if (key < root.key) root.left = deleteNode(root.left, key); // If the key to be deleted is greater than the root's key, // then it lies in right subtree else if (key > root.key) root.right = deleteNode(root.right, key); // if key is same as root's key, then This is the node // to be deleted else { // If key is present more than once, simply decrement // count and return if (root.count > 1) { (root.count)--; return null; } // ElSE, delete the node // node with only one child or no child if ((root.left == null) || (root.right == null)) { let temp = root.left != null ? root.left : root.right; // No child case if (temp == null) { temp = root; root = null; } else // One child case // Copy the contents of the non-empty child root = temp; } else { // node with two children: Get the // inorder successor (smallest // in the right subtree) let temp = minValueNode(root.right); // Copy the inorder successor's data to // this node and update the count root.key = temp.key; root.count = temp.count; temp.count = 1; // Delete the inorder successor root.right = deleteNode(root.right, temp.key); } } // If the tree had only one node then return if (root == null) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root.height = max(height(root.left), height(root.right)) + 1; // STEP 3: GET THE BALANCE FACTOR // OF THIS NODE (to check whether // this node became unbalanced) let balance = getBalance(root); // If this node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root.left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root.left) < 0) { root.left = leftRotate(root.left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root.right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root.right) > 0) { root.right = rightRotate(root.right); return leftRotate(root); } return root; } // A utility function to print preorder traversal of the tree. // The function also prints height of every node function preOrder(root) { if (root != null) { document.write(root.key + \"(\" + root.count + \") \"); preOrder(root.left); preOrder(root.right); } } let root = null; /* Constructing tree given in the above figure */ root = insert(root, 9); root = insert(root, 5); root = insert(root, 10); root = insert(root, 5); root = insert(root, 9); root = insert(root, 7); root = insert(root, 17); document.write( \"Pre order traversal of the constructed AVL tree is \" + \"</br>\"); preOrder(root); deleteNode(root, 9); document.write( \"</br>\" + \"Pre order traversal after deletion of 9 \" + \"</br>\"); preOrder(root); </script>", "e": 80587, "s": 72956, "text": null }, { "code": null, "e": 80596, "s": 80587, "text": "Output: " }, { "code": null, "e": 80742, "s": 80596, "text": "Pre order traversal of the constructed AVL tree is\n9(2) 5(2) 7(1) 10(1) 17(1)\nPre order traversal after deletion of 9\n9(1) 5(2) 7(1) 10(1) 17(1) " }, { "code": null, "e": 80925, "s": 80742, "text": "Thanks to Rounaq Jhunjhunu Wala for sharing initial code. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 80936, "s": 80925, "text": "andrew1234" }, { "code": null, "e": 80947, "s": 80936, "text": "TapanMeena" }, { "code": null, "e": 80956, "s": 80947, "text": "rohitgr7" }, { "code": null, "e": 80967, "s": 80956, "text": "nidhi_biet" }, { "code": null, "e": 80976, "s": 80967, "text": "20ajinky" }, { "code": null, "e": 80985, "s": 80976, "text": "mukesh07" }, { "code": null, "e": 81004, "s": 80985, "text": "shivanisinghss2110" }, { "code": null, "e": 81019, "s": 81004, "text": "varshagumber28" }, { "code": null, "e": 81038, "s": 81019, "text": "surindertarika1234" }, { "code": null, "e": 81055, "s": 81038, "text": "surinderdawra388" }, { "code": null, "e": 81064, "s": 81055, "text": "AVL-Tree" }, { "code": null, "e": 81069, "s": 81064, "text": "Tree" }, { "code": null, "e": 81074, "s": 81069, "text": "Tree" }, { "code": null, "e": 81083, "s": 81074, "text": "AVL-Tree" }, { "code": null, "e": 81181, "s": 81083, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 81190, "s": 81181, "text": "Comments" }, { "code": null, "e": 81203, "s": 81190, "text": "Old Comments" }, { "code": null, "e": 81253, "s": 81203, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 81288, "s": 81253, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 81322, "s": 81288, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 81351, "s": 81322, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 81392, "s": 81351, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 81435, "s": 81392, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 81497, "s": 81435, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" }, { "code": null, "e": 81530, "s": 81497, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 81544, "s": 81530, "text": "Decision Tree" } ]
Combining python and d3.js to create dynamic visualization applications | by Kanishka Narayan | Towards Data Science
The visual form is hypnotic and arresting, unlike any other medium. A painting or an image forces the eyes to see the full picture and presents a form that is free of the constraints of time. It is no wonder that visuals help in adopting a non-linear perspective while trying to understand and solve complex problems. Problem solving through data analysis and programming, on the other hand, is still very much rooted in the linear perspective, since they involve a step by step breakdown of data to understand and solve a problem. However, data analysis when done correctly allows a user to account for minute details and idiosyncrasies that are usually missed when looking at the whole picture. Combing a data driven approach along with a more visual oriented approach provides a holistic approach to problem solving and analysis that combines linear and non-linear perspectives. In this article, I explain through a detailed, reproducible example, how a user can combine python (a powerful programming language for data processing) and d3.js (a powerful language for generating visuals) to create a visualization application that provides useful insights for problem solvers. What I will demonstrate is how a user can effectively create a data processing back end in python while maintaining a visual front end in d3.js to create an effective application. We will also add some controllable features so that the front end and the back end can communicate with each other effectively on the basis of inputs from the final user. The python module we will use is ‘Flask’ which will act as the intermediary between the back end and the front end. The d3 visualization I have chosen is the collapsible bar chart example created by Mike Bostock. Creation of the visualization structure will involve some use of html, js and some jinja code. The problem - We will be using agricultural production data from the FAOSTAT database. The FAOSTAT database provides data for 213 regions for different years on several variables that is disaggregated by crop type, meat type and fish type. We will try to understand and explore the aggregations and disaggregations in the FAOSTAT data across countries across time through a dynamic visualization application. You can find the edited data sets used for this example here. We will use two datasets, one on production which is dis-aggregated by different types of crops, meat and fish and one on agricultural losses dis-aggregated by the same categories. Both data sets contain data for 213 regions from 2010 to 2013. We will create an application that helps a user compare the losses and production for any category or sub-category using the collapsible bar chart visualizations. The user should also be able to select any country and year to create visualizations for those countries. Basically, the end (edited) product will look like the below image and gif, Part 1: Defining the structure of the application What we will be doing, is create a front end on a html page which will host our visualization and d3.js scripts. We will send the data to this html page from python code contained in a file called ‘application.py’. The structure of the application on the computer will be as follows. #Application file structureroot/ static/ This folder contains your supplementary JavaScript files /templates This folder contains the index.html fileapplication.py (The main python file and data are hosted in the root folder) Below is a diagrammatic representation of the application Part 1: Defining the front end (html, d3.js) First, let’s design the front end which will be a basic html page (“index.html”) which will host our d3 visualization along with a form where a user can submit a country and year selection. The final html is hosted here. I won’t walk through some basic things like the css and formatting, etc. Those you can take directly from the html or customize as per your preferences. The steps to create the basic html page will be as follows, 1. Get all scripts required 2. Create a form where the user can change selections of the country and year. 3. Create “div” elements to host the visualizations 4. Insert d3 code to create graphs. We will also define links between the python back end and the d3 using jinja code. You will need to have basic d3 version (d3.v3.min.js) which you can bring into the html using this command, <script src=”https://d3js.org/d3.v3.min.js"></script> Let’s first create the form where the user can submit country and year information. This can be accomplished through some html code that will generate a ‘form’ where a user can submit a request. Note that the names assigned below such as “Country_field” and “Year_field” are important since those will be referenced again in the back end in python. <form method=”post” ><input name=”Country_field” placeholder=”Enter country name” > <input type=”number” name=”Year_field” placeholder=”Enter Year” > <input type=”submit” value=”Submit Country and Year” > </form> Now, we will create two divisions, one to host the production data graph on the left and one to host the loss data on the right. The divisions should also display the country and the year selected. We will have to specify ids for the graphs and will have to write out some code in jinja to get the country name and the year. The jinja code basically uses curly brackets {{}} to access data from python. Assigning a class to the divisions helps in easy additions of formatting later. The code for the same is, <div class=”left-div” id=”graphDiv” style=”border: thin solid black”> <p> <b> <i> Production data by category and sub-categories in 1000 tonnes for {{CountryName}}(Click on the bars to explore sub-divisions)</b> <br> <br> FAO defines production as “Unless otherwise indicated, production is reported at the farm level for crop and livestock products (i.e. in the case of crops, excluding harvesting losses) and in terms of live weight for fish items.” </i> </p></div> The above code produces this, We will have to repeat the same code to create another division for the loss data. After that, let’s define our d3 functions to create the plots. I have defined 2 functions, svg1 and svg2 for the left and the right plot respectively. I have used the code as is for the most part from Mike Bostock’s example here. We will only make a couple of changes. Firstly, where the svg object is defined in the code, we will have to reference our graph div ids so that the function will create the graph in the divisions we made above. So, in our example this becomes, var svg1 = d3.select(“#graphDiv”).append(“svg”).attr(“width”, width + margin.left + margin.right).attr(“height”, height + margin.top + margin.bottom).append(“g”).attr(“transform”, “translate(“ + margin.left + “,” + margin.top + “)”); Now, as mentioned above, the back end data processor will be constructed in python. Therefore, we will have to pass the data from python to the js script using the code below. The “/get-data” is a function that we will define in our python code later. “d3.json” will read in data in a json format. d3.json(“/get-data”, function(error, root){partition.nodes(root);x.domain([0, root.value]).nice();down(root, 0);}); Finally, we make a small tweak in the code for the color of the bars. We want green bars for the production graph and blue bars for the loss graph. We will change the color by changing the color variable in the code below, var color = d3.scale.ordinal() .range([“green”, “#ccc”]); Part 3: Creating the back end in python (flask) The steps in creating the python file are a bit more time consuming. The final application file is available here. We will need to perform the following steps, 1. Import neccessary packages, define the application in flask and create a datastore. 2. Create the code to generate data to send to the front end for the home page. 3. Convert data into json format for d3 and send the same to the front end 4. Similarly, define functions specifically for the production and loss graphs. OK, let's get the easy stuff out of the way. Let’s get the packages, define the flask application and create a datastore function with 4 variables. The datastore variable will help later on to save data before passing the same to the front-end. We will create a ‘CountryName’ variable, a ‘Year’ variable, both of which the user will send to the application through the form. We will create a “Prod” variable which will store the production data, and a “Loss” variable which will store the loss data. #1. Import packagesfrom flask import Flask, flash, redirect, render_template, request, session, abort,send_from_directory,send_file,jsonifyimport pandas as pdimport json #2. Declare applicationapp= Flask(__name__) #3. Create datastore variableclass DataStore(): CountryName=None Year=None Prod= None Loss=Nonedata=DataStore() Now, let's define the main page of the application. We will first have to define the route to the main page and a homepage function that will create the data for the homepage. What is basically happening is that when a user visits the main page, the homepage function will be called. We will also “get” the data from the front-end using a simple flask function called “request”. When requesting the data, note that we are using the ids defined in the html such as ‘Country_field’ and ‘Year_field’. We are also setting a default value of India for the country, and 2013 for the year. We will also pass this requested data to our datastore function variables ‘Year’ and ‘CountryName’ (The difference between datastore variables and other variables is explained below). Finally, we will read in the data for production and create variables for our analysis called CountryName and Year. Note that these are the actual variables that will be passed to the html and not internally stored in python. A good way to think of this is that the datastore is python’s internal memory which is being constantly updated with time. The static temporary variables are values created at a single point in time to be passed to the front end. As mentioned above, the visualization is created for 1 point in time and hence uses the temporary variables. #We are defining a route along with the relevant methods for the #route, in this case they are get and post. @app.route(“/”,methods=[“GET”,”POST”])#We are defining a home page function below. We will get the #CountryName and the Year from the form we defined in the html def homepage(): data.CountryName = request.form.get(‘Country_field’,’India’) data.Year = request.form.get(‘Year_field’, 2013) data.CountryName=CountryName df = pd.read_csv(‘CropsFull.csv’) CountryName = data.CountryName Year= data.Year Now, we will filter the data (df) for the values we received from the form. This is a straightforward filter in python. We will also keep only relevant columns for further processing. I have converted the Year variable to an integer since sometimes the request will return a string and this may lead to python being unable to filter the data. # Filter the data frame (df)df = df[df.Country == CountryName]df = df[df.Year == int(Year)]#Keep only relevant columns df = df[[“Category”, “Cat”, “value”]] Now, we will need to convert this dataframe into a layered json. The json is layered in accordance with the aggregation categories in the data, and is therefore useful for the visualization. I have attached the code for the same below. But I have used Andrew Heekin’s code to create nested jsons for the same. The code can be found here. I will not go into the details of the code here. df1 = df.groupby([‘Category’, ‘Cat’])[‘value’].sum()df1 = df1.reset_index()#Lets create a dictd = {"name": "flare", "children": []} for line in df1.values: Category = line[0] Cat = line[1] value = line[2] # make a list of keys keys_list = [] for item in d['children']: keys_list.append(item['name']) # if 'the_parent' is NOT a key in the flare.json yet, append it if not Category in keys_list: d['children'].append({"name": Category, "children": [{"name": Cat, "size": value}]}) # if 'the_parent' IS a key in the flare.json, add a new child to it else: d['children'][keys_list.index(Category)] ['children'].append({"name": Cat, "size": value}) flare = d Now, we will have to dump this data into a json format. and each time we assign it we can load it using the json load function. As mentioned above, let's save this data to both a temporary variable ‘Prod’ to pass to the front end and to a python memory variable called ‘data.Prod’ from our datastore function. #Dump data to jsonflare = json.dumps(flare)#Save to datastoredata.Prod = json.loads(flare)#Save to temporary variableProd=data.Prod We will process data for losses using the above steps. I won’t repeat the entire code here. The last lines for the loss code will be, #Dump data to jsonflare = json.dumps(flare)#Save to datastoredata.Loss = json.loads(flare)#Save to temporary variableLoss = data.Loss Finally let’s wrap up our function with a return statement. We will use the flask ‘render_template’ function to send the data to our front end (the index.html’ file. We will also return all our temporary variables such as the CountryName, Year, the production and loss data return render_template(“index.html”,CountryName=CountryName,Year=Year,Prod=Prod,Loss=Loss) The above code send data to the main page. We will also have to write 2 other functions to send the production and loss data to our js functions. Given that we have a datastore that remembers our production and loss data, this should be fairly simple. Lets define a route called “/get-data” and send our production data to it. Note that the function returns a ‘jsonified’ version of the data. @app.route(“/get-data”,methods=[“GET”,”POST”]) def returnProdData(): f=data.Prod return jsonify(f) We will create a similar function for the loss data at a route called ‘/get-loss-data’. @app.route(“/get-loss-data”,methods=[“GET”,”POST”]) def returnLossData(): g=data.Loss return jsonify(g) Finally lets define the code to run the app, if __name__ == "__main__": app.run(debug=True) There you have it. Your application is ready! Go ahead and run it! On running the code, you should get the following message with a link to the application on a local drive. * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) This application is easily deployable on servers. I have deployed it on a free heroku server. The same can be accessed here. Note that I am using the free version of heroku, so the load time is a bit slow (You may have to referesh the application a couple of times). I have also added the requirements.txt and .gitignore and procfile in case you would like to deploy it yourself to heroku or to any other server. This code is obviously easily adaptable to other d3 visualizations that you like! Many thanks to Mike Bostock for creating a wonderful language like d3 and to Andrew Heekin for writing the code that generates layered jsons. Thank you to David Bohl and Aditya Kulkarni for their feedback and comments. I attach below links to the github repository and other sources below for your reference and convenience. 1. Link to github project- https://github.com/kanishkan91/FAO-FBS-Data-Explorer 2. Link to application deployed on heroku server- https://faoexplorer-flask-d3.herokuapp.com/ 3. Link to Mike Bostocks collapsible bar chart example- https://observablehq.com/@d3/hierarchical-bar-chart 4. Link to Andrew Heekin’s code for creating layered json- https://github.com/andrewheekin/csv2flare.json/blob/master/csv2flare.json.py
[ { "code": null, "e": 490, "s": 172, "text": "The visual form is hypnotic and arresting, unlike any other medium. A painting or an image forces the eyes to see the full picture and presents a form that is free of the constraints of time. It is no wonder that visuals help in adopting a non-linear perspective while trying to understand and solve complex problems." }, { "code": null, "e": 1351, "s": 490, "text": "Problem solving through data analysis and programming, on the other hand, is still very much rooted in the linear perspective, since they involve a step by step breakdown of data to understand and solve a problem. However, data analysis when done correctly allows a user to account for minute details and idiosyncrasies that are usually missed when looking at the whole picture. Combing a data driven approach along with a more visual oriented approach provides a holistic approach to problem solving and analysis that combines linear and non-linear perspectives. In this article, I explain through a detailed, reproducible example, how a user can combine python (a powerful programming language for data processing) and d3.js (a powerful language for generating visuals) to create a visualization application that provides useful insights for problem solvers." }, { "code": null, "e": 2010, "s": 1351, "text": "What I will demonstrate is how a user can effectively create a data processing back end in python while maintaining a visual front end in d3.js to create an effective application. We will also add some controllable features so that the front end and the back end can communicate with each other effectively on the basis of inputs from the final user. The python module we will use is ‘Flask’ which will act as the intermediary between the back end and the front end. The d3 visualization I have chosen is the collapsible bar chart example created by Mike Bostock. Creation of the visualization structure will involve some use of html, js and some jinja code." }, { "code": null, "e": 2024, "s": 2010, "text": "The problem -" }, { "code": null, "e": 3070, "s": 2024, "text": "We will be using agricultural production data from the FAOSTAT database. The FAOSTAT database provides data for 213 regions for different years on several variables that is disaggregated by crop type, meat type and fish type. We will try to understand and explore the aggregations and disaggregations in the FAOSTAT data across countries across time through a dynamic visualization application. You can find the edited data sets used for this example here. We will use two datasets, one on production which is dis-aggregated by different types of crops, meat and fish and one on agricultural losses dis-aggregated by the same categories. Both data sets contain data for 213 regions from 2010 to 2013. We will create an application that helps a user compare the losses and production for any category or sub-category using the collapsible bar chart visualizations. The user should also be able to select any country and year to create visualizations for those countries. Basically, the end (edited) product will look like the below image and gif," }, { "code": null, "e": 3120, "s": 3070, "text": "Part 1: Defining the structure of the application" }, { "code": null, "e": 3404, "s": 3120, "text": "What we will be doing, is create a front end on a html page which will host our visualization and d3.js scripts. We will send the data to this html page from python code contained in a file called ‘application.py’. The structure of the application on the computer will be as follows." }, { "code": null, "e": 3639, "s": 3404, "text": "#Application file structureroot/ static/ This folder contains your supplementary JavaScript files /templates This folder contains the index.html fileapplication.py (The main python file and data are hosted in the root folder)" }, { "code": null, "e": 3697, "s": 3639, "text": "Below is a diagrammatic representation of the application" }, { "code": null, "e": 3742, "s": 3697, "text": "Part 1: Defining the front end (html, d3.js)" }, { "code": null, "e": 4176, "s": 3742, "text": "First, let’s design the front end which will be a basic html page (“index.html”) which will host our d3 visualization along with a form where a user can submit a country and year selection. The final html is hosted here. I won’t walk through some basic things like the css and formatting, etc. Those you can take directly from the html or customize as per your preferences. The steps to create the basic html page will be as follows," }, { "code": null, "e": 4204, "s": 4176, "text": "1. Get all scripts required" }, { "code": null, "e": 4283, "s": 4204, "text": "2. Create a form where the user can change selections of the country and year." }, { "code": null, "e": 4335, "s": 4283, "text": "3. Create “div” elements to host the visualizations" }, { "code": null, "e": 4454, "s": 4335, "text": "4. Insert d3 code to create graphs. We will also define links between the python back end and the d3 using jinja code." }, { "code": null, "e": 4562, "s": 4454, "text": "You will need to have basic d3 version (d3.v3.min.js) which you can bring into the html using this command," }, { "code": null, "e": 4616, "s": 4562, "text": "<script src=”https://d3js.org/d3.v3.min.js\"></script>" }, { "code": null, "e": 4965, "s": 4616, "text": "Let’s first create the form where the user can submit country and year information. This can be accomplished through some html code that will generate a ‘form’ where a user can submit a request. Note that the names assigned below such as “Country_field” and “Year_field” are important since those will be referenced again in the back end in python." }, { "code": null, "e": 5178, "s": 4965, "text": "<form method=”post” ><input name=”Country_field” placeholder=”Enter country name” > <input type=”number” name=”Year_field” placeholder=”Enter Year” > <input type=”submit” value=”Submit Country and Year” > </form>" }, { "code": null, "e": 5687, "s": 5178, "text": "Now, we will create two divisions, one to host the production data graph on the left and one to host the loss data on the right. The divisions should also display the country and the year selected. We will have to specify ids for the graphs and will have to write out some code in jinja to get the country name and the year. The jinja code basically uses curly brackets {{}} to access data from python. Assigning a class to the divisions helps in easy additions of formatting later. The code for the same is," }, { "code": null, "e": 6158, "s": 5687, "text": "<div class=”left-div” id=”graphDiv” style=”border: thin solid black”> <p> <b> <i> Production data by category and sub-categories in 1000 tonnes for {{CountryName}}(Click on the bars to explore sub-divisions)</b> <br> <br> FAO defines production as “Unless otherwise indicated, production is reported at the farm level for crop and livestock products (i.e. in the case of crops, excluding harvesting losses) and in terms of live weight for fish items.” </i> </p></div>" }, { "code": null, "e": 6188, "s": 6158, "text": "The above code produces this," }, { "code": null, "e": 6746, "s": 6188, "text": "We will have to repeat the same code to create another division for the loss data. After that, let’s define our d3 functions to create the plots. I have defined 2 functions, svg1 and svg2 for the left and the right plot respectively. I have used the code as is for the most part from Mike Bostock’s example here. We will only make a couple of changes. Firstly, where the svg object is defined in the code, we will have to reference our graph div ids so that the function will create the graph in the divisions we made above. So, in our example this becomes," }, { "code": null, "e": 6980, "s": 6746, "text": "var svg1 = d3.select(“#graphDiv”).append(“svg”).attr(“width”, width + margin.left + margin.right).attr(“height”, height + margin.top + margin.bottom).append(“g”).attr(“transform”, “translate(“ + margin.left + “,” + margin.top + “)”);" }, { "code": null, "e": 7278, "s": 6980, "text": "Now, as mentioned above, the back end data processor will be constructed in python. Therefore, we will have to pass the data from python to the js script using the code below. The “/get-data” is a function that we will define in our python code later. “d3.json” will read in data in a json format." }, { "code": null, "e": 7394, "s": 7278, "text": "d3.json(“/get-data”, function(error, root){partition.nodes(root);x.domain([0, root.value]).nice();down(root, 0);});" }, { "code": null, "e": 7617, "s": 7394, "text": "Finally, we make a small tweak in the code for the color of the bars. We want green bars for the production graph and blue bars for the loss graph. We will change the color by changing the color variable in the code below," }, { "code": null, "e": 7678, "s": 7617, "text": "var color = d3.scale.ordinal() .range([“green”, “#ccc”]);" }, { "code": null, "e": 7726, "s": 7678, "text": "Part 3: Creating the back end in python (flask)" }, { "code": null, "e": 7886, "s": 7726, "text": "The steps in creating the python file are a bit more time consuming. The final application file is available here. We will need to perform the following steps," }, { "code": null, "e": 7973, "s": 7886, "text": "1. Import neccessary packages, define the application in flask and create a datastore." }, { "code": null, "e": 8053, "s": 7973, "text": "2. Create the code to generate data to send to the front end for the home page." }, { "code": null, "e": 8128, "s": 8053, "text": "3. Convert data into json format for d3 and send the same to the front end" }, { "code": null, "e": 8208, "s": 8128, "text": "4. Similarly, define functions specifically for the production and loss graphs." }, { "code": null, "e": 8708, "s": 8208, "text": "OK, let's get the easy stuff out of the way. Let’s get the packages, define the flask application and create a datastore function with 4 variables. The datastore variable will help later on to save data before passing the same to the front-end. We will create a ‘CountryName’ variable, a ‘Year’ variable, both of which the user will send to the application through the form. We will create a “Prod” variable which will store the production data, and a “Loss” variable which will store the loss data." }, { "code": null, "e": 9053, "s": 8708, "text": "#1. Import packagesfrom flask import Flask, flash, redirect, render_template, request, session, abort,send_from_directory,send_file,jsonifyimport pandas as pdimport json #2. Declare applicationapp= Flask(__name__) #3. Create datastore variableclass DataStore(): CountryName=None Year=None Prod= None Loss=Nonedata=DataStore()" }, { "code": null, "e": 10385, "s": 9053, "text": "Now, let's define the main page of the application. We will first have to define the route to the main page and a homepage function that will create the data for the homepage. What is basically happening is that when a user visits the main page, the homepage function will be called. We will also “get” the data from the front-end using a simple flask function called “request”. When requesting the data, note that we are using the ids defined in the html such as ‘Country_field’ and ‘Year_field’. We are also setting a default value of India for the country, and 2013 for the year. We will also pass this requested data to our datastore function variables ‘Year’ and ‘CountryName’ (The difference between datastore variables and other variables is explained below). Finally, we will read in the data for production and create variables for our analysis called CountryName and Year. Note that these are the actual variables that will be passed to the html and not internally stored in python. A good way to think of this is that the datastore is python’s internal memory which is being constantly updated with time. The static temporary variables are values created at a single point in time to be passed to the front end. As mentioned above, the visualization is created for 1 point in time and hence uses the temporary variables." }, { "code": null, "e": 10911, "s": 10385, "text": "#We are defining a route along with the relevant methods for the #route, in this case they are get and post. @app.route(“/”,methods=[“GET”,”POST”])#We are defining a home page function below. We will get the #CountryName and the Year from the form we defined in the html def homepage(): data.CountryName = request.form.get(‘Country_field’,’India’) data.Year = request.form.get(‘Year_field’, 2013) data.CountryName=CountryName df = pd.read_csv(‘CropsFull.csv’) CountryName = data.CountryName Year= data.Year" }, { "code": null, "e": 11254, "s": 10911, "text": "Now, we will filter the data (df) for the values we received from the form. This is a straightforward filter in python. We will also keep only relevant columns for further processing. I have converted the Year variable to an integer since sometimes the request will return a string and this may lead to python being unable to filter the data." }, { "code": null, "e": 11411, "s": 11254, "text": "# Filter the data frame (df)df = df[df.Country == CountryName]df = df[df.Year == int(Year)]#Keep only relevant columns df = df[[“Category”, “Cat”, “value”]]" }, { "code": null, "e": 11798, "s": 11411, "text": "Now, we will need to convert this dataframe into a layered json. The json is layered in accordance with the aggregation categories in the data, and is therefore useful for the visualization. I have attached the code for the same below. But I have used Andrew Heekin’s code to create nested jsons for the same. The code can be found here. I will not go into the details of the code here." }, { "code": null, "e": 12517, "s": 11798, "text": "df1 = df.groupby([‘Category’, ‘Cat’])[‘value’].sum()df1 = df1.reset_index()#Lets create a dictd = {\"name\": \"flare\", \"children\": []} for line in df1.values: Category = line[0] Cat = line[1] value = line[2] # make a list of keys keys_list = [] for item in d['children']: keys_list.append(item['name']) # if 'the_parent' is NOT a key in the flare.json yet, append it if not Category in keys_list: d['children'].append({\"name\": Category, \"children\": [{\"name\": Cat, \"size\": value}]}) # if 'the_parent' IS a key in the flare.json, add a new child to it else: d['children'][keys_list.index(Category)] ['children'].append({\"name\": Cat, \"size\": value}) flare = d" }, { "code": null, "e": 12827, "s": 12517, "text": "Now, we will have to dump this data into a json format. and each time we assign it we can load it using the json load function. As mentioned above, let's save this data to both a temporary variable ‘Prod’ to pass to the front end and to a python memory variable called ‘data.Prod’ from our datastore function." }, { "code": null, "e": 12959, "s": 12827, "text": "#Dump data to jsonflare = json.dumps(flare)#Save to datastoredata.Prod = json.loads(flare)#Save to temporary variableProd=data.Prod" }, { "code": null, "e": 13093, "s": 12959, "text": "We will process data for losses using the above steps. I won’t repeat the entire code here. The last lines for the loss code will be," }, { "code": null, "e": 13227, "s": 13093, "text": "#Dump data to jsonflare = json.dumps(flare)#Save to datastoredata.Loss = json.loads(flare)#Save to temporary variableLoss = data.Loss" }, { "code": null, "e": 13501, "s": 13227, "text": "Finally let’s wrap up our function with a return statement. We will use the flask ‘render_template’ function to send the data to our front end (the index.html’ file. We will also return all our temporary variables such as the CountryName, Year, the production and loss data" }, { "code": null, "e": 13592, "s": 13501, "text": "return render_template(“index.html”,CountryName=CountryName,Year=Year,Prod=Prod,Loss=Loss)" }, { "code": null, "e": 13985, "s": 13592, "text": "The above code send data to the main page. We will also have to write 2 other functions to send the production and loss data to our js functions. Given that we have a datastore that remembers our production and loss data, this should be fairly simple. Lets define a route called “/get-data” and send our production data to it. Note that the function returns a ‘jsonified’ version of the data." }, { "code": null, "e": 14091, "s": 13985, "text": "@app.route(“/get-data”,methods=[“GET”,”POST”]) def returnProdData(): f=data.Prod return jsonify(f)" }, { "code": null, "e": 14179, "s": 14091, "text": "We will create a similar function for the loss data at a route called ‘/get-loss-data’." }, { "code": null, "e": 14290, "s": 14179, "text": "@app.route(“/get-loss-data”,methods=[“GET”,”POST”]) def returnLossData(): g=data.Loss return jsonify(g)" }, { "code": null, "e": 14335, "s": 14290, "text": "Finally lets define the code to run the app," }, { "code": null, "e": 14385, "s": 14335, "text": "if __name__ == \"__main__\": app.run(debug=True)" }, { "code": null, "e": 14559, "s": 14385, "text": "There you have it. Your application is ready! Go ahead and run it! On running the code, you should get the following message with a link to the application on a local drive." }, { "code": null, "e": 14618, "s": 14559, "text": "* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)" }, { "code": null, "e": 15113, "s": 14618, "text": "This application is easily deployable on servers. I have deployed it on a free heroku server. The same can be accessed here. Note that I am using the free version of heroku, so the load time is a bit slow (You may have to referesh the application a couple of times). I have also added the requirements.txt and .gitignore and procfile in case you would like to deploy it yourself to heroku or to any other server. This code is obviously easily adaptable to other d3 visualizations that you like!" }, { "code": null, "e": 15332, "s": 15113, "text": "Many thanks to Mike Bostock for creating a wonderful language like d3 and to Andrew Heekin for writing the code that generates layered jsons. Thank you to David Bohl and Aditya Kulkarni for their feedback and comments." }, { "code": null, "e": 15438, "s": 15332, "text": "I attach below links to the github repository and other sources below for your reference and convenience." }, { "code": null, "e": 15518, "s": 15438, "text": "1. Link to github project- https://github.com/kanishkan91/FAO-FBS-Data-Explorer" }, { "code": null, "e": 15612, "s": 15518, "text": "2. Link to application deployed on heroku server- https://faoexplorer-flask-d3.herokuapp.com/" }, { "code": null, "e": 15720, "s": 15612, "text": "3. Link to Mike Bostocks collapsible bar chart example- https://observablehq.com/@d3/hierarchical-bar-chart" } ]
GATE | GATE-CS-2015 (Set 1) | Question 65 - GeeksforGeeks
28 Jun, 2021 Consider a system with byte-addressable memory, 32 bit logical addresses, 4 kilobyte page size and page table entries of 4 bytes each. The size of the page table in the system in megabytes is ___________(A) 2(B) 4(C) 8(D) 16Answer: (B)Explanation: Number of entries in page table = 232 / 4Kbyte = 232 / 212 = 220 Size of page table = (No. page table entries)*(Size of an entry) = 220 * 4 bytes = 222 = 4 Megabytes Quiz of this Question GATE-CS-2015 (Set 1) GATE-GATE-CS-2015 (Set 1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25809, "s": 25781, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26057, "s": 25809, "text": "Consider a system with byte-addressable memory, 32 bit logical addresses, 4 kilobyte page size and page table entries of 4 bytes each. The size of the page table in the system in megabytes is ___________(A) 2(B) 4(C) 8(D) 16Answer: (B)Explanation:" }, { "code": null, "e": 26360, "s": 26057, "text": "Number of entries in page table = 232 / 4Kbyte \n = 232 / 212 \n = 220\n\nSize of page table = (No. page table entries)*(Size of an entry) \n = 220 * 4 bytes \n = 222 \n = 4 Megabytes\n" }, { "code": null, "e": 26382, "s": 26360, "text": "Quiz of this Question" }, { "code": null, "e": 26403, "s": 26382, "text": "GATE-CS-2015 (Set 1)" }, { "code": null, "e": 26429, "s": 26403, "text": "GATE-GATE-CS-2015 (Set 1)" }, { "code": null, "e": 26434, "s": 26429, "text": "GATE" }, { "code": null, "e": 26532, "s": 26434, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26566, "s": 26532, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26600, "s": 26566, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26634, "s": 26600, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26667, "s": 26634, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26703, "s": 26667, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26737, "s": 26703, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 26773, "s": 26737, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 26807, "s": 26773, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 26841, "s": 26807, "text": "GATE | GATE-CS-2009 | Question 38" } ]
How can we insert current date and time automatically on inserting values in other columns in MySQL?
In MySQL, we can insert the current date and time automatically to a column on inserting the values in another column by declaring that column as DEFAULT CURRENT_TIMESTAMP. mysql> Create table testing -> ( -> StudentName varchar(20) NOT NULL, -> RegDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP -> ); Query OK, 0 rows affected (0.49 sec) Above query will create a table ‘testing’ with a column named StudentName and other column named ‘RegDate’ declared as DEFAULT CURRENT_TIMESTAMP. Now, on inserting the values i.e. names in StudentName column, the current date and time will be inserted in the other column automatically. mysql> Insert into testing(StudentName) values ('Ram'); Query OK, 1 row affected (0.14 sec) mysql> Insert into testing(StudentName) values ('Shyam'); Query OK, 1 row affected (0.06 sec) mysql> Select * from testing; +-------------+---------------------+ | StudentName | RegDate | +-------------+---------------------+ | Ram | 2017-10-28 21:24:24 | | Shyam | 2017-10-28 21:24:30 | +-------------+---------------------+ 2 rows in set (0.02 sec) mysql> Insert into testing(StudentName) values ('Mohan'); Query OK, 1 row affected (0.06 sec) mysql> Select * from testing; +-------------+---------------------+ | StudentName | RegDate | +-------------+---------------------+ | Ram | 2017-10-28 21:24:24 | | Shyam | 2017-10-28 21:24:30 | | Mohan | 2017-10-28 21:24:47 | +-------------+---------------------+ 3 rows in set (0.00 sec) From the above queries, we can see that on inserting the values in StudentName, the date and time is also inserting automatically. With the help of the above concept, we can also know that exactly on what date and time the values in other column inserted.
[ { "code": null, "e": 1235, "s": 1062, "text": "In MySQL, we can insert the current date and time automatically to a column on inserting the values in another column by declaring that column as DEFAULT CURRENT_TIMESTAMP." }, { "code": null, "e": 1407, "s": 1235, "text": "mysql> Create table testing\n -> (\n -> StudentName varchar(20) NOT NULL,\n -> RegDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n -> );\nQuery OK, 0 rows affected (0.49 sec)" }, { "code": null, "e": 1694, "s": 1407, "text": "Above query will create a table ‘testing’ with a column named StudentName and other column named ‘RegDate’ declared as DEFAULT CURRENT_TIMESTAMP. Now, on inserting the values i.e. names in StudentName column, the current date and time will be inserted in the other column automatically." }, { "code": null, "e": 2582, "s": 1694, "text": "mysql> Insert into testing(StudentName) values ('Ram');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> Insert into testing(StudentName) values ('Shyam');\nQuery OK, 1 row affected (0.06 sec)\n\nmysql> Select * from testing;\n+-------------+---------------------+\n| StudentName | RegDate |\n+-------------+---------------------+\n| Ram | 2017-10-28 21:24:24 |\n| Shyam | 2017-10-28 21:24:30 |\n+-------------+---------------------+\n2 rows in set (0.02 sec)\n\nmysql> Insert into testing(StudentName) values ('Mohan');\nQuery OK, 1 row affected (0.06 sec)\n\nmysql> Select * from testing;\n+-------------+---------------------+\n| StudentName | RegDate |\n+-------------+---------------------+\n| Ram | 2017-10-28 21:24:24 |\n| Shyam | 2017-10-28 21:24:30 |\n| Mohan | 2017-10-28 21:24:47 |\n+-------------+---------------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2713, "s": 2582, "text": "From the above queries, we can see that on inserting the values in StudentName, the date and time is also inserting automatically." }, { "code": null, "e": 2838, "s": 2713, "text": "With the help of the above concept, we can also know that exactly on what date and time the values in other column inserted." } ]
AWT Line2D Class
The Line2D class states a line segment in (x,y) coordinate space. Following is the declaration for java.awt.geom.Line2D class: public abstract class Line2D extends Object implements Shape, Cloneable protected Line2D() () This is an abstract class that cannot be instantiated directly. Object clone() Creates a new object of the same class as this object. boolean contains(double x, double y) Tests if a specified coordinate is inside the boundary of this Line2D. boolean contains(double x, double y, double w, double h) Tests if the interior of this Line2D entirely contains the specified set of rectangular coordinates. boolean contains(Point2D p) Tests if a given Point2D is inside the boundary of this Line2D. boolean contains(Rectangle2D r) Tests if the interior of this Line2D entirely contains the specified Rectangle2D. Rectangle getBounds() Returns an integer Rectangle that completely encloses the Shape. abstract Point2D getP1() Returns the start Point2D of this Line2D. abstract Point2D getP2() Returns the end Point2D of this Line2D. PathIterator getPathIterator(AffineTransform at) Returns an iteration object that defines the boundary of this Line2D. PathIterator getPathIterator(AffineTransform at, double flatness) Returns an iteration object that defines the boundary of this flattened Line2D. abstract double getX1() Returns the X coordinate of the start point in double precision. abstract double getX2() Returns the X coordinate of the end point in double precision. abstract double getY1() Returns the Y coordinate of the start point in double precision. abstract double getY2() Returns the Y coordinate of the end point in double precision. boolean intersects(double x, double y, double w, double h) Tests if the interior of the Shape intersects the interior of a specified rectangular area. boolean intersects(Rectangle2D r) Tests if the interior of the Shape intersects the interior of a specified Rectangle2D. boolean intersectsLine(double x1, double y1, double x2, double y2) Tests if the line segment from (x1,y1) to (x2,y2) intersects this line segment. boolean intersectsLine(Line2D l) Tests if the specified line segment intersects this line segment. static boolean linesIntersect(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) Tests if the line segment from (x1,y1) to (x2,y2) intersects the line segment from (x3,y3) to (x4,y4). double ptLineDist(double px, double py) Returns the distance from a point to this line. static double ptLineDist(double x1, double y1, double x2, double y2, double px, double py) Returns the distance from a point to a line. double ptLineDist(Point2D pt) Returns the distance from a Point2D to this line. double ptLineDistSq(double px, double py) Returns the square of the distance from a point to this line. static double ptLineDistSq(double x1, double y1, double x2, double y2, double px, double py) Returns the square of the distance from a point to a line. double ptLineDistSq(Point2D pt) Returns the square of the distance from a specified Point2D to this line. double ptSegDist(double px, double py) Returns the distance from a point to this line segment. static double ptSegDist(double x1, double y1, double x2, double y2, double px, double py) Returns the distance from a point to a line segment. double ptSegDist(Point2D pt) Returns the distance from a Point2D to this line segment. double ptSegDistSq(double px, double py) Returns the square of the distance from a point to this line segment. static double ptSegDistSq(double x1, double y1, double x2, double y2, double px, double py) Returns the square of the distance from a point to a line segment. double ptSegDistSq(Point2D pt) Returns the square of the distance from a Point2D to this line segment. int relativeCCW(double px, double py) Returns an indicator of where the specified point (px,py) lies with respect to this line segment. static int relativeCCW(double x1, double y1, double x2, double y2, double px, double py) Returns an indicator of where the specified point (px,py) lies with respect to the line segment from (x1,y1) to (x2,y2). int relativeCCW(Point2D p) Returns an indicator of where the specified Point2D lies with respect to this line segment. abstract void setLine(double x1, double y1, double x2, double y2) Sets the location of the end points of this Line2D to the specified double coordinates. void setLine(Line2D l) Sets the location of the end points of this Line2D to the same as those end points of the specified Line2D. void setLine(Point2D p1, Point2D p2) Sets the location of the end points of this Line2D to the specified Point2D coordinates. This class inherits methods from the following classes: java.lang.Object java.lang.Object Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui > package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; public class AWTGraphicsDemo extends Frame { public AWTGraphicsDemo(){ super("Java AWT Examples"); prepareGUI(); } public static void main(String[] args){ AWTGraphicsDemo awtGraphicsDemo = new AWTGraphicsDemo(); awtGraphicsDemo.setVisible(true); } private void prepareGUI(){ setSize(400,400); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); } @Override public void paint(Graphics g) { Line2D shape = new Line2D.Double(); shape.setLine(250D,250D,150D,150D); Graphics2D g2 = (Graphics2D) g; g2.draw (shape); Font font = new Font("Serif", Font.PLAIN, 24); g2.setFont(font); g.drawString("Welcome to TutorialsPoint", 50, 70); g2.drawString("Line2D.Line", 100, 120); } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo Verify the following output 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 1813, "s": 1747, "text": "The Line2D class states a line segment in (x,y) coordinate space." }, { "code": null, "e": 1874, "s": 1813, "text": "Following is the declaration for java.awt.geom.Line2D class:" }, { "code": null, "e": 1955, "s": 1874, "text": "public abstract class Line2D\n extends Object\n implements Shape, Cloneable" }, { "code": null, "e": 1978, "s": 1955, "text": "protected Line2D() () " }, { "code": null, "e": 2043, "s": 1978, "text": " This is an abstract class that cannot be instantiated directly." }, { "code": null, "e": 2060, "s": 2043, "text": "Object clone() " }, { "code": null, "e": 2115, "s": 2060, "text": "Creates a new object of the same class as this object." }, { "code": null, "e": 2153, "s": 2115, "text": "boolean contains(double x, double y) " }, { "code": null, "e": 2225, "s": 2153, "text": " Tests if a specified coordinate is inside the boundary of this Line2D." }, { "code": null, "e": 2284, "s": 2225, "text": "boolean contains(double x, double y, double w, double h) " }, { "code": null, "e": 2385, "s": 2284, "text": "Tests if the interior of this Line2D entirely contains the specified set of rectangular coordinates." }, { "code": null, "e": 2415, "s": 2385, "text": "boolean contains(Point2D p) " }, { "code": null, "e": 2479, "s": 2415, "text": "Tests if a given Point2D is inside the boundary of this Line2D." }, { "code": null, "e": 2513, "s": 2479, "text": "boolean contains(Rectangle2D r) " }, { "code": null, "e": 2595, "s": 2513, "text": "Tests if the interior of this Line2D entirely contains the specified Rectangle2D." }, { "code": null, "e": 2619, "s": 2595, "text": "Rectangle getBounds() " }, { "code": null, "e": 2684, "s": 2619, "text": "Returns an integer Rectangle that completely encloses the Shape." }, { "code": null, "e": 2711, "s": 2684, "text": "abstract Point2D getP1() " }, { "code": null, "e": 2753, "s": 2711, "text": "Returns the start Point2D of this Line2D." }, { "code": null, "e": 2780, "s": 2753, "text": "abstract Point2D getP2() " }, { "code": null, "e": 2820, "s": 2780, "text": "Returns the end Point2D of this Line2D." }, { "code": null, "e": 2870, "s": 2820, "text": "PathIterator getPathIterator(AffineTransform at) " }, { "code": null, "e": 2940, "s": 2870, "text": "Returns an iteration object that defines the boundary of this Line2D." }, { "code": null, "e": 3008, "s": 2940, "text": "PathIterator getPathIterator(AffineTransform at, double flatness) " }, { "code": null, "e": 3088, "s": 3008, "text": "Returns an iteration object that defines the boundary of this flattened Line2D." }, { "code": null, "e": 3114, "s": 3088, "text": "abstract double getX1() " }, { "code": null, "e": 3179, "s": 3114, "text": "Returns the X coordinate of the start point in double precision." }, { "code": null, "e": 3205, "s": 3179, "text": "abstract double getX2() " }, { "code": null, "e": 3268, "s": 3205, "text": "Returns the X coordinate of the end point in double precision." }, { "code": null, "e": 3294, "s": 3268, "text": "abstract double getY1() " }, { "code": null, "e": 3359, "s": 3294, "text": "Returns the Y coordinate of the start point in double precision." }, { "code": null, "e": 3385, "s": 3359, "text": "abstract double getY2() " }, { "code": null, "e": 3448, "s": 3385, "text": "Returns the Y coordinate of the end point in double precision." }, { "code": null, "e": 3509, "s": 3448, "text": "boolean intersects(double x, double y, double w, double h) " }, { "code": null, "e": 3602, "s": 3509, "text": " Tests if the interior of the Shape intersects the interior of a specified rectangular area." }, { "code": null, "e": 3638, "s": 3602, "text": "boolean intersects(Rectangle2D r) " }, { "code": null, "e": 3725, "s": 3638, "text": "Tests if the interior of the Shape intersects the interior of a specified Rectangle2D." }, { "code": null, "e": 3794, "s": 3725, "text": "boolean intersectsLine(double x1, double y1, double x2, double y2) " }, { "code": null, "e": 3874, "s": 3794, "text": "Tests if the line segment from (x1,y1) to (x2,y2) intersects this line segment." }, { "code": null, "e": 3909, "s": 3874, "text": "boolean intersectsLine(Line2D l) " }, { "code": null, "e": 3975, "s": 3909, "text": "Tests if the specified line segment intersects this line segment." }, { "code": null, "e": 4095, "s": 3975, "text": "static boolean linesIntersect(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) " }, { "code": null, "e": 4199, "s": 4095, "text": " Tests if the line segment from (x1,y1) to (x2,y2) intersects the line segment from (x3,y3) to (x4,y4)." }, { "code": null, "e": 4241, "s": 4199, "text": "double ptLineDist(double px, double py) " }, { "code": null, "e": 4290, "s": 4241, "text": " Returns the distance from a point to this line." }, { "code": null, "e": 4381, "s": 4290, "text": "static double ptLineDist(double x1, double y1, double x2, double y2, double px, double py)" }, { "code": null, "e": 4426, "s": 4381, "text": "Returns the distance from a point to a line." }, { "code": null, "e": 4456, "s": 4426, "text": "double ptLineDist(Point2D pt)" }, { "code": null, "e": 4506, "s": 4456, "text": "Returns the distance from a Point2D to this line." }, { "code": null, "e": 4548, "s": 4506, "text": "double ptLineDistSq(double px, double py)" }, { "code": null, "e": 4610, "s": 4548, "text": "Returns the square of the distance from a point to this line." }, { "code": null, "e": 4703, "s": 4610, "text": "static double ptLineDistSq(double x1, double y1, double x2, double y2, double px, double py)" }, { "code": null, "e": 4762, "s": 4703, "text": "Returns the square of the distance from a point to a line." }, { "code": null, "e": 4794, "s": 4762, "text": "double ptLineDistSq(Point2D pt)" }, { "code": null, "e": 4868, "s": 4794, "text": "Returns the square of the distance from a specified Point2D to this line." }, { "code": null, "e": 4909, "s": 4868, "text": "double ptSegDist(double px, double py) " }, { "code": null, "e": 4965, "s": 4909, "text": "Returns the distance from a point to this line segment." }, { "code": null, "e": 5055, "s": 4965, "text": "static double ptSegDist(double x1, double y1, double x2, double y2, double px, double py)" }, { "code": null, "e": 5108, "s": 5055, "text": "Returns the distance from a point to a line segment." }, { "code": null, "e": 5139, "s": 5108, "text": "double ptSegDist(Point2D pt) " }, { "code": null, "e": 5197, "s": 5139, "text": "Returns the distance from a Point2D to this line segment." }, { "code": null, "e": 5240, "s": 5197, "text": "double ptSegDistSq(double px, double py) " }, { "code": null, "e": 5310, "s": 5240, "text": "Returns the square of the distance from a point to this line segment." }, { "code": null, "e": 5402, "s": 5310, "text": "static double ptSegDistSq(double x1, double y1, double x2, double y2, double px, double py)" }, { "code": null, "e": 5469, "s": 5402, "text": "Returns the square of the distance from a point to a line segment." }, { "code": null, "e": 5502, "s": 5469, "text": "double ptSegDistSq(Point2D pt) " }, { "code": null, "e": 5574, "s": 5502, "text": "Returns the square of the distance from a Point2D to this line segment." }, { "code": null, "e": 5614, "s": 5574, "text": "int relativeCCW(double px, double py) " }, { "code": null, "e": 5712, "s": 5614, "text": "Returns an indicator of where the specified point (px,py) lies with respect to this line segment." }, { "code": null, "e": 5801, "s": 5712, "text": "static int relativeCCW(double x1, double y1, double x2, double y2, double px, double py)" }, { "code": null, "e": 5923, "s": 5801, "text": "Returns an indicator of where the specified point (px,py) lies with respect to the line segment from (x1,y1) to (x2,y2).\n" }, { "code": null, "e": 5950, "s": 5923, "text": "int relativeCCW(Point2D p)" }, { "code": null, "e": 6042, "s": 5950, "text": "Returns an indicator of where the specified Point2D lies with respect to this line segment." }, { "code": null, "e": 6110, "s": 6042, "text": "abstract void setLine(double x1, double y1, double x2, double y2) " }, { "code": null, "e": 6198, "s": 6110, "text": "Sets the location of the end points of this Line2D to the specified double coordinates." }, { "code": null, "e": 6221, "s": 6198, "text": "void setLine(Line2D l)" }, { "code": null, "e": 6329, "s": 6221, "text": "Sets the location of the end points of this Line2D to the same as those end points of the specified Line2D." }, { "code": null, "e": 6366, "s": 6329, "text": "void setLine(Point2D p1, Point2D p2)" }, { "code": null, "e": 6455, "s": 6366, "text": "Sets the location of the end points of this Line2D to the specified Point2D coordinates." }, { "code": null, "e": 6511, "s": 6455, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 6528, "s": 6511, "text": "java.lang.Object" }, { "code": null, "e": 6545, "s": 6528, "text": "java.lang.Object" }, { "code": null, "e": 6659, "s": 6545, "text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >" }, { "code": null, "e": 7672, "s": 6659, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport java.awt.geom.*;\n\npublic class AWTGraphicsDemo extends Frame {\n \n public AWTGraphicsDemo(){\n super(\"Java AWT Examples\");\n prepareGUI();\n }\n\n public static void main(String[] args){\n AWTGraphicsDemo awtGraphicsDemo = new AWTGraphicsDemo(); \n awtGraphicsDemo.setVisible(true);\n }\n\n private void prepareGUI(){\n setSize(400,400);\n addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n } \n\n @Override\n public void paint(Graphics g) {\n Line2D shape = new Line2D.Double();\n shape.setLine(250D,250D,150D,150D); \n Graphics2D g2 = (Graphics2D) g; \n g2.draw (shape);\n Font font = new Font(\"Serif\", Font.PLAIN, 24);\n g2.setFont(font);\n g.drawString(\"Welcome to TutorialsPoint\", 50, 70);\n g2.drawString(\"Line2D.Line\", 100, 120); \n }\n}" }, { "code": null, "e": 7763, "s": 7672, "text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command." }, { "code": null, "e": 7820, "s": 7763, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AWTGraphicsDemo.java" }, { "code": null, "e": 7917, "s": 7820, "text": "If no error comes that means compilation is successful. Run the program using following command." }, { "code": null, "e": 7968, "s": 7917, "text": "D:\\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo" }, { "code": null, "e": 7996, "s": 7968, "text": "Verify the following output" }, { "code": null, "e": 8029, "s": 7996, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 8037, "s": 8029, "text": " EduOLC" }, { "code": null, "e": 8044, "s": 8037, "text": " Print" }, { "code": null, "e": 8055, "s": 8044, "text": " Add Notes" } ]
Extracting locations from text using Python - GeeksforGeeks
30 Jun, 2021 In this article, we are going to see how to extract location from text using Python. While working with texts, the requirement can be the detection of cities, regions, states, and countries and relationships between them in the received text. This can be very useful for geographical studies. In this article, we will use the locationtagger library. Text mining that requires some grammar-based rules and statistical modelling approaches is usually carried using NER (Named Enitity Recognition) Algorithms. An entity extracted from NER can be the name of a person, place, organization, or product. The locationtagger library is a byproduct of further tagging and filtering places from all the other entities present. To install this module type the below command in the terminal. pip install locationtagger After the installation, a few nltk modules are required to download using code. Python3 import nltkimport spacy # essential entity models downloadsnltk.downloader.download('maxent_ne_chunker')nltk.downloader.download('words')nltk.downloader.download('treebank')nltk.downloader.download('maxent_treebank_pos_tagger')nltk.downloader.download('punkt')nltk.download('averaged_perceptron_tagger') Also from the command line: python -m spacy download en_core_web_sm Example 1: Printing countries, cities and regions from Text. Various functions can be used to get cities, countries, regions etc from the text. Functions Used: locationtagger.find_location(text) : Return the entity with location information. The “text” parameter takes text as input. entity.countries : Extracts all the countries in text. entity.regions : Extracts all the states in text. entity.cities : Extracts all the cities in text. Code: Python3 import locationtagger # initializing sample textsample_text = "India has very rich and vivid culture\ widely spread from Kerala to Nagaland to Haryana to Maharashtra. " \ "Delhi being capital with Mumbai financial capital.\ Can be said better than some western cities such as " \ " Munich, London etc. Pakistan and Bangladesh share its borders" # extracting entities.place_entity = locationtagger.find_locations(text = sample_text) # getting all countriesprint("The countries in text : ")print(place_entity.countries) # getting all statesprint("The states in text : ")print(place_entity.regions) # getting all citiesprint("The cities in text : ")print(place_entity.cities) Output : Example 2: Extracting Relations of locations In this example, various functions are discussed which perform the task of getting relations of cities, regions, and states with each other. Functions Used: entity.country_regions : Extracts the country where regions are found in text. entity.country_cities : Extracts the country where cities are found in text. entity.other_countries : Extracts all countries list whose regions or cities are present in text. entity.region_cities : Extracts the regions with whose cities are found in text. entity.other_regions : Extracts all regions list whose cities are present in text. entity.other : All entities not recognized as place names, are extracted to this. Python3 import locationtagger # initializing sample textsample_text = "India has very rich and vivid culture widely\ spread from Kerala to Nagaland to Haryana to Maharashtra. " \ "Mumbai being financial capital can be said better\ than some western cities such as " \ " Lahore, Canberra etc. Pakistan and Nepal share its borders" # extracting entities.place_entity = locationtagger.find_locations(text = sample_text) # getting all country regionsprint("The countries regions in text : ")print(place_entity.country_regions) # getting all country citiesprint("The countries cities in text : ")print(place_entity.country_cities) # getting all other countriesprint("All other countries in text : ")print(place_entity.other_countries) # getting all region citiesprint("The region cities in text : ")print(place_entity.region_cities) # getting all other regionsprint("All other regions in text : ")print(place_entity.other_regions) # getting all other entitiesprint("All other entities in text : ")print(place_entity.other) Output: Python Framework Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Python | Get unique values from a list Python | Pandas dataframe.groupby() Defaultdict in Python
[ { "code": null, "e": 25555, "s": 25527, "text": "\n30 Jun, 2021" }, { "code": null, "e": 25640, "s": 25555, "text": "In this article, we are going to see how to extract location from text using Python." }, { "code": null, "e": 25905, "s": 25640, "text": "While working with texts, the requirement can be the detection of cities, regions, states, and countries and relationships between them in the received text. This can be very useful for geographical studies. In this article, we will use the locationtagger library." }, { "code": null, "e": 26272, "s": 25905, "text": "Text mining that requires some grammar-based rules and statistical modelling approaches is usually carried using NER (Named Enitity Recognition) Algorithms. An entity extracted from NER can be the name of a person, place, organization, or product. The locationtagger library is a byproduct of further tagging and filtering places from all the other entities present." }, { "code": null, "e": 26335, "s": 26272, "text": "To install this module type the below command in the terminal." }, { "code": null, "e": 26362, "s": 26335, "text": "pip install locationtagger" }, { "code": null, "e": 26442, "s": 26362, "text": "After the installation, a few nltk modules are required to download using code." }, { "code": null, "e": 26450, "s": 26442, "text": "Python3" }, { "code": "import nltkimport spacy # essential entity models downloadsnltk.downloader.download('maxent_ne_chunker')nltk.downloader.download('words')nltk.downloader.download('treebank')nltk.downloader.download('maxent_treebank_pos_tagger')nltk.downloader.download('punkt')nltk.download('averaged_perceptron_tagger')", "e": 26755, "s": 26450, "text": null }, { "code": null, "e": 26783, "s": 26755, "text": "Also from the command line:" }, { "code": null, "e": 26823, "s": 26783, "text": "python -m spacy download en_core_web_sm" }, { "code": null, "e": 26884, "s": 26823, "text": "Example 1: Printing countries, cities and regions from Text." }, { "code": null, "e": 26968, "s": 26884, "text": "Various functions can be used to get cities, countries, regions etc from the text. " }, { "code": null, "e": 26984, "s": 26968, "text": "Functions Used:" }, { "code": null, "e": 27108, "s": 26984, "text": "locationtagger.find_location(text) : Return the entity with location information. The “text” parameter takes text as input." }, { "code": null, "e": 27163, "s": 27108, "text": "entity.countries : Extracts all the countries in text." }, { "code": null, "e": 27213, "s": 27163, "text": "entity.regions : Extracts all the states in text." }, { "code": null, "e": 27262, "s": 27213, "text": "entity.cities : Extracts all the cities in text." }, { "code": null, "e": 27269, "s": 27262, "text": "Code: " }, { "code": null, "e": 27277, "s": 27269, "text": "Python3" }, { "code": "import locationtagger # initializing sample textsample_text = \"India has very rich and vivid culture\\ widely spread from Kerala to Nagaland to Haryana to Maharashtra. \" \\ \"Delhi being capital with Mumbai financial capital.\\ Can be said better than some western cities such as \" \\ \" Munich, London etc. Pakistan and Bangladesh share its borders\" # extracting entities.place_entity = locationtagger.find_locations(text = sample_text) # getting all countriesprint(\"The countries in text : \")print(place_entity.countries) # getting all statesprint(\"The states in text : \")print(place_entity.regions) # getting all citiesprint(\"The cities in text : \")print(place_entity.cities)", "e": 27979, "s": 27277, "text": null }, { "code": null, "e": 27989, "s": 27979, "text": "Output : " }, { "code": null, "e": 28034, "s": 27989, "text": "Example 2: Extracting Relations of locations" }, { "code": null, "e": 28176, "s": 28034, "text": "In this example, various functions are discussed which perform the task of getting relations of cities, regions, and states with each other. " }, { "code": null, "e": 28192, "s": 28176, "text": "Functions Used:" }, { "code": null, "e": 28271, "s": 28192, "text": "entity.country_regions : Extracts the country where regions are found in text." }, { "code": null, "e": 28348, "s": 28271, "text": "entity.country_cities : Extracts the country where cities are found in text." }, { "code": null, "e": 28446, "s": 28348, "text": "entity.other_countries : Extracts all countries list whose regions or cities are present in text." }, { "code": null, "e": 28527, "s": 28446, "text": "entity.region_cities : Extracts the regions with whose cities are found in text." }, { "code": null, "e": 28610, "s": 28527, "text": "entity.other_regions : Extracts all regions list whose cities are present in text." }, { "code": null, "e": 28692, "s": 28610, "text": "entity.other : All entities not recognized as place names, are extracted to this." }, { "code": null, "e": 28700, "s": 28692, "text": "Python3" }, { "code": "import locationtagger # initializing sample textsample_text = \"India has very rich and vivid culture widely\\ spread from Kerala to Nagaland to Haryana to Maharashtra. \" \\ \"Mumbai being financial capital can be said better\\ than some western cities such as \" \\ \" Lahore, Canberra etc. Pakistan and Nepal share its borders\" # extracting entities.place_entity = locationtagger.find_locations(text = sample_text) # getting all country regionsprint(\"The countries regions in text : \")print(place_entity.country_regions) # getting all country citiesprint(\"The countries cities in text : \")print(place_entity.country_cities) # getting all other countriesprint(\"All other countries in text : \")print(place_entity.other_countries) # getting all region citiesprint(\"The region cities in text : \")print(place_entity.region_cities) # getting all other regionsprint(\"All other regions in text : \")print(place_entity.other_regions) # getting all other entitiesprint(\"All other entities in text : \")print(place_entity.other)", "e": 29743, "s": 28700, "text": null }, { "code": null, "e": 29752, "s": 29743, "text": "Output: " }, { "code": null, "e": 29769, "s": 29752, "text": "Python Framework" }, { "code": null, "e": 29776, "s": 29769, "text": "Python" }, { "code": null, "e": 29874, "s": 29776, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29906, "s": 29874, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29948, "s": 29906, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29990, "s": 29948, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30046, "s": 29990, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30073, "s": 30046, "text": "Python Classes and Objects" }, { "code": null, "e": 30104, "s": 30073, "text": "Python | os.path.join() method" }, { "code": null, "e": 30133, "s": 30104, "text": "Create a directory in Python" }, { "code": null, "e": 30172, "s": 30133, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30208, "s": 30172, "text": "Python | Pandas dataframe.groupby()" } ]
How to print without newline in Python?
09 Aug, 2021 Generally, people switching from C/C++ to Python wonder how to print two or more variables or statements without going into a new line in python. Since the python print() function by default ends with a newline. Python has a predefined format if you use print(a_variable) then it will go to the next line automatically. For example: Python3 print("geeks")print("geeksforgeeks") Will result in this: geeks geeksforgeeks But sometimes it may happen that we don’t want to go to the next line but want to print on the same line. So what we can do? For Example: Input : print("geeks") print("geeksforgeeks") Output : geeks geeksforgeeks Input : a = [1, 2, 3, 4] Output : 1 2 3 4 The solution discussed here is totally dependent on the python version you are using. python # Python 2 code for printing# on the same line printing# geeks and geeksforgeeks# in the same line print("geeks"),print("geeksforgeeks") # arraya = [1, 2, 3, 4] # printing a element in same# linefor i in range(4): print(a[i]), Output: geeks geeksforgeeks 1 2 3 4 python3 # Python 3 code for printing# on the same line printing# geeks and geeksforgeeks# in the same line print("geeks", end =" ")print("geeksforgeeks") # arraya = [1, 2, 3, 4] # printing a element in same# linefor i in range(4): print(a[i], end =" ") Output: geeks geeksforgeeks 1 2 3 4 Python3 # Print without newline in Python 3.x without using for loop l=[1,2,3,4,5,6] # using * symbol prints the list# elements in a single lineprint(*l) #This code is contributed by anuragsingh1022 Output: 1 2 3 4 5 6 anuragsingh1022 python-basics Python Python Programs School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Python program to convert a list to string Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 53, "s": 25, "text": "\n09 Aug, 2021" }, { "code": null, "e": 375, "s": 53, "text": "Generally, people switching from C/C++ to Python wonder how to print two or more variables or statements without going into a new line in python. Since the python print() function by default ends with a newline. Python has a predefined format if you use print(a_variable) then it will go to the next line automatically. " }, { "code": null, "e": 389, "s": 375, "text": "For example: " }, { "code": null, "e": 397, "s": 389, "text": "Python3" }, { "code": "print(\"geeks\")print(\"geeksforgeeks\")", "e": 434, "s": 397, "text": null }, { "code": null, "e": 456, "s": 434, "text": "Will result in this: " }, { "code": null, "e": 476, "s": 456, "text": "geeks\ngeeksforgeeks" }, { "code": null, "e": 603, "s": 476, "text": "But sometimes it may happen that we don’t want to go to the next line but want to print on the same line. So what we can do? " }, { "code": null, "e": 617, "s": 603, "text": "For Example: " }, { "code": null, "e": 736, "s": 617, "text": "Input : print(\"geeks\") print(\"geeksforgeeks\")\nOutput : geeks geeksforgeeks\n\nInput : a = [1, 2, 3, 4]\nOutput : 1 2 3 4 " }, { "code": null, "e": 824, "s": 736, "text": "The solution discussed here is totally dependent on the python version you are using. " }, { "code": null, "e": 831, "s": 824, "text": "python" }, { "code": "# Python 2 code for printing# on the same line printing# geeks and geeksforgeeks# in the same line print(\"geeks\"),print(\"geeksforgeeks\") # arraya = [1, 2, 3, 4] # printing a element in same# linefor i in range(4): print(a[i]),", "e": 1061, "s": 831, "text": null }, { "code": null, "e": 1070, "s": 1061, "text": "Output: " }, { "code": null, "e": 1098, "s": 1070, "text": "geeks geeksforgeeks\n1 2 3 4" }, { "code": null, "e": 1106, "s": 1098, "text": "python3" }, { "code": "# Python 3 code for printing# on the same line printing# geeks and geeksforgeeks# in the same line print(\"geeks\", end =\" \")print(\"geeksforgeeks\") # arraya = [1, 2, 3, 4] # printing a element in same# linefor i in range(4): print(a[i], end =\" \")", "e": 1354, "s": 1106, "text": null }, { "code": null, "e": 1363, "s": 1354, "text": "Output: " }, { "code": null, "e": 1391, "s": 1363, "text": "geeks geeksforgeeks\n1 2 3 4" }, { "code": null, "e": 1399, "s": 1391, "text": "Python3" }, { "code": "# Print without newline in Python 3.x without using for loop l=[1,2,3,4,5,6] # using * symbol prints the list# elements in a single lineprint(*l) #This code is contributed by anuragsingh1022", "e": 1590, "s": 1399, "text": null }, { "code": null, "e": 1598, "s": 1590, "text": "Output:" }, { "code": null, "e": 1610, "s": 1598, "text": "1 2 3 4 5 6" }, { "code": null, "e": 1626, "s": 1610, "text": "anuragsingh1022" }, { "code": null, "e": 1640, "s": 1626, "text": "python-basics" }, { "code": null, "e": 1647, "s": 1640, "text": "Python" }, { "code": null, "e": 1663, "s": 1647, "text": "Python Programs" }, { "code": null, "e": 1682, "s": 1663, "text": "School Programming" }, { "code": null, "e": 1780, "s": 1682, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1808, "s": 1780, "text": "Read JSON file using Python" }, { "code": null, "e": 1858, "s": 1808, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 1880, "s": 1858, "text": "Python map() function" }, { "code": null, "e": 1924, "s": 1880, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 1966, "s": 1924, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2009, "s": 1966, "text": "Python program to convert a list to string" }, { "code": null, "e": 2048, "s": 2009, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2086, "s": 2048, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2135, "s": 2086, "text": "Python | Convert string dictionary to dictionary" } ]
Proof that Dominant Set of a Graph is NP-Complete
04 Jun, 2020 Pre-requisite: Dominant Set of a Graph, NP-Complete A dominating set in a graph G = (V, E) is a subset of vertices V’ following the condition that the vertices not belonging in V’ are adjacent to some vertex in V’. Problem: Given a graph G(V, E) and an integer k, the problem is to determine if the graph has a Dominating Set of size k.Explanation:An instance of the problem is an input specified to the problem. An instance of the Dominating Set problem is a graph G (V, E) and an integer k, and the problem is to check whether the graph can have a dominating set in G. Since an NP-Complete problem, by definition, is a problem which is both in NP and NP-hard, the proof for the statement that a problem is NP-Complete consists of two parts: Dominating Set is NP CompleteIf any problem is in NP, then, given a ‘certificate’, which is a solution to the problem and an instance of the problem (a graph G and a positive integer k, in this case), we will be able to verify (check whether the solution given is correct or not) the certificate in polynomial time.The certificate is a sequence of vertices forming a Dominating Set in the graph. We can validate this solution by checking that all the vertices belong to the vertices of the graph and all the vertices that are not a part of this sequence are adjacent to some of the vertex in this set. This can be done in polynomial time, that is O(V +E) using the following strategy :flag=true for every vertex v in V: if v doesn't belong to Dominating Set: verify the set of edges corresponding to v if v is not adjacent to any of the vertices in DS, set flag=False and break if (flag) solution is correct else solution is incorrect Dominating Set is NP-HardIn order to prove that the Dominating Set is NP-Hard, we will have to reduce a known NP-Hard problem to this problem. We will carry out a reduction from the Vertex Cover problem to the Dominating Set problem.Every instance of the Vertex Cover problem consists of a graph G = (V, E) and an integer k consisting of the subset of vertices as the input can be converted to a Dominating Set problem consisting of graph G’ = (V’, E’). We will construct the graph G’ in the following way:E’ = For every edge E consisting of vertices {u, v} in the graph G, add a new vertex {uv} and individually join it to the new vertices u and v.V’ = Add all the vertices V of the original graph G.The new graph G’ can be obtained in polynomial time, by adding new edges corresponding to the new vertex, that requires O(V+E) time. This reduction can be proved by the following two claims:Let us assume that the graph G has a vertex cover VC of size k. Every edge in G has one of the vertices belonging to the vertex cover. Therefore, for every edge e, consisting of vertices {u, v} at least either u or v is a part of the vertex cover. So, if u is contained in VC, then the adjacent vertex is v, is also covered by some of the elements in VC. Now, for all the newly added vertices UV for each edge, the vertex is adjacent to both u and v, one of which is at least a part of the VC, as proved above. Therefore, the additional vertices for all the edges are also covered by this VC. The set of vertices forming the Vertex Cover of size k form Dominating Set in graph G’. Therefore, if G has a vertex cover G’ has a dominating set of the same size.We assume that the graph G’ has a Dominating Set of size k. Two possibilities may arise, either the vertex in the DS is an original vertex or it belongs to the newly added vertex UV for each edge {u, v}. In the second case, since every new vertex is connected to the two vertices of the edge, u and v, therefore, it can be replaced by either u or v. Since, these three vertices form a triangle, therefore, even by substituting view with either u or v, we can continue to span all the vertices that were spanned before replacing. This will lead to the elimination of all the newly added vertices while spanning all the edges of the graph G’. The newly added vertices are dominated by the modified DS and cover all the edges in G with at least either u or v for each edge UV. Therefore, if G’ has a Dominating Set of size k, G will have a vertex cover with size utmost k . Dominating Set is NP CompleteIf any problem is in NP, then, given a ‘certificate’, which is a solution to the problem and an instance of the problem (a graph G and a positive integer k, in this case), we will be able to verify (check whether the solution given is correct or not) the certificate in polynomial time.The certificate is a sequence of vertices forming a Dominating Set in the graph. We can validate this solution by checking that all the vertices belong to the vertices of the graph and all the vertices that are not a part of this sequence are adjacent to some of the vertex in this set. This can be done in polynomial time, that is O(V +E) using the following strategy :flag=true for every vertex v in V: if v doesn't belong to Dominating Set: verify the set of edges corresponding to v if v is not adjacent to any of the vertices in DS, set flag=False and break if (flag) solution is correct else solution is incorrect flag=true for every vertex v in V: if v doesn't belong to Dominating Set: verify the set of edges corresponding to v if v is not adjacent to any of the vertices in DS, set flag=False and break if (flag) solution is correct else solution is incorrect Dominating Set is NP-HardIn order to prove that the Dominating Set is NP-Hard, we will have to reduce a known NP-Hard problem to this problem. We will carry out a reduction from the Vertex Cover problem to the Dominating Set problem.Every instance of the Vertex Cover problem consists of a graph G = (V, E) and an integer k consisting of the subset of vertices as the input can be converted to a Dominating Set problem consisting of graph G’ = (V’, E’). We will construct the graph G’ in the following way:E’ = For every edge E consisting of vertices {u, v} in the graph G, add a new vertex {uv} and individually join it to the new vertices u and v.V’ = Add all the vertices V of the original graph G.The new graph G’ can be obtained in polynomial time, by adding new edges corresponding to the new vertex, that requires O(V+E) time. This reduction can be proved by the following two claims:Let us assume that the graph G has a vertex cover VC of size k. Every edge in G has one of the vertices belonging to the vertex cover. Therefore, for every edge e, consisting of vertices {u, v} at least either u or v is a part of the vertex cover. So, if u is contained in VC, then the adjacent vertex is v, is also covered by some of the elements in VC. Now, for all the newly added vertices UV for each edge, the vertex is adjacent to both u and v, one of which is at least a part of the VC, as proved above. Therefore, the additional vertices for all the edges are also covered by this VC. The set of vertices forming the Vertex Cover of size k form Dominating Set in graph G’. Therefore, if G has a vertex cover G’ has a dominating set of the same size.We assume that the graph G’ has a Dominating Set of size k. Two possibilities may arise, either the vertex in the DS is an original vertex or it belongs to the newly added vertex UV for each edge {u, v}. In the second case, since every new vertex is connected to the two vertices of the edge, u and v, therefore, it can be replaced by either u or v. Since, these three vertices form a triangle, therefore, even by substituting view with either u or v, we can continue to span all the vertices that were spanned before replacing. This will lead to the elimination of all the newly added vertices while spanning all the edges of the graph G’. The newly added vertices are dominated by the modified DS and cover all the edges in G with at least either u or v for each edge UV. Therefore, if G’ has a Dominating Set of size k, G will have a vertex cover with size utmost k . E’ = For every edge E consisting of vertices {u, v} in the graph G, add a new vertex {uv} and individually join it to the new vertices u and v. V’ = Add all the vertices V of the original graph G. The new graph G’ can be obtained in polynomial time, by adding new edges corresponding to the new vertex, that requires O(V+E) time. This reduction can be proved by the following two claims: Let us assume that the graph G has a vertex cover VC of size k. Every edge in G has one of the vertices belonging to the vertex cover. Therefore, for every edge e, consisting of vertices {u, v} at least either u or v is a part of the vertex cover. So, if u is contained in VC, then the adjacent vertex is v, is also covered by some of the elements in VC. Now, for all the newly added vertices UV for each edge, the vertex is adjacent to both u and v, one of which is at least a part of the VC, as proved above. Therefore, the additional vertices for all the edges are also covered by this VC. The set of vertices forming the Vertex Cover of size k form Dominating Set in graph G’. Therefore, if G has a vertex cover G’ has a dominating set of the same size. We assume that the graph G’ has a Dominating Set of size k. Two possibilities may arise, either the vertex in the DS is an original vertex or it belongs to the newly added vertex UV for each edge {u, v}. In the second case, since every new vertex is connected to the two vertices of the edge, u and v, therefore, it can be replaced by either u or v. Since, these three vertices form a triangle, therefore, even by substituting view with either u or v, we can continue to span all the vertices that were spanned before replacing. This will lead to the elimination of all the newly added vertices while spanning all the edges of the graph G’. The newly added vertices are dominated by the modified DS and cover all the edges in G with at least either u or v for each edge UV. Therefore, if G’ has a Dominating Set of size k, G will have a vertex cover with size utmost k . In the following figure, the vertex B dominates both AB and BE, therefore, it can be easily replaced. Therefore, these two vertices are redundant. Thus we can say that the graph G’ contains a dominating set iff graph G contains vertex cover. Therefore, any instance of the dominating set problem can be reduced to an instance of the vertex cover problem. Thus, the dominating set is also NP-Hard. Since vertex cover is in both NP and NP-Hard classes, the dominant Set of a Graph is NP-Complete. NP Complete NPHard Advanced Data Structure Analysis Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree) Ordered Set and GNU C++ PBDS 2-3 Trees | (Search, Insert and Deletion) Extendible Hashing (Dynamic approach to DBMS) Segment Tree | Set 2 (Range Minimum Query) Analysis of Algorithms | Set 1 (Asymptotic Analysis) Understanding Time Complexity with Simple Examples Practice Questions on Time Complexity Analysis Time Complexity and Space Complexity Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jun, 2020" }, { "code": null, "e": 106, "s": 54, "text": "Pre-requisite: Dominant Set of a Graph, NP-Complete" }, { "code": null, "e": 269, "s": 106, "text": "A dominating set in a graph G = (V, E) is a subset of vertices V’ following the condition that the vertices not belonging in V’ are adjacent to some vertex in V’." }, { "code": null, "e": 797, "s": 269, "text": "Problem: Given a graph G(V, E) and an integer k, the problem is to determine if the graph has a Dominating Set of size k.Explanation:An instance of the problem is an input specified to the problem. An instance of the Dominating Set problem is a graph G (V, E) and an integer k, and the problem is to check whether the graph can have a dominating set in G. Since an NP-Complete problem, by definition, is a problem which is both in NP and NP-hard, the proof for the statement that a problem is NP-Complete consists of two parts:" }, { "code": null, "e": 4294, "s": 797, "text": "Dominating Set is NP CompleteIf any problem is in NP, then, given a ‘certificate’, which is a solution to the problem and an instance of the problem (a graph G and a positive integer k, in this case), we will be able to verify (check whether the solution given is correct or not) the certificate in polynomial time.The certificate is a sequence of vertices forming a Dominating Set in the graph. We can validate this solution by checking that all the vertices belong to the vertices of the graph and all the vertices that are not a part of this sequence are adjacent to some of the vertex in this set. This can be done in polynomial time, that is O(V +E) using the following strategy :flag=true\nfor every vertex v in V:\n if v doesn't belong to Dominating Set:\n verify the set of edges \n corresponding to v \n if v is not adjacent \n to any of the vertices in DS, \n set flag=False and break\nif (flag)\n solution is correct\nelse\n solution is incorrect\nDominating Set is NP-HardIn order to prove that the Dominating Set is NP-Hard, we will have to reduce a known NP-Hard problem to this problem. We will carry out a reduction from the Vertex Cover problem to the Dominating Set problem.Every instance of the Vertex Cover problem consists of a graph G = (V, E) and an integer k consisting of the subset of vertices as the input can be converted to a Dominating Set problem consisting of graph G’ = (V’, E’). We will construct the graph G’ in the following way:E’ = For every edge E consisting of vertices {u, v} in the graph G, add a new vertex {uv} and individually join it to the new vertices u and v.V’ = Add all the vertices V of the original graph G.The new graph G’ can be obtained in polynomial time, by adding new edges corresponding to the new vertex, that requires O(V+E) time. This reduction can be proved by the following two claims:Let us assume that the graph G has a vertex cover VC of size k. Every edge in G has one of the vertices belonging to the vertex cover. Therefore, for every edge e, consisting of vertices {u, v} at least either u or v is a part of the vertex cover. So, if u is contained in VC, then the adjacent vertex is v, is also covered by some of the elements in VC. Now, for all the newly added vertices UV for each edge, the vertex is adjacent to both u and v, one of which is at least a part of the VC, as proved above. Therefore, the additional vertices for all the edges are also covered by this VC. The set of vertices forming the Vertex Cover of size k form Dominating Set in graph G’. Therefore, if G has a vertex cover G’ has a dominating set of the same size.We assume that the graph G’ has a Dominating Set of size k. Two possibilities may arise, either the vertex in the DS is an original vertex or it belongs to the newly added vertex UV for each edge {u, v}. In the second case, since every new vertex is connected to the two vertices of the edge, u and v, therefore, it can be replaced by either u or v. Since, these three vertices form a triangle, therefore, even by substituting view with either u or v, we can continue to span all the vertices that were spanned before replacing. This will lead to the elimination of all the newly added vertices while spanning all the edges of the graph G’. The newly added vertices are dominated by the modified DS and cover all the edges in G with at least either u or v for each edge UV. Therefore, if G’ has a Dominating Set of size k, G will have a vertex cover with size utmost k ." }, { "code": null, "e": 5273, "s": 4294, "text": "Dominating Set is NP CompleteIf any problem is in NP, then, given a ‘certificate’, which is a solution to the problem and an instance of the problem (a graph G and a positive integer k, in this case), we will be able to verify (check whether the solution given is correct or not) the certificate in polynomial time.The certificate is a sequence of vertices forming a Dominating Set in the graph. We can validate this solution by checking that all the vertices belong to the vertices of the graph and all the vertices that are not a part of this sequence are adjacent to some of the vertex in this set. This can be done in polynomial time, that is O(V +E) using the following strategy :flag=true\nfor every vertex v in V:\n if v doesn't belong to Dominating Set:\n verify the set of edges \n corresponding to v \n if v is not adjacent \n to any of the vertices in DS, \n set flag=False and break\nif (flag)\n solution is correct\nelse\n solution is incorrect\n" }, { "code": null, "e": 5567, "s": 5273, "text": "flag=true\nfor every vertex v in V:\n if v doesn't belong to Dominating Set:\n verify the set of edges \n corresponding to v \n if v is not adjacent \n to any of the vertices in DS, \n set flag=False and break\nif (flag)\n solution is correct\nelse\n solution is incorrect\n" }, { "code": null, "e": 8086, "s": 5567, "text": "Dominating Set is NP-HardIn order to prove that the Dominating Set is NP-Hard, we will have to reduce a known NP-Hard problem to this problem. We will carry out a reduction from the Vertex Cover problem to the Dominating Set problem.Every instance of the Vertex Cover problem consists of a graph G = (V, E) and an integer k consisting of the subset of vertices as the input can be converted to a Dominating Set problem consisting of graph G’ = (V’, E’). We will construct the graph G’ in the following way:E’ = For every edge E consisting of vertices {u, v} in the graph G, add a new vertex {uv} and individually join it to the new vertices u and v.V’ = Add all the vertices V of the original graph G.The new graph G’ can be obtained in polynomial time, by adding new edges corresponding to the new vertex, that requires O(V+E) time. This reduction can be proved by the following two claims:Let us assume that the graph G has a vertex cover VC of size k. Every edge in G has one of the vertices belonging to the vertex cover. Therefore, for every edge e, consisting of vertices {u, v} at least either u or v is a part of the vertex cover. So, if u is contained in VC, then the adjacent vertex is v, is also covered by some of the elements in VC. Now, for all the newly added vertices UV for each edge, the vertex is adjacent to both u and v, one of which is at least a part of the VC, as proved above. Therefore, the additional vertices for all the edges are also covered by this VC. The set of vertices forming the Vertex Cover of size k form Dominating Set in graph G’. Therefore, if G has a vertex cover G’ has a dominating set of the same size.We assume that the graph G’ has a Dominating Set of size k. Two possibilities may arise, either the vertex in the DS is an original vertex or it belongs to the newly added vertex UV for each edge {u, v}. In the second case, since every new vertex is connected to the two vertices of the edge, u and v, therefore, it can be replaced by either u or v. Since, these three vertices form a triangle, therefore, even by substituting view with either u or v, we can continue to span all the vertices that were spanned before replacing. This will lead to the elimination of all the newly added vertices while spanning all the edges of the graph G’. The newly added vertices are dominated by the modified DS and cover all the edges in G with at least either u or v for each edge UV. Therefore, if G’ has a Dominating Set of size k, G will have a vertex cover with size utmost k ." }, { "code": null, "e": 8230, "s": 8086, "text": "E’ = For every edge E consisting of vertices {u, v} in the graph G, add a new vertex {uv} and individually join it to the new vertices u and v." }, { "code": null, "e": 8283, "s": 8230, "text": "V’ = Add all the vertices V of the original graph G." }, { "code": null, "e": 8474, "s": 8283, "text": "The new graph G’ can be obtained in polynomial time, by adding new edges corresponding to the new vertex, that requires O(V+E) time. This reduction can be proved by the following two claims:" }, { "code": null, "e": 9232, "s": 8474, "text": "Let us assume that the graph G has a vertex cover VC of size k. Every edge in G has one of the vertices belonging to the vertex cover. Therefore, for every edge e, consisting of vertices {u, v} at least either u or v is a part of the vertex cover. So, if u is contained in VC, then the adjacent vertex is v, is also covered by some of the elements in VC. Now, for all the newly added vertices UV for each edge, the vertex is adjacent to both u and v, one of which is at least a part of the VC, as proved above. Therefore, the additional vertices for all the edges are also covered by this VC. The set of vertices forming the Vertex Cover of size k form Dominating Set in graph G’. Therefore, if G has a vertex cover G’ has a dominating set of the same size." }, { "code": null, "e": 10103, "s": 9232, "text": "We assume that the graph G’ has a Dominating Set of size k. Two possibilities may arise, either the vertex in the DS is an original vertex or it belongs to the newly added vertex UV for each edge {u, v}. In the second case, since every new vertex is connected to the two vertices of the edge, u and v, therefore, it can be replaced by either u or v. Since, these three vertices form a triangle, therefore, even by substituting view with either u or v, we can continue to span all the vertices that were spanned before replacing. This will lead to the elimination of all the newly added vertices while spanning all the edges of the graph G’. The newly added vertices are dominated by the modified DS and cover all the edges in G with at least either u or v for each edge UV. Therefore, if G’ has a Dominating Set of size k, G will have a vertex cover with size utmost k ." }, { "code": null, "e": 10250, "s": 10103, "text": "In the following figure, the vertex B dominates both AB and BE, therefore, it can be easily replaced. Therefore, these two vertices are redundant." }, { "code": null, "e": 10598, "s": 10250, "text": "Thus we can say that the graph G’ contains a dominating set iff graph G contains vertex cover. Therefore, any instance of the dominating set problem can be reduced to an instance of the vertex cover problem. Thus, the dominating set is also NP-Hard. Since vertex cover is in both NP and NP-Hard classes, the dominant Set of a Graph is NP-Complete." }, { "code": null, "e": 10610, "s": 10598, "text": "NP Complete" }, { "code": null, "e": 10617, "s": 10610, "text": "NPHard" }, { "code": null, "e": 10641, "s": 10617, "text": "Advanced Data Structure" }, { "code": null, "e": 10650, "s": 10641, "text": "Analysis" }, { "code": null, "e": 10656, "s": 10650, "text": "Graph" }, { "code": null, "e": 10662, "s": 10656, "text": "Graph" }, { "code": null, "e": 10760, "s": 10662, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10840, "s": 10760, "text": "Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree)" }, { "code": null, "e": 10869, "s": 10840, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 10911, "s": 10869, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 10957, "s": 10911, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 11000, "s": 10957, "text": "Segment Tree | Set 2 (Range Minimum Query)" }, { "code": null, "e": 11053, "s": 11000, "text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)" }, { "code": null, "e": 11104, "s": 11053, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 11151, "s": 11104, "text": "Practice Questions on Time Complexity Analysis" }, { "code": null, "e": 11188, "s": 11151, "text": "Time Complexity and Space Complexity" } ]
Replace duplicates with greater than previous duplicate value
25 May, 2021 Given an array of elements and change the array in such a way that all the elements on the array are distinct. If you are replacing a value, then the replacing value should be greater than the previous value and, after modification, the sum of the elements should be as small as possible. Examples: Input : arr = {1, 2, 2, 5, 8, 8, 8} Output : 1 2 3 5 8 9 10 8 is replaced with 9 (A non-existing element greater than 8). Next, duplicate occurrence of 8 is replaced with 10. Input : arr = {1, 2, 5, 7, 8, 8, 7} Output : 1 2 5 7 8 9 10 Input : arr = {9, 9, 9, 9, 9} Output : 9 10 11 12 13 Source: Paytm Interview Experience 30. This problem is a variation of this article. In the above article, we had to replace the duplicates with the greatest value so far. But in this problem, we have to replace elements with duplicates greater than the previous duplicate value. The idea is to find the next greater element to be replaced to minimize the total sum. To find the next greater element, we have to iterate from the repeated element till the INT_MAX until the next greater element is found. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // CPP program to replace every repeating// element with next greater element.#include <bits/stdc++.h>using namespace std; void replaceElements(int arr[], int n){ unordered_set<int> s; for (int i = 0; i < n; i++) { // check whether the element is // repeated or not if (s.find(arr[i]) == s.end()) s.insert(arr[i]); else { // find the next greatest element for (int j = arr[i] + 1; j < INT_MAX; j++) { if (s.find(j) == s.end()) { arr[i] = j; s.insert(j); break; } } } }} int main(){ int arr[] = { 1, 2, 5, 7, 8, 8, 7 }; int n = sizeof(arr) / sizeof(arr[0]); replaceElements(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << "\n";} // Java program to replace every repeating// element with next greater element.import java.util.HashSet;import java.util.Set; public class ReplaceDuplicateWithGreaterThanPreviousDuplicate { private static void replaceElements(int[] arr, int n) { Set<Integer> st = new HashSet<>(); for (int i = 0; i < n; i++) { // check whether the element is // repeated or not if (!st.contains(arr[i])) { st.add(arr[i]); } else { // find the next greatest element for (int j = arr[i] + 1; j < Integer.MAX_VALUE; j++) { if (!st.contains(j)) { arr[i] = j; st.add(j); break; } } } } } public static void main(String[] args) { int[] arr = new int[] { 1, 2, 5, 7, 8, 8, 7 }; int n = arr.length; replaceElements(arr, n); for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } }} # Python3 program to replace every repeating# element with next greater element.import sys def replaceElements(arr, n): s = [] for i in range (n): # check whether the element # is repeated or not if arr[i] not in s: s.append(arr[i]) else : # find the next greatest element for j in range(arr[i] + 1, sys.maxsize) : if j not in s: arr[i] = j s.append(j) break # Driver Codeif __name__ == "__main__": arr = [ 1, 2, 5, 7, 8, 8, 7 ] n = len(arr) replaceElements(arr, n) for i in range(n): print (arr[i], end = " ") print () # This code is contributed# by ChitraNayal // C# program to replace every repeating// element with next greater element.using System;using System.Collections.Generic; public class ReplaceDuplicateWithGreaterThanPreviousDuplicate{ private static void replaceElements(int[] arr, int n) { HashSet<int> st = new HashSet<int>(); for (int i = 0; i < n; i++) { // check whether the element is // repeated or not if (!st.Contains(arr[i])) { st.Add(arr[i]); } else { // find the next greatest element for (int j = arr[i] + 1; j < int.MaxValue; j++) { if (!st.Contains(j)) { arr[i] = j; st.Add(j); break; } } } } } // Driver Code public static void Main(String[] args) { int[] arr = new int[] { 1, 2, 5, 7, 8, 8, 7 }; int n = arr.Length; replaceElements(arr, n); for (int i = 0; i < n; i++) { Console.Write(arr[i] + " "); } }} // This code is contributed by PrinciRaj1992 <script>// Javascript program to replace every repeating// element with next greater element. function replaceElements(arr,n) { let st = new Set(); for (let i = 0; i < n; i++) { // check whether the element is // repeated or not if (!st.has(arr[i])) { st.add(arr[i]); } else { // find the next greatest element for (let j = arr[i] + 1; j < Number.MAX_VALUE; j++) { if (!st.has(j)) { arr[i] = j; st.add(j); break; } } } } } let arr=[1, 2, 5, 7, 8, 8, 7]; let n = arr.length; replaceElements(arr, n); for (let i = 0; i < n; i++) { document.write(arr[i] + " "); } // This code is contributed by avanitrachhadiya2155</script> 1 2 5 7 8 9 10 ukasp indolia143 princiraj1992 avanitrachhadiya2155 cpp-unordered_set Paytm Technical Scripter 2018 Arrays Hash Paytm Arrays Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in Java Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Subset Sum Problem | DP-25 Python | Using 2D arrays/lists the right way What is Hashing | A Complete Tutorial Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Count pairs with given sum Longest Consecutive Subsequence
[ { "code": null, "e": 54, "s": 26, "text": "\n25 May, 2021" }, { "code": null, "e": 343, "s": 54, "text": "Given an array of elements and change the array in such a way that all the elements on the array are distinct. If you are replacing a value, then the replacing value should be greater than the previous value and, after modification, the sum of the elements should be as small as possible." }, { "code": null, "e": 354, "s": 343, "text": "Examples: " }, { "code": null, "e": 529, "s": 354, "text": "Input : arr = {1, 2, 2, 5, 8, 8, 8} Output : 1 2 3 5 8 9 10 8 is replaced with 9 (A non-existing element greater than 8). Next, duplicate occurrence of 8 is replaced with 10." }, { "code": null, "e": 589, "s": 529, "text": "Input : arr = {1, 2, 5, 7, 8, 8, 7} Output : 1 2 5 7 8 9 10" }, { "code": null, "e": 643, "s": 589, "text": "Input : arr = {9, 9, 9, 9, 9} Output : 9 10 11 12 13 " }, { "code": null, "e": 682, "s": 643, "text": "Source: Paytm Interview Experience 30." }, { "code": null, "e": 1146, "s": 682, "text": "This problem is a variation of this article. In the above article, we had to replace the duplicates with the greatest value so far. But in this problem, we have to replace elements with duplicates greater than the previous duplicate value. The idea is to find the next greater element to be replaced to minimize the total sum. To find the next greater element, we have to iterate from the repeated element till the INT_MAX until the next greater element is found." }, { "code": null, "e": 1199, "s": 1146, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 1203, "s": 1199, "text": "C++" }, { "code": null, "e": 1208, "s": 1203, "text": "Java" }, { "code": null, "e": 1216, "s": 1208, "text": "Python3" }, { "code": null, "e": 1219, "s": 1216, "text": "C#" }, { "code": null, "e": 1230, "s": 1219, "text": "Javascript" }, { "code": "// CPP program to replace every repeating// element with next greater element.#include <bits/stdc++.h>using namespace std; void replaceElements(int arr[], int n){ unordered_set<int> s; for (int i = 0; i < n; i++) { // check whether the element is // repeated or not if (s.find(arr[i]) == s.end()) s.insert(arr[i]); else { // find the next greatest element for (int j = arr[i] + 1; j < INT_MAX; j++) { if (s.find(j) == s.end()) { arr[i] = j; s.insert(j); break; } } } }} int main(){ int arr[] = { 1, 2, 5, 7, 8, 8, 7 }; int n = sizeof(arr) / sizeof(arr[0]); replaceElements(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << \" \"; cout << \"\\n\";}", "e": 2081, "s": 1230, "text": null }, { "code": "// Java program to replace every repeating// element with next greater element.import java.util.HashSet;import java.util.Set; public class ReplaceDuplicateWithGreaterThanPreviousDuplicate { private static void replaceElements(int[] arr, int n) { Set<Integer> st = new HashSet<>(); for (int i = 0; i < n; i++) { // check whether the element is // repeated or not if (!st.contains(arr[i])) { st.add(arr[i]); } else { // find the next greatest element for (int j = arr[i] + 1; j < Integer.MAX_VALUE; j++) { if (!st.contains(j)) { arr[i] = j; st.add(j); break; } } } } } public static void main(String[] args) { int[] arr = new int[] { 1, 2, 5, 7, 8, 8, 7 }; int n = arr.length; replaceElements(arr, n); for (int i = 0; i < n; i++) { System.out.print(arr[i] + \" \"); } }}", "e": 3168, "s": 2081, "text": null }, { "code": "# Python3 program to replace every repeating# element with next greater element.import sys def replaceElements(arr, n): s = [] for i in range (n): # check whether the element # is repeated or not if arr[i] not in s: s.append(arr[i]) else : # find the next greatest element for j in range(arr[i] + 1, sys.maxsize) : if j not in s: arr[i] = j s.append(j) break # Driver Codeif __name__ == \"__main__\": arr = [ 1, 2, 5, 7, 8, 8, 7 ] n = len(arr) replaceElements(arr, n) for i in range(n): print (arr[i], end = \" \") print () # This code is contributed# by ChitraNayal", "e": 3900, "s": 3168, "text": null }, { "code": "// C# program to replace every repeating// element with next greater element.using System;using System.Collections.Generic; public class ReplaceDuplicateWithGreaterThanPreviousDuplicate{ private static void replaceElements(int[] arr, int n) { HashSet<int> st = new HashSet<int>(); for (int i = 0; i < n; i++) { // check whether the element is // repeated or not if (!st.Contains(arr[i])) { st.Add(arr[i]); } else { // find the next greatest element for (int j = arr[i] + 1; j < int.MaxValue; j++) { if (!st.Contains(j)) { arr[i] = j; st.Add(j); break; } } } } } // Driver Code public static void Main(String[] args) { int[] arr = new int[] { 1, 2, 5, 7, 8, 8, 7 }; int n = arr.Length; replaceElements(arr, n); for (int i = 0; i < n; i++) { Console.Write(arr[i] + \" \"); } }} // This code is contributed by PrinciRaj1992", "e": 5116, "s": 3900, "text": null }, { "code": "<script>// Javascript program to replace every repeating// element with next greater element. function replaceElements(arr,n) { let st = new Set(); for (let i = 0; i < n; i++) { // check whether the element is // repeated or not if (!st.has(arr[i])) { st.add(arr[i]); } else { // find the next greatest element for (let j = arr[i] + 1; j < Number.MAX_VALUE; j++) { if (!st.has(j)) { arr[i] = j; st.add(j); break; } } } } } let arr=[1, 2, 5, 7, 8, 8, 7]; let n = arr.length; replaceElements(arr, n); for (let i = 0; i < n; i++) { document.write(arr[i] + \" \"); } // This code is contributed by avanitrachhadiya2155</script>", "e": 6049, "s": 5116, "text": null }, { "code": null, "e": 6064, "s": 6049, "text": "1 2 5 7 8 9 10" }, { "code": null, "e": 6072, "s": 6066, "text": "ukasp" }, { "code": null, "e": 6083, "s": 6072, "text": "indolia143" }, { "code": null, "e": 6097, "s": 6083, "text": "princiraj1992" }, { "code": null, "e": 6118, "s": 6097, "text": "avanitrachhadiya2155" }, { "code": null, "e": 6136, "s": 6118, "text": "cpp-unordered_set" }, { "code": null, "e": 6142, "s": 6136, "text": "Paytm" }, { "code": null, "e": 6166, "s": 6142, "text": "Technical Scripter 2018" }, { "code": null, "e": 6173, "s": 6166, "text": "Arrays" }, { "code": null, "e": 6178, "s": 6173, "text": "Hash" }, { "code": null, "e": 6184, "s": 6178, "text": "Paytm" }, { "code": null, "e": 6191, "s": 6184, "text": "Arrays" }, { "code": null, "e": 6196, "s": 6191, "text": "Hash" }, { "code": null, "e": 6294, "s": 6196, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6326, "s": 6294, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 6349, "s": 6326, "text": "Introduction to Arrays" }, { "code": null, "e": 6405, "s": 6349, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 6432, "s": 6405, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 6477, "s": 6432, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 6515, "s": 6477, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 6551, "s": 6515, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 6582, "s": 6551, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 6609, "s": 6582, "text": "Count pairs with given sum" } ]
Routing in Angular JS using Angular UI Router
19 Feb, 2019 AngularJS is a front-end web application framework based on JavaScript and is maintained by Google. AngularJS interprets the attributes of HTML as directives to bind input/output components to a model represented by standard JavaScript variables. Pre-requisites: HTML CSS JavaScript AngularJS Angular-UI-Router is an AngularJS module used to create routes for AngularJS applications. Routes are an important part of Single-Page-Applications (SPAs) as well as regular applications and Angular-UI-Router provides easy creation and usage of routes in AngularJS. Angular-UI-Router has stateProvider method which is used to create routes/states in application. State Provider takes state name and state configurations as parameters. Syntax: $stateProvider .state('StateName', { url: 'Url pattern for this State', template: "Html content", controller: "Name of the Controller for this state" }); Instead of template, templateUrl can be used and given the path of the HTML file to render for the state.Example: $stateProvider .state('Home', { url: '/home', templateUrl: "home.html", controller: "HomeCtrl" }); Simple project to navigate between the routes to demonstrate the use of the Angular-UI-Router module.Pre-requisites: Node.js and npm To run and install http-server node module to host demo app. Steps to perform the operation:1. Create a directory structure as below: routingDemo --app.js --index.html --nav.html 2. Create nav.html file as below. This file consist of nav bar title and contents of it. 3. Create index.html file as below. All the required dependencies are included in this file along with nav.html file and definition of ui-view where content of different routes will be rendered. Explanation: All the dependencies are included via CDN in the head tag. nav.html file is included to the index.html page in the body tag The last division in body defines ui-view div where the content of different routes will be rendered. Note:If it does not work, replace the second and third script with below: <script src="angular.min.js"></script> <script src = " https://unpkg.com/@uirouter/angularjs@1.0.7/release/angular-ui-router.min.js"> </script> 4. Create app.js file as below. This is the application file with routes information and actions to be performed through controller. // declares application module with name "myApp"// inject ui.router dependencyvar app = angular.module('myApp', [ "ui.router" ]); // define route configurations inside app.config// injecting dependenciesapp.config(function($stateProvider, $locationProvider, $urlRouterProvider) { // creating routes or states $stateProvider .state('Home', { url : '/home', template : "<h1>Home Page</h1>", controller : "HomeCtrl" }) .state('Login', { url : '/login', template : "<h1>Login Page</h1>", controller : "LoginCtrl" }) .state('Signup', { url : '/signup', template : "<h1>Signup Page</h1>", controller : "SignupCtrl" }); // Redirect to home page if url does not // matches any of the three mentioned above $urlRouterProvider.otherwise("/home");}); // create empty controllers for the states as we are// not doing anything but just displaying messageapp.controller('MainCtrl', function() {});app.controller('HomeCtrl', function() {});app.controller('LoginCtrl', function() {});app.controller('SignupCtrl', function() {}); 5. To run the above demo app in the browser, install http-server node module. To install the http-server module use the following command: npm install http-server -g 6. After Installing:–From routingDemo folder, run following command: http-server Above command will host the demo app on port 8080. app can be accessed using below link: localhost:8080/ 7. If this application is accessed via browser, Output will be as below: 8. After clicking on Login tab in the nav bar, Output will be as below: 9. Clicking on Sign up tab in the nav bar, Output will be as below: Three routes namely Home, Login and Sign up are created in this sample application. Applications: Routes are important for Single Page applications as they provide different functionalities to the application on the same page. Routes creation and manipulation is easy with the angular-ui-router module. References: https://github.com/angular-ui/ui-router/wiki/quick-reference https://ui-router.github.io/ng1/docs/1.0.0-beta.1/classes/state.stateprovider.html https://en.wikipedia.org/wiki/AngularJS JavaScript-Misc 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 Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Feb, 2019" }, { "code": null, "e": 299, "s": 52, "text": "AngularJS is a front-end web application framework based on JavaScript and is maintained by Google. AngularJS interprets the attributes of HTML as directives to bind input/output components to a model represented by standard JavaScript variables." }, { "code": null, "e": 315, "s": 299, "text": "Pre-requisites:" }, { "code": null, "e": 320, "s": 315, "text": "HTML" }, { "code": null, "e": 324, "s": 320, "text": "CSS" }, { "code": null, "e": 335, "s": 324, "text": "JavaScript" }, { "code": null, "e": 345, "s": 335, "text": "AngularJS" }, { "code": null, "e": 611, "s": 345, "text": "Angular-UI-Router is an AngularJS module used to create routes for AngularJS applications. Routes are an important part of Single-Page-Applications (SPAs) as well as regular applications and Angular-UI-Router provides easy creation and usage of routes in AngularJS." }, { "code": null, "e": 780, "s": 611, "text": "Angular-UI-Router has stateProvider method which is used to create routes/states in application. State Provider takes state name and state configurations as parameters." }, { "code": null, "e": 788, "s": 780, "text": "Syntax:" }, { "code": null, "e": 955, "s": 788, "text": "$stateProvider\n.state('StateName', {\n url: 'Url pattern for this State',\n template: \"Html content\",\n controller: \"Name of the Controller for this state\"\n});\n" }, { "code": null, "e": 1069, "s": 955, "text": "Instead of template, templateUrl can be used and given the path of the HTML file to render for the state.Example:" }, { "code": null, "e": 1181, "s": 1069, "text": "$stateProvider\n.state('Home', {\n url: '/home',\n templateUrl: \"home.html\",\n controller: \"HomeCtrl\"\n});\n" }, { "code": null, "e": 1314, "s": 1181, "text": "Simple project to navigate between the routes to demonstrate the use of the Angular-UI-Router module.Pre-requisites: Node.js and npm" }, { "code": null, "e": 1375, "s": 1314, "text": "To run and install http-server node module to host demo app." }, { "code": null, "e": 1448, "s": 1375, "text": "Steps to perform the operation:1. Create a directory structure as below:" }, { "code": null, "e": 1494, "s": 1448, "text": "routingDemo\n--app.js\n--index.html\n--nav.html\n" }, { "code": null, "e": 1583, "s": 1494, "text": "2. Create nav.html file as below. This file consist of nav bar title and contents of it." }, { "code": null, "e": 1778, "s": 1583, "text": "3. Create index.html file as below. All the required dependencies are included in this file along with nav.html file and definition of ui-view where content of different routes will be rendered." }, { "code": null, "e": 1791, "s": 1778, "text": "Explanation:" }, { "code": null, "e": 1850, "s": 1791, "text": "All the dependencies are included via CDN in the head tag." }, { "code": null, "e": 1915, "s": 1850, "text": "nav.html file is included to the index.html page in the body tag" }, { "code": null, "e": 2017, "s": 1915, "text": "The last division in body defines ui-view div where the content of different routes will be rendered." }, { "code": null, "e": 2091, "s": 2017, "text": "Note:If it does not work, replace the second and third script with below:" }, { "code": null, "e": 2236, "s": 2091, "text": "<script src=\"angular.min.js\"></script>\n<script src = \"\nhttps://unpkg.com/@uirouter/angularjs@1.0.7/release/angular-ui-router.min.js\">\n</script>\n" }, { "code": null, "e": 2369, "s": 2236, "text": "4. Create app.js file as below. This is the application file with routes information and actions to be performed through controller." }, { "code": "// declares application module with name \"myApp\"// inject ui.router dependencyvar app = angular.module('myApp', [ \"ui.router\" ]); // define route configurations inside app.config// injecting dependenciesapp.config(function($stateProvider, $locationProvider, $urlRouterProvider) { // creating routes or states $stateProvider .state('Home', { url : '/home', template : \"<h1>Home Page</h1>\", controller : \"HomeCtrl\" }) .state('Login', { url : '/login', template : \"<h1>Login Page</h1>\", controller : \"LoginCtrl\" }) .state('Signup', { url : '/signup', template : \"<h1>Signup Page</h1>\", controller : \"SignupCtrl\" }); // Redirect to home page if url does not // matches any of the three mentioned above $urlRouterProvider.otherwise(\"/home\");}); // create empty controllers for the states as we are// not doing anything but just displaying messageapp.controller('MainCtrl', function() {});app.controller('HomeCtrl', function() {});app.controller('LoginCtrl', function() {});app.controller('SignupCtrl', function() {});", "e": 3577, "s": 2369, "text": null }, { "code": null, "e": 3716, "s": 3577, "text": "5. To run the above demo app in the browser, install http-server node module. To install the http-server module use the following command:" }, { "code": null, "e": 3751, "s": 3716, "text": " npm install http-server -g\n" }, { "code": null, "e": 3820, "s": 3751, "text": "6. After Installing:–From routingDemo folder, run following command:" }, { "code": null, "e": 3840, "s": 3820, "text": " http-server\n" }, { "code": null, "e": 3929, "s": 3840, "text": "Above command will host the demo app on port 8080. app can be accessed using below link:" }, { "code": null, "e": 3953, "s": 3929, "text": " localhost:8080/\n" }, { "code": null, "e": 4026, "s": 3953, "text": "7. If this application is accessed via browser, Output will be as below:" }, { "code": null, "e": 4098, "s": 4026, "text": "8. After clicking on Login tab in the nav bar, Output will be as below:" }, { "code": null, "e": 4166, "s": 4098, "text": "9. Clicking on Sign up tab in the nav bar, Output will be as below:" }, { "code": null, "e": 4250, "s": 4166, "text": "Three routes namely Home, Login and Sign up are created in this sample application." }, { "code": null, "e": 4264, "s": 4250, "text": "Applications:" }, { "code": null, "e": 4393, "s": 4264, "text": "Routes are important for Single Page applications as they provide different functionalities to the application on the same page." }, { "code": null, "e": 4469, "s": 4393, "text": "Routes creation and manipulation is easy with the angular-ui-router module." }, { "code": null, "e": 4481, "s": 4469, "text": "References:" }, { "code": null, "e": 4542, "s": 4481, "text": "https://github.com/angular-ui/ui-router/wiki/quick-reference" }, { "code": null, "e": 4625, "s": 4542, "text": "https://ui-router.github.io/ng1/docs/1.0.0-beta.1/classes/state.stateprovider.html" }, { "code": null, "e": 4665, "s": 4625, "text": "https://en.wikipedia.org/wiki/AngularJS" }, { "code": null, "e": 4681, "s": 4665, "text": "JavaScript-Misc" }, { "code": null, "e": 4692, "s": 4681, "text": "JavaScript" }, { "code": null, "e": 4709, "s": 4692, "text": "Web Technologies" }, { "code": null, "e": 4807, "s": 4709, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4868, "s": 4807, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4940, "s": 4868, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 4980, "s": 4940, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5032, "s": 4980, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 5073, "s": 5032, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 5135, "s": 5073, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5168, "s": 5135, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5229, "s": 5168, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5279, "s": 5229, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python | Pandas dataframe.rdiv()
22 Nov, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.rdiv() function compute Floating division of dataframe and other, element-wise (binary operator rtruediv). Other object could be a scalar, pandas series or pandas dataframe. This function is essentially same as doing other / dataframe but with support to substitute a fill_value for missing data in one of the inputs. Syntax: DataFrame.rdiv(other, axis=’columns’, level=None, fill_value=None) Parameters :other : Series, DataFrame, or constantaxis : For Series input, axis to match Series index onlevel : Broadcast across a level, matching Index values on the passed MultiIndex levelnumeric_only : Include only float, int, boolean data. Valid only for DataFrame or Panel objectsfill_value : Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing Returns : result : DataFrame Example #1: Use rdiv() function to divide a series with a dataframe element-wise # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[1, 5, 3, 4, 2], "B":[3, 2, 4, 3, 4], "C":[2, 2, 7, 3, 4], "D":[4, 3, 6, 12, 7]}) # Print the dataframedf Lets create a series # importing pandas as pdimport pandas as pd # Create a seriessr = pd.Series([5, 10, 15, 20], index =["A", "B", "C", "D"]) # Print the seriessr Let’s use the dataframe.rdiv() function to divide the series with a dataframe # perform division of series with # dataframe element-wise over the column axisdf.rdiv(sr, axis = 1) Output : Example #2: Use rdiv() function to divide one dataframe with other which contains NaN value. # importing pandas as pdimport pandas as pd # Creating the first dataframe df1 = pd.DataFrame({"A":[1, 5, 3, 4, 2], "B":[3, 2, 4, 3, 4], "C":[2, 2, 7, 3, 4], "D":[4, 3, 6, 12, 7]}) # Creating the second dataframedf2 = pd.DataFrame({"A":[14, 5, None, 4, 12], "B":[7, 6, 4, 5, None], "C":[2, 11, 4, 3, 6], "D":[4, None, 6, 2, 4]}) # divide df2 by df1 element-wise# Fill all the missing values by 100df1.rdiv(df2, fill_value = 100) Output : 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. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method 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": 28, "s": 0, "text": "\n22 Nov, 2018" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 577, "s": 242, "text": "Pandas dataframe.rdiv() function compute Floating division of dataframe and other, element-wise (binary operator rtruediv). Other object could be a scalar, pandas series or pandas dataframe. This function is essentially same as doing other / dataframe but with support to substitute a fill_value for missing data in one of the inputs." }, { "code": null, "e": 652, "s": 577, "text": "Syntax: DataFrame.rdiv(other, axis=’columns’, level=None, fill_value=None)" }, { "code": null, "e": 1173, "s": 652, "text": "Parameters :other : Series, DataFrame, or constantaxis : For Series input, axis to match Series index onlevel : Broadcast across a level, matching Index values on the passed MultiIndex levelnumeric_only : Include only float, int, boolean data. Valid only for DataFrame or Panel objectsfill_value : Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing" }, { "code": null, "e": 1202, "s": 1173, "text": "Returns : result : DataFrame" }, { "code": null, "e": 1283, "s": 1202, "text": "Example #1: Use rdiv() function to divide a series with a dataframe element-wise" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[1, 5, 3, 4, 2], \"B\":[3, 2, 4, 3, 4], \"C\":[2, 2, 7, 3, 4], \"D\":[4, 3, 6, 12, 7]}) # Print the dataframedf", "e": 1538, "s": 1283, "text": null }, { "code": null, "e": 1559, "s": 1538, "text": "Lets create a series" }, { "code": "# importing pandas as pdimport pandas as pd # Create a seriessr = pd.Series([5, 10, 15, 20], index =[\"A\", \"B\", \"C\", \"D\"]) # Print the seriessr", "e": 1704, "s": 1559, "text": null }, { "code": null, "e": 1782, "s": 1704, "text": "Let’s use the dataframe.rdiv() function to divide the series with a dataframe" }, { "code": "# perform division of series with # dataframe element-wise over the column axisdf.rdiv(sr, axis = 1)", "e": 1883, "s": 1782, "text": null }, { "code": null, "e": 1985, "s": 1883, "text": "Output : Example #2: Use rdiv() function to divide one dataframe with other which contains NaN value." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the first dataframe df1 = pd.DataFrame({\"A\":[1, 5, 3, 4, 2], \"B\":[3, 2, 4, 3, 4], \"C\":[2, 2, 7, 3, 4], \"D\":[4, 3, 6, 12, 7]}) # Creating the second dataframedf2 = pd.DataFrame({\"A\":[14, 5, None, 4, 12], \"B\":[7, 6, 4, 5, None], \"C\":[2, 11, 4, 3, 6], \"D\":[4, None, 6, 2, 4]}) # divide df2 by df1 element-wise# Fill all the missing values by 100df1.rdiv(df2, fill_value = 100)", "e": 2533, "s": 1985, "text": null }, { "code": null, "e": 2542, "s": 2533, "text": "Output :" }, { "code": null, "e": 2566, "s": 2542, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2598, "s": 2566, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2612, "s": 2598, "text": "Python-pandas" }, { "code": null, "e": 2619, "s": 2612, "text": "Python" }, { "code": null, "e": 2717, "s": 2619, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2749, "s": 2717, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2776, "s": 2749, "text": "Python Classes and Objects" }, { "code": null, "e": 2797, "s": 2776, "text": "Python OOPs Concepts" }, { "code": null, "e": 2820, "s": 2797, "text": "Introduction To PYTHON" }, { "code": null, "e": 2876, "s": 2820, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2907, "s": 2876, "text": "Python | os.path.join() method" }, { "code": null, "e": 2949, "s": 2907, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2991, "s": 2949, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3030, "s": 2991, "text": "Python | datetime.timedelta() function" } ]
How to Display Bluetooth Paired Devices Programmatically in Android?
23 Feb, 2021 Bluetooth’s technology is a high-speed, low-powered wireless technology link designed to connect devices such as phones or other portable equipment. It has a specification (IEEE 802.15.1) for low-power radio communications to link computers, phones, and other network devices over a short distance in a wireless manner. Bluetooth signals cover distances, typically up to 10 meters or 30 feet. Bluetooth supports the waveband of 2.45 GHz and may support up to 721 kbps alongside three voice channels. This waveband has been put aside by international agreement to use Industrial, Scientific, and Medical devices (ISM).rd-compatible with 1.0 devices. Bluetooth is capable of connecting up to “eight devices” at a time. Every device offers a unique 48-bit address from the IEEE 802 standard. The Bluetooth specification defines and supports a variety of Bluetooth network connections. In this way, Bluetooth networking may be a remarkably flexible form of a wireless system for various short-range applications. Through this article, we want to share with you the implementation of an application that displays a list of Bluetooth Paired Devices along with their MAC IDs. A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using both Java and Kotlin language. To programmatically show a list of Bluetooth Paired devices against our device in Android, follow the following steps: 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: Working with the AndroidManifest.xml file Go to the AndroidManifest.xml file and add these permissions required by the Bluetooth adapter: BLUETOOTH, BLUETOOTH_ADMIN, and ACCESS_COARSE_LOCATION. <uses-permission android:name=”android.permission.BLUETOOTH”/> <uses-permission android:name=”android.permission.BLUETOOTH_ADMIN”/> <uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION”/> Below is the complete code for the AndroidManifest.xml file. XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.geeksforgeeks.bluetoothpairedlist"> <!--Permissions Required for accessing Bluetooth services--> <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Step 3: Working with the activity_main.xml file Now go to the activity_main.xml file which represents the UI of the application. Create a Layout that will display the Paired list of Bluetooth devices along with their MAC Addresses, and a Button to fetch them. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!--Button will perform a task to fetch the list of paired Bluetooth Devices--> <Button android:id="@+id/btnGet" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:text="Get Paired Devices" /> <!--A layout to display 2 text views, one consisting of names and the other displaying their mac ids--> <RelativeLayout android:id="@+id/info" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/btnGet" android:layout_centerHorizontal="true"> <!--Paired devices name--> <TextView android:id="@+id/nameTv" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <!--Paired devices mac ID--> <TextView android:id="@+id/macAddressTv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/nameTv" /> </RelativeLayout></RelativeLayout> Step 4: Working with the MainActivity file Go to the MainActivity file, and refer to the following code. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail. Kotlin Java import android.bluetooth.BluetoothAdapterimport android.os.Buildimport android.os.Bundleimport android.widget.Buttonimport android.widget.TextViewimport android.widget.Toastimport androidx.annotation.RequiresApiimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR2) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring the textView for name from the layout file val tvName = findViewById<TextView>(R.id.nameTv) // Declaring the textView for MAC ID from the layout file val tvMac = findViewById<TextView>(R.id.macAddressTv) // Declaring the button from the layout file val btn = findViewById<Button>(R.id.btnGet) // Initializing the Bluetooth Adapter val bAdapter = BluetoothAdapter.getDefaultAdapter() // Button Action when clicked btn.setOnClickListener { // Checks if Bluetooth Adapter is present if (bAdapter == null) { Toast.makeText(applicationContext, "Bluetooth Not Supported", Toast.LENGTH_SHORT).show() } else { // Arraylist of all the bonded (paired) devices val pairedDevices = bAdapter.bondedDevices if (pairedDevices.size > 0) { for (device in pairedDevices) { // get the device name val deviceName = device.name // get the mac address val macAddress = device.address // append in the two separate views tvName.append("$deviceName\n") tvMac.append("$macAddress\n") } } } } }} import android.bluetooth.BluetoothAdapter;import android.bluetooth.BluetoothDevice;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import java.util.Set; public class MainActivity extends AppCompatActivity { TextView tvName, tvMac; Button btn; BluetoothAdapter bAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Declaring the textView for name from the layout file tvName = (TextView) findViewById(R.id.nameTv); // Declaring the textView for MAC ID from the layout file tvMac = (TextView) findViewById(R.id.macAddressTv); // Declaring the button from the layout file btn = (Button) findViewById(R.id.btnGet); // Initializing the Bluetooth Adapter bAdapter = BluetoothAdapter.getDefaultAdapter(); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Checks if Bluetooth Adapter is present if (bAdapter == null) { Toast.makeText(getApplicationContext(), "Bluetooth Not Supported", Toast.LENGTH_SHORT).show(); } else { // List all the bonded devices(paired) Set<BluetoothDevice> pairedDevices = bAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { // get the device name String deviceName = device.getName(); // get the mac address String macAddress = device.getAddress(); // append in the two separate views tvName.append(deviceName + "\n"); tvMac.append(macAddress + "\n"); } } } } }); }} Note: Some data is masked to maintain privacy. raghav14 Android-Misc 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 RecyclerView in Kotlin Broadcast Receiver in Android With Example Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Add Views Dynamically and Store Data in Arraylist in Android? Android UI Layouts Android RecyclerView in Kotlin Broadcast Receiver in Android With Example
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Feb, 2021" }, { "code": null, "e": 1376, "s": 28, "text": "Bluetooth’s technology is a high-speed, low-powered wireless technology link designed to connect devices such as phones or other portable equipment. It has a specification (IEEE 802.15.1) for low-power radio communications to link computers, phones, and other network devices over a short distance in a wireless manner. Bluetooth signals cover distances, typically up to 10 meters or 30 feet. Bluetooth supports the waveband of 2.45 GHz and may support up to 721 kbps alongside three voice channels. This waveband has been put aside by international agreement to use Industrial, Scientific, and Medical devices (ISM).rd-compatible with 1.0 devices. Bluetooth is capable of connecting up to “eight devices” at a time. Every device offers a unique 48-bit address from the IEEE 802 standard. The Bluetooth specification defines and supports a variety of Bluetooth network connections. In this way, Bluetooth networking may be a remarkably flexible form of a wireless system for various short-range applications. Through this article, we want to share with you the implementation of an application that displays a list of Bluetooth Paired Devices along with their MAC IDs. A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using both Java and Kotlin language. " }, { "code": null, "e": 1495, "s": 1376, "text": "To programmatically show a list of Bluetooth Paired devices against our device in Android, follow the following steps:" }, { "code": null, "e": 1524, "s": 1495, "text": "Step 1: Create a New Project" }, { "code": null, "e": 1688, "s": 1524, "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": 1738, "s": 1688, "text": "Step 2: Working with the AndroidManifest.xml file" }, { "code": null, "e": 1891, "s": 1738, "text": "Go to the AndroidManifest.xml file and add these permissions required by the Bluetooth adapter: BLUETOOTH, BLUETOOTH_ADMIN, and ACCESS_COARSE_LOCATION. " }, { "code": null, "e": 1954, "s": 1891, "text": "<uses-permission android:name=”android.permission.BLUETOOTH”/>" }, { "code": null, "e": 2023, "s": 1954, "text": "<uses-permission android:name=”android.permission.BLUETOOTH_ADMIN”/>" }, { "code": null, "e": 2099, "s": 2023, "text": "<uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION”/>" }, { "code": null, "e": 2160, "s": 2099, "text": "Below is the complete code for the AndroidManifest.xml file." }, { "code": null, "e": 2164, "s": 2160, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"org.geeksforgeeks.bluetoothpairedlist\"> <!--Permissions Required for accessing Bluetooth services--> <uses-permission android:name=\"android.permission.BLUETOOTH\"/> <uses-permission android:name=\"android.permission.BLUETOOTH_ADMIN\"/> <uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\"/> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>", "e": 3167, "s": 2164, "text": null }, { "code": null, "e": 3215, "s": 3167, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 3552, "s": 3215, "text": "Now go to the activity_main.xml file which represents the UI of the application. Create a Layout that will display the Paired list of Bluetooth devices along with their MAC Addresses, and a Button to fetch them. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail. " }, { "code": null, "e": 3556, "s": 3552, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> <!--Button will perform a task to fetch the list of paired Bluetooth Devices--> <Button android:id=\"@+id/btnGet\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:text=\"Get Paired Devices\" /> <!--A layout to display 2 text views, one consisting of names and the other displaying their mac ids--> <RelativeLayout android:id=\"@+id/info\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/btnGet\" android:layout_centerHorizontal=\"true\"> <!--Paired devices name--> <TextView android:id=\"@+id/nameTv\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" /> <!--Paired devices mac ID--> <TextView android:id=\"@+id/macAddressTv\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_toRightOf=\"@id/nameTv\" /> </RelativeLayout></RelativeLayout>", "e": 4912, "s": 3556, "text": null }, { "code": null, "e": 4955, "s": 4912, "text": "Step 4: Working with the MainActivity file" }, { "code": null, "e": 5137, "s": 4955, "text": "Go to the MainActivity file, and refer to the following code. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail. " }, { "code": null, "e": 5144, "s": 5137, "text": "Kotlin" }, { "code": null, "e": 5149, "s": 5144, "text": "Java" }, { "code": "import android.bluetooth.BluetoothAdapterimport android.os.Buildimport android.os.Bundleimport android.widget.Buttonimport android.widget.TextViewimport android.widget.Toastimport androidx.annotation.RequiresApiimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR2) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring the textView for name from the layout file val tvName = findViewById<TextView>(R.id.nameTv) // Declaring the textView for MAC ID from the layout file val tvMac = findViewById<TextView>(R.id.macAddressTv) // Declaring the button from the layout file val btn = findViewById<Button>(R.id.btnGet) // Initializing the Bluetooth Adapter val bAdapter = BluetoothAdapter.getDefaultAdapter() // Button Action when clicked btn.setOnClickListener { // Checks if Bluetooth Adapter is present if (bAdapter == null) { Toast.makeText(applicationContext, \"Bluetooth Not Supported\", Toast.LENGTH_SHORT).show() } else { // Arraylist of all the bonded (paired) devices val pairedDevices = bAdapter.bondedDevices if (pairedDevices.size > 0) { for (device in pairedDevices) { // get the device name val deviceName = device.name // get the mac address val macAddress = device.address // append in the two separate views tvName.append(\"$deviceName\\n\") tvMac.append(\"$macAddress\\n\") } } } } }}", "e": 7047, "s": 5149, "text": null }, { "code": "import android.bluetooth.BluetoothAdapter;import android.bluetooth.BluetoothDevice;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import java.util.Set; public class MainActivity extends AppCompatActivity { TextView tvName, tvMac; Button btn; BluetoothAdapter bAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Declaring the textView for name from the layout file tvName = (TextView) findViewById(R.id.nameTv); // Declaring the textView for MAC ID from the layout file tvMac = (TextView) findViewById(R.id.macAddressTv); // Declaring the button from the layout file btn = (Button) findViewById(R.id.btnGet); // Initializing the Bluetooth Adapter bAdapter = BluetoothAdapter.getDefaultAdapter(); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Checks if Bluetooth Adapter is present if (bAdapter == null) { Toast.makeText(getApplicationContext(), \"Bluetooth Not Supported\", Toast.LENGTH_SHORT).show(); } else { // List all the bonded devices(paired) Set<BluetoothDevice> pairedDevices = bAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { // get the device name String deviceName = device.getName(); // get the mac address String macAddress = device.getAddress(); // append in the two separate views tvName.append(deviceName + \"\\n\"); tvMac.append(macAddress + \"\\n\"); } } } } }); }}", "e": 9219, "s": 7047, "text": null }, { "code": null, "e": 9266, "s": 9219, "text": "Note: Some data is masked to maintain privacy." }, { "code": null, "e": 9275, "s": 9266, "text": "raghav14" }, { "code": null, "e": 9288, "s": 9275, "text": "Android-Misc" }, { "code": null, "e": 9296, "s": 9288, "text": "Android" }, { "code": null, "e": 9303, "s": 9296, "text": "Kotlin" }, { "code": null, "e": 9311, "s": 9303, "text": "Android" }, { "code": null, "e": 9409, "s": 9311, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9478, "s": 9409, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 9509, "s": 9478, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 9552, "s": 9509, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 9584, "s": 9552, "text": "Android SDK and it's Components" }, { "code": null, "e": 9623, "s": 9584, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 9692, "s": 9623, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 9711, "s": 9692, "text": "Android UI Layouts" }, { "code": null, "e": 9742, "s": 9711, "text": "Android RecyclerView in Kotlin" } ]
Find a local minima in an array
19 Dec, 2021 Given an array arr[0 .. n-1] of distinct integers, the task is to find a local minima in it. We say that an element arr[x] is a local minimum if it is less than both its neighbors. For corner elements, we need to consider only one neighbor for comparison. There can be more than one local minima in an array, we need to find one of them. Examples: Input: arr[] = {9, 6, 3, 14, 5, 7, 4}; Output: Index of local minima is 2 The output prints index of 3 because it is smaller than both of its neighbors. Note that indexes of elements 5 and 4 are also valid outputs. Input: arr[] = {23, 8, 15, 2, 3}; Output: Index of local minima is 1 Input: arr[] = {1, 2, 3}; Output: Index of local minima is 0 Input: arr[] = {3, 2, 1}; Output: Index of local minima is 2 A simple solution is to do a linear scan of array and as soon as we find a local minima, we return it. The worst case time complexity of this method would be O(n).An efficient solution is based on Binary Search. We compare middle element with its neighbors. If middle element is not greater than any of its neighbors, then we return it. If the middle element is greater than its left neighbor, then there is always a local minima in left half (Why? take few examples). If the middle element is greater than its right neighbor, then there is always a local minima in right half (due to same reason as left half). Below is the implementation of the above idea : C++ Java Python3 C# PHP // A C++ program to find a local minima in an array#include <stdio.h> // A binary search based function that returns// index of a local minima.int localMinUtil(int arr[], int low, int high, int n){ // Find index of middle element int mid = low + (high - low)/2; /* (low + high)/2 */ // Compare middle element with its neighbours // (if neighbours exist) if ((mid == 0 || arr[mid-1] > arr[mid]) && (mid == n-1 || arr[mid+1] > arr[mid])) return mid; // If middle element is not minima and its left // neighbour is smaller than it, then left half // must have a local minima. else if (mid > 0 && arr[mid-1] < arr[mid]) return localMinUtil(arr, low, (mid -1), n); // If middle element is not minima and its right // neighbour is smaller than it, then right half // must have a local minima. return localMinUtil(arr, (mid + 1), high, n);} // A wrapper over recursive function localMinUtil()int localMin(int arr[], int n){ return localMinUtil(arr, 0, n-1, n);} /* Driver program to check above functions */int main(){ int arr[] = {4, 3, 1, 14, 16, 40}; int n = sizeof(arr)/sizeof(arr[0]); printf("Index of a local minima is %d", localMin(arr, n)); return 0;} // A Java program to find a local minima in an arrayimport java.io.*; class GFG{ // A binary search based function that returns // index of a local minima. public static int localMinUtil(int[] arr, int low, int high, int n) { // Find index of middle element int mid = low + (high - low) / 2; // Compare middle element with its neighbours // (if neighbours exist) if(mid == 0 || arr[mid - 1] > arr[mid] && mid == n - 1 || arr[mid] < arr[mid + 1]) return mid; // If middle element is not minima and its left // neighbour is smaller than it, then left half // must have a local minima. else if(mid > 0 && arr[mid - 1] < arr[mid]) return localMinUtil(arr, low, mid - 1, n); // If middle element is not minima and its right // neighbour is smaller than it, then right half // must have a local minima. return localMinUtil(arr, mid + 1, high, n); } // A wrapper over recursive function localMinUtil() public static int localMin(int[] arr, int n) { return localMinUtil(arr, 0, n - 1, n); } public static void main (String[] args) { int arr[] = {4, 3, 1, 14, 16, 40}; int n = arr.length; System.out.println("Index of a local minima is " + localMin(arr, n)); }} //This code is contributed by Dheerendra Singh # Python3 program to find a# local minima in an array # A binary search based function that# returns index of a local minima.def localMinUtil(arr, low, high, n): # Find index of middle element mid = low + (high - low) // 2 # Compare middle element with its # neighbours (if neighbours exist) if(mid == 0 or arr[mid - 1] > arr[mid] and mid == n - 1 or arr[mid] < arr[mid + 1]): return mid # If middle element is not minima and its left # neighbour is smaller than it, then left half # must have a local minima. elif(mid > 0 and arr[mid - 1] < arr[mid]): return localMinUtil(arr, low, mid - 1, n) # If middle element is not minima and its right # neighbour is smaller than it, then right half # must have a local minima. return localMinUtil(arr, mid + 1, high, n) # A wrapper over recursive function localMinUtil()def localMin(arr, n): return localMinUtil(arr, 0, n - 1, n) # Driver codearr = [4, 3, 1, 14, 16, 40]n = len(arr)print("Index of a local minima is " , localMin(arr, n)) # This code is contributed by Anant Agarwal. // A C# program to find a// local minima in an arrayusing System; class GFG{ // A binary search based function that returns // index of a local minima. public static int localMinUtil(int[] arr, int low, int high, int n) { // Find index of middle element int mid = low + (high - low) / 2; // Compare middle element with its neighbours // (if neighbours exist) if(mid == 0 || arr[mid - 1] > arr[mid] && mid == n - 1 || arr[mid] < arr[mid + 1]) return mid; // If middle element is not minima and its left // neighbour is smaller than it, then left half // must have a local minima. else if(mid > 0 && arr[mid - 1] < arr[mid]) return localMinUtil(arr, low, mid - 1, n); // If middle element is not minima and its right // neighbour is smaller than it, then right half // must have a local minima. return localMinUtil(arr, mid + 1, high, n); } // A wrapper over recursive function localMinUtil() public static int localMin(int[] arr, int n) { return localMinUtil(arr, 0, n - 1, n); } // Driver Code public static void Main () { int []arr = {4, 3, 1, 14, 16, 40}; int n = arr.Length; Console.WriteLine("Index of a local minima is " + localMin(arr, n)); }} // This code is contributed by vt_m. <?php// A PHP program to find a// local minima in an array // A binary search based// function that returns// index of a local minima.function localMinUtil($arr, $low, $high, $n){ // Find index of middle element /* (low + high)/2 */ $mid = $low + ($high - $low) / 2; // Compare middle element // with its neighbours // (if neighbours exist) if (($mid == 0 or $arr[$mid - 1] > $arr[$mid]) and ($mid == $n - 1 or $arr[$mid + 1] > $arr[$mid])) return $mid; // If middle element is not // minima and its left // neighbour is smaller than // it, then left half // must have a local minima. else if ($mid > 0 and $arr[$mid - 1] < $arr[$mid]) return localMinUtil($arr, $low, ($mid - 1), $n); // If middle element is not // minima and its right // neighbour is smaller than // it, then right half // must have a local minima. return localMinUtil(arr, (mid + 1), high, n);} // A wrapper over recursive// function localMinUtil()function localMin( $arr, $n){ return floor(localMinUtil($arr, 0, $n - 1, $n));} // Driver Code $arr = array(4, 3, 1, 14, 16, 40); $n = count($arr); echo "Index of a local minima is ", localMin($arr, $n); // This code is contributed by anuj_67.?> Output: Index of a local minima is 2 Time Complexity : O(Log n)Related Problem : Find a peak elementThis article is contributed by Roshni Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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. vt_m yedidyaep Binary Search Arrays Arrays Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Subset Sum Problem | DP-25 Introduction to Data Structures
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Dec, 2021" }, { "code": null, "e": 235, "s": 52, "text": "Given an array arr[0 .. n-1] of distinct integers, the task is to find a local minima in it. We say that an element arr[x] is a local minimum if it is less than both its neighbors. " }, { "code": null, "e": 310, "s": 235, "text": "For corner elements, we need to consider only one neighbor for comparison." }, { "code": null, "e": 392, "s": 310, "text": "There can be more than one local minima in an array, we need to find one of them." }, { "code": null, "e": 404, "s": 392, "text": "Examples: " }, { "code": null, "e": 816, "s": 404, "text": "Input: arr[] = {9, 6, 3, 14, 5, 7, 4};\nOutput: Index of local minima is 2\nThe output prints index of 3 because it is \nsmaller than both of its neighbors. \nNote that indexes of elements 5 and 4 are \nalso valid outputs.\n\nInput: arr[] = {23, 8, 15, 2, 3};\nOutput: Index of local minima is 1\n\nInput: arr[] = {1, 2, 3};\nOutput: Index of local minima is 0\n\nInput: arr[] = {3, 2, 1};\nOutput: Index of local minima is 2" }, { "code": null, "e": 1480, "s": 818, "text": "A simple solution is to do a linear scan of array and as soon as we find a local minima, we return it. The worst case time complexity of this method would be O(n).An efficient solution is based on Binary Search. We compare middle element with its neighbors. If middle element is not greater than any of its neighbors, then we return it. If the middle element is greater than its left neighbor, then there is always a local minima in left half (Why? take few examples). If the middle element is greater than its right neighbor, then there is always a local minima in right half (due to same reason as left half). Below is the implementation of the above idea : " }, { "code": null, "e": 1484, "s": 1480, "text": "C++" }, { "code": null, "e": 1489, "s": 1484, "text": "Java" }, { "code": null, "e": 1497, "s": 1489, "text": "Python3" }, { "code": null, "e": 1500, "s": 1497, "text": "C#" }, { "code": null, "e": 1504, "s": 1500, "text": "PHP" }, { "code": "// A C++ program to find a local minima in an array#include <stdio.h> // A binary search based function that returns// index of a local minima.int localMinUtil(int arr[], int low, int high, int n){ // Find index of middle element int mid = low + (high - low)/2; /* (low + high)/2 */ // Compare middle element with its neighbours // (if neighbours exist) if ((mid == 0 || arr[mid-1] > arr[mid]) && (mid == n-1 || arr[mid+1] > arr[mid])) return mid; // If middle element is not minima and its left // neighbour is smaller than it, then left half // must have a local minima. else if (mid > 0 && arr[mid-1] < arr[mid]) return localMinUtil(arr, low, (mid -1), n); // If middle element is not minima and its right // neighbour is smaller than it, then right half // must have a local minima. return localMinUtil(arr, (mid + 1), high, n);} // A wrapper over recursive function localMinUtil()int localMin(int arr[], int n){ return localMinUtil(arr, 0, n-1, n);} /* Driver program to check above functions */int main(){ int arr[] = {4, 3, 1, 14, 16, 40}; int n = sizeof(arr)/sizeof(arr[0]); printf(\"Index of a local minima is %d\", localMin(arr, n)); return 0;}", "e": 2766, "s": 1504, "text": null }, { "code": "// A Java program to find a local minima in an arrayimport java.io.*; class GFG{ // A binary search based function that returns // index of a local minima. public static int localMinUtil(int[] arr, int low, int high, int n) { // Find index of middle element int mid = low + (high - low) / 2; // Compare middle element with its neighbours // (if neighbours exist) if(mid == 0 || arr[mid - 1] > arr[mid] && mid == n - 1 || arr[mid] < arr[mid + 1]) return mid; // If middle element is not minima and its left // neighbour is smaller than it, then left half // must have a local minima. else if(mid > 0 && arr[mid - 1] < arr[mid]) return localMinUtil(arr, low, mid - 1, n); // If middle element is not minima and its right // neighbour is smaller than it, then right half // must have a local minima. return localMinUtil(arr, mid + 1, high, n); } // A wrapper over recursive function localMinUtil() public static int localMin(int[] arr, int n) { return localMinUtil(arr, 0, n - 1, n); } public static void main (String[] args) { int arr[] = {4, 3, 1, 14, 16, 40}; int n = arr.length; System.out.println(\"Index of a local minima is \" + localMin(arr, n)); }} //This code is contributed by Dheerendra Singh", "e": 4265, "s": 2766, "text": null }, { "code": "# Python3 program to find a# local minima in an array # A binary search based function that# returns index of a local minima.def localMinUtil(arr, low, high, n): # Find index of middle element mid = low + (high - low) // 2 # Compare middle element with its # neighbours (if neighbours exist) if(mid == 0 or arr[mid - 1] > arr[mid] and mid == n - 1 or arr[mid] < arr[mid + 1]): return mid # If middle element is not minima and its left # neighbour is smaller than it, then left half # must have a local minima. elif(mid > 0 and arr[mid - 1] < arr[mid]): return localMinUtil(arr, low, mid - 1, n) # If middle element is not minima and its right # neighbour is smaller than it, then right half # must have a local minima. return localMinUtil(arr, mid + 1, high, n) # A wrapper over recursive function localMinUtil()def localMin(arr, n): return localMinUtil(arr, 0, n - 1, n) # Driver codearr = [4, 3, 1, 14, 16, 40]n = len(arr)print(\"Index of a local minima is \" , localMin(arr, n)) # This code is contributed by Anant Agarwal.", "e": 5441, "s": 4265, "text": null }, { "code": "// A C# program to find a// local minima in an arrayusing System; class GFG{ // A binary search based function that returns // index of a local minima. public static int localMinUtil(int[] arr, int low, int high, int n) { // Find index of middle element int mid = low + (high - low) / 2; // Compare middle element with its neighbours // (if neighbours exist) if(mid == 0 || arr[mid - 1] > arr[mid] && mid == n - 1 || arr[mid] < arr[mid + 1]) return mid; // If middle element is not minima and its left // neighbour is smaller than it, then left half // must have a local minima. else if(mid > 0 && arr[mid - 1] < arr[mid]) return localMinUtil(arr, low, mid - 1, n); // If middle element is not minima and its right // neighbour is smaller than it, then right half // must have a local minima. return localMinUtil(arr, mid + 1, high, n); } // A wrapper over recursive function localMinUtil() public static int localMin(int[] arr, int n) { return localMinUtil(arr, 0, n - 1, n); } // Driver Code public static void Main () { int []arr = {4, 3, 1, 14, 16, 40}; int n = arr.Length; Console.WriteLine(\"Index of a local minima is \" + localMin(arr, n)); }} // This code is contributed by vt_m.", "e": 6952, "s": 5441, "text": null }, { "code": "<?php// A PHP program to find a// local minima in an array // A binary search based// function that returns// index of a local minima.function localMinUtil($arr, $low, $high, $n){ // Find index of middle element /* (low + high)/2 */ $mid = $low + ($high - $low) / 2; // Compare middle element // with its neighbours // (if neighbours exist) if (($mid == 0 or $arr[$mid - 1] > $arr[$mid]) and ($mid == $n - 1 or $arr[$mid + 1] > $arr[$mid])) return $mid; // If middle element is not // minima and its left // neighbour is smaller than // it, then left half // must have a local minima. else if ($mid > 0 and $arr[$mid - 1] < $arr[$mid]) return localMinUtil($arr, $low, ($mid - 1), $n); // If middle element is not // minima and its right // neighbour is smaller than // it, then right half // must have a local minima. return localMinUtil(arr, (mid + 1), high, n);} // A wrapper over recursive// function localMinUtil()function localMin( $arr, $n){ return floor(localMinUtil($arr, 0, $n - 1, $n));} // Driver Code $arr = array(4, 3, 1, 14, 16, 40); $n = count($arr); echo \"Index of a local minima is \", localMin($arr, $n); // This code is contributed by anuj_67.?>", "e": 8257, "s": 6952, "text": null }, { "code": null, "e": 8267, "s": 8257, "text": "Output: " }, { "code": null, "e": 8296, "s": 8267, "text": "Index of a local minima is 2" }, { "code": null, "e": 8782, "s": 8296, "text": "Time Complexity : O(Log n)Related Problem : Find a peak elementThis article is contributed by Roshni Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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": 8787, "s": 8782, "text": "vt_m" }, { "code": null, "e": 8797, "s": 8787, "text": "yedidyaep" }, { "code": null, "e": 8811, "s": 8797, "text": "Binary Search" }, { "code": null, "e": 8818, "s": 8811, "text": "Arrays" }, { "code": null, "e": 8825, "s": 8818, "text": "Arrays" }, { "code": null, "e": 8839, "s": 8825, "text": "Binary Search" }, { "code": null, "e": 8937, "s": 8839, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9005, "s": 8937, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 9049, "s": 9005, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 9081, "s": 9049, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 9129, "s": 9081, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 9143, "s": 9129, "text": "Linear Search" }, { "code": null, "e": 9228, "s": 9143, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 9251, "s": 9228, "text": "Introduction to Arrays" }, { "code": null, "e": 9307, "s": 9251, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 9334, "s": 9307, "text": "Subset Sum Problem | DP-25" } ]
PostgreSQL – RENAME COLUMN
28 Aug, 2020 In PostgreSQL, the RENAME COLUMN clause is used with the ALTER TABLE statement to rename one or more columns in a table. Syntax: ALTER TABLE table_name RENAME COLUMN column_name TO new_column_name; Let’s analyze t5he above syntax: First, specify the table, which contains the column you want to rename, after the ALTER TABLE clause. Second, provide the column name after the RENAME COLUMN clause. Third, give the new column name after the TO keyword. Let’s take some examples of using the ALTER TABLE RENAME COLUMN to get a better understanding. Example 1:First, let’s create two new tables namely customers and customer_groups using the below statement: CREATE TABLE customer_groups ( id serial PRIMARY KEY, name VARCHAR NOT NULL ); CREATE TABLE customers ( id serial PRIMARY KEY, name VARCHAR NOT NULL, phone VARCHAR NOT NULL, email VARCHAR, group_id INT, FOREIGN KEY (group_id) REFERENCES customer_groups (id) ); Then we create a new view named customer_data based on the customers and customer_groups tables as follows: CREATE VIEW customer_data AS SELECT c.id, c.name, g.name customer_group FROM customers c INNER JOIN customer_groups g ON g.id = c.group_id; Now we will use the ALTER TABLE RENAME COLUMN statement to rename the email column of the customers table to contact_email: ALTER TABLE customers RENAME COLUMN email TO contact_email; Now verify the changes made using the below statement: SELECT * FROM customers; Output: Example 2:These statements rename two columns name and phone of the customers table to customer_name and contact_phone respectively: ALTER TABLE customers RENAME COLUMN name TO customer_name; ALTER TABLE customers RENAME COLUMN phone TO contact_phone; Now verify the changes made using the below statement: SELECT * FROM customers; Output: postgreSQL-managing-table PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - LIMIT with OFFSET clause PostgreSQL - REPLACE Function PostgreSQL - DROP INDEX PostgreSQL - INSERT PostgreSQL - TIME Data Type PostgreSQL - ROW_NUMBER Function PostgreSQL - Identity Column PostgreSQL - SELECT PostgreSQL - CREATE SCHEMA PostgreSQL - EXISTS Operator
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Aug, 2020" }, { "code": null, "e": 149, "s": 28, "text": "In PostgreSQL, the RENAME COLUMN clause is used with the ALTER TABLE statement to rename one or more columns in a table." }, { "code": null, "e": 227, "s": 149, "text": "Syntax:\nALTER TABLE table_name \nRENAME COLUMN column_name TO new_column_name;" }, { "code": null, "e": 260, "s": 227, "text": "Let’s analyze t5he above syntax:" }, { "code": null, "e": 362, "s": 260, "text": "First, specify the table, which contains the column you want to rename, after the ALTER TABLE clause." }, { "code": null, "e": 426, "s": 362, "text": "Second, provide the column name after the RENAME COLUMN clause." }, { "code": null, "e": 480, "s": 426, "text": "Third, give the new column name after the TO keyword." }, { "code": null, "e": 575, "s": 480, "text": "Let’s take some examples of using the ALTER TABLE RENAME COLUMN to get a better understanding." }, { "code": null, "e": 684, "s": 575, "text": "Example 1:First, let’s create two new tables namely customers and customer_groups using the below statement:" }, { "code": null, "e": 978, "s": 684, "text": "CREATE TABLE customer_groups (\n id serial PRIMARY KEY,\n name VARCHAR NOT NULL\n);\n\nCREATE TABLE customers (\n id serial PRIMARY KEY,\n name VARCHAR NOT NULL,\n phone VARCHAR NOT NULL,\n email VARCHAR,\n group_id INT,\n FOREIGN KEY (group_id) REFERENCES customer_groups (id)\n);" }, { "code": null, "e": 1086, "s": 978, "text": "Then we create a new view named customer_data based on the customers and customer_groups tables as follows:" }, { "code": null, "e": 1243, "s": 1086, "text": "CREATE VIEW customer_data \nAS SELECT\n c.id,\n c.name,\n g.name customer_group\nFROM\n customers c\nINNER JOIN customer_groups g ON g.id = c.group_id;" }, { "code": null, "e": 1367, "s": 1243, "text": "Now we will use the ALTER TABLE RENAME COLUMN statement to rename the email column of the customers table to contact_email:" }, { "code": null, "e": 1428, "s": 1367, "text": "ALTER TABLE customers \nRENAME COLUMN email TO contact_email;" }, { "code": null, "e": 1483, "s": 1428, "text": "Now verify the changes made using the below statement:" }, { "code": null, "e": 1508, "s": 1483, "text": "SELECT * FROM customers;" }, { "code": null, "e": 1516, "s": 1508, "text": "Output:" }, { "code": null, "e": 1649, "s": 1516, "text": "Example 2:These statements rename two columns name and phone of the customers table to customer_name and contact_phone respectively:" }, { "code": null, "e": 1770, "s": 1649, "text": "ALTER TABLE customers \nRENAME COLUMN name TO customer_name;\n\nALTER TABLE customers\nRENAME COLUMN phone TO contact_phone;" }, { "code": null, "e": 1825, "s": 1770, "text": "Now verify the changes made using the below statement:" }, { "code": null, "e": 1850, "s": 1825, "text": "SELECT * FROM customers;" }, { "code": null, "e": 1858, "s": 1850, "text": "Output:" }, { "code": null, "e": 1884, "s": 1858, "text": "postgreSQL-managing-table" }, { "code": null, "e": 1895, "s": 1884, "text": "PostgreSQL" }, { "code": null, "e": 1993, "s": 1895, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2031, "s": 1993, "text": "PostgreSQL - LIMIT with OFFSET clause" }, { "code": null, "e": 2061, "s": 2031, "text": "PostgreSQL - REPLACE Function" }, { "code": null, "e": 2085, "s": 2061, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 2105, "s": 2085, "text": "PostgreSQL - INSERT" }, { "code": null, "e": 2133, "s": 2105, "text": "PostgreSQL - TIME Data Type" }, { "code": null, "e": 2166, "s": 2133, "text": "PostgreSQL - ROW_NUMBER Function" }, { "code": null, "e": 2195, "s": 2166, "text": "PostgreSQL - Identity Column" }, { "code": null, "e": 2215, "s": 2195, "text": "PostgreSQL - SELECT" }, { "code": null, "e": 2242, "s": 2215, "text": "PostgreSQL - CREATE SCHEMA" } ]
Sorting Arrays in PHP 5
14 Nov, 2017 What is sorting?Sorting refers to ordering data in an alphabetical, numerical order and increasing or decreasing fashion according to some linear relationship among the data items.Sorting greatly improves the efficiency of searching. Sorting Functions For Arrays In PHP sort() – sorts arrays in ascending orderrsort() – sorts arrays in descending orderasort() – sorts associative arrays in ascending order, according to the valueksort() – sorts associative arrays in ascending order, according to the keyarsort() – sorts associative arrays in descending order, according to the valuekrsort() – sorts associative arrays in descending order, according to the key sort() – sorts arrays in ascending order rsort() – sorts arrays in descending order asort() – sorts associative arrays in ascending order, according to the value ksort() – sorts associative arrays in ascending order, according to the key arsort() – sorts associative arrays in descending order, according to the value krsort() – sorts associative arrays in descending order, according to the key Sort Array in Ascending Order – sort() The following function sorts the elements of a numerical array in ascending numerical order: INPUT : <!DOCTYPE html><html><body> <?php$numbers = array(40, 61, 2, 22, 13);sort($numbers); $arrlength = count($numbers);for($x = 0; $x < $arrlength; $x++) { echo $numbers[$x]; echo "<br>";}?> </body></html> OUTPUT : 213224061 Sort Array in Descending Order – rsort()The following function sorts the elements of a numerical array in descending numerical order: INPUT : <!DOCTYPE html><html><body> <?php$numbers = array(40, 61, 2, 22, 13);rsort($numbers); $arrlength = count($numbers);for($x = 0; $x < $arrlength; $x++) { echo $numbers[$x]; echo "<br>";}?> </body></html> OUTPUT : 614022132 Sort Array in Ascending Order,According to Value – asort()The following function sorts an associative array in ascending order, according to the value: INPUT : <!DOCTYPE html><html><body> <?php$age = array("ayush"=>"23", "shankar"=>"47", "kailash"=>"41");asort($age); foreach($age as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>";}?> </body></html> OUTPUT : Key=Ayush, Value=23Key=Kailash, Value=41Key=Shankar, Value=47 Sort Array in Ascending Order, According to Key – ksort()The following function sorts an associative array in ascending order, according to the key: INPUT : <!DOCTYPE html><html><body> <?php$age = array("ayush"=>"23", "shankar"=>"47", "kailash"=>"41");ksort($age); foreach($age as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>";}?> </body></html> OUTPUT : Key=Ayush, Value=23Key=Kailash, Value=41Key=Shankar, Value=47 Sort Array in Descending Order, According to Value – arsort()The following function sorts an associative array in descending order, according to the value. INPUT : <!DOCTYPE html><html><body> <?php$age = array("ayush"=>"23", "shankar"=>"47", "kailash"=>"41");arsort($age); foreach($age as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>";}?> </body></html> OUTPUT : Key=Shankar, Value=47Key=Kailash, Value=41Key=Ayush, Value=23 Sort Array in Descending Order, According to Key – krsort()The following function sorts an associative array in descending order, according to the key. INPUT : <!DOCTYPE html><html><body> <?php$age = array("ayush"=>"23", "shankar"=>"47", "kailash"=>"41");krsort($age); foreach($age as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>";}?> </body></html> OUTPUT : Key=Shankar, Value=47Key=Kailash, Value=41Key=Ayush, Value=23 PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime 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? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Nov, 2017" }, { "code": null, "e": 286, "s": 52, "text": "What is sorting?Sorting refers to ordering data in an alphabetical, numerical order and increasing or decreasing fashion according to some linear relationship among the data items.Sorting greatly improves the efficiency of searching." }, { "code": null, "e": 322, "s": 286, "text": "Sorting Functions For Arrays In PHP" }, { "code": null, "e": 713, "s": 322, "text": "sort() – sorts arrays in ascending orderrsort() – sorts arrays in descending orderasort() – sorts associative arrays in ascending order, according to the valueksort() – sorts associative arrays in ascending order, according to the keyarsort() – sorts associative arrays in descending order, according to the valuekrsort() – sorts associative arrays in descending order, according to the key" }, { "code": null, "e": 754, "s": 713, "text": "sort() – sorts arrays in ascending order" }, { "code": null, "e": 797, "s": 754, "text": "rsort() – sorts arrays in descending order" }, { "code": null, "e": 875, "s": 797, "text": "asort() – sorts associative arrays in ascending order, according to the value" }, { "code": null, "e": 951, "s": 875, "text": "ksort() – sorts associative arrays in ascending order, according to the key" }, { "code": null, "e": 1031, "s": 951, "text": "arsort() – sorts associative arrays in descending order, according to the value" }, { "code": null, "e": 1109, "s": 1031, "text": "krsort() – sorts associative arrays in descending order, according to the key" }, { "code": null, "e": 1148, "s": 1109, "text": "Sort Array in Ascending Order – sort()" }, { "code": null, "e": 1241, "s": 1148, "text": "The following function sorts the elements of a numerical array in ascending numerical order:" }, { "code": null, "e": 1249, "s": 1241, "text": "INPUT :" }, { "code": "<!DOCTYPE html><html><body> <?php$numbers = array(40, 61, 2, 22, 13);sort($numbers); $arrlength = count($numbers);for($x = 0; $x < $arrlength; $x++) { echo $numbers[$x]; echo \"<br>\";}?> </body></html>", "e": 1459, "s": 1249, "text": null }, { "code": null, "e": 1468, "s": 1459, "text": "OUTPUT :" }, { "code": null, "e": 1478, "s": 1468, "text": "213224061" }, { "code": null, "e": 1612, "s": 1478, "text": "Sort Array in Descending Order – rsort()The following function sorts the elements of a numerical array in descending numerical order:" }, { "code": null, "e": 1620, "s": 1612, "text": "INPUT :" }, { "code": "<!DOCTYPE html><html><body> <?php$numbers = array(40, 61, 2, 22, 13);rsort($numbers); $arrlength = count($numbers);for($x = 0; $x < $arrlength; $x++) { echo $numbers[$x]; echo \"<br>\";}?> </body></html>", "e": 1831, "s": 1620, "text": null }, { "code": null, "e": 1840, "s": 1831, "text": "OUTPUT :" }, { "code": null, "e": 1850, "s": 1840, "text": "614022132" }, { "code": null, "e": 2002, "s": 1850, "text": "Sort Array in Ascending Order,According to Value – asort()The following function sorts an associative array in ascending order, according to the value:" }, { "code": null, "e": 2010, "s": 2002, "text": "INPUT :" }, { "code": "<!DOCTYPE html><html><body> <?php$age = array(\"ayush\"=>\"23\", \"shankar\"=>\"47\", \"kailash\"=>\"41\");asort($age); foreach($age as $x => $x_value) { echo \"Key=\" . $x . \", Value=\" . $x_value; echo \"<br>\";}?> </body></html>", "e": 2234, "s": 2010, "text": null }, { "code": null, "e": 2243, "s": 2234, "text": "OUTPUT :" }, { "code": null, "e": 2305, "s": 2243, "text": "Key=Ayush, Value=23Key=Kailash, Value=41Key=Shankar, Value=47" }, { "code": null, "e": 2454, "s": 2305, "text": "Sort Array in Ascending Order, According to Key – ksort()The following function sorts an associative array in ascending order, according to the key:" }, { "code": null, "e": 2462, "s": 2454, "text": "INPUT :" }, { "code": "<!DOCTYPE html><html><body> <?php$age = array(\"ayush\"=>\"23\", \"shankar\"=>\"47\", \"kailash\"=>\"41\");ksort($age); foreach($age as $x => $x_value) { echo \"Key=\" . $x . \", Value=\" . $x_value; echo \"<br>\";}?> </body></html>", "e": 2686, "s": 2462, "text": null }, { "code": null, "e": 2695, "s": 2686, "text": "OUTPUT :" }, { "code": null, "e": 2757, "s": 2695, "text": "Key=Ayush, Value=23Key=Kailash, Value=41Key=Shankar, Value=47" }, { "code": null, "e": 2913, "s": 2757, "text": "Sort Array in Descending Order, According to Value – arsort()The following function sorts an associative array in descending order, according to the value." }, { "code": null, "e": 2921, "s": 2913, "text": "INPUT :" }, { "code": "<!DOCTYPE html><html><body> <?php$age = array(\"ayush\"=>\"23\", \"shankar\"=>\"47\", \"kailash\"=>\"41\");arsort($age); foreach($age as $x => $x_value) { echo \"Key=\" . $x . \", Value=\" . $x_value; echo \"<br>\";}?> </body></html>", "e": 3146, "s": 2921, "text": null }, { "code": null, "e": 3155, "s": 3146, "text": "OUTPUT :" }, { "code": null, "e": 3217, "s": 3155, "text": "Key=Shankar, Value=47Key=Kailash, Value=41Key=Ayush, Value=23" }, { "code": null, "e": 3369, "s": 3217, "text": "Sort Array in Descending Order, According to Key – krsort()The following function sorts an associative array in descending order, according to the key." }, { "code": null, "e": 3377, "s": 3369, "text": "INPUT :" }, { "code": "<!DOCTYPE html><html><body> <?php$age = array(\"ayush\"=>\"23\", \"shankar\"=>\"47\", \"kailash\"=>\"41\");krsort($age); foreach($age as $x => $x_value) { echo \"Key=\" . $x . \", Value=\" . $x_value; echo \"<br>\";}?> </body></html>", "e": 3602, "s": 3377, "text": null }, { "code": null, "e": 3611, "s": 3602, "text": "OUTPUT :" }, { "code": null, "e": 3673, "s": 3611, "text": "Key=Shankar, Value=47Key=Kailash, Value=41Key=Ayush, Value=23" }, { "code": null, "e": 3677, "s": 3673, "text": "PHP" }, { "code": null, "e": 3694, "s": 3677, "text": "Web Technologies" }, { "code": null, "e": 3698, "s": 3694, "text": "PHP" }, { "code": null, "e": 3796, "s": 3698, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3846, "s": 3796, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 3886, "s": 3846, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 3947, "s": 3886, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 3997, "s": 3947, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 4042, "s": 3997, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 4075, "s": 4042, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4137, "s": 4075, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4198, "s": 4137, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4248, "s": 4198, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python __iter__() and __next__() | Converting an object into an iterator
31 Aug, 2021 At many instances, we get a need to access an object like an iterator. One way is to form a generator loop but that extends the task and time taken by the programmer. Python eases this task by providing a built-in method __iter__() for this task.The __iter__() function returns an iterator for the given object (array, set, tuple, etc. or custom objects). It creates an object that can be accessed one element at a time using __next__() function, which generally comes in handy when dealing with loops. Syntax : iter(object) iter(callable, sentinel) Object: The object whose iterator has to be created. It can be a collection object like list or tuple or a user-defined object (using OOPS). Callable, Sentinel: Callable represents a callable object, and sentinel is the value at which the iteration is needed to be terminated, sentinel value represents the end of sequence being iterated. Exception : If we call the iterator after all the elements have been iterated, then StopIterationError is raised. The __iter__() function returns an iterator object that goes through each element of the given object. The next element can be accessed through __next__() function. In the case of callable object and sentinel value, the iteration is done until the value is found or the end of elements reached. In any case, the original object is not modified. Code #1 : Python3 # Python code demonstrating# basic use of iter()listA = ['a','e','i','o','u'] iter_listA = iter(listA) try: print( next(iter_listA)) print( next(iter_listA)) print( next(iter_listA)) print( next(iter_listA)) print( next(iter_listA)) print( next(iter_listA)) #StopIteration errorexcept: pass Output : a e i o u Code #2 : Python3 # Python code demonstrating# basic use of iter()lst = [11, 22, 33, 44, 55] iter_lst = iter(lst)while True: try: print(iter_lst.__next__()) except: break Output : 11 22 33 44 55 Code #3 : Python3 # Python code demonstrating# basic use of iter() listB = ['Cat', 'Bat', 'Sat', 'Mat'] iter_listB = listB.__iter__() try: print(iter_listB.__next__()) print(iter_listB.__next__()) print(iter_listB.__next__()) print(iter_listB.__next__()) print(iter_listB.__next__()) #StopIteration errorexcept: print(" \nThrowing 'StopIterationError'", "I cannot count more.") Output : Cat Bat Sat Mat Throwing 'StopIterationError' I cannot count more. Code #4 : User-defined objects (using OOPS) Python3 # Python code showing use of iter() using OOPs class Counter: def __init__(self, start, end): self.num = start self.end = end def __iter__(self): return self def __next__(self): if self.num > self.end: raise StopIteration else: self.num += 1 return self.num - 1 # Driver codeif __name__ == '__main__' : a, b = 2, 5 c1 = Counter(a, b) c2 = Counter(a, b) # Way 1-to print the range without iter() print ("Print the range without iter()") for i in c1: print ("Eating more Pizzas, counting ", i, end ="\n") print ("\nPrint the range using iter()\n") # Way 2- using iter() obj = iter(c2) try: while True: # Print till error raised print ("Eating more Pizzas, counting ", next(obj)) except: # when StopIteration raised, Print custom message print ("\nDead on overfood, GAME OVER") Print the range without iter() Eating more Pizzas, counting 2 Eating more Pizzas, counting 3 Eating more Pizzas, counting 4 Eating more Pizzas, counting 5 Print the range using iter() Eating more Pizzas, counting 2 Eating more Pizzas, counting 3 Eating more Pizzas, counting 4 Eating more Pizzas, counting 5 Dead on overfood, GAME OVER gulshankumarar231 Python-Built-in-functions Python-Functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Taking input in Python Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ?
[ { "code": null, "e": 54, "s": 26, "text": "\n31 Aug, 2021" }, { "code": null, "e": 557, "s": 54, "text": "At many instances, we get a need to access an object like an iterator. One way is to form a generator loop but that extends the task and time taken by the programmer. Python eases this task by providing a built-in method __iter__() for this task.The __iter__() function returns an iterator for the given object (array, set, tuple, etc. or custom objects). It creates an object that can be accessed one element at a time using __next__() function, which generally comes in handy when dealing with loops." }, { "code": null, "e": 567, "s": 557, "text": "Syntax : " }, { "code": null, "e": 605, "s": 567, "text": "iter(object)\niter(callable, sentinel)" }, { "code": null, "e": 746, "s": 605, "text": "Object: The object whose iterator has to be created. It can be a collection object like list or tuple or a user-defined object (using OOPS)." }, { "code": null, "e": 944, "s": 746, "text": "Callable, Sentinel: Callable represents a callable object, and sentinel is the value at which the iteration is needed to be terminated, sentinel value represents the end of sequence being iterated." }, { "code": null, "e": 958, "s": 944, "text": "Exception : " }, { "code": null, "e": 1061, "s": 958, "text": "If we call the iterator after all the elements have \nbeen iterated, then StopIterationError is raised." }, { "code": null, "e": 1406, "s": 1061, "text": "The __iter__() function returns an iterator object that goes through each element of the given object. The next element can be accessed through __next__() function. In the case of callable object and sentinel value, the iteration is done until the value is found or the end of elements reached. In any case, the original object is not modified." }, { "code": null, "e": 1418, "s": 1406, "text": "Code #1 : " }, { "code": null, "e": 1426, "s": 1418, "text": "Python3" }, { "code": "# Python code demonstrating# basic use of iter()listA = ['a','e','i','o','u'] iter_listA = iter(listA) try: print( next(iter_listA)) print( next(iter_listA)) print( next(iter_listA)) print( next(iter_listA)) print( next(iter_listA)) print( next(iter_listA)) #StopIteration errorexcept: pass", "e": 1738, "s": 1426, "text": null }, { "code": null, "e": 1748, "s": 1738, "text": "Output : " }, { "code": null, "e": 1758, "s": 1748, "text": "a\ne\ni\no\nu" }, { "code": null, "e": 1769, "s": 1758, "text": "Code #2 : " }, { "code": null, "e": 1777, "s": 1769, "text": "Python3" }, { "code": "# Python code demonstrating# basic use of iter()lst = [11, 22, 33, 44, 55] iter_lst = iter(lst)while True: try: print(iter_lst.__next__()) except: break", "e": 1950, "s": 1777, "text": null }, { "code": null, "e": 1960, "s": 1950, "text": "Output : " }, { "code": null, "e": 1975, "s": 1960, "text": "11\n22\n33\n44\n55" }, { "code": null, "e": 1987, "s": 1975, "text": "Code #3 : " }, { "code": null, "e": 1995, "s": 1987, "text": "Python3" }, { "code": "# Python code demonstrating# basic use of iter() listB = ['Cat', 'Bat', 'Sat', 'Mat'] iter_listB = listB.__iter__() try: print(iter_listB.__next__()) print(iter_listB.__next__()) print(iter_listB.__next__()) print(iter_listB.__next__()) print(iter_listB.__next__()) #StopIteration errorexcept: print(\" \\nThrowing 'StopIterationError'\", \"I cannot count more.\")", "e": 2394, "s": 1995, "text": null }, { "code": null, "e": 2404, "s": 2394, "text": "Output : " }, { "code": null, "e": 2473, "s": 2404, "text": "Cat\nBat\nSat\nMat\n \nThrowing 'StopIterationError' I cannot count more." }, { "code": null, "e": 2518, "s": 2473, "text": "Code #4 : User-defined objects (using OOPS) " }, { "code": null, "e": 2526, "s": 2518, "text": "Python3" }, { "code": "# Python code showing use of iter() using OOPs class Counter: def __init__(self, start, end): self.num = start self.end = end def __iter__(self): return self def __next__(self): if self.num > self.end: raise StopIteration else: self.num += 1 return self.num - 1 # Driver codeif __name__ == '__main__' : a, b = 2, 5 c1 = Counter(a, b) c2 = Counter(a, b) # Way 1-to print the range without iter() print (\"Print the range without iter()\") for i in c1: print (\"Eating more Pizzas, counting \", i, end =\"\\n\") print (\"\\nPrint the range using iter()\\n\") # Way 2- using iter() obj = iter(c2) try: while True: # Print till error raised print (\"Eating more Pizzas, counting \", next(obj)) except: # when StopIteration raised, Print custom message print (\"\\nDead on overfood, GAME OVER\")", "e": 3507, "s": 2526, "text": null }, { "code": null, "e": 3854, "s": 3507, "text": "Print the range without iter()\nEating more Pizzas, counting 2\nEating more Pizzas, counting 3\nEating more Pizzas, counting 4\nEating more Pizzas, counting 5\n\nPrint the range using iter()\n\nEating more Pizzas, counting 2\nEating more Pizzas, counting 3\nEating more Pizzas, counting 4\nEating more Pizzas, counting 5\n\nDead on overfood, GAME OVER" }, { "code": null, "e": 3872, "s": 3854, "text": "gulshankumarar231" }, { "code": null, "e": 3898, "s": 3872, "text": "Python-Built-in-functions" }, { "code": null, "e": 3915, "s": 3898, "text": "Python-Functions" }, { "code": null, "e": 3922, "s": 3915, "text": "Python" }, { "code": null, "e": 4020, "s": 3922, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4048, "s": 4020, "text": "Read JSON file using Python" }, { "code": null, "e": 4098, "s": 4048, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 4120, "s": 4098, "text": "Python map() function" }, { "code": null, "e": 4164, "s": 4120, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 4206, "s": 4164, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4229, "s": 4206, "text": "Taking input in Python" }, { "code": null, "e": 4251, "s": 4229, "text": "Enumerate() in Python" }, { "code": null, "e": 4286, "s": 4251, "text": "Read a file line by line in Python" }, { "code": null, "e": 4312, "s": 4286, "text": "Python String | replace()" } ]
ImageView ScaleType in Android with Example
29 Dec, 2021 ScaleType is used for uniformly scaling the image bounds to the ImageView. Android ImageView provides various types of ScaleType for different configurations. CENTER CENTER_CROP CENTER_INSIDE FIT_CENTER FIT_END FIT_START FIT_XY MATRIX Now, we will look at each of these ScaleType in detail. For exploring these scale types we will use the GeeksforGeeks logo as our image resource also set the background color of ImageView as black for the reference purpose. 1. CENTER This scale type will center the image inside the view. But, it does not perform any scale to the image. Below is the code for the CENTER scale type. XML <ImageView android:id="@+id/simpleImageView" android:layout_width="fill_parent" android:layout_height="200dp" android:scaleType="center" android:src="@drawable/gfg" android:background="@color/black" tools:ignore="MissingConstraints" /> CENTER 2. CENTER_CROP This scale type scale the image uniformly .i.e., maintain the image’s aspect ratio in order to make the dimensions(width and height) equal to or larger than the ImageView dimension. XML <ImageView android:id="@+id/simpleImageView" android:layout_width="fill_parent" android:layout_height="200dp" android:scaleType="centerCrop" android:src="@drawable/gfg" android:background="@color/black" tools:ignore="MissingConstraints" /> CENTER_CROP 3. CENTER_INSIDE CENTER_INSIDE will center the image inside the ImageView container. This scale type does not match the image edge to the edge of the view. XML <ImageView android:id="@+id/simpleImageView" android:layout_width="fill_parent" android:layout_height="200dp" android:scaleType="centerInside" android:src="@drawable/gfg" android:background="@color/black" tools:ignore="MissingConstraints" /> CENTER_INSIDE 4. FIT_CENTER It will scale the image from the center. FIT_CENTER makes sure that the image is completely fit inside the ImageView and the image’s vertical or the horizontal axis is going to be exactly the same as the view. XML <ImageView android:id="@+id/simpleImageView" android:layout_width="fill_parent" android:layout_height="200dp" android:scaleType="fitCenter" android:src="@drawable/gfg" android:background="@color/black" tools:ignore="MissingConstraints" /> FIT_CENTER 5. FIT_END It is used to scale the image file to the end of the view(ImageView). This scale type scale the image from the end of the container. XML <ImageView android:id="@+id/simpleImageView" android:layout_width="fill_parent" android:layout_height="200dp" android:scaleType="fitEnd" android:src="@drawable/gfg" android:background="@color/black" tools:ignore="MissingConstraints" /> FIT_END 6. FIT_START This is used to scale the image to the start of the container. FIT_START scale the image from the start of the container. XML <ImageView android:id="@+id/simpleImageView" android:layout_width="fill_parent" android:layout_height="200dp" android:scaleType="fitStart" android:src="@drawable/gfg" android:background="@color/black" tools:ignore="MissingConstraints" /> FIT_START 7. FIT_XY FIT_XY done the scaling using the fill attribute. It will fill the image from the X and Y coordinates of ImageView. XML <ImageView android:id="@+id/simpleImageView" android:layout_width="fill_parent" android:layout_height="200dp" android:scaleType="fitXY" android:src="@drawable/gfg" android:background="@color/black" tools:ignore="MissingConstraints" /> FIT_XY 8. MATRIX It is used to scale the image using the image matrix when drawing. It is recommended to use whenever you want to customize the way you want to rotate the image or scale the image etc. XML <ImageView android:id="@+id/simpleImageView" android:layout_width="fill_parent" android:layout_height="200dp" android:scaleType="matrix" android:src="@drawable/gfg" android:background="@color/black" tools:ignore="MissingConstraints" /> MATRIX In this example, we will perform scaling using the various scale type attributes on the click event listener of a button and shows the image with various scale type, and also toast a message for the name of the scale type. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Adding resources Before moving further, we will add the following color attributes in our colors.xml resource file. Go to res > values > colors.xml and add them. XML <resources> <color name="colorPrimary">#0F9D58</color> <color name="colorPrimaryDark">#16E37F</color> <color name="colorAccent">#03DAC5</color></resources> Step 3: Creating the layout file In this step, we will create the layout for our application. For this, we are using the buttons for various scale types. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <ImageView android:id="@+id/st_image" android:layout_width="fill_parent" android:layout_height="200dp" android:src="@drawable/gfg" android:background="@color/black" tools:ignore="MissingConstraints" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/st_center" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:layout_margin="8dp" android:backgroundTint="@color/colorPrimary" android:text="CENTER"/> <Button android:id="@+id/st_center_crop" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="8dp" android:layout_weight="1" android:backgroundTint="@color/colorPrimary" android:text="CENTER_CROP"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/st_center_inside" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:backgroundTint="@color/colorPrimary" android:layout_margin="8dp" android:text="CENTER_INSIDE"/> <Button android:id="@+id/st_fit_center" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="8dp" android:layout_weight="1" android:backgroundTint="@color/colorPrimary" android:text="FIT_CENTER"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/st_fit_end" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:layout_margin="8dp" android:backgroundTint="@color/colorPrimary" android:text="FIT_END"/> <Button android:id="@+id/st_fit_start" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="8dp" android:backgroundTint="@color/colorPrimary" android:layout_weight="1" android:text="FIT_START"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/st_fit_xy" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:layout_margin="8dp" android:backgroundTint="@color/colorPrimary" android:text="FIT_XY"/> <Button android:id="@+id/st_matrix" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="8dp" android:layout_weight="1" android:backgroundTint="@color/colorPrimary" android:text="MATRIX"/> </LinearLayout> </LinearLayout> Step 4: Working with MainActivity.java file In this step, we will initialize our ImageView and Buttons and attach a listener to them. On completion of the listener event, a toast message will be shown about the name of the scale type. We can also setup the scale type using java code. Below is the code for the MainActivity.java file. Java import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private ImageView img; private Button center, center_crop, center_inside, fit_center, fit_end, fit_start, fit_xy, matrix; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initializing method.. init(); } private void init(){ img = findViewById(R.id.st_image); center = findViewById(R.id.st_center); center.setOnClickListener((View.OnClickListener) this); center_crop = findViewById(R.id.st_center_crop); center_crop.setOnClickListener((View.OnClickListener) this); center_inside = findViewById(R.id.st_center_inside); center_inside.setOnClickListener((View.OnClickListener) this); fit_center = findViewById(R.id.st_fit_center); fit_center.setOnClickListener((View.OnClickListener) this); fit_end = findViewById(R.id.st_fit_end); fit_end.setOnClickListener((View.OnClickListener) this); fit_start = findViewById(R.id.st_fit_start); fit_start.setOnClickListener((View.OnClickListener) this); fit_xy = findViewById(R.id.st_fit_xy); fit_xy.setOnClickListener((View.OnClickListener) this); matrix = findViewById(R.id.st_matrix); matrix.setOnClickListener((View.OnClickListener) this); } public void onClick(View view){ switch (view.getId()){ case R.id.st_center: img.setScaleType(ImageView.ScaleType.CENTER); Toast.makeText(this, "SCALE TYPE - CENTER", Toast.LENGTH_SHORT).show(); break; case R.id.st_center_crop: img.setScaleType(ImageView.ScaleType.CENTER_CROP); Toast.makeText(this, "SCALE TYPE - CENTER_CROP", Toast.LENGTH_SHORT).show(); break; case R.id.st_center_inside: img.setScaleType(ImageView.ScaleType.CENTER_INSIDE); Toast.makeText(this, "SCALE TYPE - CENTER_INSIDE", Toast.LENGTH_SHORT).show(); break; case R.id.st_fit_center: img.setScaleType(ImageView.ScaleType.FIT_CENTER); Toast.makeText(this, "SCALE TYPE - FIT_CENTER", Toast.LENGTH_SHORT).show(); break; case R.id.st_fit_end: img.setScaleType(ImageView.ScaleType.FIT_END); Toast.makeText(this, "SCALE TYPE - FIT_END", Toast.LENGTH_SHORT).show(); break; case R.id.st_fit_start: img.setScaleType(ImageView.ScaleType.FIT_START); Toast.makeText(this, "SCALE TYPE - FIT_START", Toast.LENGTH_SHORT).show(); break; case R.id.st_fit_xy: img.setScaleType(ImageView.ScaleType.FIT_XY); Toast.makeText(this, "SCALE TYPE - FIT_XY", Toast.LENGTH_SHORT).show(); break; case R.id.st_matrix: img.setScaleType(ImageView.ScaleType.MATRIX); Toast.makeText(this, "SCALE TYPE - MATRIX", Toast.LENGTH_SHORT).show(); break; } } } Output: Picked Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Dec, 2021" }, { "code": null, "e": 187, "s": 28, "text": "ScaleType is used for uniformly scaling the image bounds to the ImageView. Android ImageView provides various types of ScaleType for different configurations." }, { "code": null, "e": 195, "s": 187, "text": "CENTER " }, { "code": null, "e": 207, "s": 195, "text": "CENTER_CROP" }, { "code": null, "e": 221, "s": 207, "text": "CENTER_INSIDE" }, { "code": null, "e": 232, "s": 221, "text": "FIT_CENTER" }, { "code": null, "e": 240, "s": 232, "text": "FIT_END" }, { "code": null, "e": 250, "s": 240, "text": "FIT_START" }, { "code": null, "e": 257, "s": 250, "text": "FIT_XY" }, { "code": null, "e": 264, "s": 257, "text": "MATRIX" }, { "code": null, "e": 488, "s": 264, "text": "Now, we will look at each of these ScaleType in detail. For exploring these scale types we will use the GeeksforGeeks logo as our image resource also set the background color of ImageView as black for the reference purpose." }, { "code": null, "e": 498, "s": 488, "text": "1. CENTER" }, { "code": null, "e": 647, "s": 498, "text": "This scale type will center the image inside the view. But, it does not perform any scale to the image. Below is the code for the CENTER scale type." }, { "code": null, "e": 651, "s": 647, "text": "XML" }, { "code": "<ImageView android:id=\"@+id/simpleImageView\" android:layout_width=\"fill_parent\" android:layout_height=\"200dp\" android:scaleType=\"center\" android:src=\"@drawable/gfg\" android:background=\"@color/black\" tools:ignore=\"MissingConstraints\" />", "e": 936, "s": 651, "text": null }, { "code": null, "e": 943, "s": 936, "text": "CENTER" }, { "code": null, "e": 958, "s": 943, "text": "2. CENTER_CROP" }, { "code": null, "e": 1141, "s": 958, "text": "This scale type scale the image uniformly .i.e., maintain the image’s aspect ratio in order to make the dimensions(width and height) equal to or larger than the ImageView dimension." }, { "code": null, "e": 1145, "s": 1141, "text": "XML" }, { "code": "<ImageView android:id=\"@+id/simpleImageView\" android:layout_width=\"fill_parent\" android:layout_height=\"200dp\" android:scaleType=\"centerCrop\" android:src=\"@drawable/gfg\" android:background=\"@color/black\" tools:ignore=\"MissingConstraints\" />", "e": 1434, "s": 1145, "text": null }, { "code": null, "e": 1446, "s": 1434, "text": "CENTER_CROP" }, { "code": null, "e": 1463, "s": 1446, "text": "3. CENTER_INSIDE" }, { "code": null, "e": 1602, "s": 1463, "text": "CENTER_INSIDE will center the image inside the ImageView container. This scale type does not match the image edge to the edge of the view." }, { "code": null, "e": 1606, "s": 1602, "text": "XML" }, { "code": "<ImageView android:id=\"@+id/simpleImageView\" android:layout_width=\"fill_parent\" android:layout_height=\"200dp\" android:scaleType=\"centerInside\" android:src=\"@drawable/gfg\" android:background=\"@color/black\" tools:ignore=\"MissingConstraints\" />", "e": 1897, "s": 1606, "text": null }, { "code": null, "e": 1911, "s": 1897, "text": "CENTER_INSIDE" }, { "code": null, "e": 1925, "s": 1911, "text": "4. FIT_CENTER" }, { "code": null, "e": 2135, "s": 1925, "text": "It will scale the image from the center. FIT_CENTER makes sure that the image is completely fit inside the ImageView and the image’s vertical or the horizontal axis is going to be exactly the same as the view." }, { "code": null, "e": 2139, "s": 2135, "text": "XML" }, { "code": "<ImageView android:id=\"@+id/simpleImageView\" android:layout_width=\"fill_parent\" android:layout_height=\"200dp\" android:scaleType=\"fitCenter\" android:src=\"@drawable/gfg\" android:background=\"@color/black\" tools:ignore=\"MissingConstraints\" />", "e": 2427, "s": 2139, "text": null }, { "code": null, "e": 2438, "s": 2427, "text": "FIT_CENTER" }, { "code": null, "e": 2449, "s": 2438, "text": "5. FIT_END" }, { "code": null, "e": 2582, "s": 2449, "text": "It is used to scale the image file to the end of the view(ImageView). This scale type scale the image from the end of the container." }, { "code": null, "e": 2586, "s": 2582, "text": "XML" }, { "code": "<ImageView android:id=\"@+id/simpleImageView\" android:layout_width=\"fill_parent\" android:layout_height=\"200dp\" android:scaleType=\"fitEnd\" android:src=\"@drawable/gfg\" android:background=\"@color/black\" tools:ignore=\"MissingConstraints\" />", "e": 2871, "s": 2586, "text": null }, { "code": null, "e": 2879, "s": 2871, "text": "FIT_END" }, { "code": null, "e": 2892, "s": 2879, "text": "6. FIT_START" }, { "code": null, "e": 3014, "s": 2892, "text": "This is used to scale the image to the start of the container. FIT_START scale the image from the start of the container." }, { "code": null, "e": 3018, "s": 3014, "text": "XML" }, { "code": "<ImageView android:id=\"@+id/simpleImageView\" android:layout_width=\"fill_parent\" android:layout_height=\"200dp\" android:scaleType=\"fitStart\" android:src=\"@drawable/gfg\" android:background=\"@color/black\" tools:ignore=\"MissingConstraints\" />", "e": 3305, "s": 3018, "text": null }, { "code": null, "e": 3315, "s": 3305, "text": "FIT_START" }, { "code": null, "e": 3326, "s": 3315, "text": "7. FIT_XY" }, { "code": null, "e": 3442, "s": 3326, "text": "FIT_XY done the scaling using the fill attribute. It will fill the image from the X and Y coordinates of ImageView." }, { "code": null, "e": 3446, "s": 3442, "text": "XML" }, { "code": "<ImageView android:id=\"@+id/simpleImageView\" android:layout_width=\"fill_parent\" android:layout_height=\"200dp\" android:scaleType=\"fitXY\" android:src=\"@drawable/gfg\" android:background=\"@color/black\" tools:ignore=\"MissingConstraints\" />", "e": 3730, "s": 3446, "text": null }, { "code": null, "e": 3737, "s": 3730, "text": "FIT_XY" }, { "code": null, "e": 3747, "s": 3737, "text": "8. MATRIX" }, { "code": null, "e": 3931, "s": 3747, "text": "It is used to scale the image using the image matrix when drawing. It is recommended to use whenever you want to customize the way you want to rotate the image or scale the image etc." }, { "code": null, "e": 3935, "s": 3931, "text": "XML" }, { "code": "<ImageView android:id=\"@+id/simpleImageView\" android:layout_width=\"fill_parent\" android:layout_height=\"200dp\" android:scaleType=\"matrix\" android:src=\"@drawable/gfg\" android:background=\"@color/black\" tools:ignore=\"MissingConstraints\" />", "e": 4220, "s": 3935, "text": null }, { "code": null, "e": 4227, "s": 4220, "text": "MATRIX" }, { "code": null, "e": 4450, "s": 4227, "text": "In this example, we will perform scaling using the various scale type attributes on the click event listener of a button and shows the image with various scale type, and also toast a message for the name of the scale type." }, { "code": null, "e": 4479, "s": 4450, "text": "Step 1: Create a New Project" }, { "code": null, "e": 4641, "s": 4479, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 4666, "s": 4641, "text": "Step 2: Adding resources" }, { "code": null, "e": 4811, "s": 4666, "text": "Before moving further, we will add the following color attributes in our colors.xml resource file. Go to res > values > colors.xml and add them." }, { "code": null, "e": 4815, "s": 4811, "text": "XML" }, { "code": "<resources> <color name=\"colorPrimary\">#0F9D58</color> <color name=\"colorPrimaryDark\">#16E37F</color> <color name=\"colorAccent\">#03DAC5</color></resources>", "e": 4980, "s": 4815, "text": null }, { "code": null, "e": 5013, "s": 4980, "text": "Step 3: Creating the layout file" }, { "code": null, "e": 5184, "s": 5013, "text": "In this step, we will create the layout for our application. For this, we are using the buttons for various scale types. Below is the code for the activity_main.xml file." }, { "code": null, "e": 5188, "s": 5184, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <ImageView android:id=\"@+id/st_image\" android:layout_width=\"fill_parent\" android:layout_height=\"200dp\" android:src=\"@drawable/gfg\" android:background=\"@color/black\" tools:ignore=\"MissingConstraints\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\"> <Button android:id=\"@+id/st_center\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:layout_margin=\"8dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"CENTER\"/> <Button android:id=\"@+id/st_center_crop\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"8dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"CENTER_CROP\"/> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\"> <Button android:id=\"@+id/st_center_inside\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:backgroundTint=\"@color/colorPrimary\" android:layout_margin=\"8dp\" android:text=\"CENTER_INSIDE\"/> <Button android:id=\"@+id/st_fit_center\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"8dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"FIT_CENTER\"/> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\"> <Button android:id=\"@+id/st_fit_end\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:layout_margin=\"8dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"FIT_END\"/> <Button android:id=\"@+id/st_fit_start\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"8dp\" android:backgroundTint=\"@color/colorPrimary\" android:layout_weight=\"1\" android:text=\"FIT_START\"/> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\"> <Button android:id=\"@+id/st_fit_xy\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:layout_margin=\"8dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"FIT_XY\"/> <Button android:id=\"@+id/st_matrix\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"8dp\" android:layout_weight=\"1\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"MATRIX\"/> </LinearLayout> </LinearLayout>", "e": 9006, "s": 5188, "text": null }, { "code": null, "e": 9050, "s": 9006, "text": "Step 4: Working with MainActivity.java file" }, { "code": null, "e": 9342, "s": 9050, "text": "In this step, we will initialize our ImageView and Buttons and attach a listener to them. On completion of the listener event, a toast message will be shown about the name of the scale type. We can also setup the scale type using java code. Below is the code for the MainActivity.java file." }, { "code": null, "e": 9347, "s": 9342, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private ImageView img; private Button center, center_crop, center_inside, fit_center, fit_end, fit_start, fit_xy, matrix; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initializing method.. init(); } private void init(){ img = findViewById(R.id.st_image); center = findViewById(R.id.st_center); center.setOnClickListener((View.OnClickListener) this); center_crop = findViewById(R.id.st_center_crop); center_crop.setOnClickListener((View.OnClickListener) this); center_inside = findViewById(R.id.st_center_inside); center_inside.setOnClickListener((View.OnClickListener) this); fit_center = findViewById(R.id.st_fit_center); fit_center.setOnClickListener((View.OnClickListener) this); fit_end = findViewById(R.id.st_fit_end); fit_end.setOnClickListener((View.OnClickListener) this); fit_start = findViewById(R.id.st_fit_start); fit_start.setOnClickListener((View.OnClickListener) this); fit_xy = findViewById(R.id.st_fit_xy); fit_xy.setOnClickListener((View.OnClickListener) this); matrix = findViewById(R.id.st_matrix); matrix.setOnClickListener((View.OnClickListener) this); } public void onClick(View view){ switch (view.getId()){ case R.id.st_center: img.setScaleType(ImageView.ScaleType.CENTER); Toast.makeText(this, \"SCALE TYPE - CENTER\", Toast.LENGTH_SHORT).show(); break; case R.id.st_center_crop: img.setScaleType(ImageView.ScaleType.CENTER_CROP); Toast.makeText(this, \"SCALE TYPE - CENTER_CROP\", Toast.LENGTH_SHORT).show(); break; case R.id.st_center_inside: img.setScaleType(ImageView.ScaleType.CENTER_INSIDE); Toast.makeText(this, \"SCALE TYPE - CENTER_INSIDE\", Toast.LENGTH_SHORT).show(); break; case R.id.st_fit_center: img.setScaleType(ImageView.ScaleType.FIT_CENTER); Toast.makeText(this, \"SCALE TYPE - FIT_CENTER\", Toast.LENGTH_SHORT).show(); break; case R.id.st_fit_end: img.setScaleType(ImageView.ScaleType.FIT_END); Toast.makeText(this, \"SCALE TYPE - FIT_END\", Toast.LENGTH_SHORT).show(); break; case R.id.st_fit_start: img.setScaleType(ImageView.ScaleType.FIT_START); Toast.makeText(this, \"SCALE TYPE - FIT_START\", Toast.LENGTH_SHORT).show(); break; case R.id.st_fit_xy: img.setScaleType(ImageView.ScaleType.FIT_XY); Toast.makeText(this, \"SCALE TYPE - FIT_XY\", Toast.LENGTH_SHORT).show(); break; case R.id.st_matrix: img.setScaleType(ImageView.ScaleType.MATRIX); Toast.makeText(this, \"SCALE TYPE - MATRIX\", Toast.LENGTH_SHORT).show(); break; } } }", "e": 12754, "s": 9347, "text": null }, { "code": null, "e": 12762, "s": 12754, "text": "Output:" }, { "code": null, "e": 12769, "s": 12762, "text": "Picked" }, { "code": null, "e": 12777, "s": 12769, "text": "Android" }, { "code": null, "e": 12782, "s": 12777, "text": "Java" }, { "code": null, "e": 12787, "s": 12782, "text": "Java" }, { "code": null, "e": 12795, "s": 12787, "text": "Android" } ]
PostgreSQL – Create Auto-increment Column using SERIAL
28 Aug, 2020 In PostgreSQL, a sequence is a special kind of database object that generates a sequence of integers. A sequence is often used as the primary key column in a table.The SERIAL pseudo-type can be used to generate a sequence while creating a new table. Syntax: CREATE TABLE table_name( id SERIAL ); In the above syntax by setting the SERIAL pseudo-type to the id column, PostgreSQL performs the following: First, create a sequence object and set the next value generated by the sequence as the default value for the column. Second, add a NOT NULL constraint to the id column because a sequence always generates an integer, which is a non-null value. Third, assign the owner of the sequence to the id column; as a result, the sequence object is deleted when the id column or table is dropped. The above syntax is equivalent to the below statement: CREATE SEQUENCE table_name_id_seq; CREATE TABLE table_name ( id integer NOT NULL DEFAULT nextval('table_name_id_seq') ); ALTER SEQUENCE table_name_id_seq OWNED BY table_name.id; PostgreSQL provides three serial pseudo-types SMALLSERIAL, SERIAL, and BIGSERIAL with the following characteristics: Now let’s look into an example for better understanding.Example:The following statement creates the animals table with the id column as the SERIAL column: CREATE TABLE animals( id SERIAL PRIMARY KEY, name VARCHAR NOT NULL ); Now we will insert a single value to the animal table as below: INSERT INTO animals(name) VALUES('Dog'); We repeat the above statement wit5h a different value as below: INSERT INTO animals(name) VALUES('Cat'); PostgreSQL inserted two rows into the animals table with the values for the id column are 1 and 2. To verify so use the below statement: SELECT * FROM animals; Output: Example 2:The following statement inserts a new row into the animals table and returns the value generated for the id column: INSERT INTO animals(name) VALUES('Tiger') RETURNING id; Output: postgreSQL-managing-table PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - IF Statement PostgreSQL - LIMIT with OFFSET clause PostgreSQL - SELECT PostgreSQL - REPLACE Function PostgreSQL - GROUP BY clause PostgreSQL - Create Database PostgreSQL Tutorial PostgreSQL - FETCH clause PostgreSQL - INSERT PostgreSQL - BETWEEN operator
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Aug, 2020" }, { "code": null, "e": 278, "s": 28, "text": "In PostgreSQL, a sequence is a special kind of database object that generates a sequence of integers. A sequence is often used as the primary key column in a table.The SERIAL pseudo-type can be used to generate a sequence while creating a new table." }, { "code": null, "e": 328, "s": 278, "text": "Syntax:\nCREATE TABLE table_name(\n id SERIAL\n);" }, { "code": null, "e": 435, "s": 328, "text": "In the above syntax by setting the SERIAL pseudo-type to the id column, PostgreSQL performs the following:" }, { "code": null, "e": 553, "s": 435, "text": "First, create a sequence object and set the next value generated by the sequence as the default value for the column." }, { "code": null, "e": 679, "s": 553, "text": "Second, add a NOT NULL constraint to the id column because a sequence always generates an integer, which is a non-null value." }, { "code": null, "e": 821, "s": 679, "text": "Third, assign the owner of the sequence to the id column; as a result, the sequence object is deleted when the id column or table is dropped." }, { "code": null, "e": 876, "s": 821, "text": "The above syntax is equivalent to the below statement:" }, { "code": null, "e": 1060, "s": 876, "text": "CREATE SEQUENCE table_name_id_seq;\n\nCREATE TABLE table_name (\n id integer NOT NULL DEFAULT nextval('table_name_id_seq')\n);\n\nALTER SEQUENCE table_name_id_seq\nOWNED BY table_name.id;" }, { "code": null, "e": 1177, "s": 1060, "text": "PostgreSQL provides three serial pseudo-types SMALLSERIAL, SERIAL, and BIGSERIAL with the following characteristics:" }, { "code": null, "e": 1332, "s": 1177, "text": "Now let’s look into an example for better understanding.Example:The following statement creates the animals table with the id column as the SERIAL column:" }, { "code": null, "e": 1408, "s": 1332, "text": "CREATE TABLE animals(\n id SERIAL PRIMARY KEY,\n name VARCHAR NOT NULL\n);" }, { "code": null, "e": 1472, "s": 1408, "text": "Now we will insert a single value to the animal table as below:" }, { "code": null, "e": 1514, "s": 1472, "text": "INSERT INTO animals(name) \nVALUES('Dog');" }, { "code": null, "e": 1578, "s": 1514, "text": "We repeat the above statement wit5h a different value as below:" }, { "code": null, "e": 1620, "s": 1578, "text": "INSERT INTO animals(name) \nVALUES('Cat');" }, { "code": null, "e": 1757, "s": 1620, "text": "PostgreSQL inserted two rows into the animals table with the values for the id column are 1 and 2. To verify so use the below statement:" }, { "code": null, "e": 1780, "s": 1757, "text": "SELECT * FROM animals;" }, { "code": null, "e": 1788, "s": 1780, "text": "Output:" }, { "code": null, "e": 1914, "s": 1788, "text": "Example 2:The following statement inserts a new row into the animals table and returns the value generated for the id column:" }, { "code": null, "e": 1972, "s": 1914, "text": "INSERT INTO animals(name) \nVALUES('Tiger')\nRETURNING id; " }, { "code": null, "e": 1980, "s": 1972, "text": "Output:" }, { "code": null, "e": 2006, "s": 1980, "text": "postgreSQL-managing-table" }, { "code": null, "e": 2017, "s": 2006, "text": "PostgreSQL" }, { "code": null, "e": 2115, "s": 2017, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2141, "s": 2115, "text": "PostgreSQL - IF Statement" }, { "code": null, "e": 2179, "s": 2141, "text": "PostgreSQL - LIMIT with OFFSET clause" }, { "code": null, "e": 2199, "s": 2179, "text": "PostgreSQL - SELECT" }, { "code": null, "e": 2229, "s": 2199, "text": "PostgreSQL - REPLACE Function" }, { "code": null, "e": 2258, "s": 2229, "text": "PostgreSQL - GROUP BY clause" }, { "code": null, "e": 2287, "s": 2258, "text": "PostgreSQL - Create Database" }, { "code": null, "e": 2307, "s": 2287, "text": "PostgreSQL Tutorial" }, { "code": null, "e": 2333, "s": 2307, "text": "PostgreSQL - FETCH clause" }, { "code": null, "e": 2353, "s": 2333, "text": "PostgreSQL - INSERT" } ]
matplotlib.pyplot.scatter() in Python
15 Feb, 2022 Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. It is used for plotting various plots in Python like scatter plot, bar charts, pie charts, line plots, histograms, 3-D plots and many more. We will learn about the scatter plot from the matplotlib library. Note: For more information, refer to Python Matplotlib – An Overview Scatter plots are used to observe relationship between variables and uses dots to represent the relationship between them. The scatter() method in the matplotlib library is used to draw a scatter plot. Scatter plots are widely used to represent relation among variables and how change in one affects the other. Syntax The syntax for scatter() method is given below: matplotlib.pyplot.scatter(x_axis_data, y_axis_data, s=None, c=None, marker=None, cmap=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=None) The scatter() method takes in the following parameters: x_axis_data- An array containing x-axis data y_axis_data- An array containing y-axis data s- marker size (can be scalar or array of size equal to size of x or y) c- color of sequence of colors for markers marker- marker style cmap- cmap name linewidths- width of marker border edgecolor- marker border color alpha- blending value, between 0 (transparent) and 1 (opaque) Except x_axis_data and y_axis_data all other parameters are optional and their default value is None. Below are the scatter plot examples with various parameters.Example 1: This is the most basic example of a scatter plot. Python3 import matplotlib.pyplot as plt x =[5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6] y =[99, 86, 87, 88, 100, 86, 103, 87, 94, 78, 77, 85, 86] plt.scatter(x, y, c ="blue") # To show the plotplt.show() Output Example 2: Scatter plot with different shape and colour for two datasets. Python3 import matplotlib.pyplot as plt # dataset-1x1 = [89, 43, 36, 36, 95, 10, 66, 34, 38, 20] y1 = [21, 46, 3, 35, 67, 95, 53, 72, 58, 10] # dataset2x2 = [26, 29, 48, 64, 6, 5, 36, 66, 72, 40] y2 = [26, 34, 90, 33, 38, 20, 56, 2, 47, 15] plt.scatter(x1, y1, c ="pink", linewidths = 2, marker ="s", edgecolor ="green", s = 50) plt.scatter(x2, y2, c ="yellow", linewidths = 2, marker ="^", edgecolor ="red", s = 200) plt.xlabel("X-axis")plt.ylabel("Y-axis")plt.show() Output varshagumber28 simranarora5sos Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Feb, 2022" }, { "code": null, "e": 415, "s": 28, "text": "Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. It is used for plotting various plots in Python like scatter plot, bar charts, pie charts, line plots, histograms, 3-D plots and many more. We will learn about the scatter plot from the matplotlib library. Note: For more information, refer to Python Matplotlib – An Overview " }, { "code": null, "e": 782, "s": 415, "text": "Scatter plots are used to observe relationship between variables and uses dots to represent the relationship between them. The scatter() method in the matplotlib library is used to draw a scatter plot. Scatter plots are widely used to represent relation among variables and how change in one affects the other. Syntax The syntax for scatter() method is given below: " }, { "code": null, "e": 944, "s": 782, "text": "matplotlib.pyplot.scatter(x_axis_data, y_axis_data, s=None, c=None, marker=None, cmap=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=None) " }, { "code": null, "e": 1002, "s": 944, "text": "The scatter() method takes in the following parameters: " }, { "code": null, "e": 1047, "s": 1002, "text": "x_axis_data- An array containing x-axis data" }, { "code": null, "e": 1092, "s": 1047, "text": "y_axis_data- An array containing y-axis data" }, { "code": null, "e": 1164, "s": 1092, "text": "s- marker size (can be scalar or array of size equal to size of x or y)" }, { "code": null, "e": 1207, "s": 1164, "text": "c- color of sequence of colors for markers" }, { "code": null, "e": 1228, "s": 1207, "text": "marker- marker style" }, { "code": null, "e": 1244, "s": 1228, "text": "cmap- cmap name" }, { "code": null, "e": 1279, "s": 1244, "text": "linewidths- width of marker border" }, { "code": null, "e": 1310, "s": 1279, "text": "edgecolor- marker border color" }, { "code": null, "e": 1372, "s": 1310, "text": "alpha- blending value, between 0 (transparent) and 1 (opaque)" }, { "code": null, "e": 1597, "s": 1372, "text": "Except x_axis_data and y_axis_data all other parameters are optional and their default value is None. Below are the scatter plot examples with various parameters.Example 1: This is the most basic example of a scatter plot. " }, { "code": null, "e": 1605, "s": 1597, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt x =[5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6] y =[99, 86, 87, 88, 100, 86, 103, 87, 94, 78, 77, 85, 86] plt.scatter(x, y, c =\"blue\") # To show the plotplt.show()", "e": 1806, "s": 1605, "text": null }, { "code": null, "e": 1815, "s": 1806, "text": "Output " }, { "code": null, "e": 1891, "s": 1815, "text": "Example 2: Scatter plot with different shape and colour for two datasets. " }, { "code": null, "e": 1899, "s": 1891, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # dataset-1x1 = [89, 43, 36, 36, 95, 10, 66, 34, 38, 20] y1 = [21, 46, 3, 35, 67, 95, 53, 72, 58, 10] # dataset2x2 = [26, 29, 48, 64, 6, 5, 36, 66, 72, 40] y2 = [26, 34, 90, 33, 38, 20, 56, 2, 47, 15] plt.scatter(x1, y1, c =\"pink\", linewidths = 2, marker =\"s\", edgecolor =\"green\", s = 50) plt.scatter(x2, y2, c =\"yellow\", linewidths = 2, marker =\"^\", edgecolor =\"red\", s = 200) plt.xlabel(\"X-axis\")plt.ylabel(\"Y-axis\")plt.show()", "e": 2468, "s": 1899, "text": null }, { "code": null, "e": 2477, "s": 2468, "text": "Output " }, { "code": null, "e": 2494, "s": 2479, "text": "varshagumber28" }, { "code": null, "e": 2510, "s": 2494, "text": "simranarora5sos" }, { "code": null, "e": 2528, "s": 2510, "text": "Python-matplotlib" }, { "code": null, "e": 2535, "s": 2528, "text": "Python" } ]
UCASE() or UPPER() Function in MySQL
16 Jun, 2021 1. UCASE() : This function could be used to convert a string to upper-case. This function is similar to the UPPER() function. UPPER()\UCASE() are built-in MySQL function. Syntax : SELECT UCASE(text) Example – SELECT UCASE("MySQL on geeksforgeeks is FUN!") AS UpperText; Output : Now, here you will see UPPER function. 2. UPPER() : Syntax : SELECT UPPER(text) Example – SELECT UPPER("MySQL on geeksforgeeks is FUN!") AS UpperText; Output : Dealing with binary string data : The UPPER() function does not affect the binary strings such as BINARY, VARBINARY, or BLOB. Hence, to use binary string in the UPPER() function, it needed to convert to the string to non-binary string. Example – SET @str = BINARY 'Geeksforgeeks'; Now, If you want to read binary string used the following syntax given below. SELECT UPPER(@str), UPPER(CONVERT(@str USING utf8mb4)) AS UpperText; Output : Note – It is clearly observed from the output, the UPPER() function has no effect on the binary string. rajeev0719singh DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jun, 2021" }, { "code": null, "e": 200, "s": 28, "text": "1. UCASE() : This function could be used to convert a string to upper-case. This function is similar to the UPPER() function. UPPER()\\UCASE() are built-in MySQL function. " }, { "code": null, "e": 211, "s": 200, "text": "Syntax : " }, { "code": null, "e": 230, "s": 211, "text": "SELECT UCASE(text)" }, { "code": null, "e": 242, "s": 230, "text": "Example – " }, { "code": null, "e": 303, "s": 242, "text": "SELECT UCASE(\"MySQL on geeksforgeeks is FUN!\") AS UpperText;" }, { "code": null, "e": 313, "s": 303, "text": "Output : " }, { "code": null, "e": 355, "s": 315, "text": "Now, here you will see UPPER function. " }, { "code": null, "e": 369, "s": 355, "text": "2. UPPER() : " }, { "code": null, "e": 380, "s": 369, "text": "Syntax : " }, { "code": null, "e": 399, "s": 380, "text": "SELECT UPPER(text)" }, { "code": null, "e": 411, "s": 399, "text": "Example – " }, { "code": null, "e": 472, "s": 411, "text": "SELECT UPPER(\"MySQL on geeksforgeeks is FUN!\") AS UpperText;" }, { "code": null, "e": 482, "s": 472, "text": "Output : " }, { "code": null, "e": 721, "s": 484, "text": "Dealing with binary string data : The UPPER() function does not affect the binary strings such as BINARY, VARBINARY, or BLOB. Hence, to use binary string in the UPPER() function, it needed to convert to the string to non-binary string. " }, { "code": null, "e": 733, "s": 721, "text": "Example – " }, { "code": null, "e": 768, "s": 733, "text": "SET @str = BINARY 'Geeksforgeeks';" }, { "code": null, "e": 848, "s": 768, "text": "Now, If you want to read binary string used the following syntax given below. " }, { "code": null, "e": 917, "s": 848, "text": "SELECT UPPER(@str), UPPER(CONVERT(@str USING utf8mb4)) AS UpperText;" }, { "code": null, "e": 927, "s": 917, "text": "Output : " }, { "code": null, "e": 1034, "s": 929, "text": "Note – It is clearly observed from the output, the UPPER() function has no effect on the binary string. " }, { "code": null, "e": 1050, "s": 1034, "text": "rajeev0719singh" }, { "code": null, "e": 1059, "s": 1050, "text": "DBMS-SQL" }, { "code": null, "e": 1065, "s": 1059, "text": "mysql" }, { "code": null, "e": 1069, "s": 1065, "text": "SQL" }, { "code": null, "e": 1073, "s": 1069, "text": "SQL" } ]
Scala List min() method with example
26 Jul, 2019 The min() method is utilized to find the smallest element of all the elements in the stated list. Method Definition: def min[B >: A](implicit ord: math.Ordering[B]): A Return Type: It returns the smallest of all the elements in the stated list. Example #1: // Scala program of min()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 2, 3) // Applying min method val result = m1.min // Displays output println(result) }} 1 Example #2: // Scala program of min()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(5, 12, 3, 13) // Applying min method val result = m1.min // Displays output println(result) }} 3 Scala Scala-list Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Scala Map Scala Tutorial – Learn Scala with Step By Step Guide Scala Lists Scala | Arrays Lambda Expression in Scala How to Install Scala with VSCode? Enumeration in Scala How to get the first element of List in Scala HashMap in Scala Scala String replace() method with example
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jul, 2019" }, { "code": null, "e": 126, "s": 28, "text": "The min() method is utilized to find the smallest element of all the elements in the stated list." }, { "code": null, "e": 196, "s": 126, "text": "Method Definition: def min[B >: A](implicit ord: math.Ordering[B]): A" }, { "code": null, "e": 273, "s": 196, "text": "Return Type: It returns the smallest of all the elements in the stated list." }, { "code": null, "e": 285, "s": 273, "text": "Example #1:" }, { "code": "// Scala program of min()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 2, 3) // Applying min method val result = m1.min // Displays output println(result) }}", "e": 609, "s": 285, "text": null }, { "code": null, "e": 612, "s": 609, "text": "1\n" }, { "code": null, "e": 624, "s": 612, "text": "Example #2:" }, { "code": "// Scala program of min()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(5, 12, 3, 13) // Applying min method val result = m1.min // Displays output println(result) }}", "e": 953, "s": 624, "text": null }, { "code": null, "e": 956, "s": 953, "text": "3\n" }, { "code": null, "e": 962, "s": 956, "text": "Scala" }, { "code": null, "e": 973, "s": 962, "text": "Scala-list" }, { "code": null, "e": 986, "s": 973, "text": "Scala-Method" }, { "code": null, "e": 992, "s": 986, "text": "Scala" }, { "code": null, "e": 1090, "s": 992, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1100, "s": 1090, "text": "Scala Map" }, { "code": null, "e": 1153, "s": 1100, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 1165, "s": 1153, "text": "Scala Lists" }, { "code": null, "e": 1180, "s": 1165, "text": "Scala | Arrays" }, { "code": null, "e": 1207, "s": 1180, "text": "Lambda Expression in Scala" }, { "code": null, "e": 1241, "s": 1207, "text": "How to Install Scala with VSCode?" }, { "code": null, "e": 1262, "s": 1241, "text": "Enumeration in Scala" }, { "code": null, "e": 1308, "s": 1262, "text": "How to get the first element of List in Scala" }, { "code": null, "e": 1325, "s": 1308, "text": "HashMap in Scala" } ]
Sorting an array in Bash using Bubble sort
25 Nov, 2021 Prerequisite: Bubble Sort Given an array arr sort the array in ascending order using bash scripting. Examples: Input : 9 7 2 5 Output : Array in sorted order : 2 5 7 9 Approach : For sorting the array bubble sort is the simplest technique. Bubble sort works by swapping the adjacent elements if they are in the wrong order. Example: Given array - (9, 7, 2, 5) After first iteration - (7, 2, 5, 9) After second iteration - (2, 5, 7, 9) and so on... In this way, the array is sorted by placing the greater element at the end of the array. # Sorting the array in Bash # using Bubble sort # Static input of Array arr=(10 8 20 100 12) echo "Array in original order" echo ${arr[*]} # Performing Bubble sort for ((i = 0; i<5; i++)) do for((j = 0; j<5-i-1; j++)) do if [ ${arr[j]} -gt ${arr[$((j+1))]} ] then # swap temp=${arr[j]} arr[$j]=${arr[$((j+1))]} arr[$((j+1))]=$temp fi done done echo "Array in sorted order :" echo ${arr[*]} Output : Array in sorted order : 8 10 12 20 100 Optimized Implementation: The above function always runs O(n^2) time even if the array is sorted. It can be optimized by stopping the algorithm if the inner loop didn’t cause any swap. n=5 arr=(10 8 20 100 12) echo "Original array is: ${arr[*]}"; flag=1; for (( i = 0; i < $n-1; i++ )) do flag=0; for ((j = 0; j < $n-1-$i; j++ )) do if [[ ${arr[$j]} -gt ${arr[$j+1]} ]] then temp=${arr[$j]}; arr[$j]=${arr[$j+1]}; arr[$j+1]=$temp; flag=1; fi done if [[ $flag -eq 0 ]]; then break; fi Output: Original array is: 10 8 20 100 12 Final sorted Array is 8 10 12 20 100 Worst and Average Case Time Complexity: O(n*n). The worst-case occurs when an array is reverse sorted. Best Case Time Complexity: O(n). The best-case occurs when the array is already sorted. Auxiliary Space: O(1) Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted. Sorting In Place: Yes Stable: Yes nitin_19520 kr123manish ruhelaa48 Shell Script Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Nov, 2021" }, { "code": null, "e": 79, "s": 52, "text": "Prerequisite: Bubble Sort " }, { "code": null, "e": 154, "s": 79, "text": "Given an array arr sort the array in ascending order using bash scripting." }, { "code": null, "e": 166, "s": 154, "text": "Examples: " }, { "code": null, "e": 223, "s": 166, "text": "Input : 9 7 2 5\nOutput :\nArray in sorted order :\n2 5 7 9" }, { "code": null, "e": 234, "s": 223, "text": "Approach :" }, { "code": null, "e": 380, "s": 234, "text": "For sorting the array bubble sort is the simplest technique. Bubble sort works by swapping the adjacent elements if they are in the wrong order. " }, { "code": null, "e": 390, "s": 380, "text": "Example: " }, { "code": null, "e": 505, "s": 390, "text": "Given array - (9, 7, 2, 5)\nAfter first iteration - (7, 2, 5, 9)\nAfter second iteration - (2, 5, 7, 9)\nand so on..." }, { "code": null, "e": 596, "s": 505, "text": "In this way, the array is sorted by placing the greater element at the end of the array. " }, { "code": null, "e": 1088, "s": 596, "text": "# Sorting the array in Bash \n# using Bubble sort\n\n# Static input of Array\narr=(10 8 20 100 12)\n\necho \"Array in original order\"\necho ${arr[*]}\n\n# Performing Bubble sort \nfor ((i = 0; i<5; i++))\ndo\n \n for((j = 0; j<5-i-1; j++))\n do\n \n if [ ${arr[j]} -gt ${arr[$((j+1))]} ]\n then\n # swap\n temp=${arr[j]}\n arr[$j]=${arr[$((j+1))]} \n arr[$((j+1))]=$temp\n fi\n done\ndone\n\necho \"Array in sorted order :\"\necho ${arr[*]}" }, { "code": null, "e": 1098, "s": 1088, "text": "Output : " }, { "code": null, "e": 1137, "s": 1098, "text": "Array in sorted order :\n8 10 12 20 100" }, { "code": null, "e": 1324, "s": 1137, "text": "Optimized Implementation: The above function always runs O(n^2) time even if the array is sorted. It can be optimized by stopping the algorithm if the inner loop didn’t cause any swap. " }, { "code": null, "e": 1733, "s": 1324, "text": "n=5\narr=(10 8 20 100 12) \n\necho \"Original array is: ${arr[*]}\";\n\nflag=1;\nfor (( i = 0; i < $n-1; i++ ))\ndo\n flag=0;\n for ((j = 0; j < $n-1-$i; j++ ))\n do\n if [[ ${arr[$j]} -gt ${arr[$j+1]} ]]\n then\n temp=${arr[$j]};\n arr[$j]=${arr[$j+1]};\n arr[$j+1]=$temp;\n flag=1;\n fi\n done\n\n if [[ $flag -eq 0 ]]; then\n break;\n fi" }, { "code": null, "e": 1741, "s": 1733, "text": "Output:" }, { "code": null, "e": 1812, "s": 1741, "text": "Original array is: 10 8 20 100 12\nFinal sorted Array is 8 10 12 20 100" }, { "code": null, "e": 1915, "s": 1812, "text": "Worst and Average Case Time Complexity: O(n*n). The worst-case occurs when an array is reverse sorted." }, { "code": null, "e": 2003, "s": 1915, "text": "Best Case Time Complexity: O(n). The best-case occurs when the array is already sorted." }, { "code": null, "e": 2025, "s": 2003, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 2119, "s": 2025, "text": "Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted." }, { "code": null, "e": 2141, "s": 2119, "text": "Sorting In Place: Yes" }, { "code": null, "e": 2153, "s": 2141, "text": "Stable: Yes" }, { "code": null, "e": 2165, "s": 2153, "text": "nitin_19520" }, { "code": null, "e": 2177, "s": 2165, "text": "kr123manish" }, { "code": null, "e": 2187, "s": 2177, "text": "ruhelaa48" }, { "code": null, "e": 2200, "s": 2187, "text": "Shell Script" }, { "code": null, "e": 2211, "s": 2200, "text": "Linux-Unix" } ]
Turn off the rightmost set bit
08 Jul, 2022 Write a program that unsets the rightmost set bit of an integer. Examples : Input: 12 (00...01100) Output: 8 (00...01000) Input: 7 (00...00111) Output: 6 (00...00110) Let the input number be n. n-1 would have all the bits flipped after the rightmost set bit (including the set bit). So, doing n&(n-1) would give us the required result. So, now let us see how n – 1 is flipping all the bits to the right (including the rightmost set bit also) of the n. Taking n = 12, so (n – 1) = 11, n can be written like (n = (n – 1) + 1), so now we can think of this problem as Adding 1 to Any Number (refer this article for better understanding)Binary representation of (n-1) = 11 = 1011, so now lets make n from (n-1), which can be done by adding a 1 to (n-1)On adding 1 to any number X, all bits to the right of rightmost 0 (including the rightmost zero) gets flipped(n-1) = 1011 (n-1) + 1 = 1100 (all the bits to the right of rightmost zero (including rightmost zero) got flipped)Since we have flipped the rightmost zero, so now, rightmost zero is now flipped to rightmost 1 (aka the rightmost set bit of n) and all bits before rightmost 0 are the same as beforeX = 010 . . . . . 0 (rightmost zero) 111 Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. X + 1 = 010 . . . . . 1 (rightmost one) 0 0 0 Example : X = 71 = Think of it as n – 1 Binary Representation of X = 1000111 X + 1 = 72 = Think of it as n Binary Representation of (X+1) = 1001000Observation : 1. All the bits to the left of rightmost 0 (excluding rightmost 0) in X (thinking it as n – 1) are same as in to the left of the rightmost 1(excluding rightmost 1) in X + 1 (thinking of it as n) 2. All the bits to the right of rightmost 0 (including rightmost 0) in X (thinking it as n – 1) are different as in to the right of the rightmost 1 (including rightmost 1) in X + 1 (thinking of it as n) So bitwise AND of left part of X (till rightmost 0, excluding rightmost 0) and left part of X + 1 (till rightmost 1, excluding rightmost 1) will give the required answer, bitwise AND right part of X (from rightmost 0) and right part of X + 1 (from rightmost 1 (rightmost set bit)) will result in 0 C++ C Java Python3 C# Javascript PHP #include <bits/stdc++.h>using namespace std; // unsets the rightmost set bit// of n and returns the resultint fun(unsigned int n){ return n & (n - 1);} // Driver Codeint main(){ int n = 7; cout<<"The number after unsetting the"; cout<<" rightmost set bit "<<fun(n); return 0;} //This code is contributed by rathbhupendra #include <stdio.h> // unsets the rightmost set bit// of n and returns the resultint fun(unsigned int n){ return n & (n - 1);} // Driver Codeint main(){ int n = 7; printf("The number after unsetting the"); printf(" rightmost set bit %d", fun(n)); return 0;} // Java program to unset the// rightmost set bit of an integer. class GFG { /* unsets the rightmost set bit of n and returns the result */ static int fun(int n) { return n & (n - 1); } // Driver code public static void main(String arg[]) { int n = 7; System.out.print("The number after unsetting " + "the rightmost set bit " + fun(n)); }} // This code is contributed by Anant Agarwal. # unsets the rightmost set bit# of n and returns the resultdef fun(n): return n & (n-1) # Driver code n = 7print("The number after unsetting the rightmost set bit", fun(n)) # This code is contributed# by Anant Agarwal. // C# program to unset the// rightmost set bit of an integer.using System; class GFG { /* unsets the rightmost set bit of n and returns the result */ static int fun(int n) { return n & (n - 1); } // Driver code public static void Main() { int n = 7; Console.Write("The number after unsetting " + "the rightmost set bit " + fun(n)); }} // This code is contributed by Sam007 <script>// JavaScript program for the above approach /* unsets the rightmost set bit of n and returns the result */ function fun(n) { return n & (n - 1); } // Driver Code let n = 7; document.write("The number after unsetting " + "the rightmost set bit " + fun(n)); // This code is contributed by susmitakundugoaldanga.</script> <?php// unsets the rightmost set bit// of n and returns the resultfunction fun($n){return $n & ($n - 1);} // Driver Code$n = 7;echo "The number after unsetting the". " rightmost set bit ", fun($n); // This code is contributed by vt_m. ?> The number after unsetting the rightmost set bit 6 Time Complexity: O(1) Auxiliary Space: O(1) Another Approach: The rightmost set bit can be switched off by subtracting the LSB from the number. The LSB of a number can be obtained using (n & (-n)), therefore the number with the rightmost set bit of n switched off is equal to n – (n & (-n)); C++ Java Python3 C# Javascript //C++ program to implement the approach #include <bits/stdc++.h>using namespace std; // unsets the rightmost set bit// of n and returns the resultint fun(unsigned int n){ return n - (n & (-n));} // Driver Codeint main(){ int n = 7; cout<<"The number after unsetting the"; cout<<" rightmost set bit: "<<fun(n); return 0;} //This code is contributed by phasing17 // Java program to implement the approachclass GFG{ // unsets the rightmost set bit // of n and returns the result static int fun(int n) { return n - (n & (-n)); } // Driver Code public static void main(String[] args) { int n = 7; System.out.print("The number after unsetting the"); System.out.print(" rightmost set bit: " + fun(n)); }} // This code is contributed by phasing17 # Python3 program to implement the approach # unsets the rightmost set bit# of n and returns the resultdef fun(n): return n - (n & (-n)) # Driver Coden = 7print("The number after unsetting the rightmost set bit:", fun(n)) # This code is contributed by phasing17 // C# program to implement the approachusing System; class GFG { // unsets the rightmost set bit // of n and returns the result static int fun(int n) { return n - (n & (-n)); } // Driver Code public static void Main(string[] args) { int n = 7; Console.Write("The number after unsetting the"); Console.Write(" rightmost set bit: " + fun(n)); }} // This code is contributed by phasing17 // JavaScript program to implement the approach // unsets the rightmost set bit// of n and returns the resultfunction fun(n){ return n - (n & (-n));} // Driver Codelet n = 7;console.log("The number after unsetting the rightmost set bit:", fun(n)); // This code is contributed by phasing17 The number after unsetting the rightmost set bit: 6 Time Complexity: O(1) Auxiliary Space: O(1) Turn off the rightmost set bit | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersTurn off the rightmost set bit | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:27•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=QKUh9hHqL4w" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem vt_m rathbhupendra susmitakundugoaldanga anshkush92 souravmahato348 phasing17 Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jul, 2022" }, { "code": null, "e": 132, "s": 54, "text": "Write a program that unsets the rightmost set bit of an integer. Examples : " }, { "code": null, "e": 226, "s": 132, "text": "Input: 12 (00...01100)\nOutput: 8 (00...01000)\n\nInput: 7 (00...00111)\nOutput: 6 (00...00110)" }, { "code": null, "e": 398, "s": 228, "text": "Let the input number be n. n-1 would have all the bits flipped after the rightmost set bit (including the set bit). So, doing n&(n-1) would give us the required result. " }, { "code": null, "e": 548, "s": 398, "text": "So, now let us see how n – 1 is flipping all the bits to the right (including the rightmost set bit also) of the n. Taking n = 12, so (n – 1) = 11, " }, { "code": null, "e": 935, "s": 548, "text": "n can be written like (n = (n – 1) + 1), so now we can think of this problem as Adding 1 to Any Number (refer this article for better understanding)Binary representation of (n-1) = 11 = 1011, so now lets make n from (n-1), which can be done by adding a 1 to (n-1)On adding 1 to any number X, all bits to the right of rightmost 0 (including the rightmost zero) gets flipped(n-1) = 1011 " }, { "code": null, "e": 1259, "s": 935, "text": "(n-1) + 1 = 1100 (all the bits to the right of rightmost zero (including rightmost zero) got flipped)Since we have flipped the rightmost zero, so now, rightmost zero is now flipped to rightmost 1 (aka the rightmost set bit of n) and all bits before rightmost 0 are the same as beforeX = 010 . . . . . 0 (rightmost zero) 111" }, { "code": null, "e": 1268, "s": 1259, "text": "Chapters" }, { "code": null, "e": 1295, "s": 1268, "text": "descriptions off, selected" }, { "code": null, "e": 1345, "s": 1295, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1368, "s": 1345, "text": "captions off, selected" }, { "code": null, "e": 1376, "s": 1368, "text": "English" }, { "code": null, "e": 1400, "s": 1376, "text": "This is a modal window." }, { "code": null, "e": 1469, "s": 1400, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1491, "s": 1469, "text": "End of dialog window." }, { "code": null, "e": 1537, "s": 1491, "text": "X + 1 = 010 . . . . . 1 (rightmost one) 0 0 0" }, { "code": null, "e": 1548, "s": 1537, "text": "Example : " }, { "code": null, "e": 1579, "s": 1548, "text": "X = 71 = Think of it as n – 1 " }, { "code": null, "e": 1616, "s": 1579, "text": "Binary Representation of X = 1000111" }, { "code": null, "e": 1647, "s": 1616, "text": "X + 1 = 72 = Think of it as n " }, { "code": null, "e": 1702, "s": 1647, "text": "Binary Representation of (X+1) = 1001000Observation : " }, { "code": null, "e": 1898, "s": 1702, "text": "1. All the bits to the left of rightmost 0 (excluding rightmost 0) in X (thinking it as n – 1) are same as in to the left of the rightmost 1(excluding rightmost 1) in X + 1 (thinking of it as n)" }, { "code": null, "e": 2101, "s": 1898, "text": "2. All the bits to the right of rightmost 0 (including rightmost 0) in X (thinking it as n – 1) are different as in to the right of the rightmost 1 (including rightmost 1) in X + 1 (thinking of it as n)" }, { "code": null, "e": 2402, "s": 2101, "text": "So bitwise AND of left part of X (till rightmost 0, excluding rightmost 0) and left part of X + 1 (till rightmost 1, excluding rightmost 1) will give the required answer, bitwise AND right part of X (from rightmost 0) and right part of X + 1 (from rightmost 1 (rightmost set bit)) will result in 0 " }, { "code": null, "e": 2406, "s": 2402, "text": "C++" }, { "code": null, "e": 2408, "s": 2406, "text": "C" }, { "code": null, "e": 2413, "s": 2408, "text": "Java" }, { "code": null, "e": 2421, "s": 2413, "text": "Python3" }, { "code": null, "e": 2424, "s": 2421, "text": "C#" }, { "code": null, "e": 2435, "s": 2424, "text": "Javascript" }, { "code": null, "e": 2439, "s": 2435, "text": "PHP" }, { "code": "#include <bits/stdc++.h>using namespace std; // unsets the rightmost set bit// of n and returns the resultint fun(unsigned int n){ return n & (n - 1);} // Driver Codeint main(){ int n = 7; cout<<\"The number after unsetting the\"; cout<<\" rightmost set bit \"<<fun(n); return 0;} //This code is contributed by rathbhupendra", "e": 2777, "s": 2439, "text": null }, { "code": "#include <stdio.h> // unsets the rightmost set bit// of n and returns the resultint fun(unsigned int n){ return n & (n - 1);} // Driver Codeint main(){ int n = 7; printf(\"The number after unsetting the\"); printf(\" rightmost set bit %d\", fun(n)); return 0;}", "e": 3049, "s": 2777, "text": null }, { "code": "// Java program to unset the// rightmost set bit of an integer. class GFG { /* unsets the rightmost set bit of n and returns the result */ static int fun(int n) { return n & (n - 1); } // Driver code public static void main(String arg[]) { int n = 7; System.out.print(\"The number after unsetting \" + \"the rightmost set bit \" + fun(n)); }} // This code is contributed by Anant Agarwal.", "e": 3509, "s": 3049, "text": null }, { "code": "# unsets the rightmost set bit# of n and returns the resultdef fun(n): return n & (n-1) # Driver code n = 7print(\"The number after unsetting the rightmost set bit\", fun(n)) # This code is contributed# by Anant Agarwal.", "e": 3733, "s": 3509, "text": null }, { "code": "// C# program to unset the// rightmost set bit of an integer.using System; class GFG { /* unsets the rightmost set bit of n and returns the result */ static int fun(int n) { return n & (n - 1); } // Driver code public static void Main() { int n = 7; Console.Write(\"The number after unsetting \" + \"the rightmost set bit \" + fun(n)); }} // This code is contributed by Sam007", "e": 4177, "s": 3733, "text": null }, { "code": "<script>// JavaScript program for the above approach /* unsets the rightmost set bit of n and returns the result */ function fun(n) { return n & (n - 1); } // Driver Code let n = 7; document.write(\"The number after unsetting \" + \"the rightmost set bit \" + fun(n)); // This code is contributed by susmitakundugoaldanga.</script>", "e": 4546, "s": 4177, "text": null }, { "code": "<?php// unsets the rightmost set bit// of n and returns the resultfunction fun($n){return $n & ($n - 1);} // Driver Code$n = 7;echo \"The number after unsetting the\". \" rightmost set bit \", fun($n); // This code is contributed by vt_m. ?>", "e": 4788, "s": 4546, "text": null }, { "code": null, "e": 4839, "s": 4788, "text": "The number after unsetting the rightmost set bit 6" }, { "code": null, "e": 4861, "s": 4839, "text": "Time Complexity: O(1)" }, { "code": null, "e": 4883, "s": 4861, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 4901, "s": 4883, "text": "Another Approach:" }, { "code": null, "e": 4983, "s": 4901, "text": "The rightmost set bit can be switched off by subtracting the LSB from the number." }, { "code": null, "e": 5131, "s": 4983, "text": "The LSB of a number can be obtained using (n & (-n)), therefore the number with the rightmost set bit of n switched off is equal to n – (n & (-n));" }, { "code": null, "e": 5135, "s": 5131, "text": "C++" }, { "code": null, "e": 5140, "s": 5135, "text": "Java" }, { "code": null, "e": 5148, "s": 5140, "text": "Python3" }, { "code": null, "e": 5151, "s": 5148, "text": "C#" }, { "code": null, "e": 5162, "s": 5151, "text": "Javascript" }, { "code": "//C++ program to implement the approach #include <bits/stdc++.h>using namespace std; // unsets the rightmost set bit// of n and returns the resultint fun(unsigned int n){ return n - (n & (-n));} // Driver Codeint main(){ int n = 7; cout<<\"The number after unsetting the\"; cout<<\" rightmost set bit: \"<<fun(n); return 0;} //This code is contributed by phasing17", "e": 5541, "s": 5162, "text": null }, { "code": "// Java program to implement the approachclass GFG{ // unsets the rightmost set bit // of n and returns the result static int fun(int n) { return n - (n & (-n)); } // Driver Code public static void main(String[] args) { int n = 7; System.out.print(\"The number after unsetting the\"); System.out.print(\" rightmost set bit: \" + fun(n)); }} // This code is contributed by phasing17", "e": 5942, "s": 5541, "text": null }, { "code": "# Python3 program to implement the approach # unsets the rightmost set bit# of n and returns the resultdef fun(n): return n - (n & (-n)) # Driver Coden = 7print(\"The number after unsetting the rightmost set bit:\", fun(n)) # This code is contributed by phasing17", "e": 6207, "s": 5942, "text": null }, { "code": "// C# program to implement the approachusing System; class GFG { // unsets the rightmost set bit // of n and returns the result static int fun(int n) { return n - (n & (-n)); } // Driver Code public static void Main(string[] args) { int n = 7; Console.Write(\"The number after unsetting the\"); Console.Write(\" rightmost set bit: \" + fun(n)); }} // This code is contributed by phasing17", "e": 6610, "s": 6207, "text": null }, { "code": "// JavaScript program to implement the approach // unsets the rightmost set bit// of n and returns the resultfunction fun(n){ return n - (n & (-n));} // Driver Codelet n = 7;console.log(\"The number after unsetting the rightmost set bit:\", fun(n)); // This code is contributed by phasing17", "e": 6903, "s": 6610, "text": null }, { "code": null, "e": 6955, "s": 6903, "text": "The number after unsetting the rightmost set bit: 6" }, { "code": null, "e": 6977, "s": 6955, "text": "Time Complexity: O(1)" }, { "code": null, "e": 6999, "s": 6977, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 7879, "s": 7001, "text": "Turn off the rightmost set bit | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersTurn off the rightmost set bit | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:27•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=QKUh9hHqL4w\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 7996, "s": 7879, "text": "Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem " }, { "code": null, "e": 8001, "s": 7996, "text": "vt_m" }, { "code": null, "e": 8015, "s": 8001, "text": "rathbhupendra" }, { "code": null, "e": 8037, "s": 8015, "text": "susmitakundugoaldanga" }, { "code": null, "e": 8048, "s": 8037, "text": "anshkush92" }, { "code": null, "e": 8064, "s": 8048, "text": "souravmahato348" }, { "code": null, "e": 8074, "s": 8064, "text": "phasing17" }, { "code": null, "e": 8084, "s": 8074, "text": "Bit Magic" }, { "code": null, "e": 8094, "s": 8084, "text": "Bit Magic" } ]
ES6 | Date
23 Oct, 2019 The ES6 Date is defined as the number of milliseconds that have been passed since midnight on January 1, 1970 UTC. Date objects can be created by the new Date() constructor. In JavaScript both date and time are represented by the Date object. Constructors: Date() – Create a date object for the current time and date.var date = new Date(); console.log(date); Date(milliseconds) – Create a date object with time equal to the number of milliseconds passed from January 1, 1970 UTC.var date = new Date(1570991017113); console.log(date); Date(datestring) – Create a date object with the specified date string, then it is parsed automatically same as Date.parse() does.var date = new Date("2019-10-11"); console.log(date); Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]) – Create a date object with the specified date in local time zone. The first two arguments are necessary and the rest are optional.var date = new Date(2019, 0, 11, 15, 45, 55, 55); console.log(date); Date() – Create a date object for the current time and date.var date = new Date(); console.log(date); var date = new Date(); console.log(date); Date(milliseconds) – Create a date object with time equal to the number of milliseconds passed from January 1, 1970 UTC.var date = new Date(1570991017113); console.log(date); var date = new Date(1570991017113); console.log(date); Date(datestring) – Create a date object with the specified date string, then it is parsed automatically same as Date.parse() does.var date = new Date("2019-10-11"); console.log(date); var date = new Date("2019-10-11"); console.log(date); Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]) – Create a date object with the specified date in local time zone. The first two arguments are necessary and the rest are optional.var date = new Date(2019, 0, 11, 15, 45, 55, 55); console.log(date); var date = new Date(2019, 0, 11, 15, 45, 55, 55); console.log(date); Properties: Date.prototype: It represents the prototype for the Date constructor. Date.prototype is itself an ordinary object rather than the Date instance. It allows to add properties to the Date object.Date.constructor: It returns the reference of the array function that created the instance of the Date object. Date.prototype: It represents the prototype for the Date constructor. Date.prototype is itself an ordinary object rather than the Date instance. It allows to add properties to the Date object. Date.constructor: It returns the reference of the array function that created the instance of the Date object. Methods: Date.now(): It returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.console.log(Date.now()); // 1571060400486 // i.e. number of milliseconds elapsed since January 1, 1970 00:00:00 UTC Date.parse(): It returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC for provided string representation of date.console.log(Date.parse("2019-10-11")); // 1570800633000 Date.UTC(): It returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC for provided date separated by comma.console.log(Date.parse("2019, 9, 11")); // 1570800633000 Date.now(): It returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.console.log(Date.now()); // 1571060400486 // i.e. number of milliseconds elapsed since January 1, 1970 00:00:00 UTC console.log(Date.now()); // 1571060400486 // i.e. number of milliseconds elapsed since January 1, 1970 00:00:00 UTC Date.parse(): It returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC for provided string representation of date.console.log(Date.parse("2019-10-11")); // 1570800633000 console.log(Date.parse("2019-10-11")); // 1570800633000 Date.UTC(): It returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC for provided date separated by comma.console.log(Date.parse("2019, 9, 11")); // 1570800633000 console.log(Date.parse("2019, 9, 11")); // 1570800633000 Date.prototype Methods: getDate(): It returns the date of the month from the given date object.var d = new Date("2019-10-11"); console.log(d.getDate()); // 11 getDay(): It returns the day of the week from 0 to 6 according to local time of the given date object.var d = new Date("2019-10-11"); console.log(d.getDay()); // 5 i.e Friday getFullYear(): It returns the full year of the given date object.var d = new Date("2019-10-11"); console.log(d.getFullYear()); // 2019 getHours(): It returns the hour (0-23) of the given date object.var d = new Date("2019-10-11 16:30:33"); console.log(d.getHours()); // 16 getMilliseconds(): It returns the milliseconds (0-999) of the given date object according to the local time.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getMilliseconds()); // 0 getMinutes(): It returns the minute (0-59) of the given date object according to the local time.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getMinutes()); // 30 getMonth(): It returns the month (0-11) of the given date object according to the local time.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getMonth()); // 9 getSeconds(): It returns the seconds (0-59) of the given date object according to the local time.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getSeconds()); // 33 getTime(): It returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getTime()); // 1570791633000 getTimezoneOffset(): It returns the difference between UTC and local timezone in minutes.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getTimezoneOffset()); // -330 getUTCDate(): It returns the day of the month (1-31) according to universal time of the given date object.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCDate()); // 11 getUTCDay(): It returns the day of the week (0-6) according to universal time of the given date object.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCDay()); // 5 getUTCFullYear(): It returns the year according to universal time of the given date object.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCFullYear()); // 2019 getUTCHours(): It returns the hour (0-23) according to universal time of the given date object.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCHours()); // 11 getUTCMilliseconds(): It returns the milliseconds (0-999) according to universal time of the given date object.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCMilliseconds()); // 0 getUTCMinutes(): It returns the minutes according to universal time of the given date object.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCMinutes()); // 0 getUTCMonth(): It returns the month (0-11) according to universal time of the given date object.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCMonth()); // 9 getUTCSeconds(): It returns seconds (0-59) according to universal time of the given date object.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCSeconds()); // 33 setDate(): It is used to set the date of a month to the date object in local time.var d = new Date("October 11, 2019 16:30:33"); d.setDate(13); console.log(d.getDate()); // 13 setFullYear(): It is used to set year to the date object in local time.var d = new Date("October 11, 2019 16:30:33"); d.setYear(2018); console.log(d.getFullYear()); // 2018 setHours(): It is used to set hour (0-23) to the date object in local time.var d = new Date("October 11, 2019 16:30:33"); d.setHours(19); console.log(d.getHours()); // 19 setMilliseconds(): It is used to set milliseconds to the date object in local time.var d = new Date("October 11, 2019 16:30:33"); d.setMilliseconds(200); console.log(d.getMilliseconds()); // 200 setMinutes(): It is used to set minutes (0-59) to the date object in local time.var d = new Date("October 11, 2019 16:30:33"); d.setMinutes(20); console.log(d.getMinutes()); // 20 setMonth(): It is used to set month (0-11) to the date object in local time.var d = new Date("October 11, 2019 16:30:33"); d.setMonth(8); console.log(d.getMonth()); // 8 setSeconds(): It is used to set seconds (0-59) to the date object in local time.var d = new Date("October 11, 2019 16:30:33"); d.setSeconds(34); console.log(d.getSeconds()); // 34 setTime(): It is used to set milliseconds after January 1, 1970 00:00:00 UTC to the date object in local time.var d = new Date("October 11, 2019 16:30:33"); d.setTime(1570815753000); console.log(d.toDateString()); // "Fri Oct 11 2019" setUTCDate(): It is used to set date of the month (0-11) to the date object according to universal time.var d = new Date("October 11, 2019 16:30:33"); d.setUTCDate(12); console.log(d.getDate()); // 12 setUTCFullYear(): It is used to set year to the date object according to universal time.var d = new Date("October 11, 2019 16:30:33"); d.setUTCFullYear(2018); console.log(d.getFullYear()); // 2018 setUTCHours(): It is used to set hours (0-23) to the date object according to universal time.var d = new Date("October 11, 2019 16:30:33"); d.setUTCHours(16); console.log(d.getHours()); // 21 setUTCMilliseconds(): It is used to set milliseconds to the date object according to universal time.var d = new Date("October 11, 2019 16:30:33"); d.setUTCMilliseconds(166); console.log(d.getMilliseconds()); // 166 setUTCMinutes(): It is used to set minutes (0-59) to the date object according to universal time.var d = new Date("October 11, 2019 16:30:33"); d.setUTCMinutes(22); console.log(d.getMinutes()); // 52 setUTCMonth(): It is used to set month (0-11) to the date object according to universal time.var d = new Date("October 11, 2019 16:30:33"); d.setUTCMonth(8); console.log(d.getMonth()); // 8 setUTCSeconds(): It is used to set seconds (0-59) to the date object according to universal time.var d = new Date("October 11, 2019 16:30:33"); d.setUTCSeconds(10); console.log(d.getSeconds()); // 10 getDate(): It returns the date of the month from the given date object.var d = new Date("2019-10-11"); console.log(d.getDate()); // 11 var d = new Date("2019-10-11"); console.log(d.getDate()); // 11 getDay(): It returns the day of the week from 0 to 6 according to local time of the given date object.var d = new Date("2019-10-11"); console.log(d.getDay()); // 5 i.e Friday var d = new Date("2019-10-11"); console.log(d.getDay()); // 5 i.e Friday getFullYear(): It returns the full year of the given date object.var d = new Date("2019-10-11"); console.log(d.getFullYear()); // 2019 var d = new Date("2019-10-11"); console.log(d.getFullYear()); // 2019 getHours(): It returns the hour (0-23) of the given date object.var d = new Date("2019-10-11 16:30:33"); console.log(d.getHours()); // 16 var d = new Date("2019-10-11 16:30:33"); console.log(d.getHours()); // 16 getMilliseconds(): It returns the milliseconds (0-999) of the given date object according to the local time.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getMilliseconds()); // 0 var d = new Date("October 11, 2019 16:30:33"); console.log(d.getMilliseconds()); // 0 getMinutes(): It returns the minute (0-59) of the given date object according to the local time.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getMinutes()); // 30 var d = new Date("October 11, 2019 16:30:33"); console.log(d.getMinutes()); // 30 getMonth(): It returns the month (0-11) of the given date object according to the local time.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getMonth()); // 9 var d = new Date("October 11, 2019 16:30:33"); console.log(d.getMonth()); // 9 getSeconds(): It returns the seconds (0-59) of the given date object according to the local time.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getSeconds()); // 33 var d = new Date("October 11, 2019 16:30:33"); console.log(d.getSeconds()); // 33 getTime(): It returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getTime()); // 1570791633000 var d = new Date("October 11, 2019 16:30:33"); console.log(d.getTime()); // 1570791633000 getTimezoneOffset(): It returns the difference between UTC and local timezone in minutes.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getTimezoneOffset()); // -330 var d = new Date("October 11, 2019 16:30:33"); console.log(d.getTimezoneOffset()); // -330 getUTCDate(): It returns the day of the month (1-31) according to universal time of the given date object.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCDate()); // 11 var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCDate()); // 11 getUTCDay(): It returns the day of the week (0-6) according to universal time of the given date object.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCDay()); // 5 var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCDay()); // 5 getUTCFullYear(): It returns the year according to universal time of the given date object.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCFullYear()); // 2019 var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCFullYear()); // 2019 getUTCHours(): It returns the hour (0-23) according to universal time of the given date object.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCHours()); // 11 var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCHours()); // 11 getUTCMilliseconds(): It returns the milliseconds (0-999) according to universal time of the given date object.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCMilliseconds()); // 0 var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCMilliseconds()); // 0 getUTCMinutes(): It returns the minutes according to universal time of the given date object.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCMinutes()); // 0 var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCMinutes()); // 0 getUTCMonth(): It returns the month (0-11) according to universal time of the given date object.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCMonth()); // 9 var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCMonth()); // 9 getUTCSeconds(): It returns seconds (0-59) according to universal time of the given date object.var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCSeconds()); // 33 var d = new Date("October 11, 2019 16:30:33"); console.log(d.getUTCSeconds()); // 33 setDate(): It is used to set the date of a month to the date object in local time.var d = new Date("October 11, 2019 16:30:33"); d.setDate(13); console.log(d.getDate()); // 13 var d = new Date("October 11, 2019 16:30:33"); d.setDate(13); console.log(d.getDate()); // 13 setFullYear(): It is used to set year to the date object in local time.var d = new Date("October 11, 2019 16:30:33"); d.setYear(2018); console.log(d.getFullYear()); // 2018 var d = new Date("October 11, 2019 16:30:33"); d.setYear(2018); console.log(d.getFullYear()); // 2018 setHours(): It is used to set hour (0-23) to the date object in local time.var d = new Date("October 11, 2019 16:30:33"); d.setHours(19); console.log(d.getHours()); // 19 var d = new Date("October 11, 2019 16:30:33"); d.setHours(19); console.log(d.getHours()); // 19 setMilliseconds(): It is used to set milliseconds to the date object in local time.var d = new Date("October 11, 2019 16:30:33"); d.setMilliseconds(200); console.log(d.getMilliseconds()); // 200 var d = new Date("October 11, 2019 16:30:33"); d.setMilliseconds(200); console.log(d.getMilliseconds()); // 200 setMinutes(): It is used to set minutes (0-59) to the date object in local time.var d = new Date("October 11, 2019 16:30:33"); d.setMinutes(20); console.log(d.getMinutes()); // 20 var d = new Date("October 11, 2019 16:30:33"); d.setMinutes(20); console.log(d.getMinutes()); // 20 setMonth(): It is used to set month (0-11) to the date object in local time.var d = new Date("October 11, 2019 16:30:33"); d.setMonth(8); console.log(d.getMonth()); // 8 var d = new Date("October 11, 2019 16:30:33"); d.setMonth(8); console.log(d.getMonth()); // 8 setSeconds(): It is used to set seconds (0-59) to the date object in local time.var d = new Date("October 11, 2019 16:30:33"); d.setSeconds(34); console.log(d.getSeconds()); // 34 var d = new Date("October 11, 2019 16:30:33"); d.setSeconds(34); console.log(d.getSeconds()); // 34 setTime(): It is used to set milliseconds after January 1, 1970 00:00:00 UTC to the date object in local time.var d = new Date("October 11, 2019 16:30:33"); d.setTime(1570815753000); console.log(d.toDateString()); // "Fri Oct 11 2019" var d = new Date("October 11, 2019 16:30:33"); d.setTime(1570815753000); console.log(d.toDateString()); // "Fri Oct 11 2019" setUTCDate(): It is used to set date of the month (0-11) to the date object according to universal time.var d = new Date("October 11, 2019 16:30:33"); d.setUTCDate(12); console.log(d.getDate()); // 12 var d = new Date("October 11, 2019 16:30:33"); d.setUTCDate(12); console.log(d.getDate()); // 12 setUTCFullYear(): It is used to set year to the date object according to universal time.var d = new Date("October 11, 2019 16:30:33"); d.setUTCFullYear(2018); console.log(d.getFullYear()); // 2018 var d = new Date("October 11, 2019 16:30:33"); d.setUTCFullYear(2018); console.log(d.getFullYear()); // 2018 setUTCHours(): It is used to set hours (0-23) to the date object according to universal time.var d = new Date("October 11, 2019 16:30:33"); d.setUTCHours(16); console.log(d.getHours()); // 21 var d = new Date("October 11, 2019 16:30:33"); d.setUTCHours(16); console.log(d.getHours()); // 21 setUTCMilliseconds(): It is used to set milliseconds to the date object according to universal time.var d = new Date("October 11, 2019 16:30:33"); d.setUTCMilliseconds(166); console.log(d.getMilliseconds()); // 166 var d = new Date("October 11, 2019 16:30:33"); d.setUTCMilliseconds(166); console.log(d.getMilliseconds()); // 166 setUTCMinutes(): It is used to set minutes (0-59) to the date object according to universal time.var d = new Date("October 11, 2019 16:30:33"); d.setUTCMinutes(22); console.log(d.getMinutes()); // 52 var d = new Date("October 11, 2019 16:30:33"); d.setUTCMinutes(22); console.log(d.getMinutes()); // 52 setUTCMonth(): It is used to set month (0-11) to the date object according to universal time.var d = new Date("October 11, 2019 16:30:33"); d.setUTCMonth(8); console.log(d.getMonth()); // 8 var d = new Date("October 11, 2019 16:30:33"); d.setUTCMonth(8); console.log(d.getMonth()); // 8 setUTCSeconds(): It is used to set seconds (0-59) to the date object according to universal time.var d = new Date("October 11, 2019 16:30:33"); d.setUTCSeconds(10); console.log(d.getSeconds()); // 10 var d = new Date("October 11, 2019 16:30:33"); d.setUTCSeconds(10); console.log(d.getSeconds()); // 10 Date Conversion Methods: toDateString(): It returns the string representation for the date portion of the date object.var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toDateString()); // "Fri Oct 11 2019" toISOString(): It returns the string representation for the date portion of the date object using ISO 8601 extended format.var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toISOString()); // "2019-10-11T14:00:33.000Z" toJSON(): It returns the string representation for the date portion of the date object.var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toJSON()); // "2019-10-11T14:00:33.000Z" toLocaleDateString(): It takes two parameters (optional) – locale and options and returns the string representation for the date portion according to specified locale.var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toLocaleDateString()); // "10/11/2019" // 10.2019 console.log(d.toLocaleDateString("de-DE", {year:'numeric', month: 'numeric'})) toLocaleString(): It returns the string of date object of date portion in locale format.var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toLocaleString()); // "10/11/2019, 7:30:33 PM" toLocaleTimeString(): It returns the string representation for the time portion of the date object.var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toLocaleTimeString()); // "7:30:33 PM" toString(): It returns the string representation for date of the date object.var d = new Date(2019, 9, 11, 19, 30, 33); // "Fri Oct 11 2019 19:30:33 GMT+0530 (India Standard Time)" console.log(d.toString()); toTimeString(): It returns the string representation for the time portion of the date object.var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toTimeString()); // "19:30:33 GMT+0530 (India Standard Time)" toUTCString(): It returns the string representation for the date object in format of universal timezone.var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toUTCString()); // "Fri, 11 Oct 2019 14:00:33 GMT" valueOf(): It returns the number of milliseconds elapsed from January 1, 1970 00:00:00 UTC to the date provided.var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.valueOf()); // 1570802433000 toDateString(): It returns the string representation for the date portion of the date object.var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toDateString()); // "Fri Oct 11 2019" var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toDateString()); // "Fri Oct 11 2019" toISOString(): It returns the string representation for the date portion of the date object using ISO 8601 extended format.var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toISOString()); // "2019-10-11T14:00:33.000Z" var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toISOString()); // "2019-10-11T14:00:33.000Z" toJSON(): It returns the string representation for the date portion of the date object.var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toJSON()); // "2019-10-11T14:00:33.000Z" var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toJSON()); // "2019-10-11T14:00:33.000Z" toLocaleDateString(): It takes two parameters (optional) – locale and options and returns the string representation for the date portion according to specified locale.var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toLocaleDateString()); // "10/11/2019" // 10.2019 console.log(d.toLocaleDateString("de-DE", {year:'numeric', month: 'numeric'})) var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toLocaleDateString()); // "10/11/2019" // 10.2019 console.log(d.toLocaleDateString("de-DE", {year:'numeric', month: 'numeric'})) toLocaleString(): It returns the string of date object of date portion in locale format.var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toLocaleString()); // "10/11/2019, 7:30:33 PM" var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toLocaleString()); // "10/11/2019, 7:30:33 PM" toLocaleTimeString(): It returns the string representation for the time portion of the date object.var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toLocaleTimeString()); // "7:30:33 PM" var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toLocaleTimeString()); // "7:30:33 PM" toString(): It returns the string representation for date of the date object.var d = new Date(2019, 9, 11, 19, 30, 33); // "Fri Oct 11 2019 19:30:33 GMT+0530 (India Standard Time)" console.log(d.toString()); var d = new Date(2019, 9, 11, 19, 30, 33); // "Fri Oct 11 2019 19:30:33 GMT+0530 (India Standard Time)" console.log(d.toString()); toTimeString(): It returns the string representation for the time portion of the date object.var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toTimeString()); // "19:30:33 GMT+0530 (India Standard Time)" var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toTimeString()); // "19:30:33 GMT+0530 (India Standard Time)" toUTCString(): It returns the string representation for the date object in format of universal timezone.var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toUTCString()); // "Fri, 11 Oct 2019 14:00:33 GMT" var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.toUTCString()); // "Fri, 11 Oct 2019 14:00:33 GMT" valueOf(): It returns the number of milliseconds elapsed from January 1, 1970 00:00:00 UTC to the date provided.var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.valueOf()); // 1570802433000 var d = new Date(2019, 9, 11, 19, 30, 33); console.log(d.valueOf()); // 1570802433000 JavaScript-ES Picked 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 Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request 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? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Oct, 2019" }, { "code": null, "e": 271, "s": 28, "text": "The ES6 Date is defined as the number of milliseconds that have been passed since midnight on January 1, 1970 UTC. Date objects can be created by the new Date() constructor. In JavaScript both date and time are represented by the Date object." }, { "code": null, "e": 285, "s": 271, "text": "Constructors:" }, { "code": null, "e": 1029, "s": 285, "text": "Date() – Create a date object for the current time and date.var date = new Date();\nconsole.log(date);\nDate(milliseconds) – Create a date object with time equal to the number of milliseconds passed from January 1, 1970 UTC.var date = new Date(1570991017113);\nconsole.log(date);\nDate(datestring) – Create a date object with the specified date string, then it is parsed automatically same as Date.parse() does.var date = new Date(\"2019-10-11\");\nconsole.log(date);\nDate(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]) – Create a date object with the specified date in local time zone. The first two arguments are necessary and the rest are optional.var date = new Date(2019, 0, 11, 15, 45, 55, 55);\nconsole.log(date);\n" }, { "code": null, "e": 1132, "s": 1029, "text": "Date() – Create a date object for the current time and date.var date = new Date();\nconsole.log(date);\n" }, { "code": null, "e": 1175, "s": 1132, "text": "var date = new Date();\nconsole.log(date);\n" }, { "code": null, "e": 1351, "s": 1175, "text": "Date(milliseconds) – Create a date object with time equal to the number of milliseconds passed from January 1, 1970 UTC.var date = new Date(1570991017113);\nconsole.log(date);\n" }, { "code": null, "e": 1407, "s": 1351, "text": "var date = new Date(1570991017113);\nconsole.log(date);\n" }, { "code": null, "e": 1592, "s": 1407, "text": "Date(datestring) – Create a date object with the specified date string, then it is parsed automatically same as Date.parse() does.var date = new Date(\"2019-10-11\");\nconsole.log(date);\n" }, { "code": null, "e": 1647, "s": 1592, "text": "var date = new Date(\"2019-10-11\");\nconsole.log(date);\n" }, { "code": null, "e": 1930, "s": 1647, "text": "Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]) – Create a date object with the specified date in local time zone. The first two arguments are necessary and the rest are optional.var date = new Date(2019, 0, 11, 15, 45, 55, 55);\nconsole.log(date);\n" }, { "code": null, "e": 2000, "s": 1930, "text": "var date = new Date(2019, 0, 11, 15, 45, 55, 55);\nconsole.log(date);\n" }, { "code": null, "e": 2012, "s": 2000, "text": "Properties:" }, { "code": null, "e": 2315, "s": 2012, "text": "Date.prototype: It represents the prototype for the Date constructor. Date.prototype is itself an ordinary object rather than the Date instance. It allows to add properties to the Date object.Date.constructor: It returns the reference of the array function that created the instance of the Date object." }, { "code": null, "e": 2508, "s": 2315, "text": "Date.prototype: It represents the prototype for the Date constructor. Date.prototype is itself an ordinary object rather than the Date instance. It allows to add properties to the Date object." }, { "code": null, "e": 2619, "s": 2508, "text": "Date.constructor: It returns the reference of the array function that created the instance of the Date object." }, { "code": null, "e": 2628, "s": 2619, "text": "Methods:" }, { "code": null, "e": 3220, "s": 2628, "text": "Date.now(): It returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.console.log(Date.now()); // 1571060400486 \n// i.e. number of milliseconds elapsed since January 1, 1970 00:00:00 UTC\nDate.parse(): It returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC for provided string representation of date.console.log(Date.parse(\"2019-10-11\")); // 1570800633000\nDate.UTC(): It returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC for provided date separated by comma.console.log(Date.parse(\"2019, 9, 11\")); // 1570800633000\n" }, { "code": null, "e": 3431, "s": 3220, "text": "Date.now(): It returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.console.log(Date.now()); // 1571060400486 \n// i.e. number of milliseconds elapsed since January 1, 1970 00:00:00 UTC\n" }, { "code": null, "e": 3549, "s": 3431, "text": "console.log(Date.now()); // 1571060400486 \n// i.e. number of milliseconds elapsed since January 1, 1970 00:00:00 UTC\n" }, { "code": null, "e": 3744, "s": 3549, "text": "Date.parse(): It returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC for provided string representation of date.console.log(Date.parse(\"2019-10-11\")); // 1570800633000\n" }, { "code": null, "e": 3801, "s": 3744, "text": "console.log(Date.parse(\"2019-10-11\")); // 1570800633000\n" }, { "code": null, "e": 3989, "s": 3801, "text": "Date.UTC(): It returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC for provided date separated by comma.console.log(Date.parse(\"2019, 9, 11\")); // 1570800633000\n" }, { "code": null, "e": 4047, "s": 3989, "text": "console.log(Date.parse(\"2019, 9, 11\")); // 1570800633000\n" }, { "code": null, "e": 4071, "s": 4047, "text": "Date.prototype Methods:" }, { "code": null, "e": 10079, "s": 4071, "text": "getDate(): It returns the date of the month from the given date object.var d = new Date(\"2019-10-11\");\nconsole.log(d.getDate()); // 11\ngetDay(): It returns the day of the week from 0 to 6 according to local time of the given date object.var d = new Date(\"2019-10-11\");\nconsole.log(d.getDay()); // 5 i.e Friday\ngetFullYear(): It returns the full year of the given date object.var d = new Date(\"2019-10-11\");\nconsole.log(d.getFullYear()); // 2019\ngetHours(): It returns the hour (0-23) of the given date object.var d = new Date(\"2019-10-11 16:30:33\");\nconsole.log(d.getHours()); // 16\ngetMilliseconds(): It returns the milliseconds (0-999) of the given date object according to the local time.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getMilliseconds()); // 0\ngetMinutes(): It returns the minute (0-59) of the given date object according to the local time.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getMinutes()); // 30\ngetMonth(): It returns the month (0-11) of the given date object according to the local time.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getMonth()); // 9\ngetSeconds(): It returns the seconds (0-59) of the given date object according to the local time.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getSeconds()); // 33\ngetTime(): It returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getTime()); // 1570791633000\ngetTimezoneOffset(): It returns the difference between UTC and local timezone in minutes.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getTimezoneOffset()); // -330\ngetUTCDate(): It returns the day of the month (1-31) according to universal time of the given date object.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCDate()); // 11\ngetUTCDay(): It returns the day of the week (0-6) according to universal time of the given date object.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCDay()); // 5\ngetUTCFullYear(): It returns the year according to universal time of the given date object.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCFullYear()); // 2019\ngetUTCHours(): It returns the hour (0-23) according to universal time of the given date object.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCHours()); // 11\ngetUTCMilliseconds(): It returns the milliseconds (0-999) according to universal time of the given date object.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCMilliseconds()); // 0\ngetUTCMinutes(): It returns the minutes according to universal time of the given date object.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCMinutes()); // 0\ngetUTCMonth(): It returns the month (0-11) according to universal time of the given date object.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCMonth()); // 9\ngetUTCSeconds(): It returns seconds (0-59) according to universal time of the given date object.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCSeconds()); // 33\nsetDate(): It is used to set the date of a month to the date object in local time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setDate(13);\nconsole.log(d.getDate()); // 13\nsetFullYear(): It is used to set year to the date object in local time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setYear(2018);\nconsole.log(d.getFullYear()); // 2018\nsetHours(): It is used to set hour (0-23) to the date object in local time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setHours(19);\nconsole.log(d.getHours()); // 19\nsetMilliseconds(): It is used to set milliseconds to the date object in local time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setMilliseconds(200);\nconsole.log(d.getMilliseconds()); // 200\nsetMinutes(): It is used to set minutes (0-59) to the date object in local time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setMinutes(20);\nconsole.log(d.getMinutes()); // 20\nsetMonth(): It is used to set month (0-11) to the date object in local time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setMonth(8);\nconsole.log(d.getMonth()); // 8\nsetSeconds(): It is used to set seconds (0-59) to the date object in local time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setSeconds(34);\nconsole.log(d.getSeconds()); // 34\nsetTime(): It is used to set milliseconds after January 1, 1970 00:00:00 UTC to the date object in local time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setTime(1570815753000);\nconsole.log(d.toDateString()); // \"Fri Oct 11 2019\"\nsetUTCDate(): It is used to set date of the month (0-11) to the date object according to universal time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCDate(12);\nconsole.log(d.getDate()); // 12\nsetUTCFullYear(): It is used to set year to the date object according to universal time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCFullYear(2018);\nconsole.log(d.getFullYear()); // 2018\nsetUTCHours(): It is used to set hours (0-23) to the date object according to universal time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCHours(16);\nconsole.log(d.getHours()); // 21\nsetUTCMilliseconds(): It is used to set milliseconds to the date object according to universal time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCMilliseconds(166);\nconsole.log(d.getMilliseconds()); // 166\nsetUTCMinutes(): It is used to set minutes (0-59) to the date object according to universal time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCMinutes(22);\nconsole.log(d.getMinutes()); // 52\nsetUTCMonth(): It is used to set month (0-11) to the date object according to universal time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCMonth(8);\nconsole.log(d.getMonth()); // 8\nsetUTCSeconds(): It is used to set seconds (0-59) to the date object according to universal time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCSeconds(10);\nconsole.log(d.getSeconds()); // 10\n" }, { "code": null, "e": 10215, "s": 10079, "text": "getDate(): It returns the date of the month from the given date object.var d = new Date(\"2019-10-11\");\nconsole.log(d.getDate()); // 11\n" }, { "code": null, "e": 10280, "s": 10215, "text": "var d = new Date(\"2019-10-11\");\nconsole.log(d.getDate()); // 11\n" }, { "code": null, "e": 10456, "s": 10280, "text": "getDay(): It returns the day of the week from 0 to 6 according to local time of the given date object.var d = new Date(\"2019-10-11\");\nconsole.log(d.getDay()); // 5 i.e Friday\n" }, { "code": null, "e": 10530, "s": 10456, "text": "var d = new Date(\"2019-10-11\");\nconsole.log(d.getDay()); // 5 i.e Friday\n" }, { "code": null, "e": 10666, "s": 10530, "text": "getFullYear(): It returns the full year of the given date object.var d = new Date(\"2019-10-11\");\nconsole.log(d.getFullYear()); // 2019\n" }, { "code": null, "e": 10737, "s": 10666, "text": "var d = new Date(\"2019-10-11\");\nconsole.log(d.getFullYear()); // 2019\n" }, { "code": null, "e": 10876, "s": 10737, "text": "getHours(): It returns the hour (0-23) of the given date object.var d = new Date(\"2019-10-11 16:30:33\");\nconsole.log(d.getHours()); // 16\n" }, { "code": null, "e": 10951, "s": 10876, "text": "var d = new Date(\"2019-10-11 16:30:33\");\nconsole.log(d.getHours()); // 16\n" }, { "code": null, "e": 11146, "s": 10951, "text": "getMilliseconds(): It returns the milliseconds (0-999) of the given date object according to the local time.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getMilliseconds()); // 0\n" }, { "code": null, "e": 11233, "s": 11146, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getMilliseconds()); // 0\n" }, { "code": null, "e": 11412, "s": 11233, "text": "getMinutes(): It returns the minute (0-59) of the given date object according to the local time.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getMinutes()); // 30\n" }, { "code": null, "e": 11495, "s": 11412, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getMinutes()); // 30\n" }, { "code": null, "e": 11668, "s": 11495, "text": "getMonth(): It returns the month (0-11) of the given date object according to the local time.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getMonth()); // 9\n" }, { "code": null, "e": 11748, "s": 11668, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getMonth()); // 9\n" }, { "code": null, "e": 11928, "s": 11748, "text": "getSeconds(): It returns the seconds (0-59) of the given date object according to the local time.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getSeconds()); // 33\n" }, { "code": null, "e": 12011, "s": 11928, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getSeconds()); // 33\n" }, { "code": null, "e": 12194, "s": 12011, "text": "getTime(): It returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getTime()); // 1570791633000\n" }, { "code": null, "e": 12285, "s": 12194, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getTime()); // 1570791633000\n" }, { "code": null, "e": 12466, "s": 12285, "text": "getTimezoneOffset(): It returns the difference between UTC and local timezone in minutes.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getTimezoneOffset()); // -330\n" }, { "code": null, "e": 12558, "s": 12466, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getTimezoneOffset()); // -330\n" }, { "code": null, "e": 12747, "s": 12558, "text": "getUTCDate(): It returns the day of the month (1-31) according to universal time of the given date object.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCDate()); // 11\n" }, { "code": null, "e": 12830, "s": 12747, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCDate()); // 11\n" }, { "code": null, "e": 13014, "s": 12830, "text": "getUTCDay(): It returns the day of the week (0-6) according to universal time of the given date object.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCDay()); // 5\n" }, { "code": null, "e": 13095, "s": 13014, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCDay()); // 5\n" }, { "code": null, "e": 13275, "s": 13095, "text": "getUTCFullYear(): It returns the year according to universal time of the given date object.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCFullYear()); // 2019\n" }, { "code": null, "e": 13364, "s": 13275, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCFullYear()); // 2019\n" }, { "code": null, "e": 13543, "s": 13364, "text": "getUTCHours(): It returns the hour (0-23) according to universal time of the given date object.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCHours()); // 11\n" }, { "code": null, "e": 13627, "s": 13543, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCHours()); // 11\n" }, { "code": null, "e": 13828, "s": 13627, "text": "getUTCMilliseconds(): It returns the milliseconds (0-999) according to universal time of the given date object.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCMilliseconds()); // 0\n" }, { "code": null, "e": 13918, "s": 13828, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCMilliseconds()); // 0\n" }, { "code": null, "e": 14096, "s": 13918, "text": "getUTCMinutes(): It returns the minutes according to universal time of the given date object.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCMinutes()); // 0\n" }, { "code": null, "e": 14181, "s": 14096, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCMinutes()); // 0\n" }, { "code": null, "e": 14360, "s": 14181, "text": "getUTCMonth(): It returns the month (0-11) according to universal time of the given date object.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCMonth()); // 9\n" }, { "code": null, "e": 14443, "s": 14360, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCMonth()); // 9\n" }, { "code": null, "e": 14625, "s": 14443, "text": "getUTCSeconds(): It returns seconds (0-59) according to universal time of the given date object.var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCSeconds()); // 33\n" }, { "code": null, "e": 14711, "s": 14625, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nconsole.log(d.getUTCSeconds()); // 33\n" }, { "code": null, "e": 14888, "s": 14711, "text": "setDate(): It is used to set the date of a month to the date object in local time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setDate(13);\nconsole.log(d.getDate()); // 13\n" }, { "code": null, "e": 14983, "s": 14888, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nd.setDate(13);\nconsole.log(d.getDate()); // 13\n" }, { "code": null, "e": 15157, "s": 14983, "text": "setFullYear(): It is used to set year to the date object in local time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setYear(2018);\nconsole.log(d.getFullYear()); // 2018\n" }, { "code": null, "e": 15260, "s": 15157, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nd.setYear(2018);\nconsole.log(d.getFullYear()); // 2018\n" }, { "code": null, "e": 15432, "s": 15260, "text": "setHours(): It is used to set hour (0-23) to the date object in local time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setHours(19);\nconsole.log(d.getHours()); // 19\n" }, { "code": null, "e": 15529, "s": 15432, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nd.setHours(19);\nconsole.log(d.getHours()); // 19\n" }, { "code": null, "e": 15725, "s": 15529, "text": "setMilliseconds(): It is used to set milliseconds to the date object in local time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setMilliseconds(200);\nconsole.log(d.getMilliseconds()); // 200\n" }, { "code": null, "e": 15838, "s": 15725, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nd.setMilliseconds(200);\nconsole.log(d.getMilliseconds()); // 200\n" }, { "code": null, "e": 16019, "s": 15838, "text": "setMinutes(): It is used to set minutes (0-59) to the date object in local time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setMinutes(20);\nconsole.log(d.getMinutes()); // 20\n" }, { "code": null, "e": 16120, "s": 16019, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nd.setMinutes(20);\nconsole.log(d.getMinutes()); // 20\n" }, { "code": null, "e": 16291, "s": 16120, "text": "setMonth(): It is used to set month (0-11) to the date object in local time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setMonth(8);\nconsole.log(d.getMonth()); // 8\n" }, { "code": null, "e": 16386, "s": 16291, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nd.setMonth(8);\nconsole.log(d.getMonth()); // 8\n" }, { "code": null, "e": 16567, "s": 16386, "text": "setSeconds(): It is used to set seconds (0-59) to the date object in local time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setSeconds(34);\nconsole.log(d.getSeconds()); // 34\n" }, { "code": null, "e": 16668, "s": 16567, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nd.setSeconds(34);\nconsole.log(d.getSeconds()); // 34\n" }, { "code": null, "e": 16904, "s": 16668, "text": "setTime(): It is used to set milliseconds after January 1, 1970 00:00:00 UTC to the date object in local time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setTime(1570815753000);\nconsole.log(d.toDateString()); // \"Fri Oct 11 2019\"\n" }, { "code": null, "e": 17030, "s": 16904, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nd.setTime(1570815753000);\nconsole.log(d.toDateString()); // \"Fri Oct 11 2019\"\n" }, { "code": null, "e": 17232, "s": 17030, "text": "setUTCDate(): It is used to set date of the month (0-11) to the date object according to universal time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCDate(12);\nconsole.log(d.getDate()); // 12\n" }, { "code": null, "e": 17330, "s": 17232, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCDate(12);\nconsole.log(d.getDate()); // 12\n" }, { "code": null, "e": 17528, "s": 17330, "text": "setUTCFullYear(): It is used to set year to the date object according to universal time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCFullYear(2018);\nconsole.log(d.getFullYear()); // 2018\n" }, { "code": null, "e": 17638, "s": 17528, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCFullYear(2018);\nconsole.log(d.getFullYear()); // 2018\n" }, { "code": null, "e": 17831, "s": 17638, "text": "setUTCHours(): It is used to set hours (0-23) to the date object according to universal time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCHours(16);\nconsole.log(d.getHours()); // 21\n" }, { "code": null, "e": 17931, "s": 17831, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCHours(16);\nconsole.log(d.getHours()); // 21\n" }, { "code": null, "e": 18147, "s": 17931, "text": "setUTCMilliseconds(): It is used to set milliseconds to the date object according to universal time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCMilliseconds(166);\nconsole.log(d.getMilliseconds()); // 166\n" }, { "code": null, "e": 18263, "s": 18147, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCMilliseconds(166);\nconsole.log(d.getMilliseconds()); // 166\n" }, { "code": null, "e": 18464, "s": 18263, "text": "setUTCMinutes(): It is used to set minutes (0-59) to the date object according to universal time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCMinutes(22);\nconsole.log(d.getMinutes()); // 52\n" }, { "code": null, "e": 18568, "s": 18464, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCMinutes(22);\nconsole.log(d.getMinutes()); // 52\n" }, { "code": null, "e": 18759, "s": 18568, "text": "setUTCMonth(): It is used to set month (0-11) to the date object according to universal time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCMonth(8);\nconsole.log(d.getMonth()); // 8\n" }, { "code": null, "e": 18857, "s": 18759, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCMonth(8);\nconsole.log(d.getMonth()); // 8\n" }, { "code": null, "e": 19058, "s": 18857, "text": "setUTCSeconds(): It is used to set seconds (0-59) to the date object according to universal time.var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCSeconds(10);\nconsole.log(d.getSeconds()); // 10\n" }, { "code": null, "e": 19162, "s": 19058, "text": "var d = new Date(\"October 11, 2019 16:30:33\");\nd.setUTCSeconds(10);\nconsole.log(d.getSeconds()); // 10\n" }, { "code": null, "e": 19187, "s": 19162, "text": "Date Conversion Methods:" }, { "code": null, "e": 21360, "s": 19187, "text": "toDateString(): It returns the string representation for the date portion of the date object.var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toDateString()); // \"Fri Oct 11 2019\"\ntoISOString(): It returns the string representation for the date portion of the date object using ISO 8601 extended format.var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toISOString()); // \"2019-10-11T14:00:33.000Z\"\ntoJSON(): It returns the string representation for the date portion of the date object.var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toJSON()); // \"2019-10-11T14:00:33.000Z\"\ntoLocaleDateString(): It takes two parameters (optional) – locale and options and returns the string representation for the date portion according to specified locale.var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toLocaleDateString()); // \"10/11/2019\"\n\n// 10.2019\nconsole.log(d.toLocaleDateString(\"de-DE\", {year:'numeric', month: 'numeric'}))\ntoLocaleString(): It returns the string of date object of date portion in locale format.var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toLocaleString()); // \"10/11/2019, 7:30:33 PM\"\ntoLocaleTimeString(): It returns the string representation for the time portion of the date object.var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toLocaleTimeString()); // \"7:30:33 PM\"\ntoString(): It returns the string representation for date of the date object.var d = new Date(2019, 9, 11, 19, 30, 33);\n\n// \"Fri Oct 11 2019 19:30:33 GMT+0530 (India Standard Time)\"\nconsole.log(d.toString()); \ntoTimeString(): It returns the string representation for the time portion of the date object.var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toTimeString()); // \"19:30:33 GMT+0530 (India Standard Time)\"\ntoUTCString(): It returns the string representation for the date object in format of universal timezone.var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toUTCString()); // \"Fri, 11 Oct 2019 14:00:33 GMT\"\nvalueOf(): It returns the number of milliseconds elapsed from January 1, 1970 00:00:00 UTC to the date provided.var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.valueOf()); // 1570802433000\n" }, { "code": null, "e": 21549, "s": 21360, "text": "toDateString(): It returns the string representation for the date portion of the date object.var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toDateString()); // \"Fri Oct 11 2019\"\n" }, { "code": null, "e": 21645, "s": 21549, "text": "var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toDateString()); // \"Fri Oct 11 2019\"\n" }, { "code": null, "e": 21872, "s": 21645, "text": "toISOString(): It returns the string representation for the date portion of the date object using ISO 8601 extended format.var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toISOString()); // \"2019-10-11T14:00:33.000Z\"\n" }, { "code": null, "e": 21976, "s": 21872, "text": "var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toISOString()); // \"2019-10-11T14:00:33.000Z\"\n" }, { "code": null, "e": 22162, "s": 21976, "text": "toJSON(): It returns the string representation for the date portion of the date object.var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toJSON()); // \"2019-10-11T14:00:33.000Z\"\n" }, { "code": null, "e": 22261, "s": 22162, "text": "var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toJSON()); // \"2019-10-11T14:00:33.000Z\"\n" }, { "code": null, "e": 22616, "s": 22261, "text": "toLocaleDateString(): It takes two parameters (optional) – locale and options and returns the string representation for the date portion according to specified locale.var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toLocaleDateString()); // \"10/11/2019\"\n\n// 10.2019\nconsole.log(d.toLocaleDateString(\"de-DE\", {year:'numeric', month: 'numeric'}))\n" }, { "code": null, "e": 22804, "s": 22616, "text": "var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toLocaleDateString()); // \"10/11/2019\"\n\n// 10.2019\nconsole.log(d.toLocaleDateString(\"de-DE\", {year:'numeric', month: 'numeric'}))\n" }, { "code": null, "e": 22997, "s": 22804, "text": "toLocaleString(): It returns the string of date object of date portion in locale format.var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toLocaleString()); // \"10/11/2019, 7:30:33 PM\"\n" }, { "code": null, "e": 23102, "s": 22997, "text": "var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toLocaleString()); // \"10/11/2019, 7:30:33 PM\"\n" }, { "code": null, "e": 23298, "s": 23102, "text": "toLocaleTimeString(): It returns the string representation for the time portion of the date object.var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toLocaleTimeString()); // \"7:30:33 PM\"\n" }, { "code": null, "e": 23395, "s": 23298, "text": "var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toLocaleTimeString()); // \"7:30:33 PM\"\n" }, { "code": null, "e": 23606, "s": 23395, "text": "toString(): It returns the string representation for date of the date object.var d = new Date(2019, 9, 11, 19, 30, 33);\n\n// \"Fri Oct 11 2019 19:30:33 GMT+0530 (India Standard Time)\"\nconsole.log(d.toString()); \n" }, { "code": null, "e": 23740, "s": 23606, "text": "var d = new Date(2019, 9, 11, 19, 30, 33);\n\n// \"Fri Oct 11 2019 19:30:33 GMT+0530 (India Standard Time)\"\nconsole.log(d.toString()); \n" }, { "code": null, "e": 23953, "s": 23740, "text": "toTimeString(): It returns the string representation for the time portion of the date object.var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toTimeString()); // \"19:30:33 GMT+0530 (India Standard Time)\"\n" }, { "code": null, "e": 24073, "s": 23953, "text": "var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toTimeString()); // \"19:30:33 GMT+0530 (India Standard Time)\"\n" }, { "code": null, "e": 24286, "s": 24073, "text": "toUTCString(): It returns the string representation for the date object in format of universal timezone.var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toUTCString()); // \"Fri, 11 Oct 2019 14:00:33 GMT\"\n" }, { "code": null, "e": 24395, "s": 24286, "text": "var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.toUTCString()); // \"Fri, 11 Oct 2019 14:00:33 GMT\"\n" }, { "code": null, "e": 24594, "s": 24395, "text": "valueOf(): It returns the number of milliseconds elapsed from January 1, 1970 00:00:00 UTC to the date provided.var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.valueOf()); // 1570802433000\n" }, { "code": null, "e": 24681, "s": 24594, "text": "var d = new Date(2019, 9, 11, 19, 30, 33);\nconsole.log(d.valueOf()); // 1570802433000\n" }, { "code": null, "e": 24695, "s": 24681, "text": "JavaScript-ES" }, { "code": null, "e": 24702, "s": 24695, "text": "Picked" }, { "code": null, "e": 24713, "s": 24702, "text": "JavaScript" }, { "code": null, "e": 24730, "s": 24713, "text": "Web Technologies" }, { "code": null, "e": 24828, "s": 24730, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24889, "s": 24828, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 24961, "s": 24889, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 25001, "s": 24961, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 25043, "s": 25001, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 25084, "s": 25043, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 25117, "s": 25084, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 25179, "s": 25117, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 25240, "s": 25179, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 25290, "s": 25240, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to create a Portfolio Gallery using HTML and CSS ?
02 Jun, 2022 To create a portfolio gallery we will need only HTML and CSS. We can use JavaScript also but in this article, limits are set so we will use HTML and CSS only. Divide the whole article into two different sections in the 1st section, we will create the structure for the portfolio gallery and in the second section, we will make sure the gallery looks attractive. The portfolio gallery is useful when your website contains different types of content or so much content. With the help of a portfolio gallery, you can easily display all the contents on your front page to the user. Creating Structure: In this section, we will create the basic website structure of the portfolio. Here, we will attach the title attribute so the user can know what will be the content type on each grid of the portfolio. HTML code: In this section, we will design the basic structure of the Portfolio Gallery. HTML <!DOCTYPE html><html> <head> <title> Create a Portfolio Gallery using HTML and CSS </title> <meta name="viewport" content="width=device-width, initial-scale=1"></head> <body> <!-- title and tag --> <div class="container"> <h1>GeeksforGeeks</h1> <h3>A Computer Science Portal for Geeks</h3> <hr> <!-- Content of the body--> <h2>Portfolio</h2> <div class="row"> <div class="column"> <div class="content"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/html.png" alt="" style="width:100%"> <h3> <a href="#">HTML Tutorials</a> </h3> <p> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. </p> </div> </div> <div class="column"> <div class="content"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/CSS.png" alt="" style="width:100%"> <h3> <a href="#">CSS Tutorials</a> </h3> <p> Cascading Style Sheets, fondly referred to as CSS, is a simply designed language intended to simplify the process of making web pages presentable. CSS allows you to apply styles to web pages. </p> </div> </div> <div class="column"> <div class="content"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/php-1.png" alt="" style="width:100%"> <h3> <a href="#">PHP Tutorials</a> </h3> <p> The term PHP is an acronym for PHP: Hypertext Preprocessor. PHP is a server-side scripting language designed specifically for web development. PHP can be easily embedded in HTML files. </p> </div> </div> <div class="column"> <div class="content"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/javascript.png" alt="" style="width:100%"> <h3> <a href="#">JavaScript Tutorials</a> </h3> <p> Javascript was developed by Brendan Eich in 1995. At first, it was called LiveScript but was later name to JavaScript. JavaScript is the muscle of the structure </p> </div> </div> </div> </div></body> </html> Designing Structure: In the previous section, we created the structure of the basic website and now we are going to use CSS to design the structure of the web page. CSS code: CSS <style> /* wildcard styling */ * { box-sizing: border-box; } /* padding for whole body */ body { padding: 15px; } /* styling body */ .container { max-width: 1200px; margin: auto; } h1 { color: green; } /* anchor tag decoration */ a { text-decoration: none; color: #5673C8; } a:hover { color: lightblue; } /* paragraph tag decoration */ p { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 4; overflow: hidden; } /* row and column decoration */ .row { margin: 0px -18px; padding: 8px; } .row > .column { padding: 6px; } .column { float: left; width: 25%; } .row:after { content: ""; display: table; clear: both; } /* content decoration */ .content { background-color: white; padding: 10px; border: 1px solid gray; } /* window size 850 width set */ @media screen and (max-width: 850px) { .column { width: 50%; } } /* window size 400 width set */ @media screen and (max-width: 400px) { .column { width: 100%; } }</style> Combining the HTML and CSS Code: Combining both HTML and CSS section code to make a complete Portfolio Gallery. HTML <!DOCTYPE html><html> <head> <title> Create a Portfolio Gallery using HTML and CSS </title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> /* wildcard styling */ * { box-sizing: border-box; } /* padding for whole body */ body { padding: 15px; } /* styling body */ .container { max-width: 1200px; margin: auto; } h1 { color: green; } /* anchor tag decoration */ a { text-decoration: none; color: #5673C8; } a:hover { color: lightblue; } /* paragraph tag decoration */ p { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 4; overflow: hidden; } /* row and column decoration */ .row { margin: 0px -18px; padding: 8px; } .row > .column { padding: 6px; } .column { float: left; width: 25%; } .row:after { content: ""; display: table; clear: both; } /* content decoration */ .content { background-color: white; padding: 10px; border: 1px solid gray; } /* window size 850 width set */ @media screen and (max-width: 850px) { .column { width: 50%; } } /* window size 400 width set */ @media screen and (max-width: 400px) { .column { width: 100%; } } </style></head> <body> <!-- title and tag --> <div class="container"> <h1>GeeksforGeeks</h1> <h3>A Computer Science Portal for Geeks</h3> <hr> <!-- Content of the body--> <h2>Portfolio</h2> <div class="row"> <div class="column"> <div class="content"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/html.png" alt="" style="width:100%"> <h3> <a href="#">HTML Tutorials</a> </h3> <p> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. </p> </div> </div> <div class="column"> <div class="content"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/CSS.png" alt="" style="width:100%"> <h3> <a href="#">CSS Tutorials</a> </h3> <p> Cascading Style Sheets, fondly referred to as CSS, is a simply designed language intended to simplify the process of making web pages presentable. CSS allows you to apply styles to web pages. </p> </div> </div> <div class="column"> <div class="content"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/php-1.png" alt="" style="width:100%"> <h3> <a href="#">PHP Tutorials</a> </h3> <p> The term PHP is an acronym for PHP: Hypertext Preprocessor. PHP is a server-side scripting language designed specifically for web development. PHP can be easily embedded in HTML files. </p> </div> </div> <div class="column"> <div class="content"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/javascript.png" alt="" style="width:100%"> <h3> <a href="#">JavaScript Tutorials</a> </h3> <p> Javascript was developed by Brendan Eich in 1995. At first, it was called LiveScript but was later name to JavaScript. JavaScript is the muscle of the structure </p> </div> </div> </div> </div></body> </html> Output: Supported Browser: Google Chrome Microsoft Edge Firefox Opera Safari ysachin2314 akshaysingh98088 simranarora5sos Kanchan_Ray CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Jun, 2022" }, { "code": null, "e": 631, "s": 52, "text": "To create a portfolio gallery we will need only HTML and CSS. We can use JavaScript also but in this article, limits are set so we will use HTML and CSS only. Divide the whole article into two different sections in the 1st section, we will create the structure for the portfolio gallery and in the second section, we will make sure the gallery looks attractive. The portfolio gallery is useful when your website contains different types of content or so much content. With the help of a portfolio gallery, you can easily display all the contents on your front page to the user. " }, { "code": null, "e": 853, "s": 631, "text": "Creating Structure: In this section, we will create the basic website structure of the portfolio. Here, we will attach the title attribute so the user can know what will be the content type on each grid of the portfolio. " }, { "code": null, "e": 942, "s": 853, "text": "HTML code: In this section, we will design the basic structure of the Portfolio Gallery." }, { "code": null, "e": 947, "s": 942, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> Create a Portfolio Gallery using HTML and CSS </title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"></head> <body> <!-- title and tag --> <div class=\"container\"> <h1>GeeksforGeeks</h1> <h3>A Computer Science Portal for Geeks</h3> <hr> <!-- Content of the body--> <h2>Portfolio</h2> <div class=\"row\"> <div class=\"column\"> <div class=\"content\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/html.png\" alt=\"\" style=\"width:100%\"> <h3> <a href=\"#\">HTML Tutorials</a> </h3> <p> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. </p> </div> </div> <div class=\"column\"> <div class=\"content\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/CSS.png\" alt=\"\" style=\"width:100%\"> <h3> <a href=\"#\">CSS Tutorials</a> </h3> <p> Cascading Style Sheets, fondly referred to as CSS, is a simply designed language intended to simplify the process of making web pages presentable. CSS allows you to apply styles to web pages. </p> </div> </div> <div class=\"column\"> <div class=\"content\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/php-1.png\" alt=\"\" style=\"width:100%\"> <h3> <a href=\"#\">PHP Tutorials</a> </h3> <p> The term PHP is an acronym for PHP: Hypertext Preprocessor. PHP is a server-side scripting language designed specifically for web development. PHP can be easily embedded in HTML files. </p> </div> </div> <div class=\"column\"> <div class=\"content\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/javascript.png\" alt=\"\" style=\"width:100%\"> <h3> <a href=\"#\">JavaScript Tutorials</a> </h3> <p> Javascript was developed by Brendan Eich in 1995. At first, it was called LiveScript but was later name to JavaScript. JavaScript is the muscle of the structure </p> </div> </div> </div> </div></body> </html>", "e": 4421, "s": 947, "text": null }, { "code": null, "e": 4588, "s": 4421, "text": "Designing Structure: In the previous section, we created the structure of the basic website and now we are going to use CSS to design the structure of the web page. " }, { "code": null, "e": 4598, "s": 4588, "text": "CSS code:" }, { "code": null, "e": 4602, "s": 4598, "text": "CSS" }, { "code": "<style> /* wildcard styling */ * { box-sizing: border-box; } /* padding for whole body */ body { padding: 15px; } /* styling body */ .container { max-width: 1200px; margin: auto; } h1 { color: green; } /* anchor tag decoration */ a { text-decoration: none; color: #5673C8; } a:hover { color: lightblue; } /* paragraph tag decoration */ p { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 4; overflow: hidden; } /* row and column decoration */ .row { margin: 0px -18px; padding: 8px; } .row > .column { padding: 6px; } .column { float: left; width: 25%; } .row:after { content: \"\"; display: table; clear: both; } /* content decoration */ .content { background-color: white; padding: 10px; border: 1px solid gray; } /* window size 850 width set */ @media screen and (max-width: 850px) { .column { width: 50%; } } /* window size 400 width set */ @media screen and (max-width: 400px) { .column { width: 100%; } }</style>", "e": 5932, "s": 4602, "text": null }, { "code": null, "e": 6045, "s": 5932, "text": "Combining the HTML and CSS Code: Combining both HTML and CSS section code to make a complete Portfolio Gallery. " }, { "code": null, "e": 6050, "s": 6045, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> Create a Portfolio Gallery using HTML and CSS </title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <style> /* wildcard styling */ * { box-sizing: border-box; } /* padding for whole body */ body { padding: 15px; } /* styling body */ .container { max-width: 1200px; margin: auto; } h1 { color: green; } /* anchor tag decoration */ a { text-decoration: none; color: #5673C8; } a:hover { color: lightblue; } /* paragraph tag decoration */ p { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 4; overflow: hidden; } /* row and column decoration */ .row { margin: 0px -18px; padding: 8px; } .row > .column { padding: 6px; } .column { float: left; width: 25%; } .row:after { content: \"\"; display: table; clear: both; } /* content decoration */ .content { background-color: white; padding: 10px; border: 1px solid gray; } /* window size 850 width set */ @media screen and (max-width: 850px) { .column { width: 50%; } } /* window size 400 width set */ @media screen and (max-width: 400px) { .column { width: 100%; } } </style></head> <body> <!-- title and tag --> <div class=\"container\"> <h1>GeeksforGeeks</h1> <h3>A Computer Science Portal for Geeks</h3> <hr> <!-- Content of the body--> <h2>Portfolio</h2> <div class=\"row\"> <div class=\"column\"> <div class=\"content\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/html.png\" alt=\"\" style=\"width:100%\"> <h3> <a href=\"#\">HTML Tutorials</a> </h3> <p> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. </p> </div> </div> <div class=\"column\"> <div class=\"content\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/CSS.png\" alt=\"\" style=\"width:100%\"> <h3> <a href=\"#\">CSS Tutorials</a> </h3> <p> Cascading Style Sheets, fondly referred to as CSS, is a simply designed language intended to simplify the process of making web pages presentable. CSS allows you to apply styles to web pages. </p> </div> </div> <div class=\"column\"> <div class=\"content\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/php-1.png\" alt=\"\" style=\"width:100%\"> <h3> <a href=\"#\">PHP Tutorials</a> </h3> <p> The term PHP is an acronym for PHP: Hypertext Preprocessor. PHP is a server-side scripting language designed specifically for web development. PHP can be easily embedded in HTML files. </p> </div> </div> <div class=\"column\"> <div class=\"content\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/javascript.png\" alt=\"\" style=\"width:100%\"> <h3> <a href=\"#\">JavaScript Tutorials</a> </h3> <p> Javascript was developed by Brendan Eich in 1995. At first, it was called LiveScript but was later name to JavaScript. JavaScript is the muscle of the structure </p> </div> </div> </div> </div></body> </html> ", "e": 11213, "s": 6050, "text": null }, { "code": null, "e": 11222, "s": 11213, "text": "Output: " }, { "code": null, "e": 11241, "s": 11222, "text": "Supported Browser:" }, { "code": null, "e": 11255, "s": 11241, "text": "Google Chrome" }, { "code": null, "e": 11270, "s": 11255, "text": "Microsoft Edge" }, { "code": null, "e": 11278, "s": 11270, "text": "Firefox" }, { "code": null, "e": 11284, "s": 11278, "text": "Opera" }, { "code": null, "e": 11292, "s": 11284, "text": "Safari " }, { "code": null, "e": 11304, "s": 11292, "text": "ysachin2314" }, { "code": null, "e": 11321, "s": 11304, "text": "akshaysingh98088" }, { "code": null, "e": 11337, "s": 11321, "text": "simranarora5sos" }, { "code": null, "e": 11349, "s": 11337, "text": "Kanchan_Ray" }, { "code": null, "e": 11358, "s": 11349, "text": "CSS-Misc" }, { "code": null, "e": 11368, "s": 11358, "text": "HTML-Misc" }, { "code": null, "e": 11372, "s": 11368, "text": "CSS" }, { "code": null, "e": 11377, "s": 11372, "text": "HTML" }, { "code": null, "e": 11394, "s": 11377, "text": "Web Technologies" }, { "code": null, "e": 11421, "s": 11394, "text": "Web technologies Questions" }, { "code": null, "e": 11426, "s": 11421, "text": "HTML" }, { "code": null, "e": 11524, "s": 11426, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11561, "s": 11524, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 11600, "s": 11561, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 11639, "s": 11600, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 11703, "s": 11639, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 11764, "s": 11703, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 11788, "s": 11764, "text": "REST API (Introduction)" }, { "code": null, "e": 11841, "s": 11788, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 11901, "s": 11841, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 11962, "s": 11901, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Ambiguous Grammar - GeeksforGeeks
12 Nov, 2021 You can also read our previously discussed article on Classification of Context Free Grammars. Context Free Grammars(CFGs) are classified based on: Number of Derivation trees Number of strings Depending on Number of Derivation trees, CFGs are sub-divided into 2 types: Ambiguous grammars Unambiguous grammars Ambiguous grammar: A CFG is said to ambiguous if there exists more than one derivation tree for the given input string i.e., more than one LeftMost Derivation Tree (LMDT) or RightMost Derivation Tree (RMDT). Definition: G = (V,T,P,S) is a CFG is said to be ambiguous if and only if there exist a string in T* that has more than one parse tree.where V is a finite set of variables.T is a finite set of terminals.P is a finite set of productions of the form, A -> α, where A is a variable and α ∈ (V ∪ T)* S is a designated variable called the start symbol. For Example: 1. Let us consider this grammar : E -> E+E|id We can create 2 parse tree from this grammar to obtain a string id+id+id : The following are the 2 parse trees generated by left most derivation: Both the above parse trees are derived from same grammar rules but both parse trees are different. Hence the grammar is ambiguous. 2. Let us now consider the following grammar: Set of alphabets ∑ = {0,...,9, +, *, (, )} E -> I E -> E + E E -> E * E E -> (E) I -> ε | 0 | 1 | ... | 9 From the above grammar String 3*2+5 can be derived in 2 ways: I) First leftmost derivation II) Second leftmost derivation E=>E*E E=>E+E =>I*E =>E*E+E =>3*E+E =>I*E+E =>3*I+E =>3*E+E =>3*2+E =>3*I+E =>3*2+I =>3*2+I =>3*2+5 =>3*2+5 Following are some examples of ambiguous grammars: S-> aS |Sa| Є E-> E +E | E*E| id A -> AA | (A) | a S -> SS|AB , A -> Aa|a , B -> Bb|b Whereas following grammars are unambiguous: S -> (L) | a, L -> LS | S S -> AA , A -> aA , A -> b Inherently ambiguous Language: Let L be a Context Free Language (CFL). If every Context-Free Grammar G with Language L = L(G) is ambiguous, then L is said to be inherently ambiguous Language. Ambiguity is a property of grammar not languages. Ambiguous grammar is unlikely to be useful for a programming language, because two parse trees structures(or more) for the same string(program) implies two different meanings (executable programs) for the program. An inherently ambiguous language would be absolutely unsuitable as a programming language, because we would not have any way of fixing a unique structure for all its programs. For example, L = {anbncm} ∪ {anbmcm} Note : Ambiguity of grammar is undecidable, i.e. there is no particular algorithm for removing the ambiguity of grammar, but we can remove ambiguity by: Disambiguate the grammar i.e., rewriting the grammar such that there is only one derivation or parse tree possible for a string of the language which the grammar represents. This article is compiled by Saikiran Goud Burra. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above VaibhavRai3 vaibhavsinghtanwar Compiler Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Construction of LL(1) Parsing Table Types of Parsers in Compiler Design Directed Acyclic graph in Compiler Design (with examples) Difference between Compiler and Interpreter Recursive Descent Parser Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 26597, "s": 26569, "text": "\n12 Nov, 2021" }, { "code": null, "e": 26693, "s": 26597, "text": " You can also read our previously discussed article on Classification of Context Free Grammars." }, { "code": null, "e": 26747, "s": 26693, "text": " Context Free Grammars(CFGs) are classified based on:" }, { "code": null, "e": 26774, "s": 26747, "text": "Number of Derivation trees" }, { "code": null, "e": 26792, "s": 26774, "text": "Number of strings" }, { "code": null, "e": 26869, "s": 26792, "text": " Depending on Number of Derivation trees, CFGs are sub-divided into 2 types:" }, { "code": null, "e": 26888, "s": 26869, "text": "Ambiguous grammars" }, { "code": null, "e": 26909, "s": 26888, "text": "Unambiguous grammars" }, { "code": null, "e": 27527, "s": 26909, "text": " Ambiguous grammar: A CFG is said to ambiguous if there exists more than one derivation tree for the given input string i.e., more than one LeftMost Derivation Tree (LMDT) or RightMost Derivation Tree (RMDT). Definition: G = (V,T,P,S) is a CFG is said to be ambiguous if and only if there exist a string in T* that has more than one parse tree.where V is a finite set of variables.T is a finite set of terminals.P is a finite set of productions of the form, A -> α, where A is a variable and α ∈ (V ∪ T)* S is a designated variable called the start symbol. For Example: 1. Let us consider this grammar : E -> E+E|id" }, { "code": null, "e": 27604, "s": 27527, "text": "We can create 2 parse tree from this grammar to obtain a string id+id+id :" }, { "code": null, "e": 27675, "s": 27604, "text": "The following are the 2 parse trees generated by left most derivation:" }, { "code": null, "e": 27855, "s": 27675, "text": "Both the above parse trees are derived from same grammar rules but both parse trees are different. Hence the grammar is ambiguous. 2. Let us now consider the following grammar: " }, { "code": null, "e": 27973, "s": 27855, "text": "Set of alphabets ∑ = {0,...,9, +, *, (, )}\n\nE -> I \nE -> E + E\nE -> E * E\nE -> (E)\nI -> ε | 0 | 1 | ... | 9\n \n" }, { "code": null, "e": 28036, "s": 27973, "text": "From the above grammar String 3*2+5 can be derived in 2 ways: " }, { "code": null, "e": 28479, "s": 28036, "text": "I) First leftmost derivation II) Second leftmost derivation\n E=>E*E E=>E+E\n =>I*E =>E*E+E\n =>3*E+E =>I*E+E\n =>3*I+E =>3*E+E\n =>3*2+E =>3*I+E\n =>3*2+I =>3*2+I\n =>3*2+5 =>3*2+5\n\n" }, { "code": null, "e": 28532, "s": 28479, "text": " Following are some examples of ambiguous grammars: " }, { "code": null, "e": 28546, "s": 28532, "text": "S-> aS |Sa| Є" }, { "code": null, "e": 28565, "s": 28546, "text": "E-> E +E | E*E| id" }, { "code": null, "e": 28583, "s": 28565, "text": "A -> AA | (A) | a" }, { "code": null, "e": 28618, "s": 28583, "text": "S -> SS|AB , A -> Aa|a , B -> Bb|b" }, { "code": null, "e": 28663, "s": 28618, "text": "Whereas following grammars are unambiguous: " }, { "code": null, "e": 28689, "s": 28663, "text": "S -> (L) | a, L -> LS | S" }, { "code": null, "e": 28716, "s": 28689, "text": "S -> AA , A -> aA , A -> b" }, { "code": null, "e": 29174, "s": 28716, "text": "Inherently ambiguous Language: Let L be a Context Free Language (CFL). If every Context-Free Grammar G with Language L = L(G) is ambiguous, then L is said to be inherently ambiguous Language. Ambiguity is a property of grammar not languages. Ambiguous grammar is unlikely to be useful for a programming language, because two parse trees structures(or more) for the same string(program) implies two different meanings (executable programs) for the program." }, { "code": null, "e": 29350, "s": 29174, "text": "An inherently ambiguous language would be absolutely unsuitable as a programming language, because we would not have any way of fixing a unique structure for all its programs." }, { "code": null, "e": 29363, "s": 29350, "text": "For example," }, { "code": null, "e": 29388, "s": 29363, "text": "L = {anbncm} ∪ {anbmcm} " }, { "code": null, "e": 29721, "s": 29388, "text": " Note : Ambiguity of grammar is undecidable, i.e. there is no particular algorithm for removing the ambiguity of grammar, but we can remove ambiguity by: Disambiguate the grammar i.e., rewriting the grammar such that there is only one derivation or parse tree possible for a string of the language which the grammar represents. " }, { "code": null, "e": 29894, "s": 29721, "text": "This article is compiled by Saikiran Goud Burra. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 29906, "s": 29894, "text": "VaibhavRai3" }, { "code": null, "e": 29925, "s": 29906, "text": "vaibhavsinghtanwar" }, { "code": null, "e": 29941, "s": 29925, "text": "Compiler Design" }, { "code": null, "e": 29949, "s": 29941, "text": "GATE CS" }, { "code": null, "e": 30047, "s": 29949, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30083, "s": 30047, "text": "Construction of LL(1) Parsing Table" }, { "code": null, "e": 30119, "s": 30083, "text": "Types of Parsers in Compiler Design" }, { "code": null, "e": 30177, "s": 30119, "text": "Directed Acyclic graph in Compiler Design (with examples)" }, { "code": null, "e": 30221, "s": 30177, "text": "Difference between Compiler and Interpreter" }, { "code": null, "e": 30246, "s": 30221, "text": "Recursive Descent Parser" }, { "code": null, "e": 30266, "s": 30246, "text": "Layers of OSI Model" }, { "code": null, "e": 30290, "s": 30266, "text": "ACID Properties in DBMS" }, { "code": null, "e": 30303, "s": 30290, "text": "TCP/IP Model" }, { "code": null, "e": 30330, "s": 30303, "text": "Types of Operating Systems" } ]
Zoho Interview Preparation Process and Experience - GeeksforGeeks
29 Jan, 2020 Zoho is one of the best product based company in India with friendly environment. Many engineers are passionate toward coding nowadays. But many face lot of difficulty in cracking the interview. There are few tips i like to share based on my interview experience and past guidance from my college staff and seniors. There are three stage to crack the Zoho. Learn, practice and fail. The success teach us to about us but failure teaches how we need to improve our-self. This is a cyclic process.In Zoho Software Development role there are several few round as stated below: Written testCodingCoding related to oopsHR Round Written test Coding Coding related to oops HR Round Written test: The candidate must be strong in the syntax and how it work for the given input. The candidate must be very strong in the loop and conditional statement. The pointer concept plays a major role in the shortlisting the candidate. For example, //Write C code here#include<stdio.h>#include<conio.h>void main(){ int a; if(a=0){printf("%d", a); else {printf("zoho"); break; }} Options: a. zoho b.Error c. 0 d.no output Answer: Error because of break statement Coding The candidate will be given a simple problem statement to solve. The candidate can use any programming language like c, c++ and java to solve the particular problem statement. If the candidate solves the particular problem statement within the particular time slot he/she will get the next problem statement and the process continues for the day. If not the candidate has to leave the company. Coding related to oops The candidate must be strong in oops concept the candidate will be tested based on the logical thinking. The candidate must be strong in the logic and he/she must be in the situation to execute those programs without any errors. HR InterviewThe candidate’s attitude and the personality is checked and her/his programming ability. The HR round will be based on the candidate’s resume. Marketing Zoho Interview Experiences Zoho Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (On-Campus) Microsoft Interview Experience for Internship (Via Engage) Amazon Interview Experience Amazon Interview Experience for SDE-1 Directi Interview | Set 7 (Programming Questions) Difference between ANN, CNN and RNN Amazon Interview Experience (Off-Campus) 2022 Amazon Interview Experience for SDE-1(Off-Campus) Amazon Interview Experience for SDE-1 Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
[ { "code": null, "e": 25188, "s": 25160, "text": "\n29 Jan, 2020" }, { "code": null, "e": 25762, "s": 25188, "text": "Zoho is one of the best product based company in India with friendly environment. Many engineers are passionate toward coding nowadays. But many face lot of difficulty in cracking the interview. There are few tips i like to share based on my interview experience and past guidance from my college staff and seniors. There are three stage to crack the Zoho. Learn, practice and fail. The success teach us to about us but failure teaches how we need to improve our-self. This is a cyclic process.In Zoho Software Development role there are several few round as stated below:" }, { "code": null, "e": 25811, "s": 25762, "text": "Written testCodingCoding related to oopsHR Round" }, { "code": null, "e": 25824, "s": 25811, "text": "Written test" }, { "code": null, "e": 25831, "s": 25824, "text": "Coding" }, { "code": null, "e": 25854, "s": 25831, "text": "Coding related to oops" }, { "code": null, "e": 25863, "s": 25854, "text": "HR Round" }, { "code": null, "e": 25877, "s": 25863, "text": "Written test:" }, { "code": null, "e": 26117, "s": 25877, "text": "The candidate must be strong in the syntax and how it work for the given input. The candidate must be very strong in the loop and conditional statement. The pointer concept plays a major role in the shortlisting the candidate. For example," }, { "code": "//Write C code here#include<stdio.h>#include<conio.h>void main(){ int a; if(a=0){printf(\"%d\", a); else {printf(\"zoho\"); break; }}", "e": 26249, "s": 26117, "text": null }, { "code": null, "e": 26258, "s": 26249, "text": "Options:" }, { "code": null, "e": 26326, "s": 26258, "text": "a. zoho b.Error\nc. 0 d.no output \n" }, { "code": null, "e": 26367, "s": 26326, "text": "Answer: Error because of break statement" }, { "code": null, "e": 26374, "s": 26367, "text": "Coding" }, { "code": null, "e": 26768, "s": 26374, "text": "The candidate will be given a simple problem statement to solve. The candidate can use any programming language like c, c++ and java to solve the particular problem statement. If the candidate solves the particular problem statement within the particular time slot he/she will get the next problem statement and the process continues for the day. If not the candidate has to leave the company." }, { "code": null, "e": 26791, "s": 26768, "text": "Coding related to oops" }, { "code": null, "e": 27020, "s": 26791, "text": "The candidate must be strong in oops concept the candidate will be tested based on the logical thinking. The candidate must be strong in the logic and he/she must be in the situation to execute those programs without any errors." }, { "code": null, "e": 27175, "s": 27020, "text": "HR InterviewThe candidate’s attitude and the personality is checked and her/his programming ability. The HR round will be based on the candidate’s resume." }, { "code": null, "e": 27185, "s": 27175, "text": "Marketing" }, { "code": null, "e": 27190, "s": 27185, "text": "Zoho" }, { "code": null, "e": 27212, "s": 27190, "text": "Interview Experiences" }, { "code": null, "e": 27217, "s": 27212, "text": "Zoho" }, { "code": null, "e": 27315, "s": 27217, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27365, "s": 27315, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 27424, "s": 27365, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 27452, "s": 27424, "text": "Amazon Interview Experience" }, { "code": null, "e": 27490, "s": 27452, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 27540, "s": 27490, "text": "Directi Interview | Set 7 (Programming Questions)" }, { "code": null, "e": 27576, "s": 27540, "text": "Difference between ANN, CNN and RNN" }, { "code": null, "e": 27622, "s": 27576, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 27672, "s": 27622, "text": "Amazon Interview Experience for SDE-1(Off-Campus)" }, { "code": null, "e": 27710, "s": 27672, "text": "Amazon Interview Experience for SDE-1" } ]
hostname - Unix, Linux Command
hostname - show or set the system's host name. hostname [-v] [-a] [--alias] [-d] [--domain] [-f] [--fqdn] [-A] [--all-fqdns] [-i] [--ip-address] [-I] [--all-ip-addresses] [--long] [-s] [--short] [-y] [--yp] [--nis] hostname [-v] [-F filename] [--file filename] [hostname] hostname [-v] [-h] [--help] [-V] [--version] Hostname is the program that is used to either set or display the current host, domain or node name of the system. These names are used by many of the networking programs to identify the machine. Example-1: To print the hostname of the system : $ hostname output: # hostnametestserver.tutorialspoint.com Example-2: To print IP address of the computer : $ hostname -i output: 192.168.134.128 Example-3: To print the domain name : $ hostname -d output: tutorialspoint.com Example-4: To print short hostname : $ hostname -s output: testserver 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10625, "s": 10577, "text": "hostname - show or set the system's host name." }, { "code": null, "e": 10897, "s": 10625, "text": "hostname [-v] [-a] [--alias] [-d] [--domain] [-f] [--fqdn] [-A] [--all-fqdns] [-i] [--ip-address] [-I] [--all-ip-addresses] [--long] [-s] [--short] [-y] [--yp] [--nis]\n\nhostname [-v] [-F filename] [--file filename] [hostname]\n\nhostname [-v] [-h] [--help] [-V] [--version]" }, { "code": null, "e": 11094, "s": 10897, "text": "Hostname is the program that is used to either set or display the current host, domain or node name of the system.\n These names are used by many of the networking programs to identify the machine." }, { "code": null, "e": 11105, "s": 11094, "text": "Example-1:" }, { "code": null, "e": 11143, "s": 11105, "text": "To print the hostname of the system :" }, { "code": null, "e": 11154, "s": 11143, "text": "$ hostname" }, { "code": null, "e": 11162, "s": 11154, "text": "output:" }, { "code": null, "e": 11202, "s": 11162, "text": "# hostnametestserver.tutorialspoint.com" }, { "code": null, "e": 11213, "s": 11202, "text": "Example-2:" }, { "code": null, "e": 11251, "s": 11213, "text": "To print IP address of the computer :" }, { "code": null, "e": 11265, "s": 11251, "text": "$ hostname -i" }, { "code": null, "e": 11273, "s": 11265, "text": "output:" }, { "code": null, "e": 11289, "s": 11273, "text": "192.168.134.128" }, { "code": null, "e": 11300, "s": 11289, "text": "Example-3:" }, { "code": null, "e": 11327, "s": 11300, "text": "To print the domain name :" }, { "code": null, "e": 11341, "s": 11327, "text": "$ hostname -d" }, { "code": null, "e": 11349, "s": 11341, "text": "output:" }, { "code": null, "e": 11368, "s": 11349, "text": "tutorialspoint.com" }, { "code": null, "e": 11379, "s": 11368, "text": "Example-4:" }, { "code": null, "e": 11405, "s": 11379, "text": "To print short hostname :" }, { "code": null, "e": 11419, "s": 11405, "text": "$ hostname -s" }, { "code": null, "e": 11427, "s": 11419, "text": "output:" }, { "code": null, "e": 11438, "s": 11427, "text": "testserver" }, { "code": null, "e": 11473, "s": 11438, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 11501, "s": 11473, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11535, "s": 11501, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11552, "s": 11535, "text": " Frahaan Hussain" }, { "code": null, "e": 11585, "s": 11552, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 11596, "s": 11585, "text": " Pradeep D" }, { "code": null, "e": 11631, "s": 11596, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11647, "s": 11631, "text": " Musab Zayadneh" }, { "code": null, "e": 11680, "s": 11647, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 11692, "s": 11680, "text": " GUHARAJANM" }, { "code": null, "e": 11724, "s": 11692, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 11732, "s": 11724, "text": " Uplatz" }, { "code": null, "e": 11739, "s": 11732, "text": " Print" }, { "code": null, "e": 11750, "s": 11739, "text": " Add Notes" } ]
Scala - do-while Loop
Unlike while loop, which tests the loop condition at the top of the loop, the do-while loop checks its condition at the bottom of the loop. A do-while loop is similar to a while loop, except that a do-while loop is guaranteed to execute at least one time. The following is the syntax for do-while loop. do { statement(s); } while( condition ); Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false. Try the following example program to understand loop control statements (while statement) in Scala Programming Language. object Demo { def main(args: Array[String]) { // Local variable declaration: var a = 10; // do loop execution do { println( "Value of a: " + a ); a = a + 1; } while( a < 20 ) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 82 Lectures 7 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 52 Lectures 1.5 hours Bigdata Engineer 76 Lectures 5.5 hours Bigdata Engineer 69 Lectures 7.5 hours Bigdata Engineer 46 Lectures 4.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2254, "s": 1998, "text": "Unlike while loop, which tests the loop condition at the top of the loop, the do-while loop checks its condition at the bottom of the loop. A do-while loop is similar to a while loop, except that a do-while loop is guaranteed to execute at least one time." }, { "code": null, "e": 2301, "s": 2254, "text": "The following is the syntax for do-while loop." }, { "code": null, "e": 2347, "s": 2301, "text": "do {\n statement(s);\n} \nwhile( condition );\n" }, { "code": null, "e": 2672, "s": 2347, "text": "Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false." }, { "code": null, "e": 2793, "s": 2672, "text": "Try the following example program to understand loop control statements (while statement) in Scala Programming Language." }, { "code": null, "e": 3033, "s": 2793, "text": "object Demo {\n def main(args: Array[String]) {\n // Local variable declaration:\n var a = 10;\n\n // do loop execution\n do {\n println( \"Value of a: \" + a );\n a = a + 1;\n }\n while( a < 20 )\n }\n}" }, { "code": null, "e": 3140, "s": 3033, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 3174, "s": 3140, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 3325, "s": 3174, "text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 15\nvalue of a: 16\nvalue of a: 17\nvalue of a: 18\nvalue of a: 19\n" }, { "code": null, "e": 3358, "s": 3325, "text": "\n 82 Lectures \n 7 hours \n" }, { "code": null, "e": 3377, "s": 3358, "text": " Arnab Chakraborty" }, { "code": null, "e": 3412, "s": 3377, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3433, "s": 3412, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 3468, "s": 3433, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3486, "s": 3468, "text": " Bigdata Engineer" }, { "code": null, "e": 3521, "s": 3486, "text": "\n 76 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3539, "s": 3521, "text": " Bigdata Engineer" }, { "code": null, "e": 3574, "s": 3539, "text": "\n 69 Lectures \n 7.5 hours \n" }, { "code": null, "e": 3592, "s": 3574, "text": " Bigdata Engineer" }, { "code": null, "e": 3627, "s": 3592, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3650, "s": 3627, "text": " Stone River ELearning" }, { "code": null, "e": 3657, "s": 3650, "text": " Print" }, { "code": null, "e": 3668, "s": 3657, "text": " Add Notes" } ]
Angular CLI - ng run Command
This chapter explains the syntax, argument and options of ng run command along with an example. The syntax for ng run command is as follows − ng run project:target[:configuration] ng run command runs an Architect target with an optional custom builder configuration defined in angular.json in your project. Here project is the name of the application as defined in angular.json. The argument for ng run command is as follows − Options are optional parameters. A named builder configuration, defined in the "configurations" section of angular.json. The builder uses the named configuration to run the given target. Aliases: -c. Shows a help message for this command in the console. Default: false. First move to an angular project updated using ng generate command and then run the command.This chapter is available at https://www.tutorialspoint.com/angular_cli/angular_cli_ng_generate.htm. An example for ng run command is given below − \>Node\>TutorialsPoint> ng run TutorialsPoint:build Generating ES5 bundles for differential loading... ES5 bundle generation complete. chunk {polyfills} polyfills-es2015.js, polyfills-es2015.js.map (polyfills) 141 kB [initial] [rendered] chunk {polyfills-es5} polyfills-es5.js, polyfills-es5.js.map (polyfills-es5) 656 kB [initial] [rendered] chunk {main} main-es2015.js, main-es2015.js.map (main) 12.9 kB [initial] [rendered] chunk {main} main-es5.js, main-es5.js.map (main) 15.1 kB [initial] [rendered] chunk {runtime} runtime-es2015.js, runtime-es2015.js.map (runtime) 6.16 kB [entry] [rendered] chunk {runtime} runtime-es5.js, runtime-es5.js.map (runtime) 6.16 kB [entry] [rendered] chunk {styles} styles-es2015.js, styles-es2015.js.map (styles) 12.4 kB [initial] [rendered] chunk {styles} styles-es5.js, styles-es5.js.map (styles) 13.9 kB [initial] [rendered] chunk {vendor} vendor-es2015.js, vendor-es2015.js.map (vendor) 2.66 MB [initial] [rendered] chunk {vendor} vendor-es5.js, vendor-es5.js.map (vendor) 3.11 MB [initial] [rendered] Date: 2020-06-04T02:31:28.919Z - Hash: dd73885c28e550d01341 - Time: 13742ms Here ng build command has built our project TutorialsPoint successfully. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2171, "s": 2075, "text": "This chapter explains the syntax, argument and options of ng run command along with an example." }, { "code": null, "e": 2217, "s": 2171, "text": "The syntax for ng run command is as follows −" }, { "code": null, "e": 2256, "s": 2217, "text": "ng run project:target[:configuration]\n" }, { "code": null, "e": 2456, "s": 2256, "text": "ng run command runs an Architect target with an optional custom builder configuration defined in angular.json in your project. Here project is the name of the application as defined in angular.json. " }, { "code": null, "e": 2504, "s": 2456, "text": "The argument for ng run command is as follows −" }, { "code": null, "e": 2537, "s": 2504, "text": "Options are optional parameters." }, { "code": null, "e": 2691, "s": 2537, "text": "A named builder configuration, defined in the \"configurations\" section of angular.json. The builder uses the named configuration to run the given target." }, { "code": null, "e": 2704, "s": 2691, "text": "Aliases: -c." }, { "code": null, "e": 2758, "s": 2704, "text": "Shows a help message for this command in the console." }, { "code": null, "e": 2774, "s": 2758, "text": "Default: false." }, { "code": null, "e": 2967, "s": 2774, "text": "First move to an angular project updated using ng generate command and then run the command.This chapter is available at\nhttps://www.tutorialspoint.com/angular_cli/angular_cli_ng_generate.htm." }, { "code": null, "e": 3014, "s": 2967, "text": "An example for ng run command is given below −" }, { "code": null, "e": 4135, "s": 3014, "text": "\\>Node\\>TutorialsPoint> ng run TutorialsPoint:build\nGenerating ES5 bundles for differential loading...\nES5 bundle generation complete.\n\nchunk {polyfills} polyfills-es2015.js, polyfills-es2015.js.map (polyfills) 141 kB [initial] [rendered]\nchunk {polyfills-es5} polyfills-es5.js, polyfills-es5.js.map (polyfills-es5) 656 kB [initial] [rendered]\nchunk {main} main-es2015.js, main-es2015.js.map (main) 12.9 kB [initial] [rendered]\nchunk {main} main-es5.js, main-es5.js.map (main) 15.1 kB [initial] [rendered]\nchunk {runtime} runtime-es2015.js, runtime-es2015.js.map (runtime) 6.16 kB [entry] [rendered]\nchunk {runtime} runtime-es5.js, runtime-es5.js.map (runtime) 6.16 kB [entry] [rendered]\nchunk {styles} styles-es2015.js, styles-es2015.js.map (styles) 12.4 kB [initial] [rendered]\nchunk {styles} styles-es5.js, styles-es5.js.map (styles) 13.9 kB [initial] [rendered]\nchunk {vendor} vendor-es2015.js, vendor-es2015.js.map (vendor) 2.66 MB [initial] [rendered]\nchunk {vendor} vendor-es5.js, vendor-es5.js.map (vendor) 3.11 MB [initial] [rendered]\nDate: 2020-06-04T02:31:28.919Z - Hash: dd73885c28e550d01341 - Time: 13742ms\n" }, { "code": null, "e": 4208, "s": 4135, "text": "Here ng build command has built our project TutorialsPoint successfully." }, { "code": null, "e": 4243, "s": 4208, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4257, "s": 4243, "text": " Anadi Sharma" }, { "code": null, "e": 4292, "s": 4257, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4306, "s": 4292, "text": " Anadi Sharma" }, { "code": null, "e": 4341, "s": 4306, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4361, "s": 4341, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 4396, "s": 4361, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4413, "s": 4396, "text": " Frahaan Hussain" }, { "code": null, "e": 4446, "s": 4413, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 4458, "s": 4446, "text": " Senol Atac" }, { "code": null, "e": 4493, "s": 4458, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4505, "s": 4493, "text": " Senol Atac" }, { "code": null, "e": 4512, "s": 4505, "text": " Print" }, { "code": null, "e": 4523, "s": 4512, "text": " Add Notes" } ]
JavaScript | Check if a key exists inside a JSON object - GeeksforGeeks
29 May, 2019 Given a JSON Object, the task is to check whether a key exists in Object or not using JavaScript. We’re going to discuss few methods. hasOwnProperty()This method returns a boolean denoting whether the object has the defined property as its own property (as opposed to inheriting it).Syntax:obj.hasOwnProperty(prop) Parameters:prop: This parameter is required. It specifies the string name or Symbol of the property to check.Return value:It return a boolean denoting if the object has the specified property as own property. obj.hasOwnProperty(prop) Parameters: prop: This parameter is required. It specifies the string name or Symbol of the property to check. Return value:It return a boolean denoting if the object has the specified property as own property. Example 1: This example checks for prop_1 of the obj by using hasOwnProperty property. <!DOCTYPE HTML><html> <head> <title> JavaScript | Check if a key exists inside a JSON object. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> check </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var obj = { prop_1: "val_1", prop_2: "val_2", prop_3: "val_3", prop_4: "val_4", }; el_up.innerHTML = JSON.stringify(obj); function gfg_Run() { ans = ""; var prop = 'prop_1'; if (obj.hasOwnProperty(prop)) { ans = "var 'obj' has " + prop + " property"; } else { ans = "var 'obj' has not " + prop + " property"; } el_down.innerHTML = ans; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example checks for pro_1 of the obj by simple array access. <!DOCTYPE HTML><html> <head> <title> JavaScript | Check if a key exists inside a JSON object. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> check </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var obj = { prop_1: "val_1", prop_2: "val_2", prop_3: "val_3", prop_4: "val_4", }; el_up.innerHTML = JSON.stringify(obj); function gfg_Run() { ans = ""; var prop = 'pro_1'; if (obj[prop]) { ans = "var 'obj' has " + prop + " property"; } else { ans = "var 'obj' has not " + prop + " property"; } el_down.innerHTML = ans; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JSON JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux 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": 24736, "s": 24708, "text": "\n29 May, 2019" }, { "code": null, "e": 24870, "s": 24736, "text": "Given a JSON Object, the task is to check whether a key exists in Object or not using JavaScript. We’re going to discuss few methods." }, { "code": null, "e": 25260, "s": 24870, "text": "hasOwnProperty()This method returns a boolean denoting whether the object has the defined property as its own property (as opposed to inheriting it).Syntax:obj.hasOwnProperty(prop)\nParameters:prop: This parameter is required. It specifies the string name or Symbol of the property to check.Return value:It return a boolean denoting if the object has the specified property as own property." }, { "code": null, "e": 25286, "s": 25260, "text": "obj.hasOwnProperty(prop)\n" }, { "code": null, "e": 25298, "s": 25286, "text": "Parameters:" }, { "code": null, "e": 25397, "s": 25298, "text": "prop: This parameter is required. It specifies the string name or Symbol of the property to check." }, { "code": null, "e": 25497, "s": 25397, "text": "Return value:It return a boolean denoting if the object has the specified property as own property." }, { "code": null, "e": 25584, "s": 25497, "text": "Example 1: This example checks for prop_1 of the obj by using hasOwnProperty property." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Check if a key exists inside a JSON object. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> check </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var obj = { prop_1: \"val_1\", prop_2: \"val_2\", prop_3: \"val_3\", prop_4: \"val_4\", }; el_up.innerHTML = JSON.stringify(obj); function gfg_Run() { ans = \"\"; var prop = 'prop_1'; if (obj.hasOwnProperty(prop)) { ans = \"var 'obj' has \" + prop + \" property\"; } else { ans = \"var 'obj' has not \" + prop + \" property\"; } el_down.innerHTML = ans; } </script></body> </html>", "e": 26804, "s": 25584, "text": null }, { "code": null, "e": 26812, "s": 26804, "text": "Output:" }, { "code": null, "e": 26843, "s": 26812, "text": "Before clicking on the button:" }, { "code": null, "e": 26873, "s": 26843, "text": "After clicking on the button:" }, { "code": null, "e": 26949, "s": 26873, "text": "Example 2: This example checks for pro_1 of the obj by simple array access." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Check if a key exists inside a JSON object. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> check </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var obj = { prop_1: \"val_1\", prop_2: \"val_2\", prop_3: \"val_3\", prop_4: \"val_4\", }; el_up.innerHTML = JSON.stringify(obj); function gfg_Run() { ans = \"\"; var prop = 'pro_1'; if (obj[prop]) { ans = \"var 'obj' has \" + prop + \" property\"; } else { ans = \"var 'obj' has not \" + prop + \" property\"; } el_down.innerHTML = ans; } </script></body> </html>", "e": 28153, "s": 26949, "text": null }, { "code": null, "e": 28161, "s": 28153, "text": "Output:" }, { "code": null, "e": 28192, "s": 28161, "text": "Before clicking on the button:" }, { "code": null, "e": 28222, "s": 28192, "text": "After clicking on the button:" }, { "code": null, "e": 28238, "s": 28222, "text": "JavaScript-Misc" }, { "code": null, "e": 28243, "s": 28238, "text": "JSON" }, { "code": null, "e": 28254, "s": 28243, "text": "JavaScript" }, { "code": null, "e": 28271, "s": 28254, "text": "Web Technologies" }, { "code": null, "e": 28369, "s": 28271, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28378, "s": 28369, "text": "Comments" }, { "code": null, "e": 28391, "s": 28378, "text": "Old Comments" }, { "code": null, "e": 28436, "s": 28391, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28497, "s": 28436, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28569, "s": 28497, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28621, "s": 28569, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 28667, "s": 28621, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 28709, "s": 28667, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28742, "s": 28709, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28785, "s": 28742, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28847, "s": 28785, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to create a modal popup using JavaScript and CSS?
Creating a modal popup means adding a dialog box, which generates on click of a button and close when user clicks anywhere outside of the popup. Here’s how a popup looks like below with header and a text. You can also add a footer to it − To create a modal popup using CSS and JavaScript, try to run the following code − Live Demo <!DOCTYPE html> <html> <head> <style> .popup { display: none; position: fixed; z-index: 1; left: 0; top: 0; width: 100%; height: 100%; background-color: #F1F1F1; background-color: rgba(0,0,0,0.4); -webkit-animation-name: fadeIn; -webkit-animation-duration: 0.4s; animation-name: fadeIn; animation-duration: 0.4s } .popup-content { position: fixed; bottom: 0; background-color: #ffffff; width: 100%; -webkit-animation-name: slideIn; -webkit-animation-duration: 0.5s; animation-name: slideIn; animation-duration: 0.5s } .end { color: white; float: right; font-size: 15px; font-weight: bold; } .end:hover, .end:focus { color: #000; text-decoration: underline; cursor: pointer; } .popup-header { padding: 1px 10px; background-color: #8AC1E0; color: white; } .popup-body {padding: 1px 5px;} @-webkit-keyframes slideIn { from {bottom: -300px; opacity: 0} to {bottom: 0; opacity: 1} } @keyframes slideIn { from {bottom: -300px; opacity: 0} to {bottom: 0; opacity: 1} } @-webkit-keyframes fadeIn { from {opacity: 0} to {opacity: 1} } @keyframes fadeIn { from {opacity: 0} to {opacity: 1} } </style> </head> <body> <h2>Heading</h2> <button id="btn">Click for Popup</button> <div id="myModal" class="popup"> <!-- Modal content --> <div class="popup-content"> <div class="popup-header"> <span class="end">×</span> <h2>Header</h2> </div> <div class="popup-body"> <p>Demo Text</p> </div> </div> </div> <script> var popup = document.getElementById('myModal'); var myBytton = document.getElementById("btn"); var span = document.getElementsByClassName("end")[0]; myBytton.onclick = function() { popup.style.display = "block"; } span.onclick = function() { popup.style.display = "none"; } window.onclick = function(event) { if (event.target == popup) { popup.style.display = "none"; } } </script> </body> </html>
[ { "code": null, "e": 1207, "s": 1062, "text": "Creating a modal popup means adding a dialog box, which generates on click of a button and close when user clicks anywhere outside of the popup." }, { "code": null, "e": 1301, "s": 1207, "text": "Here’s how a popup looks like below with header and a text. You can also add a footer to it −" }, { "code": null, "e": 1383, "s": 1301, "text": "To create a modal popup using CSS and JavaScript, try to run the following code −" }, { "code": null, "e": 1393, "s": 1383, "text": "Live Demo" }, { "code": null, "e": 4161, "s": 1393, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .popup {\n display: none;\n position: fixed;\n z-index: 1;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n background-color: #F1F1F1;\n background-color: rgba(0,0,0,0.4);\n -webkit-animation-name: fadeIn;\n -webkit-animation-duration: 0.4s;\n animation-name: fadeIn;\n animation-duration: 0.4s\n }\n .popup-content {\n position: fixed;\n bottom: 0;\n background-color: #ffffff;\n width: 100%;\n -webkit-animation-name: slideIn;\n -webkit-animation-duration: 0.5s;\n animation-name: slideIn;\n animation-duration: 0.5s\n }\n .end {\n color: white;\n float: right;\n font-size: 15px;\n font-weight: bold;\n }\n .end:hover,\n .end:focus {\n color: #000;\n text-decoration: underline;\n cursor: pointer;\n }\n .popup-header {\n padding: 1px 10px;\n background-color: #8AC1E0;\n color: white;\n }\n .popup-body {padding: 1px 5px;}\n @-webkit-keyframes slideIn {\n from {bottom: -300px; opacity: 0}\n to {bottom: 0; opacity: 1}\n }\n @keyframes slideIn {\n from {bottom: -300px; opacity: 0}\n to {bottom: 0; opacity: 1}\n }\n @-webkit-keyframes fadeIn {\n from {opacity: 0}\n to {opacity: 1}\n }\n @keyframes fadeIn {\n from {opacity: 0}\n to {opacity: 1}\n }\n </style>\n </head>\n <body>\n <h2>Heading</h2>\n <button id=\"btn\">Click for Popup</button>\n <div id=\"myModal\" class=\"popup\">\n <!-- Modal content -->\n <div class=\"popup-content\">\n <div class=\"popup-header\">\n <span class=\"end\">×</span>\n <h2>Header</h2>\n </div>\n <div class=\"popup-body\">\n <p>Demo Text</p>\n </div>\n </div>\n </div>\n <script>\n var popup = document.getElementById('myModal');\n var myBytton = document.getElementById(\"btn\");\n var span = document.getElementsByClassName(\"end\")[0];\n myBytton.onclick = function() {\n popup.style.display = \"block\";\n }\n span.onclick = function() {\n popup.style.display = \"none\";\n }\n window.onclick = function(event) {\n if (event.target == popup) {\n popup.style.display = \"none\";\n }\n }\n </script>\n </body>\n</html>" } ]
C++ Program to Implement Merge Sort Algorithm on Linked List
The merge sort technique is based on divide and conquer technique. We divide the while data set into smaller parts and merge them into a larger piece in sorted order. It is also very effective for worst cases because this algorithm has lower time complexity for worst case also. Linked list can be sorted using merge-sort very efficiently. For the linked list the merging task is very simple. We can simply update the links to merge them. In this section we will see how to sort the linked list using this approach. Time Complexity − O(n log n) for all cases Time Complexity − O(n log n) for all cases Space Complexity − O(n) Space Complexity − O(n) Input − The unsorted list: 14 20 78 98 20 45 Output − Array after Sorting: 14 20 20 45 78 98 Input − It takes two linked lists ll1 and ll2 Output − The merged list Begin if ll1 is empty, then return ll2 if ll2 is empty, then return ll1 if data(ll1) <= data(ll2), then new_head = ll1; next(new_head) = mergeList(next(ll1), ll2) else new_head = ll2; next(new_head) = mergeList(ll1, next(ll2)) return new_head End Input − The start pointer of a linked list, two output arguments ll1 and ll2 Output − Two linked list generated from the linked list Begin slow := start fast := next(start) while fast is not null, do fast := next(fast) if fast is not null, then slow := next(slow) fast := next(fast) end while ll1 := start ll2 := next(slow) next(slow) := null End Input − The linked list Output − Sorted linked list Begin head = start if head is null or next(head) is null, then return split_list(head, ll1, ll2) mergeSort(ll1) mergeSort(ll2) start := mergeList(ll1, ll2) End Live Demo #include<bits/stdc++.h> using namespace std; class node { //define node to store data and next address public: int data; node *next; }; void display(class node* start) { node* p = start; // current node set to head while(p != NULL) { //traverse until current node isn't NULL cout << p -> data << " "; p = p -> next; // go to next node } } node* getNode(int d) { node* temp = new node; temp -> data = d; temp -> next = NULL; return temp; } node* mergeList(node* ll1, node* ll2) { //function for merging two sorted list node* newhead = NULL; if(ll1 == NULL) return ll2; if(ll2 == NULL) return ll1; //recursively merge the lists if(ll1 -> data <= ll2 -> data) { newhead = ll1; newhead -> next = mergeList(ll1->next,ll2); } else { newhead = ll2; newhead -> next = mergeList(ll1,ll2->next); } return newhead; } void splitList(node* start, node** ll1,node** ll2) { //similar to flyod's tortoise algorithm node* slow = start; node* fast = start -> next; while(fast!= NULL) { fast = fast -> next; if(fast!= NULL) { slow = slow -> next; fast = fast -> next; } } *ll1 = start; *ll2 = slow -> next; //spliting slow -> next = NULL; } void mergeSort(node** start) { node* head = *start; node* ll1,*ll2; //base case if(head == NULL || head->next == NULL) { return; } splitList(head,&ll1,&ll2); //split the list in two halves //sort left and right sublists mergeSort(&ll1); mergeSort(&ll2); //merge two sorted list *start = mergeList(ll1,ll2); return; } int main() { cout << "Creating the linked list: " << endl; cout << "Enter 0 to stop building the list, else enter any integer" << endl; int k,count = 1,x; node* curr,*temp; cin >> k; node* head = getNode(k); //buliding list, first node cin >> k; temp = head; while(k) { curr = getNode(k); temp -> next = curr;//appending each node temp = temp -> next; cin >> k; } cout<<"Before sorting: " << endl; display(head); // displaying the list cout<<"\nAfter sorting: " << endl; mergeSort(&head); display(head); return 0; } Creating the linked list: Enter 0 to stop building the list, else enter any integer 89 54 15 64 74 98 10 24 26 0 Before sorting: 89 54 15 64 74 98 10 24 26 After sorting: 10 15 24 26 54 64 74 89 98
[ { "code": null, "e": 1341, "s": 1062, "text": "The merge sort technique is based on divide and conquer technique. We divide the while data set into smaller parts and merge them into a larger piece in sorted order. It is also very effective for worst cases because this algorithm has lower time complexity for worst case also." }, { "code": null, "e": 1578, "s": 1341, "text": "Linked list can be sorted using merge-sort very efficiently. For the linked list the merging task is very simple. We can simply update the links to merge them. In this section we will see how to sort the linked list using this approach." }, { "code": null, "e": 1621, "s": 1578, "text": "Time Complexity − O(n log n) for all cases" }, { "code": null, "e": 1664, "s": 1621, "text": "Time Complexity − O(n log n) for all cases" }, { "code": null, "e": 1688, "s": 1664, "text": "Space Complexity − O(n)" }, { "code": null, "e": 1712, "s": 1688, "text": "Space Complexity − O(n)" }, { "code": null, "e": 1805, "s": 1712, "text": "Input − The unsorted list: 14 20 78 98 20 45\nOutput − Array after Sorting: 14 20 20 45 78 98" }, { "code": null, "e": 1851, "s": 1805, "text": "Input − It takes two linked lists ll1 and ll2" }, { "code": null, "e": 1876, "s": 1851, "text": "Output − The merged list" }, { "code": null, "e": 2174, "s": 1876, "text": "Begin\n if ll1 is empty, then\n return ll2\n if ll2 is empty, then\n return ll1\n if data(ll1) <= data(ll2), then\n new_head = ll1;\n next(new_head) = mergeList(next(ll1), ll2)\n else\n new_head = ll2;\n next(new_head) = mergeList(ll1, next(ll2))\n return new_head\nEnd" }, { "code": null, "e": 2251, "s": 2174, "text": "Input − The start pointer of a linked list, two output arguments ll1 and ll2" }, { "code": null, "e": 2307, "s": 2251, "text": "Output − Two linked list generated from the linked list" }, { "code": null, "e": 2572, "s": 2307, "text": "Begin\n slow := start\n fast := next(start)\n while fast is not null, do\n fast := next(fast)\n if fast is not null, then\n slow := next(slow)\n fast := next(fast)\n end while\n ll1 := start\n ll2 := next(slow)\n next(slow) := null\nEnd" }, { "code": null, "e": 2596, "s": 2572, "text": "Input − The linked list" }, { "code": null, "e": 2624, "s": 2596, "text": "Output − Sorted linked list" }, { "code": null, "e": 2808, "s": 2624, "text": "Begin\n head = start\n if head is null or next(head) is null, then\n return\n split_list(head, ll1, ll2)\n mergeSort(ll1)\n mergeSort(ll2)\n start := mergeList(ll1, ll2)\nEnd" }, { "code": null, "e": 2819, "s": 2808, "text": " Live Demo" }, { "code": null, "e": 5055, "s": 2819, "text": "#include<bits/stdc++.h>\nusing namespace std;\nclass node { //define node to store data and next address\n public:\n int data;\n node *next;\n};\nvoid display(class node* start) {\n node* p = start; // current node set to head\n while(p != NULL) { //traverse until current node isn't NULL\n cout << p -> data << \" \";\n p = p -> next; // go to next node\n }\n}\nnode* getNode(int d) {\n node* temp = new node;\n temp -> data = d;\n temp -> next = NULL;\n return temp;\n}\nnode* mergeList(node* ll1, node* ll2) { //function for merging two sorted list\n node* newhead = NULL;\n if(ll1 == NULL)\n return ll2;\n if(ll2 == NULL)\n return ll1;\n //recursively merge the lists\n if(ll1 -> data <= ll2 -> data) {\n newhead = ll1;\n newhead -> next = mergeList(ll1->next,ll2);\n } else {\n newhead = ll2;\n newhead -> next = mergeList(ll1,ll2->next);\n }\n return newhead;\n}\nvoid splitList(node* start, node** ll1,node** ll2) {\n //similar to flyod's tortoise algorithm\n node* slow = start;\n node* fast = start -> next;\n while(fast!= NULL) {\n fast = fast -> next;\n if(fast!= NULL) {\n slow = slow -> next;\n fast = fast -> next;\n }\n }\n *ll1 = start;\n *ll2 = slow -> next;\n //spliting\n slow -> next = NULL;\n}\nvoid mergeSort(node** start) {\n node* head = *start;\n node* ll1,*ll2;\n //base case\n if(head == NULL || head->next == NULL) {\n return;\n }\n splitList(head,&ll1,&ll2); //split the list in two halves\n //sort left and right sublists\n mergeSort(&ll1);\n mergeSort(&ll2);\n //merge two sorted list\n *start = mergeList(ll1,ll2);\n return;\n}\nint main() {\n cout << \"Creating the linked list: \" << endl;\n cout << \"Enter 0 to stop building the list, else enter any integer\" << endl;\n int k,count = 1,x;\n node* curr,*temp;\n cin >> k;\n node* head = getNode(k); //buliding list, first node\n cin >> k;\n temp = head;\n while(k) {\n curr = getNode(k);\n temp -> next = curr;//appending each node\n temp = temp -> next;\n cin >> k;\n }\n cout<<\"Before sorting: \" << endl;\n display(head); // displaying the list\n cout<<\"\\nAfter sorting: \" << endl;\n mergeSort(&head);\n display(head);\n return 0;\n}" }, { "code": null, "e": 5253, "s": 5055, "text": "Creating the linked list:\nEnter 0 to stop building the list, else enter any integer\n89\n54\n15\n64\n74\n98\n10\n24\n26\n0\nBefore sorting:\n89 54 15 64 74 98 10 24 26\nAfter sorting:\n10 15 24 26 54 64 74 89 98" } ]