title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
3 Libraries You Should Know to Master Apache Kafka in Python | by Xiaoxu Gao | Towards Data Science
The world is empowered by data. We get tons of information every second, we clean it up, analyze it and create more valuable output, whether it is a log file, user activity, a chat message or something else. The faster we deliver, the more value we will bring to our customers. We’re in the era of a fast-paced and ever-changing environment. Apache Kafka is a distributed streaming platform that can publish, subscribe, store and process messages in real-time. Its pull-based architecture reduces the pressure on the service with a heavy load and makes it easy to scale. It moves a huge amount of data from the source to the destination with low latency. medium.com Kafka is a JVM based platform, so the mainstream programming language of the client is Java. But as the community is growing tremendously, high-quality open-sourced Python clients are also available and being used in production. In this article, I will cover the most well-known Python Kafka clients: kafka-python, pykafka and confluent-kafka and compare them. In the end, I will give my opinion on the pros and cons of each library. First thing first. Why Kafka? Kafka is intended for boosting an event-driven architecture. It empowers the architecture by providing high throughput, low latency, high durability, and high availability solution. (It doesn’t mean you can have all of them at the same time, there is always a tradeoff. Read this whitepaper to understand more.) www.confluent.io Besides its high performance, another attractive feature is the publish/subscribe model, where the sender doesn’t send messages specifically to a receiver. Instead, the messages are delivered to a centralized place that receivers can subscribe to, depending on the topic. By doing so, we can easily decouple applications and get rid of monolithic design. Let’s look at an example to understand why decoupling is better. You create a website that needs to send user activities somewhere, so you write a direct connection from your website to a real-time monitoring dashboard. It is a simple solution and works well. One day, you decide to store the user activities in a database for future analysis. So, you write another direct database connection to your website. Meanwhile, your website gets more and more traffic, and you want to empower it by adding an alerting service, real-time analysis service, etc. Your architecture will end up like this. Problems such as a massive code repo, security issues, scalability issues, and maintainability issues will hurt you. You need a hub to separate applications with a different role. For applications that create events, we call them producers. They publish events to a centralized hub. Each event (i.e. message) belongs to a topic. On the other side of the hub sit consumers. They subscribe to the topics that they need from the hub without directly talking to the producers. With this model in place, the architecture can be easily scaled and maintained. Engineers can focus more on the core business. You can download Apache Kafka from the official website. The Quickstart helps you to start up the server in 10 seconds. You can also download Apache Kafka from Confluent platform. It is by far the biggest Kafka-oriented streaming data platform. It provides a collection of infrastructure services surrounding Kafka to individuals and enterprises for making the data available as realtime streams. The founders were part of the team originally created Apache Kafka. Each Kafka server is called a broker, you can run it in a standalone mode or form a cluster. Besides Kafka, we need Zookeeper to store metadata about Kafka. Zookeeper acts like an orchestrator that manages the status of each broker within the distributed system. Let’s say we’ve set up the infrastructure with 1 Zookeeper and 1 Kafka broker. It’s time to connect to it! The original Java client provides 5 APIs: Producer API: Publish messages to the topics in the Kafka cluster. Consumer API: Consume messages from the topics in the Kafka cluster. Streams API: Consume messages from the topics and transform them into other topics in the Kafka cluster. The operations can be filtering, joining, mapping, grouping, etc. Connect API: Directly connect the Kafka cluster to a source system or a sink system without coding. The system can be a file, a relational database, Elasticsearch, etc. Admin API: Manage and inspect topics and brokers in the Kafka cluster. In the Python world, 3 out of 5 APIs have been implemented which are Producer API, Consumer API, and Admin API. There is no such Kafka Stream API yet in Python, but a good alternative would be Faust. The testing in this section is executed based on 1 Zookeeper and 1 Kafka broker installed locally. This is not about performance tuning, so I’m mostly using the default configurations provided by the library. Kafka-Python kafka-python is designed to function much like the official java client, with a sprinkling of pythonic interfaces. It’s best used with Kafka version 0.9+. The first release was in March 2014. It’s being actively maintained. Installation pip install kafka-python Producer Each message is sent via send() asynchronously. When called it adds the record to a buffer and returns immediately. This allows the producer to send records to Kafka brokers in batch mode for efficiency. Asynchronization can improve speed tremendously, but we should also understand a few things: In the asynchronous mode, the ordering is not guaranteed. You can’t control when each message is acknowledged (ack) by Kafka brokers.It’s a good practice to have a success callback and a failure callback for the producer. For example, you can write an Info log message in the success callback and an Exception log message in the failure callback.Extra messages might be sent before you receive an exception in the callback due to the fact that ordering can not be guaranteed. In the asynchronous mode, the ordering is not guaranteed. You can’t control when each message is acknowledged (ack) by Kafka brokers. It’s a good practice to have a success callback and a failure callback for the producer. For example, you can write an Info log message in the success callback and an Exception log message in the failure callback. Extra messages might be sent before you receive an exception in the callback due to the fact that ordering can not be guaranteed. If you want to avoid these problems, you can choose to send messages synchronously. The return of send() is a FutureRecordMetadata. By doing future.get(timeout=60), the producer will be blocked for at most 60 seconds until the message has been successfully acknowledged by the brokers. The drawback is the speed, it is relatively slow compared to asynchronous mode. Consumer The consumer instance is a Python iterator. The core of the consumer class is poll() method. It allows the consumer to keep pulling messages from the topic. One of its input parameters timeout_ms is default to 0, which means the method returns immediately with any records that are pulled and available in the buffer. You can increase timeout_ms to return a larger batch. By default, each consumer is an infinite listener, so it won’t stop until the program breaks. But on the other side, you are allowed to stop the consumer based on the message you received. For example, you can exit the loop and close the consumer if it reaches to a certain offset. The consumer can also be assigned to a partition or multiple partitions from multiple topics. This is the test result of kafka-python library. The size of each message is 100 bytes. The average throughput of the producer is 1.4MB/s. The average throughput of the consumer is 2.8MB/s. Confluent-kafka Confluent-kafka is a high-performance Kafka client for Python which leverages the high-performance C client librdkafka. Starting with version 1.0, these are distributed as self-contained binary wheels for OS X and Linux on PyPi. It supports Kafka version 0.8+. The first release was in May 2016. It’s being actively maintained. Installation For OS X and Linux, librdkafka is included in the package, there is to need to install it separately. pip install confluent-kafka For windows user, by the time I wrote this article, confluent-kafka hasn’t supported Python3.8 binary wheels on Windows yet. You will run into the issue of librdkafka. Please check their release note, it’s being actively developed. An alternative solution is to downgrade to Python3.7. Producer Confluent-kafka has incredible performance in terms of speed. The API design is somewhat similar to kafka-python. You can make it synchronous by putting flush() inside the loop. Consumer The Consumer API in confluent-kafka requires more code. Instead of calling a high-level method like consume(), you need to handle the while loop yourself. I would recommend you to create your own consume() which is essentially a Python generator. Whenever there is a message pulled and available in the buffer, it yields the message. By doing so, the main function will be clean and you are free to control the behavior of your consumer. For example, you can define a “session window” in consume(). If no messages are pulled within X seconds, then the consumer will stop. Or you can add a flag infinite=True as an input parameter to control if the consumer should be an infinite listener or not. This is the test result of conflunet-kafka library. The size of each message is 100 bytes. The average throughput of the producer is 21.97MB/s. The average throughput of the consumer is 16.8~28.7MB/s. PyKafka PyKafka is a programmer-friendly Kafka client for Python. It includes Python implementations of Kafka producers and consumers, which are optionally backed by a C extension built on librdkafka. It supports Kafka version 0.82+. The first release was in Aug 2012, but it hasn’t been updated since Nov 2018. Installation pip install pykafka librdkafka doesn’t come with the package, you need to install it separately in all the operating systems. Producer pykafka has a KafkaClient interface that covers both ProducerAPI and Consumer API. Messages can be sent in both async and sync mode. What I found out is that pykafka modifies the default value of some producer configurations such as linger_ms and min_queued_messages, which can have an impact on sending a small volume of data. You can compare it with the default configuration on Apache Kafka website. If you want to get the callback of each message, make sure you change min_queued_messages to 1, otherwise you won’t get any report if your data set is smaller than 70000. Consumer You can get a SimpleConsumer from the KafkaClinet interface. This is similar to kafka-python, where the poll is wrapped in the SimpleConsumer class. This is the test result of pykafka library. The size of each message is 100 bytes. The average throughput of the producer is 2.1MB/s. The average throughput of the consumer is 1.57MB/s. So far, I’ve explained the Producer API and Consumer API of each library. In terms of Admin API, kafka-python and confluent-kafka do provide explicit Admin API. You can use it in your unit testing where you want to create a topic and then delete it before executing the next test. Besides, if you’d like to build a Kafka monitoring dashboard in Python, Admin API can help you retrieve metadata of the cluster and topics. Confluent-kafka: Confluent-kafka has no doubt the best performance among the 3 libraries. The API is well designed and parameters keep the same name and same default as the original Apache Kafka. You can easily link it to the original parameter. Personally, I like the flexibility to customize consumer behavior. It is also being actively developed and supported by Confluent. A disadvantage is the fact that Windows users might need to struggle a bit to make it work. And debug can be tricky because of its C extension. kafka-python: kafka-python is a pure Python library without a C extension. The API is well designed and straightforward to use for beginners. It’s an actively developed project as well. The disadvantage of python-kafka is its speed. If you do care about the performance, I would recommend you to switch to confluent-kafka. pykafka: Compared to kafka-python and conflunet-kafka, the development of pykafka is less active. The release history shows that it hasn’t been updated since Nov 2018. Besides, pykafka has different API designs and uses different default parameters which might be not straightforward for the first time. I hope you enjoy this article! Leave your comments below if you have any thoughts.
[ { "code": null, "e": 514, "s": 172, "text": "The world is empowered by data. We get tons of information every second, we clean it up, analyze it and create more valuable output, whether it is a log file, user activity, a chat message or something else. The faster we deliver, the more value we will bring to our customers. We’re in the era of a fast-paced and ever-changing environment." }, { "code": null, "e": 827, "s": 514, "text": "Apache Kafka is a distributed streaming platform that can publish, subscribe, store and process messages in real-time. Its pull-based architecture reduces the pressure on the service with a heavy load and makes it easy to scale. It moves a huge amount of data from the source to the destination with low latency." }, { "code": null, "e": 838, "s": 827, "text": "medium.com" }, { "code": null, "e": 1067, "s": 838, "text": "Kafka is a JVM based platform, so the mainstream programming language of the client is Java. But as the community is growing tremendously, high-quality open-sourced Python clients are also available and being used in production." }, { "code": null, "e": 1272, "s": 1067, "text": "In this article, I will cover the most well-known Python Kafka clients: kafka-python, pykafka and confluent-kafka and compare them. In the end, I will give my opinion on the pros and cons of each library." }, { "code": null, "e": 1614, "s": 1272, "text": "First thing first. Why Kafka? Kafka is intended for boosting an event-driven architecture. It empowers the architecture by providing high throughput, low latency, high durability, and high availability solution. (It doesn’t mean you can have all of them at the same time, there is always a tradeoff. Read this whitepaper to understand more.)" }, { "code": null, "e": 1631, "s": 1614, "text": "www.confluent.io" }, { "code": null, "e": 1903, "s": 1631, "text": "Besides its high performance, another attractive feature is the publish/subscribe model, where the sender doesn’t send messages specifically to a receiver. Instead, the messages are delivered to a centralized place that receivers can subscribe to, depending on the topic." }, { "code": null, "e": 2051, "s": 1903, "text": "By doing so, we can easily decouple applications and get rid of monolithic design. Let’s look at an example to understand why decoupling is better." }, { "code": null, "e": 2539, "s": 2051, "text": "You create a website that needs to send user activities somewhere, so you write a direct connection from your website to a real-time monitoring dashboard. It is a simple solution and works well. One day, you decide to store the user activities in a database for future analysis. So, you write another direct database connection to your website. Meanwhile, your website gets more and more traffic, and you want to empower it by adding an alerting service, real-time analysis service, etc." }, { "code": null, "e": 2697, "s": 2539, "text": "Your architecture will end up like this. Problems such as a massive code repo, security issues, scalability issues, and maintainability issues will hurt you." }, { "code": null, "e": 3053, "s": 2697, "text": "You need a hub to separate applications with a different role. For applications that create events, we call them producers. They publish events to a centralized hub. Each event (i.e. message) belongs to a topic. On the other side of the hub sit consumers. They subscribe to the topics that they need from the hub without directly talking to the producers." }, { "code": null, "e": 3180, "s": 3053, "text": "With this model in place, the architecture can be easily scaled and maintained. Engineers can focus more on the core business." }, { "code": null, "e": 3300, "s": 3180, "text": "You can download Apache Kafka from the official website. The Quickstart helps you to start up the server in 10 seconds." }, { "code": null, "e": 3645, "s": 3300, "text": "You can also download Apache Kafka from Confluent platform. It is by far the biggest Kafka-oriented streaming data platform. It provides a collection of infrastructure services surrounding Kafka to individuals and enterprises for making the data available as realtime streams. The founders were part of the team originally created Apache Kafka." }, { "code": null, "e": 3908, "s": 3645, "text": "Each Kafka server is called a broker, you can run it in a standalone mode or form a cluster. Besides Kafka, we need Zookeeper to store metadata about Kafka. Zookeeper acts like an orchestrator that manages the status of each broker within the distributed system." }, { "code": null, "e": 4057, "s": 3908, "text": "Let’s say we’ve set up the infrastructure with 1 Zookeeper and 1 Kafka broker. It’s time to connect to it! The original Java client provides 5 APIs:" }, { "code": null, "e": 4124, "s": 4057, "text": "Producer API: Publish messages to the topics in the Kafka cluster." }, { "code": null, "e": 4193, "s": 4124, "text": "Consumer API: Consume messages from the topics in the Kafka cluster." }, { "code": null, "e": 4364, "s": 4193, "text": "Streams API: Consume messages from the topics and transform them into other topics in the Kafka cluster. The operations can be filtering, joining, mapping, grouping, etc." }, { "code": null, "e": 4533, "s": 4364, "text": "Connect API: Directly connect the Kafka cluster to a source system or a sink system without coding. The system can be a file, a relational database, Elasticsearch, etc." }, { "code": null, "e": 4604, "s": 4533, "text": "Admin API: Manage and inspect topics and brokers in the Kafka cluster." }, { "code": null, "e": 4804, "s": 4604, "text": "In the Python world, 3 out of 5 APIs have been implemented which are Producer API, Consumer API, and Admin API. There is no such Kafka Stream API yet in Python, but a good alternative would be Faust." }, { "code": null, "e": 5013, "s": 4804, "text": "The testing in this section is executed based on 1 Zookeeper and 1 Kafka broker installed locally. This is not about performance tuning, so I’m mostly using the default configurations provided by the library." }, { "code": null, "e": 5026, "s": 5013, "text": "Kafka-Python" }, { "code": null, "e": 5250, "s": 5026, "text": "kafka-python is designed to function much like the official java client, with a sprinkling of pythonic interfaces. It’s best used with Kafka version 0.9+. The first release was in March 2014. It’s being actively maintained." }, { "code": null, "e": 5263, "s": 5250, "text": "Installation" }, { "code": null, "e": 5288, "s": 5263, "text": "pip install kafka-python" }, { "code": null, "e": 5297, "s": 5288, "text": "Producer" }, { "code": null, "e": 5594, "s": 5297, "text": "Each message is sent via send() asynchronously. When called it adds the record to a buffer and returns immediately. This allows the producer to send records to Kafka brokers in batch mode for efficiency. Asynchronization can improve speed tremendously, but we should also understand a few things:" }, { "code": null, "e": 6070, "s": 5594, "text": "In the asynchronous mode, the ordering is not guaranteed. You can’t control when each message is acknowledged (ack) by Kafka brokers.It’s a good practice to have a success callback and a failure callback for the producer. For example, you can write an Info log message in the success callback and an Exception log message in the failure callback.Extra messages might be sent before you receive an exception in the callback due to the fact that ordering can not be guaranteed." }, { "code": null, "e": 6204, "s": 6070, "text": "In the asynchronous mode, the ordering is not guaranteed. You can’t control when each message is acknowledged (ack) by Kafka brokers." }, { "code": null, "e": 6418, "s": 6204, "text": "It’s a good practice to have a success callback and a failure callback for the producer. For example, you can write an Info log message in the success callback and an Exception log message in the failure callback." }, { "code": null, "e": 6548, "s": 6418, "text": "Extra messages might be sent before you receive an exception in the callback due to the fact that ordering can not be guaranteed." }, { "code": null, "e": 6914, "s": 6548, "text": "If you want to avoid these problems, you can choose to send messages synchronously. The return of send() is a FutureRecordMetadata. By doing future.get(timeout=60), the producer will be blocked for at most 60 seconds until the message has been successfully acknowledged by the brokers. The drawback is the speed, it is relatively slow compared to asynchronous mode." }, { "code": null, "e": 6923, "s": 6914, "text": "Consumer" }, { "code": null, "e": 7295, "s": 6923, "text": "The consumer instance is a Python iterator. The core of the consumer class is poll() method. It allows the consumer to keep pulling messages from the topic. One of its input parameters timeout_ms is default to 0, which means the method returns immediately with any records that are pulled and available in the buffer. You can increase timeout_ms to return a larger batch." }, { "code": null, "e": 7577, "s": 7295, "text": "By default, each consumer is an infinite listener, so it won’t stop until the program breaks. But on the other side, you are allowed to stop the consumer based on the message you received. For example, you can exit the loop and close the consumer if it reaches to a certain offset." }, { "code": null, "e": 7671, "s": 7577, "text": "The consumer can also be assigned to a partition or multiple partitions from multiple topics." }, { "code": null, "e": 7861, "s": 7671, "text": "This is the test result of kafka-python library. The size of each message is 100 bytes. The average throughput of the producer is 1.4MB/s. The average throughput of the consumer is 2.8MB/s." }, { "code": null, "e": 7877, "s": 7861, "text": "Confluent-kafka" }, { "code": null, "e": 8205, "s": 7877, "text": "Confluent-kafka is a high-performance Kafka client for Python which leverages the high-performance C client librdkafka. Starting with version 1.0, these are distributed as self-contained binary wheels for OS X and Linux on PyPi. It supports Kafka version 0.8+. The first release was in May 2016. It’s being actively maintained." }, { "code": null, "e": 8218, "s": 8205, "text": "Installation" }, { "code": null, "e": 8320, "s": 8218, "text": "For OS X and Linux, librdkafka is included in the package, there is to need to install it separately." }, { "code": null, "e": 8348, "s": 8320, "text": "pip install confluent-kafka" }, { "code": null, "e": 8634, "s": 8348, "text": "For windows user, by the time I wrote this article, confluent-kafka hasn’t supported Python3.8 binary wheels on Windows yet. You will run into the issue of librdkafka. Please check their release note, it’s being actively developed. An alternative solution is to downgrade to Python3.7." }, { "code": null, "e": 8643, "s": 8634, "text": "Producer" }, { "code": null, "e": 8821, "s": 8643, "text": "Confluent-kafka has incredible performance in terms of speed. The API design is somewhat similar to kafka-python. You can make it synchronous by putting flush() inside the loop." }, { "code": null, "e": 8830, "s": 8821, "text": "Consumer" }, { "code": null, "e": 9164, "s": 8830, "text": "The Consumer API in confluent-kafka requires more code. Instead of calling a high-level method like consume(), you need to handle the while loop yourself. I would recommend you to create your own consume() which is essentially a Python generator. Whenever there is a message pulled and available in the buffer, it yields the message." }, { "code": null, "e": 9526, "s": 9164, "text": "By doing so, the main function will be clean and you are free to control the behavior of your consumer. For example, you can define a “session window” in consume(). If no messages are pulled within X seconds, then the consumer will stop. Or you can add a flag infinite=True as an input parameter to control if the consumer should be an infinite listener or not." }, { "code": null, "e": 9727, "s": 9526, "text": "This is the test result of conflunet-kafka library. The size of each message is 100 bytes. The average throughput of the producer is 21.97MB/s. The average throughput of the consumer is 16.8~28.7MB/s." }, { "code": null, "e": 9735, "s": 9727, "text": "PyKafka" }, { "code": null, "e": 10039, "s": 9735, "text": "PyKafka is a programmer-friendly Kafka client for Python. It includes Python implementations of Kafka producers and consumers, which are optionally backed by a C extension built on librdkafka. It supports Kafka version 0.82+. The first release was in Aug 2012, but it hasn’t been updated since Nov 2018." }, { "code": null, "e": 10052, "s": 10039, "text": "Installation" }, { "code": null, "e": 10072, "s": 10052, "text": "pip install pykafka" }, { "code": null, "e": 10178, "s": 10072, "text": "librdkafka doesn’t come with the package, you need to install it separately in all the operating systems." }, { "code": null, "e": 10187, "s": 10178, "text": "Producer" }, { "code": null, "e": 10270, "s": 10187, "text": "pykafka has a KafkaClient interface that covers both ProducerAPI and Consumer API." }, { "code": null, "e": 10515, "s": 10270, "text": "Messages can be sent in both async and sync mode. What I found out is that pykafka modifies the default value of some producer configurations such as linger_ms and min_queued_messages, which can have an impact on sending a small volume of data." }, { "code": null, "e": 10590, "s": 10515, "text": "You can compare it with the default configuration on Apache Kafka website." }, { "code": null, "e": 10761, "s": 10590, "text": "If you want to get the callback of each message, make sure you change min_queued_messages to 1, otherwise you won’t get any report if your data set is smaller than 70000." }, { "code": null, "e": 10770, "s": 10761, "text": "Consumer" }, { "code": null, "e": 10919, "s": 10770, "text": "You can get a SimpleConsumer from the KafkaClinet interface. This is similar to kafka-python, where the poll is wrapped in the SimpleConsumer class." }, { "code": null, "e": 11105, "s": 10919, "text": "This is the test result of pykafka library. The size of each message is 100 bytes. The average throughput of the producer is 2.1MB/s. The average throughput of the consumer is 1.57MB/s." }, { "code": null, "e": 11526, "s": 11105, "text": "So far, I’ve explained the Producer API and Consumer API of each library. In terms of Admin API, kafka-python and confluent-kafka do provide explicit Admin API. You can use it in your unit testing where you want to create a topic and then delete it before executing the next test. Besides, if you’d like to build a Kafka monitoring dashboard in Python, Admin API can help you retrieve metadata of the cluster and topics." }, { "code": null, "e": 11543, "s": 11526, "text": "Confluent-kafka:" }, { "code": null, "e": 11903, "s": 11543, "text": "Confluent-kafka has no doubt the best performance among the 3 libraries. The API is well designed and parameters keep the same name and same default as the original Apache Kafka. You can easily link it to the original parameter. Personally, I like the flexibility to customize consumer behavior. It is also being actively developed and supported by Confluent." }, { "code": null, "e": 12047, "s": 11903, "text": "A disadvantage is the fact that Windows users might need to struggle a bit to make it work. And debug can be tricky because of its C extension." }, { "code": null, "e": 12061, "s": 12047, "text": "kafka-python:" }, { "code": null, "e": 12233, "s": 12061, "text": "kafka-python is a pure Python library without a C extension. The API is well designed and straightforward to use for beginners. It’s an actively developed project as well." }, { "code": null, "e": 12370, "s": 12233, "text": "The disadvantage of python-kafka is its speed. If you do care about the performance, I would recommend you to switch to confluent-kafka." }, { "code": null, "e": 12379, "s": 12370, "text": "pykafka:" }, { "code": null, "e": 12674, "s": 12379, "text": "Compared to kafka-python and conflunet-kafka, the development of pykafka is less active. The release history shows that it hasn’t been updated since Nov 2018. Besides, pykafka has different API designs and uses different default parameters which might be not straightforward for the first time." } ]
A hands-on introduction to Propensity Score use for beginners | by Núria Correa Mañas | Towards Data Science
This is a joint work with Aleix Ruiz, Jesús Cerquides, Joan Capdevila and Borja Velasco within the Causal ALGO Bcn. You can find a theory post explaining the same topic here. A common data problem to be solved in any field involves figuring out if a treatment has any effect on a certain outcome. Now, this at first glance doesn’t seem to be that difficult. But for anyone that has fallen in the rabbit hole that is the study of causal effects, it will be evident that it is not the case. It is not the same computing these effects from Randomized Control Trial (RCT) databases than doing it from observational datasets. As it is also not the same researching problems with low or high dimensional covariates. This entry can be of interest to anyone that has been partly introduced to Causal Inference and wants to see it at work with a code example, where we will review some relatively simple ways to compute the Average Treatment Effect (ATE) from observational datasets. Now, let’s make this journey with a hands-on Python code example. You can find the original notebooks and dataset in Github by Jesús Cerquides here. We are given this database coming from the historical records of a hospital: And we are asked: How much will the number of deaths change if we decide to treat everybody from now on versus not treating anyone? Our first instinct is to simply compute the percentages of deaths of the treated population versus the untreated population using the data we are given, and simply subtract one from the other. treated = df[df["treatment"]==1] untreated = df[df["treatment"]==0] percentage_dead_treated = treated["dead"].mean() percentage_dead_treated 0.32080451312239394 percentage_dead_untreated= untreated["dead"].mean() percentage_dead_untreated 0.23595664229896648 percentage_dead_treated - percentage_dead_untreated 0.08484787082342746 This calculation leads us to the following answer: The percentage of deaths will increase an 8.5% if we decide to treat everybody (it will jump from 23.56% to 32.08%). This result would then counsel us that we should not treat our population, but our common sense may be “tingling” and making us wonder if that is really the case. And rightly so, because we overlooked a tiny but very crucial detail, and that is that the treatment is not distributed equally between the smoking population and the non-smoking one. In other words, treatment is not randomized, and hence, this way of calculating the ATE is simply wrong. Another way of defining this phenomenon is with the word “confounding”. Basically, what this word means is that there is a variable or a group of them (the confounders) that affects in some way the probability of getting the treatment and at the same time, affects also the outcome. Ideally, if we want to estimate the effect of some treatment on whatever we could consider an outcome, we should avoid any kind of confounding effect. We can do that by designing an RCT where treatment is allocated randomly and hence the confounders have no effect on how it is distributed. But the issue here is that it is not always ethical to do so. Consider, for example, if we want to estimate the effect of smoking (“treatment”) in lung health (outcome) of asthmatic teenagers. To do an RCT study, we should take a number of teenagers and randomly assign half of them to forcibly smoke. Obviously, this is not ethical and should never be done. We could, however, retrieve data of asthmatic teenagers and record if they smoke or not, what is their lung health grade, and especially, any variable that can be affecting the chances of smoking of any teenager. A clear possible confounder in this example would be socioeconomic status, as a low status can increase the chances of an unstable familiar ambient and more exposition to bad habits (affecting “treatment”), and it can certainly affect the lung health (outcome) of the teenager via less access to a good health plan. This is what we would call an observational dataset, where we know a set of confounders are in play. Expert knowledge on the issue is key to try to include all possible confounders so we can estimate better the effect of treatment on outcome using Causal Inference techniques. As stated at the beginning, in this entry we will introduce some simple ways of doing so using the Adjustment Formula by Pearl [1] first; and then the Propensity Score, applying 2 methods introduced by Rosenbaum and Rubin in their famous paper of 1983 [2]. If you have read or perused the book “Causal Inference in Statistics: A primer” by Judea Pearl you certainly know and love the Adjustment Formula (if you didn’t and you are interested in this field, go now and read it!). Maybe you came to know it in another way. Just in case you still didn’t make your acquaintance with it, let me present it to you: Where Y is the outcome, X the treatment and Z the set of covariates or confounders. Now, I am not going to enter in how this formula came to be or its more formal details, as this is not the aim of this text. It is sufficient with knowing that the expression P(Y|do(X)) refers to the probability of Y (outcome) if we do X (treatment) for all the population. Following this definition, we could calculate the ATE in the following way: So, with this clarified, let’s return to our original example. This dataset that we presented is, actually, fabricated. Using Bayesian Nets, we specified the dependencies between our 3 variables (Smoker, Treatment, Dead) and generated a dataset. Since we know exactly all the true probabilities of each variable and all its possible combinations, we can apply the formula to compute the exact probability of dying if we treat everybody versus the probability of dying if we don’t treat anybody. expected_dead_if_treated = bn.cpt("smoker")[0]*bn.cpt("dead")[1,0,1] + bn.cpt("smoker")[1]*bn.cpt("dead")[1,1,1] expected_dead_if_treated 0.22699999999999998 expected_dead_if_untreated = bn.cpt("smoker")[0]*bn.cpt("dead")[0,0,1] + bn.cpt("smoker")[1]*bn.cpt("dead")[0,1,1] expected_dead_if_untreated 0.31 Now, with these two results, we can calculate the Average Treatment Effect (ATE). ATE = expected_dead_if_treated - expected_dead_if_untreated ATE -0.08300000000000002 The real effect of this treatment then, is a lowered percentage of deaths by an 8.3%, exactly the contrary that we got in the first calculations. Therefore, the real answer is that we should absolutely treat all patients. Now, to have this exact percentages is very rare. We can certainly approximate ATE with a good observational dataset, applying the same system, but the problem with this method arises when the dataset has a high dimensional set of covariates. Imagine a set of covariates in the hundreds. Computing this formula for all the covariates would be too cumbersome. It is not the case of this very simple example, but in the real world it is a very common circumstance. What should we do in those cases then? Well, that is something that Rosenbaum and Rubin tried to solve in 1983 proposing that we use the propensity score (or probability of getting a treatment given a set of covariates) as a balancing score. Their reasoning goes as follows. A balancing score is any function of the set of covariates that captures all the information of the set that is dependent on treatment. Such a balancing score would allow us to model the relation between the confounders and treatment in a relatively simple way. And the minimal expression of a balancing score is the propensity score. Computing the propensity score is relatively simple, even in high dimensional sets of covariates. In these cases what we could do is model it using logistic regression with treatment as the target variable. But to be able to use this propensity score in the methods we will review next, there are some constraints. A common theme that we are going to find in Causal Inference is the unconfoundness condition. What this means, basically, is that to be able to make a reasonable approximation of the ATE value using observational databases, it is imperative that we account for all possible variables that could act as confounders. To ensure this, formally, there are 2 assumptions that need to be met: · The stable unit-treatment value assumption (SUTVA): Any outcome of any unit of the sample is independent of the treatment assignment to other units. · Treatment assignment should be strongly ignorable given a set of covariates: It is if every unit of the sample has a chance (even if small) of receiving each treatment, and if the treatment assignment and outcome are conditionally independent given that set of covariates. If these two assumptions are met, we are good to go with the methods we are going to review now. Without further ado, let’s take a look at them. As before, we will review the methods applying them to our specific example. As stated earlier, we were able to compute the exact ATE because we knew the accurate probabilities of every variable combination. These methods assume that we don’t know them, because with high dimensional sets of covariates that would be nearly impossible. Therefore, we will compare their estimations of the value of ATE to the known true result. Let’s start by computing our propensity score values. It is defined formally as follows: Where x is a specific combination of the set of covariates and z = 1 equates to receiving treatment. And in our specific case it is translated to: Now we compute the propensity of each patient: In this case there are only 2 possible values, since our confounder is binary. Once computed and added to our dataframe we can pair match in two different ways. In this version of pair matching, we couple each treated patient with a control patient that has the same propensity score. For this example, we reduce the number of treated patients for efficiency reasons. Now, every treated patient gets a randomly sampled untreated patient with the same propensity score: Having the matched pairs, we can join both dataframes and simply compute the mean difference between treated and untreated outcomes: We get as a result that the percentage of deaths is effectively estimated to decrease, which is good as it is in line with the real effect computed before. However, we know that the real ATE is 0.083. This result is clearly biased. Let’s take a look at the second version of pair matching. We start by taking a look at the distribution of our propensity score: Clearly, we have a majority of the patients getting a low propensity score. We can split patients into two groups, those with high propensity (> 0.5) and those with low propensity (<=0.5): And now we build a paired sample, but unlike before both treated and untreated populations are sampled from high or low propensity score population at random. After calculating the value of ATE for this new paired dataset, we can see that the value is much less biased than with the first version of the pair matching. Can we do better though? Here the approach is related to the second version of pair matching, as it relies on the distribution of the propensity score. The hist of it is that we can subdivide our population by the categories of a factorized by ranges propensity score. With our population classified in each category (in this case only two, as the covariate is binary), we only need to compute the ATE for each subclass, and then apply the next formula: After doing so our results is very very close to the known true value of ATE. In this text we reviewed a few ways of computing the Average Treatment Effect relatively simply. First with the classical Adjustment Formula, perfectly usable with settings were the covariates are low dimensional like our example. And then using the propensity score, most fit for high dimensional sets of covariates. In this example, the Adjustment Formula gave us an exact result of the ATE, as we had fabricated the dataset and knew the specific probabilities needed. We were able then to compare to the propensity score approaches, and even though in this example the best method has been subclassification this doesn’t mean that in any other type of problem it will be so. We would recommend to test different methods, the ones presented and also other methodologies not reviewed here before setting into one approach. [1]Pearl, J., Glymour,M., & Jewell, N. Causal Inference in Statistics: A Primer.(2016). Wiley. [2] Rosenbaum, P., & Rubin, D. (1983). The Central Role of the Propensity Score in Observational Studies for Causal Effects. Biometrika, 70(1), 41–55. doi:10.2307/2335942
[ { "code": null, "e": 348, "s": 172, "text": "This is a joint work with Aleix Ruiz, Jesús Cerquides, Joan Capdevila and Borja Velasco within the Causal ALGO Bcn. You can find a theory post explaining the same topic here." }, { "code": null, "e": 883, "s": 348, "text": "A common data problem to be solved in any field involves figuring out if a treatment has any effect on a certain outcome. Now, this at first glance doesn’t seem to be that difficult. But for anyone that has fallen in the rabbit hole that is the study of causal effects, it will be evident that it is not the case. It is not the same computing these effects from Randomized Control Trial (RCT) databases than doing it from observational datasets. As it is also not the same researching problems with low or high dimensional covariates." }, { "code": null, "e": 1148, "s": 883, "text": "This entry can be of interest to anyone that has been partly introduced to Causal Inference and wants to see it at work with a code example, where we will review some relatively simple ways to compute the Average Treatment Effect (ATE) from observational datasets." }, { "code": null, "e": 1298, "s": 1148, "text": "Now, let’s make this journey with a hands-on Python code example. You can find the original notebooks and dataset in Github by Jesús Cerquides here." }, { "code": null, "e": 1375, "s": 1298, "text": "We are given this database coming from the historical records of a hospital:" }, { "code": null, "e": 1393, "s": 1375, "text": "And we are asked:" }, { "code": null, "e": 1507, "s": 1393, "text": "How much will the number of deaths change if we decide to treat everybody from now on versus not treating anyone?" }, { "code": null, "e": 1700, "s": 1507, "text": "Our first instinct is to simply compute the percentages of deaths of the treated population versus the untreated population using the data we are given, and simply subtract one from the other." }, { "code": null, "e": 1734, "s": 1700, "text": "treated = df[df[\"treatment\"]==1]\n" }, { "code": null, "e": 1770, "s": 1734, "text": "untreated = df[df[\"treatment\"]==0]\n" }, { "code": null, "e": 1844, "s": 1770, "text": "percentage_dead_treated = treated[\"dead\"].mean()\npercentage_dead_treated\n" }, { "code": null, "e": 1864, "s": 1844, "text": "0.32080451312239394" }, { "code": null, "e": 1943, "s": 1864, "text": "percentage_dead_untreated= untreated[\"dead\"].mean()\npercentage_dead_untreated\n" }, { "code": null, "e": 1963, "s": 1943, "text": "0.23595664229896648" }, { "code": null, "e": 2016, "s": 1963, "text": "percentage_dead_treated - percentage_dead_untreated\n" }, { "code": null, "e": 2036, "s": 2016, "text": "0.08484787082342746" }, { "code": null, "e": 2204, "s": 2036, "text": "This calculation leads us to the following answer: The percentage of deaths will increase an 8.5% if we decide to treat everybody (it will jump from 23.56% to 32.08%)." }, { "code": null, "e": 2656, "s": 2204, "text": "This result would then counsel us that we should not treat our population, but our common sense may be “tingling” and making us wonder if that is really the case. And rightly so, because we overlooked a tiny but very crucial detail, and that is that the treatment is not distributed equally between the smoking population and the non-smoking one. In other words, treatment is not randomized, and hence, this way of calculating the ATE is simply wrong." }, { "code": null, "e": 2939, "s": 2656, "text": "Another way of defining this phenomenon is with the word “confounding”. Basically, what this word means is that there is a variable or a group of them (the confounders) that affects in some way the probability of getting the treatment and at the same time, affects also the outcome." }, { "code": null, "e": 4395, "s": 2939, "text": "Ideally, if we want to estimate the effect of some treatment on whatever we could consider an outcome, we should avoid any kind of confounding effect. We can do that by designing an RCT where treatment is allocated randomly and hence the confounders have no effect on how it is distributed. But the issue here is that it is not always ethical to do so. Consider, for example, if we want to estimate the effect of smoking (“treatment”) in lung health (outcome) of asthmatic teenagers. To do an RCT study, we should take a number of teenagers and randomly assign half of them to forcibly smoke. Obviously, this is not ethical and should never be done. We could, however, retrieve data of asthmatic teenagers and record if they smoke or not, what is their lung health grade, and especially, any variable that can be affecting the chances of smoking of any teenager. A clear possible confounder in this example would be socioeconomic status, as a low status can increase the chances of an unstable familiar ambient and more exposition to bad habits (affecting “treatment”), and it can certainly affect the lung health (outcome) of the teenager via less access to a good health plan. This is what we would call an observational dataset, where we know a set of confounders are in play. Expert knowledge on the issue is key to try to include all possible confounders so we can estimate better the effect of treatment on outcome using Causal Inference techniques." }, { "code": null, "e": 4652, "s": 4395, "text": "As stated at the beginning, in this entry we will introduce some simple ways of doing so using the Adjustment Formula by Pearl [1] first; and then the Propensity Score, applying 2 methods introduced by Rosenbaum and Rubin in their famous paper of 1983 [2]." }, { "code": null, "e": 5003, "s": 4652, "text": "If you have read or perused the book “Causal Inference in Statistics: A primer” by Judea Pearl you certainly know and love the Adjustment Formula (if you didn’t and you are interested in this field, go now and read it!). Maybe you came to know it in another way. Just in case you still didn’t make your acquaintance with it, let me present it to you:" }, { "code": null, "e": 5437, "s": 5003, "text": "Where Y is the outcome, X the treatment and Z the set of covariates or confounders. Now, I am not going to enter in how this formula came to be or its more formal details, as this is not the aim of this text. It is sufficient with knowing that the expression P(Y|do(X)) refers to the probability of Y (outcome) if we do X (treatment) for all the population. Following this definition, we could calculate the ATE in the following way:" }, { "code": null, "e": 5683, "s": 5437, "text": "So, with this clarified, let’s return to our original example. This dataset that we presented is, actually, fabricated. Using Bayesian Nets, we specified the dependencies between our 3 variables (Smoker, Treatment, Dead) and generated a dataset." }, { "code": null, "e": 5932, "s": 5683, "text": "Since we know exactly all the true probabilities of each variable and all its possible combinations, we can apply the formula to compute the exact probability of dying if we treat everybody versus the probability of dying if we don’t treat anybody." }, { "code": null, "e": 6071, "s": 5932, "text": "expected_dead_if_treated = bn.cpt(\"smoker\")[0]*bn.cpt(\"dead\")[1,0,1] + bn.cpt(\"smoker\")[1]*bn.cpt(\"dead\")[1,1,1]\nexpected_dead_if_treated\n" }, { "code": null, "e": 6091, "s": 6071, "text": "0.22699999999999998" }, { "code": null, "e": 6234, "s": 6091, "text": "expected_dead_if_untreated = bn.cpt(\"smoker\")[0]*bn.cpt(\"dead\")[0,0,1] + bn.cpt(\"smoker\")[1]*bn.cpt(\"dead\")[0,1,1]\nexpected_dead_if_untreated\n" }, { "code": null, "e": 6239, "s": 6234, "text": "0.31" }, { "code": null, "e": 6321, "s": 6239, "text": "Now, with these two results, we can calculate the Average Treatment Effect (ATE)." }, { "code": null, "e": 6386, "s": 6321, "text": "ATE = expected_dead_if_treated - expected_dead_if_untreated\nATE\n" }, { "code": null, "e": 6407, "s": 6386, "text": "-0.08300000000000002" }, { "code": null, "e": 7131, "s": 6407, "text": "The real effect of this treatment then, is a lowered percentage of deaths by an 8.3%, exactly the contrary that we got in the first calculations. Therefore, the real answer is that we should absolutely treat all patients. Now, to have this exact percentages is very rare. We can certainly approximate ATE with a good observational dataset, applying the same system, but the problem with this method arises when the dataset has a high dimensional set of covariates. Imagine a set of covariates in the hundreds. Computing this formula for all the covariates would be too cumbersome. It is not the case of this very simple example, but in the real world it is a very common circumstance. What should we do in those cases then?" }, { "code": null, "e": 7702, "s": 7131, "text": "Well, that is something that Rosenbaum and Rubin tried to solve in 1983 proposing that we use the propensity score (or probability of getting a treatment given a set of covariates) as a balancing score. Their reasoning goes as follows. A balancing score is any function of the set of covariates that captures all the information of the set that is dependent on treatment. Such a balancing score would allow us to model the relation between the confounders and treatment in a relatively simple way. And the minimal expression of a balancing score is the propensity score." }, { "code": null, "e": 8017, "s": 7702, "text": "Computing the propensity score is relatively simple, even in high dimensional sets of covariates. In these cases what we could do is model it using logistic regression with treatment as the target variable. But to be able to use this propensity score in the methods we will review next, there are some constraints." }, { "code": null, "e": 8332, "s": 8017, "text": "A common theme that we are going to find in Causal Inference is the unconfoundness condition. What this means, basically, is that to be able to make a reasonable approximation of the ATE value using observational databases, it is imperative that we account for all possible variables that could act as confounders." }, { "code": null, "e": 8403, "s": 8332, "text": "To ensure this, formally, there are 2 assumptions that need to be met:" }, { "code": null, "e": 8554, "s": 8403, "text": "· The stable unit-treatment value assumption (SUTVA): Any outcome of any unit of the sample is independent of the treatment assignment to other units." }, { "code": null, "e": 8829, "s": 8554, "text": "· Treatment assignment should be strongly ignorable given a set of covariates: It is if every unit of the sample has a chance (even if small) of receiving each treatment, and if the treatment assignment and outcome are conditionally independent given that set of covariates." }, { "code": null, "e": 8926, "s": 8829, "text": "If these two assumptions are met, we are good to go with the methods we are going to review now." }, { "code": null, "e": 8974, "s": 8926, "text": "Without further ado, let’s take a look at them." }, { "code": null, "e": 9401, "s": 8974, "text": "As before, we will review the methods applying them to our specific example. As stated earlier, we were able to compute the exact ATE because we knew the accurate probabilities of every variable combination. These methods assume that we don’t know them, because with high dimensional sets of covariates that would be nearly impossible. Therefore, we will compare their estimations of the value of ATE to the known true result." }, { "code": null, "e": 9490, "s": 9401, "text": "Let’s start by computing our propensity score values. It is defined formally as follows:" }, { "code": null, "e": 9591, "s": 9490, "text": "Where x is a specific combination of the set of covariates and z = 1 equates to receiving treatment." }, { "code": null, "e": 9637, "s": 9591, "text": "And in our specific case it is translated to:" }, { "code": null, "e": 9684, "s": 9637, "text": "Now we compute the propensity of each patient:" }, { "code": null, "e": 9845, "s": 9684, "text": "In this case there are only 2 possible values, since our confounder is binary. Once computed and added to our dataframe we can pair match in two different ways." }, { "code": null, "e": 10052, "s": 9845, "text": "In this version of pair matching, we couple each treated patient with a control patient that has the same propensity score. For this example, we reduce the number of treated patients for efficiency reasons." }, { "code": null, "e": 10153, "s": 10052, "text": "Now, every treated patient gets a randomly sampled untreated patient with the same propensity score:" }, { "code": null, "e": 10286, "s": 10153, "text": "Having the matched pairs, we can join both dataframes and simply compute the mean difference between treated and untreated outcomes:" }, { "code": null, "e": 10518, "s": 10286, "text": "We get as a result that the percentage of deaths is effectively estimated to decrease, which is good as it is in line with the real effect computed before. However, we know that the real ATE is 0.083. This result is clearly biased." }, { "code": null, "e": 10576, "s": 10518, "text": "Let’s take a look at the second version of pair matching." }, { "code": null, "e": 10647, "s": 10576, "text": "We start by taking a look at the distribution of our propensity score:" }, { "code": null, "e": 10723, "s": 10647, "text": "Clearly, we have a majority of the patients getting a low propensity score." }, { "code": null, "e": 10836, "s": 10723, "text": "We can split patients into two groups, those with high propensity (> 0.5) and those with low propensity (<=0.5):" }, { "code": null, "e": 10995, "s": 10836, "text": "And now we build a paired sample, but unlike before both treated and untreated populations are sampled from high or low propensity score population at random." }, { "code": null, "e": 11155, "s": 10995, "text": "After calculating the value of ATE for this new paired dataset, we can see that the value is much less biased than with the first version of the pair matching." }, { "code": null, "e": 11180, "s": 11155, "text": "Can we do better though?" }, { "code": null, "e": 11609, "s": 11180, "text": "Here the approach is related to the second version of pair matching, as it relies on the distribution of the propensity score. The hist of it is that we can subdivide our population by the categories of a factorized by ranges propensity score. With our population classified in each category (in this case only two, as the covariate is binary), we only need to compute the ATE for each subclass, and then apply the next formula:" }, { "code": null, "e": 11687, "s": 11609, "text": "After doing so our results is very very close to the known true value of ATE." }, { "code": null, "e": 12005, "s": 11687, "text": "In this text we reviewed a few ways of computing the Average Treatment Effect relatively simply. First with the classical Adjustment Formula, perfectly usable with settings were the covariates are low dimensional like our example. And then using the propensity score, most fit for high dimensional sets of covariates." }, { "code": null, "e": 12511, "s": 12005, "text": "In this example, the Adjustment Formula gave us an exact result of the ATE, as we had fabricated the dataset and knew the specific probabilities needed. We were able then to compare to the propensity score approaches, and even though in this example the best method has been subclassification this doesn’t mean that in any other type of problem it will be so. We would recommend to test different methods, the ones presented and also other methodologies not reviewed here before setting into one approach." }, { "code": null, "e": 12606, "s": 12511, "text": "[1]Pearl, J., Glymour,M., & Jewell, N. Causal Inference in Statistics: A Primer.(2016). Wiley." } ]
Java Scope
In Java, variables are only accessible inside the region they are created. This is called scope. Variables declared directly inside a method are available anywhere in the method following the line of code in which they were declared: public class Main { public static void main(String[] args) { // Code here CANNOT use x int x = 100; // Code here can use x System.out.println(x); } } Try it Yourself » A block of code refers to all of the code between curly braces {}. Variables declared inside blocks of code are only accessible by the code between the curly braces, which follows the line in which the variable was declared: public class Main { public static void main(String[] args) { // Code here CANNOT use x { // This is a block // Code here CANNOT use x int x = 100; // Code here CAN use x System.out.println(x); } // The block ends here // Code here CANNOT use x } } Try it Yourself » A block of code may exist on its own or it can belong to an if, while or for statement. In the case of for statements, variables declared in the statement itself are also available inside the block's scope. We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 97, "s": 0, "text": "In Java, variables are only accessible inside the region they are created. This is called\nscope." }, { "code": null, "e": 234, "s": 97, "text": "Variables declared directly inside a method are available anywhere in the method following the line of code in which they were declared:" }, { "code": null, "e": 407, "s": 234, "text": "public class Main {\n public static void main(String[] args) {\n\n // Code here CANNOT use x\n\n int x = 100;\n\n // Code here can use x\n System.out.println(x);\n }\n}" }, { "code": null, "e": 427, "s": 407, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 494, "s": 427, "text": "A block of code refers to all of the code between curly braces {}." }, { "code": null, "e": 652, "s": 494, "text": "Variables\ndeclared inside blocks of code are only accessible by the code between the curly braces, which follows the line in which the variable was declared:" }, { "code": null, "e": 949, "s": 652, "text": "public class Main {\n public static void main(String[] args) {\n\n // Code here CANNOT use x\n\n { // This is a block\n\n // Code here CANNOT use x\n\n int x = 100;\n\n // Code here CAN use x\n System.out.println(x);\n\n } // The block ends here\n\n // Code here CANNOT use x\n\n }\n}" }, { "code": null, "e": 969, "s": 949, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1176, "s": 969, "text": "A block of code may exist on its\nown or it can belong to an if, while or for statement. In the case of for statements,\nvariables declared in the statement itself are also available inside the block's scope." }, { "code": null, "e": 1209, "s": 1176, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1251, "s": 1209, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1358, "s": 1251, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1377, "s": 1358, "text": "help@w3schools.com" } ]
D Programming - Data Types
In the D programming language, data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the stored bit pattern is interpreted. The types in D can be classified as follows − Basic Types They are arithmetic types and consist of the three types: (a) integer, (b) floating-point, and (c) character. Enumerated types They are again arithmetic types. They are used to define variables that can only be assigned certain discrete integer values throughout the program. The type void The type specifier void indicates that no value is available. Derived types They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types, and (e) Function types. The array types and structure types are referred to collectively as the aggregate types. The type of a function specifies the type of the function's return value. We will see basic types in the following section whereas other types will be covered in the upcoming chapters. The following table gives lists standard integer types with their storage sizes and value ranges − To get the exact size of a type or a variable, you can use the sizeof operator. The expression type.(sizeof) yields the storage size of the object or type in bytes. The following example gets the size of int type on any machine − import std.stdio; int main() { writeln("Length in bytes: ", ulong.sizeof); return 0; } When you compile and execute the above program, it produces the following result − Length in bytes: 8 The following table mentions standard float-point types with storage sizes, value ranges, and their purpose − The following example prints storage space taken by a float type and its range values − import std.stdio; int main() { writeln("Length in bytes: ", float.sizeof); return 0; } When you compile and execute the above program, it produces the following result on Linux − Length in bytes: 4 The following table lists standard character types with storage sizes and its purpose. The following example prints storage space taken by a char type. import std.stdio; int main() { writeln("Length in bytes: ", char.sizeof); return 0; } When you compile and execute the above program, it produces the following result − Length in bytes: 1 The void type specifies that no value is available. It is used in two kinds of situations − Function returns as void There are various functions in D which do not return value or you can say they return void. A function with no return value has the return type as void. For example, void exit (int status); Function arguments as void There are various functions in D which do not accept any parameter. A function with no parameter can accept as a void. For example, int rand(void); The void type may not be understood to you at this point, so let us proceed and we will cover these concepts in upcoming chapters. 10 Lectures 1.5 hours Nishant Malik 42 Lectures 1.5 hours Ravi Kiran 46 Lectures 7.5 hours Aditya Dua 32 Lectures 3.5 hours Sharad Kumar 14 Lectures 1 hours Mahesh Kumar 18 Lectures 49 mins Rushi Panchal Print Add Notes Bookmark this page
[ { "code": null, "e": 2856, "s": 2604, "text": "In the D programming language, data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the stored bit pattern is interpreted." }, { "code": null, "e": 2902, "s": 2856, "text": "The types in D can be classified as follows −" }, { "code": null, "e": 2914, "s": 2902, "text": "Basic Types" }, { "code": null, "e": 3024, "s": 2914, "text": "They are arithmetic types and consist of the three types: (a) integer, (b) floating-point, and (c) character." }, { "code": null, "e": 3041, "s": 3024, "text": "Enumerated types" }, { "code": null, "e": 3190, "s": 3041, "text": "They are again arithmetic types. They are used to define variables that can only be assigned certain discrete integer values throughout the program." }, { "code": null, "e": 3204, "s": 3190, "text": "The type void" }, { "code": null, "e": 3266, "s": 3204, "text": "The type specifier void indicates that no value is available." }, { "code": null, "e": 3280, "s": 3266, "text": "Derived types" }, { "code": null, "e": 3391, "s": 3280, "text": "They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types, and (e) Function types." }, { "code": null, "e": 3665, "s": 3391, "text": "The array types and structure types are referred to collectively as the aggregate types. The type of a function specifies the type of the function's return value. We will see basic types in the following section whereas other types will be covered in the upcoming chapters." }, { "code": null, "e": 3764, "s": 3665, "text": "The following table gives lists standard integer types with their storage sizes and value ranges −" }, { "code": null, "e": 3994, "s": 3764, "text": "To get the exact size of a type or a variable, you can use the sizeof operator. The expression type.(sizeof) yields the storage size of the object or type in bytes. The following example gets the size of int type on any machine −" }, { "code": null, "e": 4094, "s": 3994, "text": "import std.stdio; \n \nint main() { \n writeln(\"Length in bytes: \", ulong.sizeof); \n\n return 0; \n}" }, { "code": null, "e": 4177, "s": 4094, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 4198, "s": 4177, "text": "Length in bytes: 8 \n" }, { "code": null, "e": 4308, "s": 4198, "text": "The following table mentions standard float-point types with storage sizes, value ranges, and their purpose −" }, { "code": null, "e": 4396, "s": 4308, "text": "The following example prints storage space taken by a float type and its range values −" }, { "code": null, "e": 4494, "s": 4396, "text": "import std.stdio;\n\nint main() { \n writeln(\"Length in bytes: \", float.sizeof); \n\n return 0; \n}" }, { "code": null, "e": 4586, "s": 4494, "text": "When you compile and execute the above program, it produces the following result on Linux −" }, { "code": null, "e": 4606, "s": 4586, "text": "Length in bytes: 4\n" }, { "code": null, "e": 4693, "s": 4606, "text": "The following table lists standard character types with storage sizes and its purpose." }, { "code": null, "e": 4758, "s": 4693, "text": "The following example prints storage space taken by a char type." }, { "code": null, "e": 4855, "s": 4758, "text": "import std.stdio;\n\nint main() {\n writeln(\"Length in bytes: \", char.sizeof);\n \n return 0;\n}" }, { "code": null, "e": 4938, "s": 4855, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 4958, "s": 4938, "text": "Length in bytes: 1\n" }, { "code": null, "e": 5050, "s": 4958, "text": "The void type specifies that no value is available. It is used in two kinds of situations −" }, { "code": null, "e": 5075, "s": 5050, "text": "Function returns as void" }, { "code": null, "e": 5265, "s": 5075, "text": "There are various functions in D which do not return value or you can say they return void. A function with no return value has the return type as void. For example, void exit (int status);" }, { "code": null, "e": 5292, "s": 5265, "text": "Function arguments as void" }, { "code": null, "e": 5440, "s": 5292, "text": "There are various functions in D which do not accept any parameter. A function with no parameter can accept as a void. For example, int rand(void);" }, { "code": null, "e": 5571, "s": 5440, "text": "The void type may not be understood to you at this point, so let us proceed and we will cover these concepts in upcoming chapters." }, { "code": null, "e": 5606, "s": 5571, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5621, "s": 5606, "text": " Nishant Malik" }, { "code": null, "e": 5656, "s": 5621, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5668, "s": 5656, "text": " Ravi Kiran" }, { "code": null, "e": 5703, "s": 5668, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5715, "s": 5703, "text": " Aditya Dua" }, { "code": null, "e": 5750, "s": 5715, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5764, "s": 5750, "text": " Sharad Kumar" }, { "code": null, "e": 5797, "s": 5764, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 5811, "s": 5797, "text": " Mahesh Kumar" }, { "code": null, "e": 5843, "s": 5811, "text": "\n 18 Lectures \n 49 mins\n" }, { "code": null, "e": 5858, "s": 5843, "text": " Rushi Panchal" }, { "code": null, "e": 5865, "s": 5858, "text": " Print" }, { "code": null, "e": 5876, "s": 5865, "text": " Add Notes" } ]
Default constructor in Java
Java compiler automatically creates a default constructor (Constructor with no arguments) in case no constructor is present in the java class. Following are the motive behind a default constructor. Create the Object Create the Object Call the super class constructor() Call the super class constructor() Initialize all the instance variables of the class object. Initialize all the instance variables of the class object. Live Demo public class Tester { int a; String b; public static void main(String[] args) { //Default constructor //is called to create a new object Tester t = new Tester(); //print the default values System.out.println(t.a); System.out.println(t.b); } } 0 null
[ { "code": null, "e": 1260, "s": 1062, "text": "Java compiler automatically creates a default constructor (Constructor with no arguments) in case no constructor is present in the java class. Following are the motive behind a default constructor." }, { "code": null, "e": 1278, "s": 1260, "text": "Create the Object" }, { "code": null, "e": 1296, "s": 1278, "text": "Create the Object" }, { "code": null, "e": 1331, "s": 1296, "text": "Call the super class constructor()" }, { "code": null, "e": 1366, "s": 1331, "text": "Call the super class constructor()" }, { "code": null, "e": 1425, "s": 1366, "text": "Initialize all the instance variables of the class object." }, { "code": null, "e": 1484, "s": 1425, "text": "Initialize all the instance variables of the class object." }, { "code": null, "e": 1495, "s": 1484, "text": " Live Demo" }, { "code": null, "e": 1787, "s": 1495, "text": "public class Tester {\n int a;\n String b;\n public static void main(String[] args) {\n\n //Default constructor\n //is called to create a new object\n Tester t = new Tester();\n //print the default values\n System.out.println(t.a);\n System.out.println(t.b);\n }\n}" }, { "code": null, "e": 1794, "s": 1787, "text": "0\nnull" } ]
C++ List Library - pop_front() Function
The C++ function std::list::pop_front() removes first element from list and reduces size of list by one. Following is the declaration for std::list::pop_front() function form std::list header. void pop_front(); None None This member function never throws exception. Calling this function on empty list causes undefined behavior. Constant i.e. O(1) The following example shows the usage of std::list::pop_front() function. #include <iostream> #include <list> using namespace std; int main(void) { list<int> l = {1, 2, 3, 4, 5}; cout << "List contains following elements before pop_back operation" << endl; for (auto it = l.begin(); it != l.end(); ++it) cout << *it << endl; l.pop_front(); cout << "List contains following elements after pop_back operation" << endl; for (auto it = l.begin(); it != l.end(); ++it) cout << *it << endl; return 0; } Let us compile and run the above program, this will produce the following result − List contains following elements before pop_back operation 1 2 3 4 5 List contains following elements after pop_back operation 2 3 4 5 Print Add Notes Bookmark this page
[ { "code": null, "e": 2708, "s": 2603, "text": "The C++ function std::list::pop_front() removes first element from list and reduces size of list by one." }, { "code": null, "e": 2796, "s": 2708, "text": "Following is the declaration for std::list::pop_front() function form std::list header." }, { "code": null, "e": 2815, "s": 2796, "text": "void pop_front();\n" }, { "code": null, "e": 2820, "s": 2815, "text": "None" }, { "code": null, "e": 2825, "s": 2820, "text": "None" }, { "code": null, "e": 2933, "s": 2825, "text": "This member function never throws exception. Calling this function on empty list causes undefined behavior." }, { "code": null, "e": 2952, "s": 2933, "text": "Constant i.e. O(1)" }, { "code": null, "e": 3026, "s": 2952, "text": "The following example shows the usage of std::list::pop_front() function." }, { "code": null, "e": 3490, "s": 3026, "text": "#include <iostream>\n#include <list>\n\nusing namespace std;\n\nint main(void) {\n list<int> l = {1, 2, 3, 4, 5};\n\n cout << \"List contains following elements before pop_back operation\" << endl;\n\n for (auto it = l.begin(); it != l.end(); ++it)\n cout << *it << endl;\n\n l.pop_front();\n\n cout << \"List contains following elements after pop_back operation\" << endl;\n\n for (auto it = l.begin(); it != l.end(); ++it)\n cout << *it << endl;\n\n return 0;\n}" }, { "code": null, "e": 3573, "s": 3490, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3709, "s": 3573, "text": "List contains following elements before pop_back operation\n1\n2\n3\n4\n5\nList contains following elements after pop_back operation\n2\n3\n4\n5\n" }, { "code": null, "e": 3716, "s": 3709, "text": " Print" }, { "code": null, "e": 3727, "s": 3716, "text": " Add Notes" } ]
Basic Operators in Relational Algebra - GeeksforGeeks
26 Apr, 2022 Basics of Relational model: Relational Model Relational Algebra is a procedural query language that takes relations as an input and returns relations as an output. There are some basic operators which can be applied on relations to producing the required results which we will discuss one by one. We will use STUDENT_SPORTS, EMPLOYEE, and STUDENT relations as given in Table 1, Table 2, and Table 3 respectively to understand the various operators. Table 1: STUDENT_SPORTS Table 2: EMPLOYEE Table 3: STUDENT Selection operator (σ): Selection operator is used to select tuples from a relation based on some condition. Syntax: σ (Cond)(Relation Name) Extract students whose age is greater than 18 from STUDENT relation given in Table 3 σ (AGE>18)(STUDENT) [Note: SELECT operator does not show any result, the projection operator must be called before the selection operator to generate or project the result. So, the correct syntax to generate the result is: ∏(σ (AGE>18)(STUDENT))] RESULT: Projection Operator (∏): Projection operator is used to project particular columns from a relation. Syntax: ∏(Column 1,Column 2....Column n)(Relation Name) Extract ROLL_NO and NAME from STUDENT relation given in Table 3 ∏(ROLL_NO,NAME)(STUDENT) RESULT: Note: If the resultant relation after projection has duplicate rows, it will be removed. For Example ∏(ADDRESS)(STUDENT) will remove one duplicate row with the value DELHI and return three rows. Cross Product(X): Cross product is used to join two relations. For every row of Relation1, each row of Relation2 is concatenated. If Relation1 has m tuples and and Relation2 has n tuples, cross product of Relation1 and Relation2 will have m X n tuples. Syntax: Relation1 X Relation2 To apply Cross Product on STUDENT relation given in Table 1 and STUDENT_SPORTS relation given in Table 2, STUDENT X STUDENT_SPORTS RESULT: Union (U): Union on two relations R1 and R2 can only be computed if R1 and R2 are union compatible (These two relations should have the same number of attributes and corresponding attributes in two relations have the same domain). Union operator when applied on two relations R1 and R2 will give a relation with tuples that are either in R1 or in R2. The tuples which are in both R1 and R2 will appear only once in result relation. Syntax: Relation1 U Relation2 Find person who is either students or employees, we can use Union operators like: STUDENT U EMPLOYEE RESULT: Minus (-): Minus on two relations R1 and R2 can only be computed if R1 and R2 are union compatible. Minus operator when applied on two relations as R1-R2 will give a relation with tuples that are in R1 but not in R2. Syntax: Relation1 - Relation2 Find person who is student but not employee, we can use minus operator like: STUDENT - EMPLOYEE RESULT: Rename(ρ): Rename operator is used to give another name to a relation. Syntax: ρ(Relation2, Relation1) To rename STUDENT relation to STUDENT1, we can use rename operator like: ρ(STUDENT1, STUDENT) If you want to create a relation STUDENT_NAMES with ROLL_NO and NAME from STUDENT, it can be done using rename operator as: ρ(STUDENT_NAMES, ∏(ROLL_NO, NAME)(STUDENT)) Extended Relational Algebra Operators Overview of Relational Algebra Operators Previous Year Gate Questions https://www.geeksforgeeks.org/gate-gate-cs-2012-question-50/ https://www.geeksforgeeks.org/gate-gate-cs-2012-question-43/ Article contributed by Sonal Tuteja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Nityananda Gohain sushmithasushmi2012 DBMS-Relational Algebra DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SQL | Join (Inner, Left, Right and Full Joins) SQL | WITH clause SQL query to find second highest salary? SQL Trigger | Student Database Difference between Clustered and Non-clustered index SQL | Views Third Normal Form (3NF) CTE in SQL Second Normal Form (2NF) Difference between DDL and DML in DBMS
[ { "code": null, "e": 29544, "s": 29516, "text": "\n26 Apr, 2022" }, { "code": null, "e": 29590, "s": 29544, "text": "Basics of Relational model: Relational Model " }, { "code": null, "e": 29995, "s": 29590, "text": "Relational Algebra is a procedural query language that takes relations as an input and returns relations as an output. There are some basic operators which can be applied on relations to producing the required results which we will discuss one by one. We will use STUDENT_SPORTS, EMPLOYEE, and STUDENT relations as given in Table 1, Table 2, and Table 3 respectively to understand the various operators. " }, { "code": null, "e": 30019, "s": 29995, "text": "Table 1: STUDENT_SPORTS" }, { "code": null, "e": 30038, "s": 30019, "text": " Table 2: EMPLOYEE" }, { "code": null, "e": 30056, "s": 30038, "text": "Table 3: STUDENT " }, { "code": null, "e": 30174, "s": 30056, "text": "Selection operator (σ): Selection operator is used to select tuples from a relation based on some condition. Syntax: " }, { "code": null, "e": 30198, "s": 30174, "text": "σ (Cond)(Relation Name)" }, { "code": null, "e": 30285, "s": 30198, "text": "Extract students whose age is greater than 18 from STUDENT relation given in Table 3 " }, { "code": null, "e": 30305, "s": 30285, "text": "σ (AGE>18)(STUDENT)" }, { "code": null, "e": 30532, "s": 30305, "text": "[Note: SELECT operator does not show any result, the projection operator must be called before the selection operator to generate or project the result. So, the correct syntax to generate the result is: ∏(σ (AGE>18)(STUDENT))]" }, { "code": null, "e": 30541, "s": 30532, "text": "RESULT: " }, { "code": null, "e": 30651, "s": 30541, "text": "Projection Operator (∏): Projection operator is used to project particular columns from a relation. Syntax: " }, { "code": null, "e": 30699, "s": 30651, "text": "∏(Column 1,Column 2....Column n)(Relation Name)" }, { "code": null, "e": 30765, "s": 30699, "text": "Extract ROLL_NO and NAME from STUDENT relation given in Table 3 " }, { "code": null, "e": 30790, "s": 30765, "text": "∏(ROLL_NO,NAME)(STUDENT)" }, { "code": null, "e": 30800, "s": 30790, "text": "RESULT: " }, { "code": null, "e": 30997, "s": 30800, "text": "Note: If the resultant relation after projection has duplicate rows, it will be removed. For Example ∏(ADDRESS)(STUDENT) will remove one duplicate row with the value DELHI and return three rows. " }, { "code": null, "e": 31259, "s": 30997, "text": "Cross Product(X): Cross product is used to join two relations. For every row of Relation1, each row of Relation2 is concatenated. If Relation1 has m tuples and and Relation2 has n tuples, cross product of Relation1 and Relation2 will have m X n tuples. Syntax: " }, { "code": null, "e": 31281, "s": 31259, "text": "Relation1 X Relation2" }, { "code": null, "e": 31389, "s": 31281, "text": "To apply Cross Product on STUDENT relation given in Table 1 and STUDENT_SPORTS relation given in Table 2, " }, { "code": null, "e": 31414, "s": 31389, "text": "STUDENT X STUDENT_SPORTS" }, { "code": null, "e": 31423, "s": 31414, "text": "RESULT: " }, { "code": null, "e": 31864, "s": 31423, "text": "Union (U): Union on two relations R1 and R2 can only be computed if R1 and R2 are union compatible (These two relations should have the same number of attributes and corresponding attributes in two relations have the same domain). Union operator when applied on two relations R1 and R2 will give a relation with tuples that are either in R1 or in R2. The tuples which are in both R1 and R2 will appear only once in result relation. Syntax: " }, { "code": null, "e": 31887, "s": 31864, "text": " Relation1 U Relation2" }, { "code": null, "e": 31970, "s": 31887, "text": "Find person who is either students or employees, we can use Union operators like: " }, { "code": null, "e": 31989, "s": 31970, "text": "STUDENT U EMPLOYEE" }, { "code": null, "e": 31999, "s": 31989, "text": "RESULT: " }, { "code": null, "e": 32225, "s": 31999, "text": "Minus (-): Minus on two relations R1 and R2 can only be computed if R1 and R2 are union compatible. Minus operator when applied on two relations as R1-R2 will give a relation with tuples that are in R1 but not in R2. Syntax: " }, { "code": null, "e": 32248, "s": 32225, "text": " Relation1 - Relation2" }, { "code": null, "e": 32327, "s": 32248, "text": "Find person who is student but not employee, we can use minus operator like: " }, { "code": null, "e": 32346, "s": 32327, "text": "STUDENT - EMPLOYEE" }, { "code": null, "e": 32356, "s": 32346, "text": "RESULT: " }, { "code": null, "e": 32437, "s": 32356, "text": "Rename(ρ): Rename operator is used to give another name to a relation. Syntax: " }, { "code": null, "e": 32461, "s": 32437, "text": "ρ(Relation2, Relation1)" }, { "code": null, "e": 32536, "s": 32461, "text": "To rename STUDENT relation to STUDENT1, we can use rename operator like: " }, { "code": null, "e": 32557, "s": 32536, "text": "ρ(STUDENT1, STUDENT)" }, { "code": null, "e": 32683, "s": 32557, "text": "If you want to create a relation STUDENT_NAMES with ROLL_NO and NAME from STUDENT, it can be done using rename operator as: " }, { "code": null, "e": 32727, "s": 32683, "text": "ρ(STUDENT_NAMES, ∏(ROLL_NO, NAME)(STUDENT))" }, { "code": null, "e": 32845, "s": 32727, "text": "Extended Relational Algebra Operators Overview of Relational Algebra Operators" }, { "code": null, "e": 32996, "s": 32845, "text": "Previous Year Gate Questions https://www.geeksforgeeks.org/gate-gate-cs-2012-question-50/ https://www.geeksforgeeks.org/gate-gate-cs-2012-question-43/" }, { "code": null, "e": 33158, "s": 32996, "text": "Article contributed by Sonal Tuteja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 33176, "s": 33158, "text": "Nityananda Gohain" }, { "code": null, "e": 33196, "s": 33176, "text": "sushmithasushmi2012" }, { "code": null, "e": 33220, "s": 33196, "text": "DBMS-Relational Algebra" }, { "code": null, "e": 33225, "s": 33220, "text": "DBMS" }, { "code": null, "e": 33230, "s": 33225, "text": "DBMS" }, { "code": null, "e": 33328, "s": 33230, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33337, "s": 33328, "text": "Comments" }, { "code": null, "e": 33350, "s": 33337, "text": "Old Comments" }, { "code": null, "e": 33397, "s": 33350, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 33415, "s": 33397, "text": "SQL | WITH clause" }, { "code": null, "e": 33456, "s": 33415, "text": "SQL query to find second highest salary?" }, { "code": null, "e": 33487, "s": 33456, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 33540, "s": 33487, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 33552, "s": 33540, "text": "SQL | Views" }, { "code": null, "e": 33576, "s": 33552, "text": "Third Normal Form (3NF)" }, { "code": null, "e": 33587, "s": 33576, "text": "CTE in SQL" }, { "code": null, "e": 33612, "s": 33587, "text": "Second Normal Form (2NF)" } ]
AI Driven Snake Game using Deep Q Learning - GeeksforGeeks
01 Feb, 2022 Introduction: This Project is based on Reinforcement Learning which trains the snake to eat the food present in the environment. A sample gif is given below, that you can get an idea of what we are going to build. Snake Driven by AI The Prerequisite for this project are: Reinforcement Learning Deep Learning (Dense Neural Network) Pygame To understand how can we manually build this snake 2D animation simulation using pygame, please follow the link: https://www.geeksforgeeks.org/snake-game-in-python-using-pygame-module/ After building the basic snake game now we will focus on how to apply Reinforcement learning to it. We have to create three Modules in this project: The Environment (the game that we just build)The Model (Reinforcement model for move prediction)The Agent (Intermediary between Environment and Model) The Environment (the game that we just build) The Model (Reinforcement model for move prediction) The Agent (Intermediary between Environment and Model) Linking of Modules We have snake and food on the board randomly placed. Calculate the state of the snake using the 11 values. if any the condition is true then set that value to zero else set one. How 11 states are defined Based on the current Head position agent will calculate the 11 state values as described above. After getting these state, agent would pass this to the model and get the next move to perform. After executing the next state calculate the reward. Rewards are defined as below:Eat food : +10Game Over : -10Else : 0 Eat food : +10 Game Over : -10 Else : 0 Update the Q value (will be discussed later) and Train the Model. After analyzing the algorithm now we have to build the idea to proceed for coding this algorithm. Neural network Model The model is designed using Pytorch, but you can also use TensorFlow based on your comfort. We are using Dense neural network with an input layer of size 11 and one dense layer with 256 neurons and output of 3 neurons. You can tweak these hyper parameters to get the best result. The game starts, and the Q-value is randomly initialized. The system gets the current state s. Based on s, it executes an action, randomly or based on its neural network. During the first phase of the training, the system often chooses random actions to maximize exploration. Later on, the system relies more and more on its neural network. When the AI chooses and performs the action, the environment gives a reward. Then, the agent reaches the new state and it updates its Q-value according to the Bellman equation. This equation you had definitely covered in the reinforcement learning course. If not you can refer Q-learning Mathematics Bellman Equation Also, for each move, it stores the original state, the action, the state reached after performed that action, the reward obtained and whether the game ended or not. This data is later sampled to train the neural network. This operation is called Replay Memory. These last two operations are repeated until a certain condition is met (example: the game ends). The heart of this project is the model that you are going to train because the correctness of the move that the snake would play will all depend on the quality of the model you had built. So I would like to explain you this using the code in parts. Part-I 1. Creating a class named Linear_Qnet for initializing the linear neural network. 2. The function forward is used to take the input(11 state vector) and pass it through the Neural network and apply relu activation function and give the output back i.e the next move of 1 x 3 vector size. In short, this is the prediction function that would be called by the agent. 3. The save function is used to save the trained model for future use. Python3 class Linear_QNet(nn.Module): def __init__(self, input_size, hidden_size, output_size): super().__init__() self.linear1 = nn.Linear(input_size, hidden_size) self.linear2 = nn.Linear(hidden_size, output_size) def forward(self, x): x = F.relu(self.linear1(x)) x = self.linear2(x) return x def save(self, file_name='model_name.pth'): model_folder_path = 'Path' file_name = os.path.join(model_folder_path, file_name) torch.save(self.state_dict(), file_name) Part-II 1. Initialising QTrainer class ∗ setting the learning rate for the optimizer. * Gamma value that is the discount rate used in Bellman equation. * initialising the Adam optimizer for updation of weight and biases. * criterion is the Mean squared loss function. 2. Train_step function * As you know that PyTorch work only on tensors, so we are converting all the input to tensors. * As discussed above we had a short memory training then we would only pass one value of state, action, reward, move so we need to convert them into a vector, so we had used unsqueezed function . * Get the state from the model and calculate the new Q value using the below formula: Q_new = reward + gamma * max(next_predicted Qvalue) * calculate the mean squared error between the new Q value and previous Q value and backpropagate that loss for weight updation. C++ class QTrainer: def __init__(self,model,lr,gamma):#Learning Rate for Optimizer self.lr = lr#Discount Rate self.gamma = gamma#Linear NN defined above. self.model = model#optimizer for weight and biases updation self.optimer = optim.Adam(model.parameters(),lr = self.lr)#Mean Squared error loss function self.criterion = nn.MSELoss() def train_step(self,state,action,reward,next_state,done): state = torch.tensor(state,dtype=torch.float) next_state = torch.tensor(next_state,dtype=torch.float) action = torch.tensor(action,dtype=torch.long) reward = torch.tensor(reward,dtype=torch.float) #only one parameter to train, \ Hence convert to tuple of shape(1, x) if(len(state.shape) == 1):#(1, x) state = torch.unsqueeze(state,0) next_state = torch.unsqueeze(next_state,0) action = torch.unsqueeze(action,0) reward = torch.unsqueeze(reward,0) done = (done, ) # 1. Predicted Q value with current state pred = self.model(state) target = pred.clone() for idx in range(len(done)): Q_new = reward[idx] if not done[idx]: Q_new = reward[idx] + self.gamma * torch.max(self.model(next_state[idx])) target[idx][torch.argmax(action).item()] = Q_new# 2. Q_new = reward + gamma * max(next_predicted Qvalue)#pred.clone()#preds[argmax(action)] = Q_new self.optimer.zero_grad() loss = self.criterion(target,pred) loss.backward() # backward propagation of loss self.optimer.step() Get the current state of the snake from the environment. Python def get_state(self, game): head = game.snake[0] point_l = Point(head.x - BLOCK_SIZE, head.y) point_r = Point(head.x + BLOCK_SIZE, head.y) point_u = Point(head.x, head.y - BLOCK_SIZE) point_d = Point(head.x, head.y + BLOCK_SIZE) dir_l = game.direction == Direction.LEFT dir_r = game.direction == Direction.RIGHT dir_u = game.direction == Direction.UP dir_d = game.direction == Direction.DOWN state = [ # Danger Straight (dir_u and game.is_collision(point_u))or (dir_d and game.is_collision(point_d))or (dir_l and game.is_collision(point_l))or (dir_r and game.is_collision(point_r)), # Danger right (dir_u and game.is_collision(point_r))or (dir_d and game.is_collision(point_l))or (dir_u and game.is_collision(point_u))or (dir_d and game.is_collision(point_d)), # Danger Left (dir_u and game.is_collision(point_r))or (dir_d and game.is_collision(point_l))or (dir_r and game.is_collision(point_u))or (dir_l and game.is_collision(point_d)), # Move Direction dir_l, dir_r, dir_u, dir_d, # Food Location game.food.x < game.head.x, # food is in left game.food.x > game.head.x, # food is in right game.food.y < game.head.y, # food is up game.food.y > game.head.y # food is down ] return np.array(state, dtype=int) Call model for getting the next state of the snake Python def get_action(self, state): # random moves: tradeoff explotation / exploitation self.epsilon = 80 - self.n_game final_move = [0, 0, 0] if(random.randint(0, 200) < self.epsilon): move = random.randint(0, 2) final_move[move] = 1 else: state0 = torch.tensor(state, dtype=torch.float).cuda() prediction = self.model(state0).cuda() # prediction by model move = torch.argmax(prediction).item() final_move[move] = 1 return final_move Note: There is a trade-off between exploitation and exploration.Where exploitation consists of taking the decision assumed to be optimal with respect to the data observed so far. And exploration is taking decisions randomly without considering the previous actions and reward pair. So both are necessary because taking exploitation may cause the agent to not explore the whole environment and exploration may not always provide a better reward. Play the step predicted by the model in the environment. Store the current state, move performed and the reward. Train the model based on the move performed and the reward obtained by the Environment. (Training short memory) Python def train_short_memory(self, state, action, reward, next_state, done): self.trainer.train_step(state, action, reward, next_state, done) If the game end due to hitting wall or body then train the model based on all the moved performed till now and reset the environment. (Training Long memory). Training in a batch size of 1000. Python def train_long_memory(self): if (len(self.memory) > BATCH_SIZE): mini_sample = random.sample(self.memory, BATCH_SIZE) else: mini_sample = self.memory states, actions, rewards, next_states, dones = zip(*mini_sample) self.trainer.train_step(states, actions, rewards, next_states, dones) Training the model would take time approx 100 epochs for better performance. See my training progress. Output: To run this game first create an environment in the anaconda prompt or (any platform). Then install the necessary modules such as Pytorch(for DQ Learning Model), Pygame (for visuals of the game) and other basic modules. Then run the agent.py file in the environment just created and then the training will start, and you will see the following two GUI one for the training progress and the other the snake game driven by AI. After achieving certain score you can quit the game and the model that you just trained will be stored in the path that you had defined in the save function of models.py. In future, you can use this trained model by just changing the code in the agent.py file as shown below: Python self.model.load_state_dict(torch.load('PATH')) Note: Comment Down all the Training function calling. Training Progress Initial Training After 100 Epochs Source Code: https://github.com/vedantgoswami/SnakeGameAI Application: The Goal of this project is to give an idea that how Reinforcement learning can be applied and how it can be used in Real-world applications such as self-driving cars (eg: AWS DeepRacer), training robots in the assembly line and many more... Tips: Use a separate environment and install all the required modules. (You can use anaconda environment) For training the model you can use GPU for faster training. saurabh1990aror Artificial Intelligence ML-Reinforcement ProGeek 2021 ProGeek Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Project Idea | KrishiKadam- A Smart Application for Agricultural Project Idea - A website acting as transaction between oxygen sellers and buyers Project Idea – Healthcare App Project Idea | Pocket Charter Project Idea | Fuel Balance Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 26593, "s": 26565, "text": "\n01 Feb, 2022" }, { "code": null, "e": 26722, "s": 26593, "text": "Introduction: This Project is based on Reinforcement Learning which trains the snake to eat the food present in the environment." }, { "code": null, "e": 26807, "s": 26722, "text": "A sample gif is given below, that you can get an idea of what we are going to build." }, { "code": null, "e": 26826, "s": 26807, "text": "Snake Driven by AI" }, { "code": null, "e": 26865, "s": 26826, "text": "The Prerequisite for this project are:" }, { "code": null, "e": 26888, "s": 26865, "text": "Reinforcement Learning" }, { "code": null, "e": 26925, "s": 26888, "text": "Deep Learning (Dense Neural Network)" }, { "code": null, "e": 26932, "s": 26925, "text": "Pygame" }, { "code": null, "e": 27117, "s": 26932, "text": "To understand how can we manually build this snake 2D animation simulation using pygame, please follow the link: https://www.geeksforgeeks.org/snake-game-in-python-using-pygame-module/" }, { "code": null, "e": 27217, "s": 27117, "text": "After building the basic snake game now we will focus on how to apply Reinforcement learning to it." }, { "code": null, "e": 27266, "s": 27217, "text": "We have to create three Modules in this project:" }, { "code": null, "e": 27417, "s": 27266, "text": "The Environment (the game that we just build)The Model (Reinforcement model for move prediction)The Agent (Intermediary between Environment and Model)" }, { "code": null, "e": 27463, "s": 27417, "text": "The Environment (the game that we just build)" }, { "code": null, "e": 27515, "s": 27463, "text": "The Model (Reinforcement model for move prediction)" }, { "code": null, "e": 27570, "s": 27515, "text": "The Agent (Intermediary between Environment and Model)" }, { "code": null, "e": 27589, "s": 27570, "text": "Linking of Modules" }, { "code": null, "e": 27642, "s": 27589, "text": "We have snake and food on the board randomly placed." }, { "code": null, "e": 27767, "s": 27642, "text": "Calculate the state of the snake using the 11 values. if any the condition is true then set that value to zero else set one." }, { "code": null, "e": 27793, "s": 27767, "text": "How 11 states are defined" }, { "code": null, "e": 27889, "s": 27793, "text": "Based on the current Head position agent will calculate the 11 state values as described above." }, { "code": null, "e": 27985, "s": 27889, "text": "After getting these state, agent would pass this to the model and get the next move to perform." }, { "code": null, "e": 28105, "s": 27985, "text": "After executing the next state calculate the reward. Rewards are defined as below:Eat food : +10Game Over : -10Else : 0" }, { "code": null, "e": 28120, "s": 28105, "text": "Eat food : +10" }, { "code": null, "e": 28136, "s": 28120, "text": "Game Over : -10" }, { "code": null, "e": 28145, "s": 28136, "text": "Else : 0" }, { "code": null, "e": 28211, "s": 28145, "text": "Update the Q value (will be discussed later) and Train the Model." }, { "code": null, "e": 28309, "s": 28211, "text": "After analyzing the algorithm now we have to build the idea to proceed for coding this algorithm." }, { "code": null, "e": 28330, "s": 28309, "text": "Neural network Model" }, { "code": null, "e": 28422, "s": 28330, "text": "The model is designed using Pytorch, but you can also use TensorFlow based on your comfort." }, { "code": null, "e": 28610, "s": 28422, "text": "We are using Dense neural network with an input layer of size 11 and one dense layer with 256 neurons and output of 3 neurons. You can tweak these hyper parameters to get the best result." }, { "code": null, "e": 28668, "s": 28610, "text": "The game starts, and the Q-value is randomly initialized." }, { "code": null, "e": 28705, "s": 28668, "text": "The system gets the current state s." }, { "code": null, "e": 28951, "s": 28705, "text": "Based on s, it executes an action, randomly or based on its neural network. During the first phase of the training, the system often chooses random actions to maximize exploration. Later on, the system relies more and more on its neural network." }, { "code": null, "e": 29251, "s": 28951, "text": "When the AI chooses and performs the action, the environment gives a reward. Then, the agent reaches the new state and it updates its Q-value according to the Bellman equation. This equation you had definitely covered in the reinforcement learning course. If not you can refer Q-learning Mathematics" }, { "code": null, "e": 29268, "s": 29251, "text": "Bellman Equation" }, { "code": null, "e": 29529, "s": 29268, "text": "Also, for each move, it stores the original state, the action, the state reached after performed that action, the reward obtained and whether the game ended or not. This data is later sampled to train the neural network. This operation is called Replay Memory." }, { "code": null, "e": 29627, "s": 29529, "text": "These last two operations are repeated until a certain condition is met (example: the game ends)." }, { "code": null, "e": 29876, "s": 29627, "text": "The heart of this project is the model that you are going to train because the correctness of the move that the snake would play will all depend on the quality of the model you had built. So I would like to explain you this using the code in parts." }, { "code": null, "e": 29883, "s": 29876, "text": "Part-I" }, { "code": null, "e": 30327, "s": 29883, "text": "1. Creating a class named Linear_Qnet for initializing the linear neural network.\n2. The function forward is used to take the input(11 state vector) and pass it through the \n Neural network and apply relu activation function and give the output back i.e the next \n move of 1 x 3 vector size. In short, this is the prediction function that would be called by the agent.\n3. The save function is used to save the trained model for future use." }, { "code": null, "e": 30335, "s": 30327, "text": "Python3" }, { "code": "class Linear_QNet(nn.Module): def __init__(self, input_size, hidden_size, output_size): super().__init__() self.linear1 = nn.Linear(input_size, hidden_size) self.linear2 = nn.Linear(hidden_size, output_size) def forward(self, x): x = F.relu(self.linear1(x)) x = self.linear2(x) return x def save(self, file_name='model_name.pth'): model_folder_path = 'Path' file_name = os.path.join(model_folder_path, file_name) torch.save(self.state_dict(), file_name)", "e": 30863, "s": 30335, "text": null }, { "code": null, "e": 30871, "s": 30863, "text": "Part-II" }, { "code": null, "e": 31774, "s": 30871, "text": "1. Initialising QTrainer class\n ∗ setting the learning rate for the optimizer.\n * Gamma value that is the discount rate used in Bellman equation.\n * initialising the Adam optimizer for updation of weight and biases.\n * criterion is the Mean squared loss function.\n2. Train_step function \n * As you know that PyTorch work only on tensors, so we are converting all the input\n to tensors.\n * As discussed above we had a short memory training then we would only pass one value\n of state, action, reward, move so we need to convert them into a vector, so we had used\n unsqueezed function .\n * Get the state from the model and calculate the new Q value using the below formula:\n Q_new = reward + gamma * max(next_predicted Qvalue)\n * calculate the mean squared error between the new Q value and previous Q value and \n backpropagate that loss for weight updation. " }, { "code": null, "e": 31778, "s": 31774, "text": "C++" }, { "code": "class QTrainer: def __init__(self,model,lr,gamma):#Learning Rate for Optimizer self.lr = lr#Discount Rate self.gamma = gamma#Linear NN defined above. self.model = model#optimizer for weight and biases updation self.optimer = optim.Adam(model.parameters(),lr = self.lr)#Mean Squared error loss function self.criterion = nn.MSELoss() def train_step(self,state,action,reward,next_state,done): state = torch.tensor(state,dtype=torch.float) next_state = torch.tensor(next_state,dtype=torch.float) action = torch.tensor(action,dtype=torch.long) reward = torch.tensor(reward,dtype=torch.float) #only one parameter to train, \\ Hence convert to tuple of shape(1, x) if(len(state.shape) == 1):#(1, x) state = torch.unsqueeze(state,0) next_state = torch.unsqueeze(next_state,0) action = torch.unsqueeze(action,0) reward = torch.unsqueeze(reward,0) done = (done, ) # 1. Predicted Q value with current state pred = self.model(state) target = pred.clone() for idx in range(len(done)): Q_new = reward[idx] if not done[idx]: Q_new = reward[idx] + self.gamma * torch.max(self.model(next_state[idx])) target[idx][torch.argmax(action).item()] = Q_new# 2. Q_new = reward + gamma * max(next_predicted Qvalue)#pred.clone()#preds[argmax(action)] = Q_new self.optimer.zero_grad() loss = self.criterion(target,pred) loss.backward() # backward propagation of loss self.optimer.step()", "e": 33429, "s": 31778, "text": null }, { "code": null, "e": 33489, "s": 33432, "text": "Get the current state of the snake from the environment." }, { "code": null, "e": 33498, "s": 33491, "text": "Python" }, { "code": "def get_state(self, game): head = game.snake[0] point_l = Point(head.x - BLOCK_SIZE, head.y) point_r = Point(head.x + BLOCK_SIZE, head.y) point_u = Point(head.x, head.y - BLOCK_SIZE) point_d = Point(head.x, head.y + BLOCK_SIZE) dir_l = game.direction == Direction.LEFT dir_r = game.direction == Direction.RIGHT dir_u = game.direction == Direction.UP dir_d = game.direction == Direction.DOWN state = [ # Danger Straight (dir_u and game.is_collision(point_u))or (dir_d and game.is_collision(point_d))or (dir_l and game.is_collision(point_l))or (dir_r and game.is_collision(point_r)), # Danger right (dir_u and game.is_collision(point_r))or (dir_d and game.is_collision(point_l))or (dir_u and game.is_collision(point_u))or (dir_d and game.is_collision(point_d)), # Danger Left (dir_u and game.is_collision(point_r))or (dir_d and game.is_collision(point_l))or (dir_r and game.is_collision(point_u))or (dir_l and game.is_collision(point_d)), # Move Direction dir_l, dir_r, dir_u, dir_d, # Food Location game.food.x < game.head.x, # food is in left game.food.x > game.head.x, # food is in right game.food.y < game.head.y, # food is up game.food.y > game.head.y # food is down ] return np.array(state, dtype=int)", "e": 34925, "s": 33498, "text": null }, { "code": null, "e": 34976, "s": 34925, "text": "Call model for getting the next state of the snake" }, { "code": null, "e": 34983, "s": 34976, "text": "Python" }, { "code": "def get_action(self, state): # random moves: tradeoff explotation / exploitation self.epsilon = 80 - self.n_game final_move = [0, 0, 0] if(random.randint(0, 200) < self.epsilon): move = random.randint(0, 2) final_move[move] = 1 else: state0 = torch.tensor(state, dtype=torch.float).cuda() prediction = self.model(state0).cuda() # prediction by model move = torch.argmax(prediction).item() final_move[move] = 1 return final_move", "e": 35472, "s": 34983, "text": null }, { "code": null, "e": 35917, "s": 35472, "text": "Note: There is a trade-off between exploitation and exploration.Where exploitation consists of taking the decision assumed to be optimal with respect to the data observed so far. And exploration is taking decisions randomly without considering the previous actions and reward pair. So both are necessary because taking exploitation may cause the agent to not explore the whole environment and exploration may not always provide a better reward." }, { "code": null, "e": 35974, "s": 35917, "text": "Play the step predicted by the model in the environment." }, { "code": null, "e": 36030, "s": 35974, "text": "Store the current state, move performed and the reward." }, { "code": null, "e": 36142, "s": 36030, "text": "Train the model based on the move performed and the reward obtained by the Environment. (Training short memory)" }, { "code": null, "e": 36149, "s": 36142, "text": "Python" }, { "code": "def train_short_memory(self, state, action, reward, next_state, done): self.trainer.train_step(state, action, reward, next_state, done)", "e": 36288, "s": 36149, "text": null }, { "code": null, "e": 36480, "s": 36288, "text": "If the game end due to hitting wall or body then train the model based on all the moved performed till now and reset the environment. (Training Long memory). Training in a batch size of 1000." }, { "code": null, "e": 36487, "s": 36480, "text": "Python" }, { "code": "def train_long_memory(self): if (len(self.memory) > BATCH_SIZE): mini_sample = random.sample(self.memory, BATCH_SIZE) else: mini_sample = self.memory states, actions, rewards, next_states, dones = zip(*mini_sample) self.trainer.train_step(states, actions, rewards, next_states, dones)", "e": 36798, "s": 36487, "text": null }, { "code": null, "e": 36901, "s": 36798, "text": "Training the model would take time approx 100 epochs for better performance. See my training progress." }, { "code": null, "e": 36909, "s": 36901, "text": "Output:" }, { "code": null, "e": 37129, "s": 36909, "text": "To run this game first create an environment in the anaconda prompt or (any platform). Then install the necessary modules such as Pytorch(for DQ Learning Model), Pygame (for visuals of the game) and other basic modules." }, { "code": null, "e": 37334, "s": 37129, "text": "Then run the agent.py file in the environment just created and then the training will start, and you will see the following two GUI one for the training progress and the other the snake game driven by AI." }, { "code": null, "e": 37505, "s": 37334, "text": "After achieving certain score you can quit the game and the model that you just trained will be stored in the path that you had defined in the save function of models.py." }, { "code": null, "e": 37610, "s": 37505, "text": "In future, you can use this trained model by just changing the code in the agent.py file as shown below:" }, { "code": null, "e": 37617, "s": 37610, "text": "Python" }, { "code": "self.model.load_state_dict(torch.load('PATH'))", "e": 37664, "s": 37617, "text": null }, { "code": null, "e": 37719, "s": 37664, "text": "Note: Comment Down all the Training function calling." }, { "code": null, "e": 37737, "s": 37719, "text": "Training Progress" }, { "code": null, "e": 37754, "s": 37737, "text": "Initial Training" }, { "code": null, "e": 37771, "s": 37754, "text": "After 100 Epochs" }, { "code": null, "e": 37829, "s": 37771, "text": "Source Code: https://github.com/vedantgoswami/SnakeGameAI" }, { "code": null, "e": 37842, "s": 37829, "text": "Application:" }, { "code": null, "e": 38084, "s": 37842, "text": "The Goal of this project is to give an idea that how Reinforcement learning can be applied and how it can be used in Real-world applications such as self-driving cars (eg: AWS DeepRacer), training robots in the assembly line and many more..." }, { "code": null, "e": 38091, "s": 38084, "text": "Tips: " }, { "code": null, "e": 38191, "s": 38091, "text": "Use a separate environment and install all the required modules. (You can use anaconda environment)" }, { "code": null, "e": 38251, "s": 38191, "text": "For training the model you can use GPU for faster training." }, { "code": null, "e": 38267, "s": 38251, "text": "saurabh1990aror" }, { "code": null, "e": 38291, "s": 38267, "text": "Artificial Intelligence" }, { "code": null, "e": 38308, "s": 38291, "text": "ML-Reinforcement" }, { "code": null, "e": 38321, "s": 38308, "text": "ProGeek 2021" }, { "code": null, "e": 38329, "s": 38321, "text": "ProGeek" }, { "code": null, "e": 38336, "s": 38329, "text": "Python" }, { "code": null, "e": 38434, "s": 38336, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38499, "s": 38434, "text": "Project Idea | KrishiKadam- A Smart Application for Agricultural" }, { "code": null, "e": 38580, "s": 38499, "text": "Project Idea - A website acting as transaction between oxygen sellers and buyers" }, { "code": null, "e": 38610, "s": 38580, "text": "Project Idea – Healthcare App" }, { "code": null, "e": 38640, "s": 38610, "text": "Project Idea | Pocket Charter" }, { "code": null, "e": 38668, "s": 38640, "text": "Project Idea | Fuel Balance" }, { "code": null, "e": 38696, "s": 38668, "text": "Read JSON file using Python" }, { "code": null, "e": 38746, "s": 38696, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 38768, "s": 38746, "text": "Python map() function" } ]
How to Implement ColoredShadowImageView Library in Android? - GeeksforGeeks
13 Jan, 2022 Android is an open-source operating system, based on the Linux kernel and used in mobile devices like smartphones, tablets, etc. Further, it was developed for smartwatches and Android TV. Each of them has a specialized interface. Android has been one of the best-selling OS for smartphones. Android OS was developed by Android Inc. which Google bought in 2005. In this article, we are going to implement the ColoredShadowImageView library. While showing an image if we want to add shadow then we do that by creating a file in drawable and then after adding component in that we are able to show the shadow. Here we are going to show shadows in an image using the library. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add this into the build.gradle file implementation ‘com.github.armcha:ColoredShadowImageView:1.1.0’ You also need to add RenderScript to your app module. Add these lines to the defaultConfig block of your build.gradle. renderscriptTargetApi YOUR_TARGET_SDK_VERSION renderscriptSupportModeEnabled true Step 3: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. 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" android:gravity="center" tools:context=".ColorShadow"> <!--adding shadowimageview library--> <io.github.armcha.coloredshadow.ShadowImageView android:id="@+id/shadowImage" android:layout_width="250dp" android:layout_height="250dp" android:src="@drawable/circle"/> </LinearLayout> Step 4: 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 Java import androidx.appcompat.app.AppCompatActivity; import android.graphics.drawable.Drawable;import android.os.Bundle;import android.widget.ImageView; import com.bumptech.glide.Glide;import com.bumptech.glide.request.target.ViewTarget; import io.github.armcha.coloredshadow.ShadowImageView; public class ColorShadow extends AppCompatActivity { ShadowImageView imageViewl; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_color_shadow); imageViewl=findViewById(R.id.shadowImage); // showing image using Glide Library Glide.with(ColorShadow.this).load(R.drawable.circle) // adding it as placeholder if loading gets null .placeholder(R.drawable.circle) .into(imageViewl); }} Output: simranarora5sos Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Retrofit with Kotlin Coroutine in Android Flutter - Custom Bottom Navigation Bar Android Listview in Java with Example How to Read Data from SQLite Database in Android? How to Change the Background Color After Clicking the Button in Android? Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Initialize an ArrayList in Java
[ { "code": null, "e": 25116, "s": 25088, "text": "\n13 Jan, 2022" }, { "code": null, "e": 25788, "s": 25116, "text": "Android is an open-source operating system, based on the Linux kernel and used in mobile devices like smartphones, tablets, etc. Further, it was developed for smartwatches and Android TV. Each of them has a specialized interface. Android has been one of the best-selling OS for smartphones. Android OS was developed by Android Inc. which Google bought in 2005. In this article, we are going to implement the ColoredShadowImageView library. While showing an image if we want to add shadow then we do that by creating a file in drawable and then after adding component in that we are able to show the shadow. Here we are going to show shadows in an image using the library." }, { "code": null, "e": 25817, "s": 25788, "text": "Step 1: Create a New Project" }, { "code": null, "e": 25979, "s": 25817, "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": 26023, "s": 25979, "text": "Step 2: Add this into the build.gradle file" }, { "code": null, "e": 26087, "s": 26023, "text": "implementation ‘com.github.armcha:ColoredShadowImageView:1.1.0’" }, { "code": null, "e": 26206, "s": 26087, "text": "You also need to add RenderScript to your app module. Add these lines to the defaultConfig block of your build.gradle." }, { "code": null, "e": 26252, "s": 26206, "text": "renderscriptTargetApi YOUR_TARGET_SDK_VERSION" }, { "code": null, "e": 26288, "s": 26252, "text": "renderscriptSupportModeEnabled true" }, { "code": null, "e": 26336, "s": 26288, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 26452, "s": 26336, "text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file." }, { "code": null, "e": 26456, "s": 26452, "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\" android:gravity=\"center\" tools:context=\".ColorShadow\"> <!--adding shadowimageview library--> <io.github.armcha.coloredshadow.ShadowImageView android:id=\"@+id/shadowImage\" android:layout_width=\"250dp\" android:layout_height=\"250dp\" android:src=\"@drawable/circle\"/> </LinearLayout>", "e": 27116, "s": 26456, "text": null }, { "code": null, "e": 27168, "s": 27120, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 27286, "s": 27170, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file " }, { "code": null, "e": 27293, "s": 27288, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity; import android.graphics.drawable.Drawable;import android.os.Bundle;import android.widget.ImageView; import com.bumptech.glide.Glide;import com.bumptech.glide.request.target.ViewTarget; import io.github.armcha.coloredshadow.ShadowImageView; public class ColorShadow extends AppCompatActivity { ShadowImageView imageViewl; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_color_shadow); imageViewl=findViewById(R.id.shadowImage); // showing image using Glide Library Glide.with(ColorShadow.this).load(R.drawable.circle) // adding it as placeholder if loading gets null .placeholder(R.drawable.circle) .into(imageViewl); }}", "e": 28145, "s": 27293, "text": null }, { "code": null, "e": 28157, "s": 28149, "text": "Output:" }, { "code": null, "e": 28177, "s": 28161, "text": "simranarora5sos" }, { "code": null, "e": 28185, "s": 28177, "text": "Android" }, { "code": null, "e": 28190, "s": 28185, "text": "Java" }, { "code": null, "e": 28195, "s": 28190, "text": "Java" }, { "code": null, "e": 28203, "s": 28195, "text": "Android" }, { "code": null, "e": 28301, "s": 28203, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28310, "s": 28301, "text": "Comments" }, { "code": null, "e": 28323, "s": 28310, "text": "Old Comments" }, { "code": null, "e": 28365, "s": 28323, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 28404, "s": 28365, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 28442, "s": 28404, "text": "Android Listview in Java with Example" }, { "code": null, "e": 28492, "s": 28442, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 28565, "s": 28492, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 28580, "s": 28565, "text": "Arrays in Java" }, { "code": null, "e": 28624, "s": 28580, "text": "Split() String method in Java with examples" }, { "code": null, "e": 28646, "s": 28624, "text": "For-each loop in Java" }, { "code": null, "e": 28682, "s": 28646, "text": "Arrays.sort() in Java with examples" } ]
How to include() all PHP files from a directory ? - GeeksforGeeks
10 Jan, 2019 Given list of PHP files in a directory and the task is to include all files from a directory. In order to include all PHP files from directory at once need a foreach-loop. Example: This example contains four PHP files (file1.php, file2.php, file3.php, file4.php) in a directory. Create one file named as main.php which contains PHP code to include files. Create file1.php in folder ‘myGeeks’: <?php echo "1st File Included Successfully<br>";?> Create file2.php in folder ‘myGeeks’: <?php echo "2nd File Included Successfully<br>";?> Create file3.php in folder ‘myGeeks’: <?php echo "3rd File Included Successfully<br>";?> Create file4.php in folder ‘myGeeks’: <?php echo "4th File Included Successfully<br>";?> Create main.php outside folder: <?phpforeach (glob("folder/*.php") as $filename) { include $filename;}?> Run on Windows platform: Folder myGeeks which contains all files: Folder htdocs contains main.php file: Run on Browser: Run on Ubuntu platform: Folder ‘Desktop/folder’ which contains all files: Folder ‘Desktop’ contains main.php file: Run on Terminal: Output: Picked Technical Scripter 2018 PHP PHP Programs Technical Scripter 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 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 call PHP function on the click of a Button ? How to check whether an array is empty using PHP?
[ { "code": null, "e": 26399, "s": 26371, "text": "\n10 Jan, 2019" }, { "code": null, "e": 26571, "s": 26399, "text": "Given list of PHP files in a directory and the task is to include all files from a directory. In order to include all PHP files from directory at once need a foreach-loop." }, { "code": null, "e": 26754, "s": 26571, "text": "Example: This example contains four PHP files (file1.php, file2.php, file3.php, file4.php) in a directory. Create one file named as main.php which contains PHP code to include files." }, { "code": null, "e": 26792, "s": 26754, "text": "Create file1.php in folder ‘myGeeks’:" }, { "code": "<?php echo \"1st File Included Successfully<br>\";?>", "e": 26843, "s": 26792, "text": null }, { "code": null, "e": 26881, "s": 26843, "text": "Create file2.php in folder ‘myGeeks’:" }, { "code": "<?php echo \"2nd File Included Successfully<br>\";?>", "e": 26932, "s": 26881, "text": null }, { "code": null, "e": 26970, "s": 26932, "text": "Create file3.php in folder ‘myGeeks’:" }, { "code": "<?php echo \"3rd File Included Successfully<br>\";?>", "e": 27021, "s": 26970, "text": null }, { "code": null, "e": 27059, "s": 27021, "text": "Create file4.php in folder ‘myGeeks’:" }, { "code": "<?php echo \"4th File Included Successfully<br>\";?>", "e": 27110, "s": 27059, "text": null }, { "code": null, "e": 27142, "s": 27110, "text": "Create main.php outside folder:" }, { "code": "<?phpforeach (glob(\"folder/*.php\") as $filename) { include $filename;}?>", "e": 27218, "s": 27142, "text": null }, { "code": null, "e": 27243, "s": 27218, "text": "Run on Windows platform:" }, { "code": null, "e": 27284, "s": 27243, "text": "Folder myGeeks which contains all files:" }, { "code": null, "e": 27322, "s": 27284, "text": "Folder htdocs contains main.php file:" }, { "code": null, "e": 27338, "s": 27322, "text": "Run on Browser:" }, { "code": null, "e": 27362, "s": 27338, "text": "Run on Ubuntu platform:" }, { "code": null, "e": 27412, "s": 27362, "text": "Folder ‘Desktop/folder’ which contains all files:" }, { "code": null, "e": 27453, "s": 27412, "text": "Folder ‘Desktop’ contains main.php file:" }, { "code": null, "e": 27470, "s": 27453, "text": "Run on Terminal:" }, { "code": null, "e": 27478, "s": 27470, "text": "Output:" }, { "code": null, "e": 27485, "s": 27478, "text": "Picked" }, { "code": null, "e": 27509, "s": 27485, "text": "Technical Scripter 2018" }, { "code": null, "e": 27513, "s": 27509, "text": "PHP" }, { "code": null, "e": 27526, "s": 27513, "text": "PHP Programs" }, { "code": null, "e": 27545, "s": 27526, "text": "Technical Scripter" }, { "code": null, "e": 27562, "s": 27545, "text": "Web Technologies" }, { "code": null, "e": 27566, "s": 27562, "text": "PHP" }, { "code": null, "e": 27664, "s": 27566, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27714, "s": 27664, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27754, "s": 27714, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27815, "s": 27754, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 27865, "s": 27815, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 27910, "s": 27865, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 27960, "s": 27910, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28000, "s": 27960, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28061, "s": 28000, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 28113, "s": 28061, "text": "How to call PHP function on the click of a Button ?" } ]
PyQt5 - Add Label to StatusBar - GeeksforGeeks
22 Apr, 2020 In this article we will see how to add label to a status bar. We can set text to status bar by using showMessage method. Label and StatusBar ?A label is a graphical control element which displays text on a form. It is usually a static control; having no interactivity. A label is generally used to identify a nearby text box or other widget. A status bar is a horizontal bar, usually at the bottom of the screen or window, showing information about a document being edited or a program running. In order to do this we will do following steps : 1. Create a label2. Add text to label3. Create object of status bar4. Add label to status bar Code : from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Python") # setting the geometry of window self.setGeometry(60, 60, 600, 400) # setting status bar message self.statusBar().showMessage("This is status bar") # setting border and padding with different sizes self.statusBar().setStyleSheet("border :3px solid black;") # creating a label widget self.label_1 = QLabel("Label 1") # setting up the border self.label_1.setStyleSheet("border :2px solid blue;") # adding label to status bar self.statusBar().addPermanentWidget(self.label_1) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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 Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n22 Apr, 2020" }, { "code": null, "e": 25768, "s": 25647, "text": "In this article we will see how to add label to a status bar. We can set text to status bar by using showMessage method." }, { "code": null, "e": 26142, "s": 25768, "text": "Label and StatusBar ?A label is a graphical control element which displays text on a form. It is usually a static control; having no interactivity. A label is generally used to identify a nearby text box or other widget. A status bar is a horizontal bar, usually at the bottom of the screen or window, showing information about a document being edited or a program running." }, { "code": null, "e": 26191, "s": 26142, "text": "In order to do this we will do following steps :" }, { "code": null, "e": 26285, "s": 26191, "text": "1. Create a label2. Add text to label3. Create object of status bar4. Add label to status bar" }, { "code": null, "e": 26292, "s": 26285, "text": "Code :" }, { "code": "from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Python\") # setting the geometry of window self.setGeometry(60, 60, 600, 400) # setting status bar message self.statusBar().showMessage(\"This is status bar\") # setting border and padding with different sizes self.statusBar().setStyleSheet(\"border :3px solid black;\") # creating a label widget self.label_1 = QLabel(\"Label 1\") # setting up the border self.label_1.setStyleSheet(\"border :2px solid blue;\") # adding label to status bar self.statusBar().addPermanentWidget(self.label_1) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 27292, "s": 26292, "text": null }, { "code": null, "e": 27303, "s": 27292, "text": "Python-gui" }, { "code": null, "e": 27315, "s": 27303, "text": "Python-PyQt" }, { "code": null, "e": 27322, "s": 27315, "text": "Python" }, { "code": null, "e": 27420, "s": 27322, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27452, "s": 27420, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27494, "s": 27452, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27536, "s": 27494, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27592, "s": 27536, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27619, "s": 27592, "text": "Python Classes and Objects" }, { "code": null, "e": 27650, "s": 27619, "text": "Python | os.path.join() method" }, { "code": null, "e": 27679, "s": 27650, "text": "Create a directory in Python" }, { "code": null, "e": 27701, "s": 27679, "text": "Defaultdict in Python" }, { "code": null, "e": 27737, "s": 27701, "text": "Python | Pandas dataframe.groupby()" } ]
GATE | GATE-CS-2017 (Set 1) | Question 25 - GeeksforGeeks
13 Aug, 2021 Consider the following functions from positives integers to real numbers 10, √n, n, log2n, 100/n. The CORRECT arrangement of the above functions in increasing order of asymptotic complexity is:(A) log2n, 100/n, 10, √n, n(B) 100/n, 10, log2n, √n, n(C) 10, 100/n ,√n, log2n, n(D) 100/n, log2n, 10 ,√n, nAnswer: (B)Explanation: For the large number, value of inverse of number is less than a constant and value of constant is less than value of square root. 10 is constant, not affected by value of n.√n Square root and log2n is logarithmic. So log2n is definitely less than √nn has linear growth and 100/n grows inversely with value of n. For bigger value of n, we can consider it 0, so 100/n is least and n is max.So the increasing order of asymptotic complexity will be : 100/n < 10 < log2n < √n < n So, option (b) is true. YouTubeGeeksforGeeks GATE Computer Science16.3K subscribersGate PYQs on Addressing Modes with Ashish Verma |GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You'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.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:001:28 / 42:29•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=cGRKsf_9sv8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2017 (Set 1) GATE-GATE-CS-2017 (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": 25847, "s": 25819, "text": "\n13 Aug, 2021" }, { "code": null, "e": 25920, "s": 25847, "text": "Consider the following functions from positives integers to real numbers" }, { "code": null, "e": 25945, "s": 25920, "text": "10, √n, n, log2n, 100/n." }, { "code": null, "e": 26302, "s": 25945, "text": "The CORRECT arrangement of the above functions in increasing order of asymptotic complexity is:(A) log2n, 100/n, 10, √n, n(B) 100/n, 10, log2n, √n, n(C) 10, 100/n ,√n, log2n, n(D) 100/n, log2n, 10 ,√n, nAnswer: (B)Explanation: For the large number, value of inverse of number is less than a constant and value of constant is less than value of square root." }, { "code": null, "e": 26619, "s": 26302, "text": "10 is constant, not affected by value of n.√n Square root and log2n is logarithmic. So log2n is definitely less than √nn has linear growth and 100/n grows inversely with value of n. For bigger value of n, we can consider it 0, so 100/n is least and n is max.So the increasing order of asymptotic complexity will be :" }, { "code": null, "e": 26647, "s": 26619, "text": "100/n < 10 < log2n < √n < n" }, { "code": null, "e": 26671, "s": 26647, "text": "So, option (b) is true." }, { "code": null, "e": 27566, "s": 26671, "text": "YouTubeGeeksforGeeks GATE Computer Science16.3K subscribersGate PYQs on Addressing Modes with Ashish Verma |GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You'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.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:001:28 / 42:29•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=cGRKsf_9sv8\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 27587, "s": 27566, "text": "GATE-CS-2017 (Set 1)" }, { "code": null, "e": 27613, "s": 27587, "text": "GATE-GATE-CS-2017 (Set 1)" }, { "code": null, "e": 27618, "s": 27613, "text": "GATE" }, { "code": null, "e": 27716, "s": 27618, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27750, "s": 27716, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 27784, "s": 27750, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 27818, "s": 27784, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 27851, "s": 27818, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 27887, "s": 27851, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 27921, "s": 27887, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 27957, "s": 27921, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 27991, "s": 27957, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 28025, "s": 27991, "text": "GATE | GATE-CS-2009 | Question 38" } ]
How to stack elements in CSS ? - GeeksforGeeks
10 Jul, 2020 In order to create attractive and unique web pages, it is eventually required to add one element on top of the other, completely or just a section of it. There are two methods to achieve this. Using CSS position property. Using CSS grids. Using CSS position property: The position: absolute; property is used to position any element at the absolute position and this property can be used to stack elements on top of each other. Using this, any element can be positioned anywhere regardless of the position of other elements. Example 1: <!DOCTYPE html><html> <head> <style> body { font-family: "Times New Roman", sans-serif; background: green; color: black; text-align: center; } h2 { font-weight: bold; padding: 0 10px; margin-bottom: 10px; } .parentClass { background: cyan; width: 80vw; margin: 8vw 10vw; height: 210px; } .firstchild { top: 0; left: 0; } .secondchild { top: 0; right: 0; } .childClass { position: absolute; opacity: 0.6; height: 150px; background: yellow; width: 200px; } </style></head> <body> <div class="parentClass"> <h2>I am Parent</h2> <div class="childClass firstchild"> <h2>First Child </h2> </div> <div class="childClass secondchild"> <h2>Second Child </h2> </div> </div></body> </html> Output: To create a self-contained component that can be used in multiple places, you need a container inside another container such that the parent container changes relatively according to the child, you may use position: relative; on the parent element and position: absolute; on the child elements. Example 2: <!DOCTYPE html><html> <head> <style> body { font-family: "Times New Roman", sans-serif; background: green; color: black; text-align: center; } h2 { font-weight: bold; padding: 0 20px; margin-bottom: 15px; } p { padding: 15px 10px; } .parentClass { position: relative; background: cyan; width: 80vw; margin: 8vw 10vw; height: 200px; } .childClass { top: 0; left: 0; opacity: 0.7; width: 200px; height: 150px; background: yellow; position: absolute; } </style></head> <body> <div class="parentClass"> <h2>Element 1</h2> <div class="childClass"> <h2>Element 2</h2> <p>position: absolute;</p><br> </div> </div></body> </html> Output: Example 3: The same implementation can also be used to have two elements stacked on top of the parent element. <!DOCTYPE html><html> <head> <style> body { font-family: "Times New Roman", sans-serif; background: green; color: black; text-align: center; } h2 { font-weight: bold; padding: 10 20px; margin-bottom: 15px; } p { padding: 10px 10px; } .parentClass { position: relative; background: cyan; width: 80vw; margin: 8vw 10vw; height: 200px; } .childClass { opacity: 0.8; height: 150px; width: 190px; background: yellow; position: absolute; top: 0; } .child1 { left: 0; } .child2 { left: 155px; } </style></head> <body> <div class="parentClass"> <h2>Element 1</h2> <code>position: relative;</code> <div class="childClass child1"> <h2>Element 1.1</h2> <p>position: absolute;</p><br> </div> <div class="childClass child2"> <h2>Element 1.2</h2> <p>position: absolute;</p> </div> </div></body> </html> Output: Using CSS Grids: Another way of stacking elements is to use CSS grids. Grids can be used to place elements wherever required. Use the below code to do simple stacking of an element on top of the other. .parentClass { grid-template-rows: 150px 1fr; grid-template-columns: 250px 1fr; display: grid;} .childClass { grid-area: 1 / 1 / 2 / 2;} Complete code: <!DOCTYPE html><html> <head> <style> body { font-family: "Times New Roman", sans-serif; background: green; color: black; text-align: center; } h1 { color: black; font-weight: bold; } h2 { color: grey; font-weight: bold; padding: 25px 15px 20px; margin-bottom: 15px; } p { padding: 5px 10px; } .parentClass { position: relative; background: cyan; width: 80vw; margin: 8vw 10vw; height: 200px; } .childClass { opacity: 0.8; height: 150px; width: 190px; background: yellow; position: absolute; top: 0; } .child1 { left: 0; } .child2 { left: 155px; } .parentClass { display: grid; grid-template-rows: 150px 1fr; grid-template-columns: 250px 1fr; } .childClass { grid-area: 1 / 1 / 2 / 2; } </style></head> <body> <div class="parentClass"> <h1>Element 1</h1> <div class="childClass child1"> <h2>Element 1.1</h2> <p>position: absolute;</p><br> </div> <div class="childClass child2"> <h2>Element 1.2</h2> <p>position: absolute;</p> </div> </div></body> </html> Output: If one child element is needed to be stacked on top of the other and both on top of parent element. .parentClass { display: grid; grid-template-columns: 250px 1fr; grid-template-rows: 150px 1fr;} .childClass { grid-area: 1 / 1 / 2 / 2;} .child-2 { margin-left: 200px;} Complete code example: <!DOCTYPE html><html> <head> <style> body { font-family: "Times New Roman", sans-serif; background: green; color: black; text-align: center; } h2 { font-weight: bold; padding: 10 10px; margin-bottom: 5px; } .parentClass { display: grid; grid-template-columns: 250px 1fr; grid-template-rows: 150px 1fr; background: cyan; width: 80vw; margin: 8vw 10vw; height: 200px; } .childClass { grid-area: 1/1/2/2; opacity: 0.7; height: 150px; width: 250px; background: yellow; } .child2 { margin-left: 200px; } </style></head> <body> <div class="parentClass"> <h2>Element 1<br> </h2> <div class="childClass"> <h2>Element 2.1</h2> </div> <div class="childClass child2"> <h2>Element 2.2</h2> </div> </div></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. 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. How to position a div at the bottom of its container using CSS? How to set space between the flexbox ? How to Upload Image into Database and Display it using PHP ? Design a web page using HTML and CSS How to apply style to parent if it has child with CSS? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? HTML Cheat Sheet - A Basic Guide to HTML REST API (Introduction)
[ { "code": null, "e": 25885, "s": 25857, "text": "\n10 Jul, 2020" }, { "code": null, "e": 26078, "s": 25885, "text": "In order to create attractive and unique web pages, it is eventually required to add one element on top of the other, completely or just a section of it. There are two methods to achieve this." }, { "code": null, "e": 26107, "s": 26078, "text": "Using CSS position property." }, { "code": null, "e": 26124, "s": 26107, "text": "Using CSS grids." }, { "code": null, "e": 26410, "s": 26124, "text": "Using CSS position property: The position: absolute; property is used to position any element at the absolute position and this property can be used to stack elements on top of each other. Using this, any element can be positioned anywhere regardless of the position of other elements." }, { "code": null, "e": 26421, "s": 26410, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <style> body { font-family: \"Times New Roman\", sans-serif; background: green; color: black; text-align: center; } h2 { font-weight: bold; padding: 0 10px; margin-bottom: 10px; } .parentClass { background: cyan; width: 80vw; margin: 8vw 10vw; height: 210px; } .firstchild { top: 0; left: 0; } .secondchild { top: 0; right: 0; } .childClass { position: absolute; opacity: 0.6; height: 150px; background: yellow; width: 200px; } </style></head> <body> <div class=\"parentClass\"> <h2>I am Parent</h2> <div class=\"childClass firstchild\"> <h2>First Child </h2> </div> <div class=\"childClass secondchild\"> <h2>Second Child </h2> </div> </div></body> </html>", "e": 27492, "s": 26421, "text": null }, { "code": null, "e": 27500, "s": 27492, "text": "Output:" }, { "code": null, "e": 27795, "s": 27500, "text": "To create a self-contained component that can be used in multiple places, you need a container inside another container such that the parent container changes relatively according to the child, you may use position: relative; on the parent element and position: absolute; on the child elements." }, { "code": null, "e": 27806, "s": 27795, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <style> body { font-family: \"Times New Roman\", sans-serif; background: green; color: black; text-align: center; } h2 { font-weight: bold; padding: 0 20px; margin-bottom: 15px; } p { padding: 15px 10px; } .parentClass { position: relative; background: cyan; width: 80vw; margin: 8vw 10vw; height: 200px; } .childClass { top: 0; left: 0; opacity: 0.7; width: 200px; height: 150px; background: yellow; position: absolute; } </style></head> <body> <div class=\"parentClass\"> <h2>Element 1</h2> <div class=\"childClass\"> <h2>Element 2</h2> <p>position: absolute;</p><br> </div> </div></body> </html>", "e": 28784, "s": 27806, "text": null }, { "code": null, "e": 28792, "s": 28784, "text": "Output:" }, { "code": null, "e": 28903, "s": 28792, "text": "Example 3: The same implementation can also be used to have two elements stacked on top of the parent element." }, { "code": "<!DOCTYPE html><html> <head> <style> body { font-family: \"Times New Roman\", sans-serif; background: green; color: black; text-align: center; } h2 { font-weight: bold; padding: 10 20px; margin-bottom: 15px; } p { padding: 10px 10px; } .parentClass { position: relative; background: cyan; width: 80vw; margin: 8vw 10vw; height: 200px; } .childClass { opacity: 0.8; height: 150px; width: 190px; background: yellow; position: absolute; top: 0; } .child1 { left: 0; } .child2 { left: 155px; } </style></head> <body> <div class=\"parentClass\"> <h2>Element 1</h2> <code>position: relative;</code> <div class=\"childClass child1\"> <h2>Element 1.1</h2> <p>position: absolute;</p><br> </div> <div class=\"childClass child2\"> <h2>Element 1.2</h2> <p>position: absolute;</p> </div> </div></body> </html>", "e": 30134, "s": 28903, "text": null }, { "code": null, "e": 30142, "s": 30134, "text": "Output:" }, { "code": null, "e": 30344, "s": 30142, "text": "Using CSS Grids: Another way of stacking elements is to use CSS grids. Grids can be used to place elements wherever required. Use the below code to do simple stacking of an element on top of the other." }, { "code": ".parentClass { grid-template-rows: 150px 1fr; grid-template-columns: 250px 1fr; display: grid;} .childClass { grid-area: 1 / 1 / 2 / 2;}", "e": 30493, "s": 30344, "text": null }, { "code": null, "e": 30508, "s": 30493, "text": "Complete code:" }, { "code": "<!DOCTYPE html><html> <head> <style> body { font-family: \"Times New Roman\", sans-serif; background: green; color: black; text-align: center; } h1 { color: black; font-weight: bold; } h2 { color: grey; font-weight: bold; padding: 25px 15px 20px; margin-bottom: 15px; } p { padding: 5px 10px; } .parentClass { position: relative; background: cyan; width: 80vw; margin: 8vw 10vw; height: 200px; } .childClass { opacity: 0.8; height: 150px; width: 190px; background: yellow; position: absolute; top: 0; } .child1 { left: 0; } .child2 { left: 155px; } .parentClass { display: grid; grid-template-rows: 150px 1fr; grid-template-columns: 250px 1fr; } .childClass { grid-area: 1 / 1 / 2 / 2; } </style></head> <body> <div class=\"parentClass\"> <h1>Element 1</h1> <div class=\"childClass child1\"> <h2>Element 1.1</h2> <p>position: absolute;</p><br> </div> <div class=\"childClass child2\"> <h2>Element 1.2</h2> <p>position: absolute;</p> </div> </div></body> </html>", "e": 32026, "s": 30508, "text": null }, { "code": null, "e": 32034, "s": 32026, "text": "Output:" }, { "code": null, "e": 32134, "s": 32034, "text": "If one child element is needed to be stacked on top of the other and both on top of parent element." }, { "code": ".parentClass { display: grid; grid-template-columns: 250px 1fr; grid-template-rows: 150px 1fr;} .childClass { grid-area: 1 / 1 / 2 / 2;} .child-2 { margin-left: 200px;}", "e": 32320, "s": 32134, "text": null }, { "code": null, "e": 32343, "s": 32320, "text": "Complete code example:" }, { "code": "<!DOCTYPE html><html> <head> <style> body { font-family: \"Times New Roman\", sans-serif; background: green; color: black; text-align: center; } h2 { font-weight: bold; padding: 10 10px; margin-bottom: 5px; } .parentClass { display: grid; grid-template-columns: 250px 1fr; grid-template-rows: 150px 1fr; background: cyan; width: 80vw; margin: 8vw 10vw; height: 200px; } .childClass { grid-area: 1/1/2/2; opacity: 0.7; height: 150px; width: 250px; background: yellow; } .child2 { margin-left: 200px; } </style></head> <body> <div class=\"parentClass\"> <h2>Element 1<br> </h2> <div class=\"childClass\"> <h2>Element 2.1</h2> </div> <div class=\"childClass child2\"> <h2>Element 2.2</h2> </div> </div></body> </html>", "e": 33429, "s": 32343, "text": null }, { "code": null, "e": 33437, "s": 33429, "text": "Output:" }, { "code": null, "e": 33574, "s": 33437, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 33583, "s": 33574, "text": "CSS-Misc" }, { "code": null, "e": 33593, "s": 33583, "text": "HTML-Misc" }, { "code": null, "e": 33597, "s": 33593, "text": "CSS" }, { "code": null, "e": 33602, "s": 33597, "text": "HTML" }, { "code": null, "e": 33619, "s": 33602, "text": "Web Technologies" }, { "code": null, "e": 33646, "s": 33619, "text": "Web technologies Questions" }, { "code": null, "e": 33651, "s": 33646, "text": "HTML" }, { "code": null, "e": 33749, "s": 33651, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33813, "s": 33749, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 33852, "s": 33813, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 33913, "s": 33852, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 33950, "s": 33913, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 34005, "s": 33950, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 34065, "s": 34005, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 34118, "s": 34065, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 34179, "s": 34118, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 34220, "s": 34179, "text": "HTML Cheat Sheet - A Basic Guide to HTML" } ]
How to set the size of the NumericUpDown in C#?
26 Jul, 2019 In windows forms, NumericUpDown control is used to provide Windows spin box or an up-down control which displays the numeric values. Or in other words, NumericUpDown control provides an interface which moves using up and down arrow and holds some pre-defined numeric value. In NumericUpDown control, you can set the value of height and width of the up-down control in pixels using the Size Property. You can set this property in two different ways: 1. Design-Time: It is the easiest way to set the size of the NumericUpDown as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Next, drag and drop the NumericUpDown control from the toolbox on the form as shown in the below image: Step 3: After drag and drop you will go to the properties of the NumericUpDown and set the size of the NumericUpDown as shown in the below image:Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the height and width of the NumericUpDown control programmatically with the help of given syntax: public System.Drawing.Size Size { get; set; } Here, Size represents the height and width of the NumericUpDown control in pixels. The following steps show how to set the location of the NumericUpDown dynamically: Step 1: Create a NumericUpDown using the NumericUpDown() constructor is provided by the NumericUpDown class.// Creating a NumericUpDown NumericUpDown n = new NumericUpDown(); // Creating a NumericUpDown NumericUpDown n = new NumericUpDown(); Step 2: After creating NumericUpDown, set the Location property of the NumericUpDown provided by the NumericUpDown class.// Setting the size n.Size = new Size(126, 26); // Setting the size n.Size = new Size(126, 26); Step 3: And last add this NumericUpDown control to the form using the following statement:// Adding NumericUpDown control on the form this.Controls.Add(n); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp42 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the labels Label l1 = new Label(); l1.Location = new Point(348, 61); l1.Size = new Size(215, 20); l1.Text = "Form"; l1.Font = new Font("Bodoni MT", 12); this.Controls.Add(l1); Label l2 = new Label(); l2.Location = new Point(242, 136); l2.Size = new Size(103, 20); l2.Text = "Enter Age"; l2.Font = new Font("Bodoni MT", 12); this.Controls.Add(l2); // Creating and setting the // properties of NumericUpDown NumericUpDown n = new NumericUpDown(); n.Location = new Point(386, 130); n.Size = new Size(126, 26); n.Font = new Font("Bodoni MT", 12); n.Value = 18; n.Minimum = 18; n.Maximum = 30; n.BackColor = Color.LightGreen; n.ForeColor = Color.DarkGreen; n.Increment = 1; n.Name = "MySpinBox"; // Adding this control // to the form this.Controls.Add(n); }}}Output: // Adding NumericUpDown control on the form this.Controls.Add(n); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp42 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the labels Label l1 = new Label(); l1.Location = new Point(348, 61); l1.Size = new Size(215, 20); l1.Text = "Form"; l1.Font = new Font("Bodoni MT", 12); this.Controls.Add(l1); Label l2 = new Label(); l2.Location = new Point(242, 136); l2.Size = new Size(103, 20); l2.Text = "Enter Age"; l2.Font = new Font("Bodoni MT", 12); this.Controls.Add(l2); // Creating and setting the // properties of NumericUpDown NumericUpDown n = new NumericUpDown(); n.Location = new Point(386, 130); n.Size = new Size(126, 26); n.Font = new Font("Bodoni MT", 12); n.Value = 18; n.Minimum = 18; n.Maximum = 30; n.BackColor = Color.LightGreen; n.ForeColor = Color.DarkGreen; n.Increment = 1; n.Name = "MySpinBox"; // Adding this control // to the form this.Controls.Add(n); }}} Output: CSharp-Windows-Forms-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jul, 2019" }, { "code": null, "e": 477, "s": 28, "text": "In windows forms, NumericUpDown control is used to provide Windows spin box or an up-down control which displays the numeric values. Or in other words, NumericUpDown control provides an interface which moves using up and down arrow and holds some pre-defined numeric value. In NumericUpDown control, you can set the value of height and width of the up-down control in pixels using the Size Property. You can set this property in two different ways:" }, { "code": null, "e": 585, "s": 477, "text": "1. Design-Time: It is the easiest way to set the size of the NumericUpDown as shown in the following steps:" }, { "code": null, "e": 701, "s": 585, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 759, "s": 701, "text": "Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 871, "s": 759, "text": "Step 2: Next, drag and drop the NumericUpDown control from the toolbox on the form as shown in the below image:" }, { "code": null, "e": 1024, "s": 871, "text": "Step 3: After drag and drop you will go to the properties of the NumericUpDown and set the size of the NumericUpDown as shown in the below image:Output:" }, { "code": null, "e": 1032, "s": 1024, "text": "Output:" }, { "code": null, "e": 1222, "s": 1032, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the height and width of the NumericUpDown control programmatically with the help of given syntax:" }, { "code": null, "e": 1268, "s": 1222, "text": "public System.Drawing.Size Size { get; set; }" }, { "code": null, "e": 1434, "s": 1268, "text": "Here, Size represents the height and width of the NumericUpDown control in pixels. The following steps show how to set the location of the NumericUpDown dynamically:" }, { "code": null, "e": 1610, "s": 1434, "text": "Step 1: Create a NumericUpDown using the NumericUpDown() constructor is provided by the NumericUpDown class.// Creating a NumericUpDown\nNumericUpDown n = new NumericUpDown();\n" }, { "code": null, "e": 1678, "s": 1610, "text": "// Creating a NumericUpDown\nNumericUpDown n = new NumericUpDown();\n" }, { "code": null, "e": 1848, "s": 1678, "text": "Step 2: After creating NumericUpDown, set the Location property of the NumericUpDown provided by the NumericUpDown class.// Setting the size\nn.Size = new Size(126, 26);\n" }, { "code": null, "e": 1897, "s": 1848, "text": "// Setting the size\nn.Size = new Size(126, 26);\n" }, { "code": null, "e": 3484, "s": 1897, "text": "Step 3: And last add this NumericUpDown control to the form using the following statement:// Adding NumericUpDown control on the form\nthis.Controls.Add(n);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp42 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the labels Label l1 = new Label(); l1.Location = new Point(348, 61); l1.Size = new Size(215, 20); l1.Text = \"Form\"; l1.Font = new Font(\"Bodoni MT\", 12); this.Controls.Add(l1); Label l2 = new Label(); l2.Location = new Point(242, 136); l2.Size = new Size(103, 20); l2.Text = \"Enter Age\"; l2.Font = new Font(\"Bodoni MT\", 12); this.Controls.Add(l2); // Creating and setting the // properties of NumericUpDown NumericUpDown n = new NumericUpDown(); n.Location = new Point(386, 130); n.Size = new Size(126, 26); n.Font = new Font(\"Bodoni MT\", 12); n.Value = 18; n.Minimum = 18; n.Maximum = 30; n.BackColor = Color.LightGreen; n.ForeColor = Color.DarkGreen; n.Increment = 1; n.Name = \"MySpinBox\"; // Adding this control // to the form this.Controls.Add(n); }}}Output:" }, { "code": null, "e": 3551, "s": 3484, "text": "// Adding NumericUpDown control on the form\nthis.Controls.Add(n);\n" }, { "code": null, "e": 3560, "s": 3551, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp42 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the labels Label l1 = new Label(); l1.Location = new Point(348, 61); l1.Size = new Size(215, 20); l1.Text = \"Form\"; l1.Font = new Font(\"Bodoni MT\", 12); this.Controls.Add(l1); Label l2 = new Label(); l2.Location = new Point(242, 136); l2.Size = new Size(103, 20); l2.Text = \"Enter Age\"; l2.Font = new Font(\"Bodoni MT\", 12); this.Controls.Add(l2); // Creating and setting the // properties of NumericUpDown NumericUpDown n = new NumericUpDown(); n.Location = new Point(386, 130); n.Size = new Size(126, 26); n.Font = new Font(\"Bodoni MT\", 12); n.Value = 18; n.Minimum = 18; n.Maximum = 30; n.BackColor = Color.LightGreen; n.ForeColor = Color.DarkGreen; n.Increment = 1; n.Name = \"MySpinBox\"; // Adding this control // to the form this.Controls.Add(n); }}}", "e": 4976, "s": 3560, "text": null }, { "code": null, "e": 4984, "s": 4976, "text": "Output:" }, { "code": null, "e": 5015, "s": 4984, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 5018, "s": 5015, "text": "C#" } ]
How to change the text of a label using JavaScript ?
21 Jul, 2021 Given an HTML document and the task is to change the text of a label using JavaScript. What is a label ?The <label>tag is used to provide a usability improvement for mouse users i.e, if a user clicks on the text within the <label> element, it toggles the control. Approach: Create a label element and assign an id to that element. Define a button that is used to call a function. It acts as a switch to change the text in the label element. Define a javaScript function, that will update the label text. Use the innerHTML property to change the text inside the label. The innerHTML property sets or returns the HTML content of an element. Example 1: This example implements the above approach. <!DOCTYPE html><html> <head> <title> How to change the text of a label using JavaScript ? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h4> Click on the button to change the text of a label </h4> <label id = "GFG"> Welcome to GeeksforGeeks </label> <br> <button onclick="myGeeks()"> Click Here! </button> <script> function myGeeks() { document.getElementById('GFG').innerHTML = 'A computer science portal for geeks'; } </script></body> </html> Output: Before Click on the Button: After Click on the Button: Example 2: This example changes the text of a label using JavaScript. <!DOCTYPE html><html> <head> <title> How to change the text of a label using JavaScript ? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h4> Click on the button to change the text of a label </h4> <label id = "GFG"> Welcome to GeeksforGeeks </label> <br> <button onclick="myGeeks()"> Click Here! </button> <script> function myGeeks() { var x = document.getElementById("GFG"); if (x.innerHTML === "Welcome to GeeksforGeeks") { x.innerHTML = "A computer science portal for geeks"; } else { x.innerHTML = "Welcome to GeeksforGeeks"; } } </script></body> </html> Output: Before Click on the Button: After Click on the Button: JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jul, 2021" }, { "code": null, "e": 115, "s": 28, "text": "Given an HTML document and the task is to change the text of a label using JavaScript." }, { "code": null, "e": 292, "s": 115, "text": "What is a label ?The <label>tag is used to provide a usability improvement for mouse users i.e, if a user clicks on the text within the <label> element, it toggles the control." }, { "code": null, "e": 302, "s": 292, "text": "Approach:" }, { "code": null, "e": 359, "s": 302, "text": "Create a label element and assign an id to that element." }, { "code": null, "e": 469, "s": 359, "text": "Define a button that is used to call a function. It acts as a switch to change the text in the label element." }, { "code": null, "e": 532, "s": 469, "text": "Define a javaScript function, that will update the label text." }, { "code": null, "e": 667, "s": 532, "text": "Use the innerHTML property to change the text inside the label. The innerHTML property sets or returns the HTML content of an element." }, { "code": null, "e": 722, "s": 667, "text": "Example 1: This example implements the above approach." }, { "code": "<!DOCTYPE html><html> <head> <title> How to change the text of a label using JavaScript ? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h4> Click on the button to change the text of a label </h4> <label id = \"GFG\"> Welcome to GeeksforGeeks </label> <br> <button onclick=\"myGeeks()\"> Click Here! </button> <script> function myGeeks() { document.getElementById('GFG').innerHTML = 'A computer science portal for geeks'; } </script></body> </html> ", "e": 1378, "s": 722, "text": null }, { "code": null, "e": 1386, "s": 1378, "text": "Output:" }, { "code": null, "e": 1414, "s": 1386, "text": "Before Click on the Button:" }, { "code": null, "e": 1441, "s": 1414, "text": "After Click on the Button:" }, { "code": null, "e": 1511, "s": 1441, "text": "Example 2: This example changes the text of a label using JavaScript." }, { "code": "<!DOCTYPE html><html> <head> <title> How to change the text of a label using JavaScript ? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h4> Click on the button to change the text of a label </h4> <label id = \"GFG\"> Welcome to GeeksforGeeks </label> <br> <button onclick=\"myGeeks()\"> Click Here! </button> <script> function myGeeks() { var x = document.getElementById(\"GFG\"); if (x.innerHTML === \"Welcome to GeeksforGeeks\") { x.innerHTML = \"A computer science portal for geeks\"; } else { x.innerHTML = \"Welcome to GeeksforGeeks\"; } } </script></body> </html>", "e": 2337, "s": 1511, "text": null }, { "code": null, "e": 2345, "s": 2337, "text": "Output:" }, { "code": null, "e": 2373, "s": 2345, "text": "Before Click on the Button:" }, { "code": null, "e": 2400, "s": 2373, "text": "After Click on the Button:" }, { "code": null, "e": 2619, "s": 2400, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 2635, "s": 2619, "text": "JavaScript-Misc" }, { "code": null, "e": 2642, "s": 2635, "text": "Picked" }, { "code": null, "e": 2653, "s": 2642, "text": "JavaScript" }, { "code": null, "e": 2670, "s": 2653, "text": "Web Technologies" }, { "code": null, "e": 2697, "s": 2670, "text": "Web technologies Questions" } ]
Python program for multiplication and division of complex number
30 Jan, 2020 Given two complex numbers. The task is to multiply and divide them. Multiplication of complex number: In Python complex numbers can be multiplied using * operator Examples: Input: 2+3i, 4+5i Output: Multiplication is : (-7+22j) Input: 2+3i, 1+2i Output: Multiplication is : (-4+7j) # Python program to demonstrate# multiplication of complex numbers def mulComplex( z1, z2): return z1*z2 # driver codez1 = complex(2, 3)z2 = complex(4, 5) print("Multiplication is :", mulComplex(z1,z2)) Output: Multiplication is : (-7+22j) Division of complex number: In Python, complex numbers can be divided using the / operator. Examples: Input: 2+3i, 4+5i Output: Division is : (0.5609756097560976+0.0487804878048781j) Input: 2+3i, 1+2i Output: Division is :(1.6-0.2j) # Python program to demonstrate# division of complex numbers def divComplex( z1, z2): return z1 / z2 # driver code z1 = complex(2, 3)z2 = complex(4, 5) print( "Division is :", (divComplex(z1, z2)) Output: Division is : (0.5609756097560976+0.0487804878048781j) python-utility Technical Scripter 2019 Python Programs Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jan, 2020" }, { "code": null, "e": 120, "s": 52, "text": "Given two complex numbers. The task is to multiply and divide them." }, { "code": null, "e": 215, "s": 120, "text": "Multiplication of complex number: In Python complex numbers can be multiplied using * operator" }, { "code": null, "e": 225, "s": 215, "text": "Examples:" }, { "code": null, "e": 339, "s": 225, "text": "Input: 2+3i, 4+5i \nOutput: Multiplication is : (-7+22j) \n\nInput: 2+3i, 1+2i\nOutput: Multiplication is : (-4+7j) \n" }, { "code": "# Python program to demonstrate# multiplication of complex numbers def mulComplex( z1, z2): return z1*z2 # driver codez1 = complex(2, 3)z2 = complex(4, 5) print(\"Multiplication is :\", mulComplex(z1,z2))", "e": 559, "s": 339, "text": null }, { "code": null, "e": 567, "s": 559, "text": "Output:" }, { "code": null, "e": 597, "s": 567, "text": "Multiplication is : (-7+22j)\n" }, { "code": null, "e": 689, "s": 597, "text": "Division of complex number: In Python, complex numbers can be divided using the / operator." }, { "code": null, "e": 699, "s": 689, "text": "Examples:" }, { "code": null, "e": 834, "s": 699, "text": "Input: 2+3i, 4+5i\nOutput: Division is : (0.5609756097560976+0.0487804878048781j)\n\nInput: 2+3i, 1+2i\nOutput: Division is :(1.6-0.2j) \n" }, { "code": "# Python program to demonstrate# division of complex numbers def divComplex( z1, z2): return z1 / z2 # driver code z1 = complex(2, 3)z2 = complex(4, 5) print( \"Division is :\", (divComplex(z1, z2))", "e": 1040, "s": 834, "text": null }, { "code": null, "e": 1048, "s": 1040, "text": "Output:" }, { "code": null, "e": 1104, "s": 1048, "text": "Division is : (0.5609756097560976+0.0487804878048781j)\n" }, { "code": null, "e": 1119, "s": 1104, "text": "python-utility" }, { "code": null, "e": 1143, "s": 1119, "text": "Technical Scripter 2019" }, { "code": null, "e": 1159, "s": 1143, "text": "Python Programs" }, { "code": null, "e": 1178, "s": 1159, "text": "Technical Scripter" } ]
Program for Method Of False Position
13 Apr, 2021 Given a function f(x) on floating number x and two numbers ‘a’ and ‘b’ such that f(a)*f(b) < 0 and f(x) is continuous in [a, b]. Here f(x) represents algebraic or transcendental equation. Find root of function in interval [a, b] (Or find a value of x such that f(x) is 0). Input: A function of x, for example x3 – x2 + 2. And two values: a = -200 and b = 300 such that f(a)*f(b) < 0, i.e., f(a) and f(b) have opposite signs. Output: The value of root is : -1.00 OR any other value close to root. We strongly recommend to refer below post as a prerequisite of this post. Solution of Algebraic and Transcendental Equations | Set 1 (The Bisection Method)In this post The Method Of False Position is discussed. This method is also known as Regula Falsi or The Method of Chords. Similarities with Bisection Method: Same Assumptions: This method also assumes that function is continuous in [a, b] and given two numbers ‘a’ and ‘b’ are such that f(a) * f(b) < 0.Always Converges: like Bisection, it always converges, usually considerably faster than Bisection–but sometimes very much more slowly than Bisection. Same Assumptions: This method also assumes that function is continuous in [a, b] and given two numbers ‘a’ and ‘b’ are such that f(a) * f(b) < 0. Always Converges: like Bisection, it always converges, usually considerably faster than Bisection–but sometimes very much more slowly than Bisection. Differences with Bisection Method: It differs in the fact that we make a chord joining the two points [a, f(a)] and [b, f(b)]. We consider the point at which the chord touches the x axis and named it as c. Steps: Write equation of the line connecting the two points. Write equation of the line connecting the two points. y – f(a) = ( (f(b)-f(a))/(b-a) )*(x-a) Now we have to find the point which touches x axis. For that we put y = 0. so x = a - (f(a)/(f(b)-f(a))) * (b-a) x = (a*f(b) - b*f(a)) / (f(b)-f(a)) This will be our c that is c = x. If f(c) == 0, then c is the root of the solution.Else f(c) != 0If value f(a)*f(c) < 0 then root lies between a and c. So we recur for a and cElse If f(b)*f(c) < 0 then root lies between b and c. So we recur b and c.Else given function doesn’t follow one of assumptions. If f(c) == 0, then c is the root of the solution. Else f(c) != 0If value f(a)*f(c) < 0 then root lies between a and c. So we recur for a and cElse If f(b)*f(c) < 0 then root lies between b and c. So we recur b and c.Else given function doesn’t follow one of assumptions. If value f(a)*f(c) < 0 then root lies between a and c. So we recur for a and cElse If f(b)*f(c) < 0 then root lies between b and c. So we recur b and c.Else given function doesn’t follow one of assumptions. If value f(a)*f(c) < 0 then root lies between a and c. So we recur for a and c Else If f(b)*f(c) < 0 then root lies between b and c. So we recur b and c. Else given function doesn’t follow one of assumptions. Since root may be a floating point number and may converge very slow in worst case, we iterate for a very large number of times such that the answer becomes closer to the root. Following is the implementation. C++ Java Python3 C# Javascript // C++ program for implementation of Bisection Method for// solving equations#include<bits/stdc++.h>using namespace std;#define MAX_ITER 1000000 // An example function whose solution is determined using// Bisection Method. The function is x^3 - x^2 + 2double func(double x){ return x*x*x - x*x + 2;} // Prints root of func(x) in interval [a, b]void regulaFalsi(double a, double b){ if (func(a) * func(b) >= 0) { cout << "You have not assumed right a and b\n"; return; } double c = a; // Initialize result for (int i=0; i < MAX_ITER; i++) { // Find the point that touches x axis c = (a*func(b) - b*func(a))/ (func(b) - func(a)); // Check if the above found point is root if (func(c)==0) break; // Decide the side to repeat the steps else if (func(c)*func(a) < 0) b = c; else a = c; } cout << "The value of root is : " << c;} // Driver program to test above functionint main(){ // Initial values assumed double a =-200, b = 300; regulaFalsi(a, b); return 0;} // java program for implementation// of Bisection Method for// solving equationsimport java.io.*; class GFG { static int MAX_ITER = 1000000; // An example function whose // solution is determined using // Bisection Method. The function // is x^3 - x^2 + 2 static double func(double x) { return (x * x * x - x * x + 2); } // Prints root of func(x) // in interval [a, b] static void regulaFalsi(double a, double b) { if (func(a) * func(b) >= 0) { System.out.println("You have not assumed right a and b"); } // Initialize result double c = a; for (int i = 0; i < MAX_ITER; i++) { // Find the point that touches x axis c = (a * func(b) - b * func(a)) / (func(b) - func(a)); // Check if the above found point is root if (func(c) == 0) break; // Decide the side to repeat the steps else if (func(c) * func(a) < 0) b = c; else a = c; } System.out.println("The value of root is : " + (int)c); } // Driver program public static void main(String[] args) { // Initial values assumed double a = -200, b = 300; regulaFalsi(a, b); }} // This article is contributed by vt_m # Python3 implementation of Bisection# Method for solving equations MAX_ITER = 1000000 # An example function whose solution# is determined using Bisection Method.# The function is x^3 - x^2 + 2def func( x ): return (x * x * x - x * x + 2) # Prints root of func(x) in interval [a, b]def regulaFalsi( a , b): if func(a) * func(b) >= 0: print("You have not assumed right a and b") return -1 c = a # Initialize result for i in range(MAX_ITER): # Find the point that touches x axis c = (a * func(b) - b * func(a))/ (func(b) - func(a)) # Check if the above found point is root if func(c) == 0: break # Decide the side to repeat the steps elif func(c) * func(a) < 0: b = c else: a = c print("The value of root is : " , '%.4f' %c) # Driver code to test above function# Initial values assumeda =-200b = 300regulaFalsi(a, b) # This code is contributed by "Sharad_Bhardwaj". // C# program for implementation// of Bisection Method for// solving equationsusing System; class GFG { static int MAX_ITER = 1000000; // An example function whose // solution is determined using // Bisection Method. The function // is x^3 - x^2 + 2 static double func(double x) { return (x * x * x - x * x + 2); } // Prints root of func(x) // in interval [a, b] static void regulaFalsi(double a, double b) { if (func(a) * func(b) >= 0) { Console.WriteLine("You have not assumed right a and b"); } // Initialize result double c = a; for (int i = 0; i < MAX_ITER; i++) { // Find the point that touches x axis c = (a * func(b) - b * func(a)) / (func(b) - func(a)); // Check if the above found point is root if (func(c) == 0) break; // Decide the side to repeat the steps else if (func(c) * func(a) < 0) b = c; else a = c; } Console.WriteLine("The value of root is : " + (int)c); } // Driver program public static void Main(String []args) { // Initial values assumed double a = -200, b = 300; regulaFalsi(a, b); }} // This code is contributed by Sam007. <script> // JavaScript program for implementation of Bisection Method for// solving equations let MAX_ITER = 1000000 // An example function whose solution is determined using // Bisection Method. The function is x^3 - x^2 + 2 function func(x){ return x*x*x - x*x + 2; } // Prints root of func(x) in interval [a, b] function regulaFalsi( a, b){ if (func(a) * func(b) >= 0){ document.write("You have not assumed right a and b\n"); return; }// Initialize result let c = a; for (let i=0; i < MAX_ITER; i++) { // Find the point that touches x axis c = Math.floor((a*func(b) - b*func(a))/ (func(b) - func(a))); // Check if the above found point is root if (func(c)==0){ break; } // Decide the side to repeat the steps else if (func(c)*func(a) < 0){ b = c; } else{ a = c; } } document.write("The value of root is : " + c); } // Driver program to test above function // Initial values assumed let a =-200; let b = 300; regulaFalsi(a, b); </script> Output: The value of root is : -1 This method always converges, usually considerably faster than Bisection. But worst case can be very slow. We will soon be discussing other methods to solve algebraic and transcendental equations.References: Introductory Methods of Numerical Analysis by S.S. Sastry https://en.wikipedia.org/wiki/False_position_methodThis article is contributed by Abhiraj Smit. 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.
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Apr, 2021" }, { "code": null, "e": 328, "s": 54, "text": "Given a function f(x) on floating number x and two numbers ‘a’ and ‘b’ such that f(a)*f(b) < 0 and f(x) is continuous in [a, b]. Here f(x) represents algebraic or transcendental equation. Find root of function in interval [a, b] (Or find a value of x such that f(x) is 0). " }, { "code": null, "e": 585, "s": 328, "text": "Input: A function of x, for example x3 – x2 + 2. \n And two values: a = -200 and b = 300 such that\n f(a)*f(b) < 0, i.e., f(a) and f(b) have\n opposite signs.\nOutput: The value of root is : -1.00\n OR any other value close to root." }, { "code": null, "e": 901, "s": 585, "text": "We strongly recommend to refer below post as a prerequisite of this post. Solution of Algebraic and Transcendental Equations | Set 1 (The Bisection Method)In this post The Method Of False Position is discussed. This method is also known as Regula Falsi or The Method of Chords. Similarities with Bisection Method: " }, { "code": null, "e": 1196, "s": 901, "text": "Same Assumptions: This method also assumes that function is continuous in [a, b] and given two numbers ‘a’ and ‘b’ are such that f(a) * f(b) < 0.Always Converges: like Bisection, it always converges, usually considerably faster than Bisection–but sometimes very much more slowly than Bisection." }, { "code": null, "e": 1342, "s": 1196, "text": "Same Assumptions: This method also assumes that function is continuous in [a, b] and given two numbers ‘a’ and ‘b’ are such that f(a) * f(b) < 0." }, { "code": null, "e": 1492, "s": 1342, "text": "Always Converges: like Bisection, it always converges, usually considerably faster than Bisection–but sometimes very much more slowly than Bisection." }, { "code": null, "e": 1707, "s": 1492, "text": "Differences with Bisection Method: It differs in the fact that we make a chord joining the two points [a, f(a)] and [b, f(b)]. We consider the point at which the chord touches the x axis and named it as c. Steps: " }, { "code": null, "e": 1763, "s": 1707, "text": "Write equation of the line connecting the two points. " }, { "code": null, "e": 1819, "s": 1763, "text": "Write equation of the line connecting the two points. " }, { "code": null, "e": 2051, "s": 1819, "text": "y – f(a) = ( (f(b)-f(a))/(b-a) )*(x-a)\n\nNow we have to find the point which touches x axis. \nFor that we put y = 0.\n\nso x = a - (f(a)/(f(b)-f(a))) * (b-a)\n x = (a*f(b) - b*f(a)) / (f(b)-f(a)) \n\nThis will be our c that is c = x. " }, { "code": null, "e": 2321, "s": 2051, "text": "If f(c) == 0, then c is the root of the solution.Else f(c) != 0If value f(a)*f(c) < 0 then root lies between a and c. So we recur for a and cElse If f(b)*f(c) < 0 then root lies between b and c. So we recur b and c.Else given function doesn’t follow one of assumptions." }, { "code": null, "e": 2371, "s": 2321, "text": "If f(c) == 0, then c is the root of the solution." }, { "code": null, "e": 2592, "s": 2371, "text": "Else f(c) != 0If value f(a)*f(c) < 0 then root lies between a and c. So we recur for a and cElse If f(b)*f(c) < 0 then root lies between b and c. So we recur b and c.Else given function doesn’t follow one of assumptions." }, { "code": null, "e": 2799, "s": 2592, "text": "If value f(a)*f(c) < 0 then root lies between a and c. So we recur for a and cElse If f(b)*f(c) < 0 then root lies between b and c. So we recur b and c.Else given function doesn’t follow one of assumptions." }, { "code": null, "e": 2878, "s": 2799, "text": "If value f(a)*f(c) < 0 then root lies between a and c. So we recur for a and c" }, { "code": null, "e": 2953, "s": 2878, "text": "Else If f(b)*f(c) < 0 then root lies between b and c. So we recur b and c." }, { "code": null, "e": 3008, "s": 2953, "text": "Else given function doesn’t follow one of assumptions." }, { "code": null, "e": 3186, "s": 3008, "text": "Since root may be a floating point number and may converge very slow in worst case, we iterate for a very large number of times such that the answer becomes closer to the root. " }, { "code": null, "e": 3221, "s": 3186, "text": "Following is the implementation. " }, { "code": null, "e": 3225, "s": 3221, "text": "C++" }, { "code": null, "e": 3230, "s": 3225, "text": "Java" }, { "code": null, "e": 3238, "s": 3230, "text": "Python3" }, { "code": null, "e": 3241, "s": 3238, "text": "C#" }, { "code": null, "e": 3252, "s": 3241, "text": "Javascript" }, { "code": "// C++ program for implementation of Bisection Method for// solving equations#include<bits/stdc++.h>using namespace std;#define MAX_ITER 1000000 // An example function whose solution is determined using// Bisection Method. The function is x^3 - x^2 + 2double func(double x){ return x*x*x - x*x + 2;} // Prints root of func(x) in interval [a, b]void regulaFalsi(double a, double b){ if (func(a) * func(b) >= 0) { cout << \"You have not assumed right a and b\\n\"; return; } double c = a; // Initialize result for (int i=0; i < MAX_ITER; i++) { // Find the point that touches x axis c = (a*func(b) - b*func(a))/ (func(b) - func(a)); // Check if the above found point is root if (func(c)==0) break; // Decide the side to repeat the steps else if (func(c)*func(a) < 0) b = c; else a = c; } cout << \"The value of root is : \" << c;} // Driver program to test above functionint main(){ // Initial values assumed double a =-200, b = 300; regulaFalsi(a, b); return 0;}", "e": 4350, "s": 3252, "text": null }, { "code": "// java program for implementation// of Bisection Method for// solving equationsimport java.io.*; class GFG { static int MAX_ITER = 1000000; // An example function whose // solution is determined using // Bisection Method. The function // is x^3 - x^2 + 2 static double func(double x) { return (x * x * x - x * x + 2); } // Prints root of func(x) // in interval [a, b] static void regulaFalsi(double a, double b) { if (func(a) * func(b) >= 0) { System.out.println(\"You have not assumed right a and b\"); } // Initialize result double c = a; for (int i = 0; i < MAX_ITER; i++) { // Find the point that touches x axis c = (a * func(b) - b * func(a)) / (func(b) - func(a)); // Check if the above found point is root if (func(c) == 0) break; // Decide the side to repeat the steps else if (func(c) * func(a) < 0) b = c; else a = c; } System.out.println(\"The value of root is : \" + (int)c); } // Driver program public static void main(String[] args) { // Initial values assumed double a = -200, b = 300; regulaFalsi(a, b); }} // This article is contributed by vt_m", "e": 5707, "s": 4350, "text": null }, { "code": "# Python3 implementation of Bisection# Method for solving equations MAX_ITER = 1000000 # An example function whose solution# is determined using Bisection Method.# The function is x^3 - x^2 + 2def func( x ): return (x * x * x - x * x + 2) # Prints root of func(x) in interval [a, b]def regulaFalsi( a , b): if func(a) * func(b) >= 0: print(\"You have not assumed right a and b\") return -1 c = a # Initialize result for i in range(MAX_ITER): # Find the point that touches x axis c = (a * func(b) - b * func(a))/ (func(b) - func(a)) # Check if the above found point is root if func(c) == 0: break # Decide the side to repeat the steps elif func(c) * func(a) < 0: b = c else: a = c print(\"The value of root is : \" , '%.4f' %c) # Driver code to test above function# Initial values assumeda =-200b = 300regulaFalsi(a, b) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 6719, "s": 5707, "text": null }, { "code": "// C# program for implementation// of Bisection Method for// solving equationsusing System; class GFG { static int MAX_ITER = 1000000; // An example function whose // solution is determined using // Bisection Method. The function // is x^3 - x^2 + 2 static double func(double x) { return (x * x * x - x * x + 2); } // Prints root of func(x) // in interval [a, b] static void regulaFalsi(double a, double b) { if (func(a) * func(b) >= 0) { Console.WriteLine(\"You have not assumed right a and b\"); } // Initialize result double c = a; for (int i = 0; i < MAX_ITER; i++) { // Find the point that touches x axis c = (a * func(b) - b * func(a)) / (func(b) - func(a)); // Check if the above found point is root if (func(c) == 0) break; // Decide the side to repeat the steps else if (func(c) * func(a) < 0) b = c; else a = c; } Console.WriteLine(\"The value of root is : \" + (int)c); } // Driver program public static void Main(String []args) { // Initial values assumed double a = -200, b = 300; regulaFalsi(a, b); }} // This code is contributed by Sam007.", "e": 8068, "s": 6719, "text": null }, { "code": "<script> // JavaScript program for implementation of Bisection Method for// solving equations let MAX_ITER = 1000000 // An example function whose solution is determined using // Bisection Method. The function is x^3 - x^2 + 2 function func(x){ return x*x*x - x*x + 2; } // Prints root of func(x) in interval [a, b] function regulaFalsi( a, b){ if (func(a) * func(b) >= 0){ document.write(\"You have not assumed right a and b\\n\"); return; }// Initialize result let c = a; for (let i=0; i < MAX_ITER; i++) { // Find the point that touches x axis c = Math.floor((a*func(b) - b*func(a))/ (func(b) - func(a))); // Check if the above found point is root if (func(c)==0){ break; } // Decide the side to repeat the steps else if (func(c)*func(a) < 0){ b = c; } else{ a = c; } } document.write(\"The value of root is : \" + c); } // Driver program to test above function // Initial values assumed let a =-200; let b = 300; regulaFalsi(a, b); </script>", "e": 9220, "s": 8068, "text": null }, { "code": null, "e": 9228, "s": 9220, "text": "Output:" }, { "code": null, "e": 9254, "s": 9228, "text": "The value of root is : -1" }, { "code": null, "e": 9741, "s": 9254, "text": "This method always converges, usually considerably faster than Bisection. But worst case can be very slow. We will soon be discussing other methods to solve algebraic and transcendental equations.References: Introductory Methods of Numerical Analysis by S.S. Sastry https://en.wikipedia.org/wiki/False_position_methodThis article is contributed by Abhiraj Smit. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 9763, "s": 9741, "text": "Interview Experiences" } ]
ColorMaps in Seaborn HeatMaps
25 Nov, 2020 Colormaps are used to visualize heatmaps effectively and easily. One might use different sorts of colormaps for different kinds of heatmaps. In this article, we will look at how to use colormaps while working with seaborn heatmaps. Sequential Colormaps: We use sequential colormaps when the data values(numeric) goes from high to low and only one of them is important for the analysis. Example of sequential colormaps: sns.palplot(sns.color_palette("Greens",12)) Sequential color palette sns.palplot(sns.color_palette("Blues",12)) Sequential color palette Note that we have used sns.color_palette() to construct a colormap and sns.palplot() to display the colors present in the colormap. The following example shows how to implement a sequential colormap on a seaborn heatmap. Example: Python3 import seaborn as snsimport numpy as np np.random.seed(0) # generates random valuesdata = np.random.rand(12, 12) # creating a colormapcolormap = sns.color_palette("Greens") # creating a heatmap using the colormapax = sns.heatmap(data, cmap=colormap) Output: Heatmap with a sequential colormap Since “Greens” is an inbuilt colormap in seaborn, can also directly pass “Greens” to the cmap argument: Python3 import seaborn as snsimport numpy as np np.random.seed(0) data = np.random.rand(12, 12)ax = sns.heatmap(data, cmap="Greens") Output: Heatmap with a sequential colormap Note that our colormap now has a continuous color intensity unlike the one before which had a discrete intensity of green for a range of values. Here is a closer look at both of the colormaps generated in the above-mentioned heatmaps: Discrete(left) and Continuous(right) Colormaps Diverging Colormaps: They are used to represent numeric values that go from high to low(and vice-versa), and both high and low values are of interest. Here are some diverging colormaps present in seaborn: sns.palplot(sns.color_palette("PiYG", 12)) Diverging color palette sns.palplot(sns.color_palette("coolwarm", 12)) Example: The following example shows how to implement a diverging colormap on a seaborn heatmap. Python3 import seaborn as snsimport numpy as np np.random.seed(0) data = np.random.rand(12, 12)ax = sns.heatmap(data, cmap="PiYG") Output: Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Nov, 2020" }, { "code": null, "e": 260, "s": 28, "text": "Colormaps are used to visualize heatmaps effectively and easily. One might use different sorts of colormaps for different kinds of heatmaps. In this article, we will look at how to use colormaps while working with seaborn heatmaps." }, { "code": null, "e": 415, "s": 260, "text": "Sequential Colormaps: We use sequential colormaps when the data values(numeric) goes from high to low and only one of them is important for the analysis. " }, { "code": null, "e": 448, "s": 415, "text": "Example of sequential colormaps:" }, { "code": null, "e": 493, "s": 448, "text": "sns.palplot(sns.color_palette(\"Greens\",12))\n" }, { "code": null, "e": 518, "s": 493, "text": "Sequential color palette" }, { "code": null, "e": 562, "s": 518, "text": "sns.palplot(sns.color_palette(\"Blues\",12))\n" }, { "code": null, "e": 587, "s": 562, "text": "Sequential color palette" }, { "code": null, "e": 808, "s": 587, "text": "Note that we have used sns.color_palette() to construct a colormap and sns.palplot() to display the colors present in the colormap. The following example shows how to implement a sequential colormap on a seaborn heatmap." }, { "code": null, "e": 817, "s": 808, "text": "Example:" }, { "code": null, "e": 825, "s": 817, "text": "Python3" }, { "code": "import seaborn as snsimport numpy as np np.random.seed(0) # generates random valuesdata = np.random.rand(12, 12) # creating a colormapcolormap = sns.color_palette(\"Greens\") # creating a heatmap using the colormapax = sns.heatmap(data, cmap=colormap)", "e": 1081, "s": 825, "text": null }, { "code": null, "e": 1089, "s": 1081, "text": "Output:" }, { "code": null, "e": 1124, "s": 1089, "text": "Heatmap with a sequential colormap" }, { "code": null, "e": 1228, "s": 1124, "text": "Since “Greens” is an inbuilt colormap in seaborn, can also directly pass “Greens” to the cmap argument:" }, { "code": null, "e": 1236, "s": 1228, "text": "Python3" }, { "code": "import seaborn as snsimport numpy as np np.random.seed(0) data = np.random.rand(12, 12)ax = sns.heatmap(data, cmap=\"Greens\")", "e": 1365, "s": 1236, "text": null }, { "code": null, "e": 1373, "s": 1365, "text": "Output:" }, { "code": null, "e": 1408, "s": 1373, "text": "Heatmap with a sequential colormap" }, { "code": null, "e": 1643, "s": 1408, "text": "Note that our colormap now has a continuous color intensity unlike the one before which had a discrete intensity of green for a range of values. Here is a closer look at both of the colormaps generated in the above-mentioned heatmaps:" }, { "code": null, "e": 1690, "s": 1643, "text": "Discrete(left) and Continuous(right) Colormaps" }, { "code": null, "e": 1841, "s": 1690, "text": "Diverging Colormaps: They are used to represent numeric values that go from high to low(and vice-versa), and both high and low values are of interest." }, { "code": null, "e": 1895, "s": 1841, "text": "Here are some diverging colormaps present in seaborn:" }, { "code": null, "e": 1939, "s": 1895, "text": "sns.palplot(sns.color_palette(\"PiYG\", 12))\n" }, { "code": null, "e": 1963, "s": 1939, "text": "Diverging color palette" }, { "code": null, "e": 2011, "s": 1963, "text": "sns.palplot(sns.color_palette(\"coolwarm\", 12))\n" }, { "code": null, "e": 2108, "s": 2011, "text": "Example: The following example shows how to implement a diverging colormap on a seaborn heatmap." }, { "code": null, "e": 2116, "s": 2108, "text": "Python3" }, { "code": "import seaborn as snsimport numpy as np np.random.seed(0) data = np.random.rand(12, 12)ax = sns.heatmap(data, cmap=\"PiYG\")", "e": 2243, "s": 2116, "text": null }, { "code": null, "e": 2251, "s": 2243, "text": "Output:" }, { "code": null, "e": 2266, "s": 2251, "text": "Python-Seaborn" }, { "code": null, "e": 2273, "s": 2266, "text": "Python" } ]
How to make a text input non-editable using jQuery ?
22 Apr, 2020 An HTML document containing the input text area and the task is to make the text input non-editable with the help of jQuery. There are two approaches that are discussed below: Approach 1: We are going to set the property readonly to true. To set the readonly property, we will use a prop() method. Example:<!DOCTYPE HTML><html> <head> <title> How to make a text input non-editable using JQuery? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"></p> Type Here: <input id="input" /> <br><br> <button onclick="GFG_Fun()"> Click Here </button> <p id="GFG_DOWN"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = "Click on the button to " + "perform the operation."; function GFG_Fun() { $("#input").prop("readonly", true); el_down.innerHTML = "Input element is now read-only"; } </script></body> </html> <!DOCTYPE HTML><html> <head> <title> How to make a text input non-editable using JQuery? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"></p> Type Here: <input id="input" /> <br><br> <button onclick="GFG_Fun()"> Click Here </button> <p id="GFG_DOWN"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = "Click on the button to " + "perform the operation."; function GFG_Fun() { $("#input").prop("readonly", true); el_down.innerHTML = "Input element is now read-only"; } </script></body> </html> Output: Approach 2: We are going to set the property readonly to true. In this example, we will use attr() method to set the property value. Example:<!DOCTYPE HTML><html> <head> <title> How to make a text input non-editable using JQuery? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"></p> Type Here: <input id="input" /> <br><br> <button onclick="GFG_Fun()"> Click Here </button> <p id="GFG_DOWN"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = "Click on the button to " + "perform the operation."; function GFG_Fun() { $("#input").attr("readonly", true); el_down.innerHTML = "Input element is now read-only"; } </script></body> </html> <!DOCTYPE HTML><html> <head> <title> How to make a text input non-editable using JQuery? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"></p> Type Here: <input id="input" /> <br><br> <button onclick="GFG_Fun()"> Click Here </button> <p id="GFG_DOWN"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = "Click on the button to " + "perform the operation."; function GFG_Fun() { $("#input").attr("readonly", true); el_down.innerHTML = "Input element is now read-only"; } </script></body> </html> Output: CSS-Misc HTML-Misc jQuery-Misc CSS HTML JavaScript JQuery 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": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 204, "s": 28, "text": "An HTML document containing the input text area and the task is to make the text input non-editable with the help of jQuery. There are two approaches that are discussed below:" }, { "code": null, "e": 326, "s": 204, "text": "Approach 1: We are going to set the property readonly to true. To set the readonly property, we will use a prop() method." }, { "code": null, "e": 1266, "s": 326, "text": "Example:<!DOCTYPE HTML><html> <head> <title> How to make a text input non-editable using JQuery? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> Type Here: <input id=\"input\" /> <br><br> <button onclick=\"GFG_Fun()\"> Click Here </button> <p id=\"GFG_DOWN\"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = \"Click on the button to \" + \"perform the operation.\"; function GFG_Fun() { $(\"#input\").prop(\"readonly\", true); el_down.innerHTML = \"Input element is now read-only\"; } </script></body> </html>" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to make a text input non-editable using JQuery? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> Type Here: <input id=\"input\" /> <br><br> <button onclick=\"GFG_Fun()\"> Click Here </button> <p id=\"GFG_DOWN\"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = \"Click on the button to \" + \"perform the operation.\"; function GFG_Fun() { $(\"#input\").prop(\"readonly\", true); el_down.innerHTML = \"Input element is now read-only\"; } </script></body> </html>", "e": 2198, "s": 1266, "text": null }, { "code": null, "e": 2206, "s": 2198, "text": "Output:" }, { "code": null, "e": 2339, "s": 2206, "text": "Approach 2: We are going to set the property readonly to true. In this example, we will use attr() method to set the property value." }, { "code": null, "e": 3266, "s": 2339, "text": "Example:<!DOCTYPE HTML><html> <head> <title> How to make a text input non-editable using JQuery? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> Type Here: <input id=\"input\" /> <br><br> <button onclick=\"GFG_Fun()\"> Click Here </button> <p id=\"GFG_DOWN\"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = \"Click on the button to \" + \"perform the operation.\"; function GFG_Fun() { $(\"#input\").attr(\"readonly\", true); el_down.innerHTML = \"Input element is now read-only\"; } </script></body> </html>" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to make a text input non-editable using JQuery? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> Type Here: <input id=\"input\" /> <br><br> <button onclick=\"GFG_Fun()\"> Click Here </button> <p id=\"GFG_DOWN\"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = \"Click on the button to \" + \"perform the operation.\"; function GFG_Fun() { $(\"#input\").attr(\"readonly\", true); el_down.innerHTML = \"Input element is now read-only\"; } </script></body> </html>", "e": 4185, "s": 3266, "text": null }, { "code": null, "e": 4193, "s": 4185, "text": "Output:" }, { "code": null, "e": 4202, "s": 4193, "text": "CSS-Misc" }, { "code": null, "e": 4212, "s": 4202, "text": "HTML-Misc" }, { "code": null, "e": 4224, "s": 4212, "text": "jQuery-Misc" }, { "code": null, "e": 4228, "s": 4224, "text": "CSS" }, { "code": null, "e": 4233, "s": 4228, "text": "HTML" }, { "code": null, "e": 4244, "s": 4233, "text": "JavaScript" }, { "code": null, "e": 4251, "s": 4244, "text": "JQuery" }, { "code": null, "e": 4268, "s": 4251, "text": "Web Technologies" }, { "code": null, "e": 4295, "s": 4268, "text": "Web technologies Questions" }, { "code": null, "e": 4300, "s": 4295, "text": "HTML" }, { "code": null, "e": 4398, "s": 4300, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4435, "s": 4398, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 4474, "s": 4435, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 4513, "s": 4474, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 4577, "s": 4513, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 4638, "s": 4577, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 4662, "s": 4638, "text": "REST API (Introduction)" }, { "code": null, "e": 4715, "s": 4662, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 4775, "s": 4715, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 4836, "s": 4775, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Spam bot using PyAutoGUI
02 Feb, 2021 PyAutoGUI is a Python module that helps us automate the key presses and mouse clicks programmatically. In this article we will learn to develop a spam bot using PyAutoGUI. Spamming – Refers to sending unsolicited messages to large number of systems over the internet. This mini-project can be used for many real-life applications like: Remind your friends or relatives to do a particular task after every particular time interval Can be used for advertisement purpose In this article we will show the working of spam bot on telegram, but the code can also work for WhatsApp, Instagram etc. i.e. anywhere we find a text field it will work the same way. Approach Import module Add delay of 2 second in the execution of the program Create mechanism to generate text messages. typewrite() function of pyautogui helps to write the text and sleep function helps us specify the particular time interval (in seconds) after which the next instruction has to be executed. datetime.datetime.now() function helps the user keep a track of when the message was sent. Syntax: typewriter(“<message>”) Execute code Follow these simple steps to develop a spam bot using python: Example: Python3 import pyautogui, time, datetime time.sleep(2) while True: # to display the time at which the message is sent print(datetime.datetime.now()) pyautogui.typewrite("Reminder: Drink water!") pyautogui.press("enter") time.sleep(31) print(datetime.datetime.now()) pyautogui.typewrite("Reminder: Take medicine!") pyautogui.press("enter") time.sleep(31) print(datetime.datetime.now()) pyautogui.typewrite("Reminder: Take the dog for a walk!") pyautogui.press("enter") time.sleep(31) print(datetime.datetime.now()) pyautogui.typewrite("Reminder: Drink water!") pyautogui.press("enter") time.sleep(31) print(datetime.datetime.now()) pyautogui.typewrite("Reminder: Drink water!") pyautogui.press("enter") time.sleep(31) Output: Date and time at which the message was sent Python-projects Python-PyAutoGUI Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Feb, 2021" }, { "code": null, "e": 224, "s": 52, "text": "PyAutoGUI is a Python module that helps us automate the key presses and mouse clicks programmatically. In this article we will learn to develop a spam bot using PyAutoGUI." }, { "code": null, "e": 321, "s": 224, "text": "Spamming – Refers to sending unsolicited messages to large number of systems over the internet. " }, { "code": null, "e": 389, "s": 321, "text": "This mini-project can be used for many real-life applications like:" }, { "code": null, "e": 483, "s": 389, "text": "Remind your friends or relatives to do a particular task after every particular time interval" }, { "code": null, "e": 521, "s": 483, "text": "Can be used for advertisement purpose" }, { "code": null, "e": 705, "s": 521, "text": "In this article we will show the working of spam bot on telegram, but the code can also work for WhatsApp, Instagram etc. i.e. anywhere we find a text field it will work the same way." }, { "code": null, "e": 714, "s": 705, "text": "Approach" }, { "code": null, "e": 728, "s": 714, "text": "Import module" }, { "code": null, "e": 782, "s": 728, "text": "Add delay of 2 second in the execution of the program" }, { "code": null, "e": 1106, "s": 782, "text": "Create mechanism to generate text messages. typewrite() function of pyautogui helps to write the text and sleep function helps us specify the particular time interval (in seconds) after which the next instruction has to be executed. datetime.datetime.now() function helps the user keep a track of when the message was sent." }, { "code": null, "e": 1114, "s": 1106, "text": "Syntax:" }, { "code": null, "e": 1138, "s": 1114, "text": "typewriter(“<message>”)" }, { "code": null, "e": 1151, "s": 1138, "text": "Execute code" }, { "code": null, "e": 1213, "s": 1151, "text": "Follow these simple steps to develop a spam bot using python:" }, { "code": null, "e": 1222, "s": 1213, "text": "Example:" }, { "code": null, "e": 1230, "s": 1222, "text": "Python3" }, { "code": "import pyautogui, time, datetime time.sleep(2) while True: # to display the time at which the message is sent print(datetime.datetime.now()) pyautogui.typewrite(\"Reminder: Drink water!\") pyautogui.press(\"enter\") time.sleep(31) print(datetime.datetime.now()) pyautogui.typewrite(\"Reminder: Take medicine!\") pyautogui.press(\"enter\") time.sleep(31) print(datetime.datetime.now()) pyautogui.typewrite(\"Reminder: Take the dog for a walk!\") pyautogui.press(\"enter\") time.sleep(31) print(datetime.datetime.now()) pyautogui.typewrite(\"Reminder: Drink water!\") pyautogui.press(\"enter\") time.sleep(31) print(datetime.datetime.now()) pyautogui.typewrite(\"Reminder: Drink water!\") pyautogui.press(\"enter\") time.sleep(31)", "e": 2026, "s": 1230, "text": null }, { "code": null, "e": 2036, "s": 2026, "text": "Output: " }, { "code": null, "e": 2081, "s": 2036, "text": "Date and time at which the message was sent " }, { "code": null, "e": 2097, "s": 2081, "text": "Python-projects" }, { "code": null, "e": 2114, "s": 2097, "text": "Python-PyAutoGUI" }, { "code": null, "e": 2121, "s": 2114, "text": "Python" }, { "code": null, "e": 2219, "s": 2121, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2251, "s": 2219, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2278, "s": 2251, "text": "Python Classes and Objects" }, { "code": null, "e": 2299, "s": 2278, "text": "Python OOPs Concepts" }, { "code": null, "e": 2322, "s": 2299, "text": "Introduction To PYTHON" }, { "code": null, "e": 2353, "s": 2322, "text": "Python | os.path.join() method" }, { "code": null, "e": 2409, "s": 2353, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2451, "s": 2409, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2493, "s": 2451, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2532, "s": 2493, "text": "Python | Get unique values from a list" } ]
ReactJS | Calculator App ( Adding Functionality )
20 Jan, 2022 In our previous article, we had built the structure of our UI, but we haven’t added styles to it neither we have added any functionality. You can see that if you click the buttons for now then nothing is getting typed on the screen. So, in this article, we will try to make our Calculator app fully functional. Once our app becomes functional, we will add CSS to style our App. So, let’s begin. The very first functionality we will add is for the click event of the buttons. To handle the click events, we will create a new function named handleClick and will add this function to our Calculator component class. But, the next thing to observe is that the buttons from “0-9” and operators like “+,-,*,/” will have different roles and other buttons like “=”,”Clear” and “Delete” have different roles. So, what we can do is inside the handleClick function we will use a switch..case statement to perform different operations on clicking different buttons. But before doing this, let us see what states do we need? We need to create two states for our Calculator application and we will update these two states according to the user inputs. The two states that we need are: question: Initially this state will be initialized with an empty string. This state will be used to store the user input. answer: Initially this state will be initialized with an empty string. This state will be used to store the result of the evaluation of user input stored in the state question. Add the below code at the top of the class Calculator in the file calculator.js. This code will create the required states for us: javascript constructor() { super(); // set our default state this.state = { question: '', answer: '' } // Bind our handleClick method (sets 'this' explicitly // to refer to this component) We did this because 'this' // would refer to the source of the click events this.handleClick = this.handleClick.bind(this); } Since now we have created our states to store the user input and answers. Let’s just complete our handleClick function to update these states according to different button clicks.Add the below function to the class Calculator in the calculator.js file: PHP // our method to handle all click events from our buttonshandleClick(event){ // get the value from the target element (button) const value = event.target.value; switch (value) { case '=': { // if it's an equal sign, use the eval module // to evaluate the question ,convert the answer // (in number) to String if (this.state.question!=='') { var ans=''; try { ans = eval(this.state.question); } catch(err) { this.setState({answer: "Math Error"}); } if (ans===undefined) this.setState({answer: "Math Error"}); // update answer in our state. else this.setState({ answer: ans , question: ''}); break; } } case 'Clear': { // if it's the Clears sign, just clean our // question and answer in the state this.setState({ question: '', answer: '' }); break; } case 'Delete': { var str = this.state.question; str = str.substr(0,str.length-1); this.setState({question: str}); break; } default: { // for every other command, update the answer in the state this.setState({ question: this.state.question += value}) break; } }} Now, we are completed with adding all functionalities but still, if we click the buttons of our Calculator app in the browser, nothing will happen. The reason behind this is we have not linked our handleClick function with the button’s onClick attribute in our Button component in the button.js file. To do so, we will pass the handleClick function as props to the Button component and assign this function to the button’s onClick event in Button component.We will add the below line everywhere in our Calculator component from where we are calling our Button Component to pass the handleClick function as props to the Button component: handleClick = {this.handleClick} After adding this, we will go to the button.js file, and add the below attribute to the input field: onClick = {props.handleClick} Now everything is set-up. Our states are getting updated on Click of our buttons. But wait, we still can’t see any change in our app in the browser. Let’s recall what went wrong. The problem is we have not passed the states to the OutputScreen component. So our OutputScreen component has nothing to render on screen. So, let’s update our OutputScreen and OutputScreenRow components to accept props and pass the question and answer states from Calculator component to the OutputScreen component as props.After doing this, pass the props from inside of OutputScreen component to OutputScreenRow components as values to display them in the input fields.Below is our final outputscreen.js file: javascript // Import React (Mandatory Step).import React from 'react'; // Import Output Screen Row.import OutputScreenRow from './outputScreenRow.js'; // Functional Component.// Use to hold two Screen Rows.const OutputScreen = (props) => { return ( <div className="screen"> <OutputScreenRow value = {props.question}/> <OutputScreenRow value = {props.answer}/> </div> )} // Export Output Screen.export default OutputScreen; Below is our final outputscreenrow.js file: javascript // Import React (Mandatory Step).import React from 'react'; // Functional Component.// Used to show Question/Answer.const OutputScreenRow = (props) => { return ( <div className="screen-row"> <input type="text" readOnly value = {props.value}/> </div> )} // Export Output Screen Row.export default OutputScreenRow; You can see in the below image that our Calculator App is working fine and has the same functionality as that of what we saw in our first article. In our next article, we will add styles to this and will try to sum up what we have done so far to build this App. ReactJS | Calculator App ( Styling ) ManasChhabra2 clintra react-js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jan, 2022" }, { "code": null, "e": 1225, "s": 52, "text": "In our previous article, we had built the structure of our UI, but we haven’t added styles to it neither we have added any functionality. You can see that if you click the buttons for now then nothing is getting typed on the screen. So, in this article, we will try to make our Calculator app fully functional. Once our app becomes functional, we will add CSS to style our App. So, let’s begin. The very first functionality we will add is for the click event of the buttons. To handle the click events, we will create a new function named handleClick and will add this function to our Calculator component class. But, the next thing to observe is that the buttons from “0-9” and operators like “+,-,*,/” will have different roles and other buttons like “=”,”Clear” and “Delete” have different roles. So, what we can do is inside the handleClick function we will use a switch..case statement to perform different operations on clicking different buttons. But before doing this, let us see what states do we need? We need to create two states for our Calculator application and we will update these two states according to the user inputs. The two states that we need are: " }, { "code": null, "e": 1347, "s": 1225, "text": "question: Initially this state will be initialized with an empty string. This state will be used to store the user input." }, { "code": null, "e": 1524, "s": 1347, "text": "answer: Initially this state will be initialized with an empty string. This state will be used to store the result of the evaluation of user input stored in the state question." }, { "code": null, "e": 1657, "s": 1524, "text": "Add the below code at the top of the class Calculator in the file calculator.js. This code will create the required states for us: " }, { "code": null, "e": 1668, "s": 1657, "text": "javascript" }, { "code": "constructor() { super(); // set our default state this.state = { question: '', answer: '' } // Bind our handleClick method (sets 'this' explicitly // to refer to this component) We did this because 'this' // would refer to the source of the click events this.handleClick = this.handleClick.bind(this); }", "e": 2009, "s": 1668, "text": null }, { "code": null, "e": 2264, "s": 2009, "text": "Since now we have created our states to store the user input and answers. Let’s just complete our handleClick function to update these states according to different button clicks.Add the below function to the class Calculator in the calculator.js file: " }, { "code": null, "e": 2268, "s": 2264, "text": "PHP" }, { "code": "// our method to handle all click events from our buttonshandleClick(event){ // get the value from the target element (button) const value = event.target.value; switch (value) { case '=': { // if it's an equal sign, use the eval module // to evaluate the question ,convert the answer // (in number) to String if (this.state.question!=='') { var ans=''; try { ans = eval(this.state.question); } catch(err) { this.setState({answer: \"Math Error\"}); } if (ans===undefined) this.setState({answer: \"Math Error\"}); // update answer in our state. else this.setState({ answer: ans , question: ''}); break; } } case 'Clear': { // if it's the Clears sign, just clean our // question and answer in the state this.setState({ question: '', answer: '' }); break; } case 'Delete': { var str = this.state.question; str = str.substr(0,str.length-1); this.setState({question: str}); break; } default: { // for every other command, update the answer in the state this.setState({ question: this.state.question += value}) break; } }}", "e": 3614, "s": 2268, "text": null }, { "code": null, "e": 4253, "s": 3614, "text": "Now, we are completed with adding all functionalities but still, if we click the buttons of our Calculator app in the browser, nothing will happen. The reason behind this is we have not linked our handleClick function with the button’s onClick attribute in our Button component in the button.js file. To do so, we will pass the handleClick function as props to the Button component and assign this function to the button’s onClick event in Button component.We will add the below line everywhere in our Calculator component from where we are calling our Button Component to pass the handleClick function as props to the Button component: " }, { "code": null, "e": 4286, "s": 4253, "text": "handleClick = {this.handleClick}" }, { "code": null, "e": 4389, "s": 4286, "text": "After adding this, we will go to the button.js file, and add the below attribute to the input field: " }, { "code": null, "e": 4419, "s": 4389, "text": "onClick = {props.handleClick}" }, { "code": null, "e": 5113, "s": 4419, "text": "Now everything is set-up. Our states are getting updated on Click of our buttons. But wait, we still can’t see any change in our app in the browser. Let’s recall what went wrong. The problem is we have not passed the states to the OutputScreen component. So our OutputScreen component has nothing to render on screen. So, let’s update our OutputScreen and OutputScreenRow components to accept props and pass the question and answer states from Calculator component to the OutputScreen component as props.After doing this, pass the props from inside of OutputScreen component to OutputScreenRow components as values to display them in the input fields.Below is our final outputscreen.js file: " }, { "code": null, "e": 5124, "s": 5113, "text": "javascript" }, { "code": "// Import React (Mandatory Step).import React from 'react'; // Import Output Screen Row.import OutputScreenRow from './outputScreenRow.js'; // Functional Component.// Use to hold two Screen Rows.const OutputScreen = (props) => { return ( <div className=\"screen\"> <OutputScreenRow value = {props.question}/> <OutputScreenRow value = {props.answer}/> </div> )} // Export Output Screen.export default OutputScreen;", "e": 5554, "s": 5124, "text": null }, { "code": null, "e": 5600, "s": 5554, "text": "Below is our final outputscreenrow.js file: " }, { "code": null, "e": 5611, "s": 5600, "text": "javascript" }, { "code": "// Import React (Mandatory Step).import React from 'react'; // Functional Component.// Used to show Question/Answer.const OutputScreenRow = (props) => { return ( <div className=\"screen-row\"> <input type=\"text\" readOnly value = {props.value}/> </div> )} // Export Output Screen Row.export default OutputScreenRow;", "e": 5937, "s": 5611, "text": null }, { "code": null, "e": 6200, "s": 5937, "text": "You can see in the below image that our Calculator App is working fine and has the same functionality as that of what we saw in our first article. In our next article, we will add styles to this and will try to sum up what we have done so far to build this App. " }, { "code": null, "e": 6238, "s": 6200, "text": "ReactJS | Calculator App ( Styling ) " }, { "code": null, "e": 6252, "s": 6238, "text": "ManasChhabra2" }, { "code": null, "e": 6260, "s": 6252, "text": "clintra" }, { "code": null, "e": 6269, "s": 6260, "text": "react-js" }, { "code": null, "e": 6286, "s": 6269, "text": "Web Technologies" } ]
ReactJS | Rendering Elements
14 Jan, 2021 In the previous article on introduction to JSX, we got to see how to create a React element. React element is the smallest renderable unit available in React. We can render such elements using the ReactDOM as described in the previous article. React elements are different from DOM elements as React elements are simple javascript objects and are efficient to create. React elements are the building blocks of any React app and should not be confused with React components which will be discussed in further articles.Rendering an Element in React: In order to render any element into the Browser DOM, we need to have a container or root DOM element. It is almost a convention to have a div element with the id=”root” or id=”app” to be used as the root DOM element. Let’s suppose our index.html file has the following statement inside it. <div id="root"></div> Filename App.js: Now, in order to render a simple React Element to the root node, we must write the following in the App.js file. javascript import React,{ Component } from 'react'; class App extends Component { render() { return ( <div> <h1>Welcome to GeeksforGeeks!</h1> </div> ); }} export default App; Output: Now, you have created your first ever React Element and also have rendered it in place, but React was not developed to create static pages, the intention of using React is to create a more logical and active webpage. In order to do so, we will need to update the elements. This next section will guide us through the same.Updating an Element in React: React Elements are immutable i.e. once an element is created it is impossible to update its children or attribute. Thus, in order to update an element, we must use the render() method several times to update the value over time. Let’s see this in an example. javascript import React from 'react';import ReactDOM from 'react-dom'; function showTime(){const myElement = ( <div> <h1>Welcome to GeeksforGeeks!</h1> <h2>{new Date().toLocaleTimeString()}</h2> </div> ); ReactDOM.render( myElement, document.getElementById("root")); } setInterval(showTime, 1000); Output: In the above example, we have created a function showTime() that displays the current time, and we have set an interval of 1000ms or 1 sec that recalls the function each second thus updating the time in each call. For simplicity, we have only shown the timespan of one second in the given image. React Render Efficiency: React is chosen over the legacy of DOM update because of its increased efficiency. React achieves this efficiency by using the virtual DOM and efficient differentiating algorithm. In the example of displaying the current time, at each second we call the render method, and the virtual DOM gets updated and then the differentiator checks for the particular differences in Browser DOM and the Virtual DOM and then updates only what is required such as in the given example the time is the only thing that is getting changed each time not the title “Welcome to GeeksforGeeks!” thus React only updates the time itself making it much more efficient than conventional DOM manipulation. Important Points to Note: Calling the render() method multiple times may serve our purpose for this example, but in general, it is never used instead a stateful component is used which we will cover in further articles. A React Element is almost never used isolated, we can use elements as the building blocks of creating a component in React. Components will also be discussed in upcoming articles. shubhamyadav4 react-js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jan, 2021" }, { "code": null, "e": 890, "s": 52, "text": "In the previous article on introduction to JSX, we got to see how to create a React element. React element is the smallest renderable unit available in React. We can render such elements using the ReactDOM as described in the previous article. React elements are different from DOM elements as React elements are simple javascript objects and are efficient to create. React elements are the building blocks of any React app and should not be confused with React components which will be discussed in further articles.Rendering an Element in React: In order to render any element into the Browser DOM, we need to have a container or root DOM element. It is almost a convention to have a div element with the id=”root” or id=”app” to be used as the root DOM element. Let’s suppose our index.html file has the following statement inside it." }, { "code": null, "e": 912, "s": 890, "text": "<div id=\"root\"></div>" }, { "code": null, "e": 1042, "s": 912, "text": "Filename App.js: Now, in order to render a simple React Element to the root node, we must write the following in the App.js file." }, { "code": null, "e": 1053, "s": 1042, "text": "javascript" }, { "code": "import React,{ Component } from 'react'; class App extends Component { render() { return ( <div> <h1>Welcome to GeeksforGeeks!</h1> </div> ); }} export default App;", "e": 1256, "s": 1053, "text": null }, { "code": null, "e": 1264, "s": 1256, "text": "Output:" }, { "code": null, "e": 1876, "s": 1264, "text": "Now, you have created your first ever React Element and also have rendered it in place, but React was not developed to create static pages, the intention of using React is to create a more logical and active webpage. In order to do so, we will need to update the elements. This next section will guide us through the same.Updating an Element in React: React Elements are immutable i.e. once an element is created it is impossible to update its children or attribute. Thus, in order to update an element, we must use the render() method several times to update the value over time. Let’s see this in an example. " }, { "code": null, "e": 1887, "s": 1876, "text": "javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom'; function showTime(){const myElement = ( <div> <h1>Welcome to GeeksforGeeks!</h1> <h2>{new Date().toLocaleTimeString()}</h2> </div> ); ReactDOM.render( myElement, document.getElementById(\"root\")); } setInterval(showTime, 1000);", "e": 2301, "s": 1887, "text": null }, { "code": null, "e": 2309, "s": 2301, "text": "Output:" }, { "code": null, "e": 2606, "s": 2309, "text": "In the above example, we have created a function showTime() that displays the current time, and we have set an interval of 1000ms or 1 sec that recalls the function each second thus updating the time in each call. For simplicity, we have only shown the timespan of one second in the given image. " }, { "code": null, "e": 3312, "s": 2606, "text": "React Render Efficiency: React is chosen over the legacy of DOM update because of its increased efficiency. React achieves this efficiency by using the virtual DOM and efficient differentiating algorithm. In the example of displaying the current time, at each second we call the render method, and the virtual DOM gets updated and then the differentiator checks for the particular differences in Browser DOM and the Virtual DOM and then updates only what is required such as in the given example the time is the only thing that is getting changed each time not the title “Welcome to GeeksforGeeks!” thus React only updates the time itself making it much more efficient than conventional DOM manipulation. " }, { "code": null, "e": 3338, "s": 3312, "text": "Important Points to Note:" }, { "code": null, "e": 3532, "s": 3338, "text": "Calling the render() method multiple times may serve our purpose for this example, but in general, it is never used instead a stateful component is used which we will cover in further articles." }, { "code": null, "e": 3712, "s": 3532, "text": "A React Element is almost never used isolated, we can use elements as the building blocks of creating a component in React. Components will also be discussed in upcoming articles." }, { "code": null, "e": 3726, "s": 3712, "text": "shubhamyadav4" }, { "code": null, "e": 3735, "s": 3726, "text": "react-js" }, { "code": null, "e": 3752, "s": 3735, "text": "Web Technologies" } ]
PHP sizeof() Function
02 Dec, 2021 In this article, we will see how to get the length of the array using the sizeof() function in PHP. The sizeof() function is a built-in function in PHP and is used to count the number of elements present in an array or any other countable object. Syntax: int sizeof(array, mode); Parameter: This function accepts 2 parameters which are described below: array: This parameter represents the array containing elements that we need to count. mode: This is an optional parameter and specifies the mode of the function. It can take two different values as shown below: 0: It is the default, does not count all elements of multidimensional arrays1: It Counts the array recursively (counts all the elements of multidimensional arrays) 0: It is the default, does not count all elements of multidimensional arrays 1: It Counts the array recursively (counts all the elements of multidimensional arrays) Return Value: This function returns an integer value as shown in the syntax which represents the number of elements present in the array. We will understand the concept of the sizeof() function through the examples. Example 1: This example illustrates the count of the number of elements in the one-dimensional array. PHP <?php // input array $a=array(1,2,3,4,5,6); // getting total number of elements // present in the array. $result = sizeof($a); print($result);?> Output: 6 Example: This example illustrates the counting the number of elements in the multi-dimensional array. PHP <?php $array = array('name' => array('Geeks', 'For', 'Geeks'), 'article' => array('sizeof', 'function', 'PHP')); // Recursive count echo sizeof($array, 1); // Normal count echo sizeof($array);?> Output: 8 2 Reference: http://php.net/manual/en/function.sizeof.php shubham_singh bhaskargeeksforgeeks PHP-array PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime Comparing two dates in PHP How to receive JSON POST with PHP ? How to get parameters from a URL string in PHP? 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": "\n02 Dec, 2021" }, { "code": null, "e": 275, "s": 28, "text": "In this article, we will see how to get the length of the array using the sizeof() function in PHP. The sizeof() function is a built-in function in PHP and is used to count the number of elements present in an array or any other countable object." }, { "code": null, "e": 283, "s": 275, "text": "Syntax:" }, { "code": null, "e": 308, "s": 283, "text": "int sizeof(array, mode);" }, { "code": null, "e": 381, "s": 308, "text": "Parameter: This function accepts 2 parameters which are described below:" }, { "code": null, "e": 467, "s": 381, "text": "array: This parameter represents the array containing elements that we need to count." }, { "code": null, "e": 756, "s": 467, "text": "mode: This is an optional parameter and specifies the mode of the function. It can take two different values as shown below: 0: It is the default, does not count all elements of multidimensional arrays1: It Counts the array recursively (counts all the elements of multidimensional arrays)" }, { "code": null, "e": 833, "s": 756, "text": "0: It is the default, does not count all elements of multidimensional arrays" }, { "code": null, "e": 921, "s": 833, "text": "1: It Counts the array recursively (counts all the elements of multidimensional arrays)" }, { "code": null, "e": 1059, "s": 921, "text": "Return Value: This function returns an integer value as shown in the syntax which represents the number of elements present in the array." }, { "code": null, "e": 1137, "s": 1059, "text": "We will understand the concept of the sizeof() function through the examples." }, { "code": null, "e": 1239, "s": 1137, "text": "Example 1: This example illustrates the count of the number of elements in the one-dimensional array." }, { "code": null, "e": 1243, "s": 1239, "text": "PHP" }, { "code": "<?php // input array $a=array(1,2,3,4,5,6); // getting total number of elements // present in the array. $result = sizeof($a); print($result);?>", "e": 1402, "s": 1243, "text": null }, { "code": null, "e": 1410, "s": 1402, "text": "Output:" }, { "code": null, "e": 1412, "s": 1410, "text": "6" }, { "code": null, "e": 1514, "s": 1412, "text": "Example: This example illustrates the counting the number of elements in the multi-dimensional array." }, { "code": null, "e": 1518, "s": 1514, "text": "PHP" }, { "code": "<?php $array = array('name' => array('Geeks', 'For', 'Geeks'), 'article' => array('sizeof', 'function', 'PHP')); // Recursive count echo sizeof($array, 1); // Normal count echo sizeof($array);?>", "e": 1735, "s": 1518, "text": null }, { "code": null, "e": 1743, "s": 1735, "text": "Output:" }, { "code": null, "e": 1747, "s": 1743, "text": "8\n2" }, { "code": null, "e": 1803, "s": 1747, "text": "Reference: http://php.net/manual/en/function.sizeof.php" }, { "code": null, "e": 1817, "s": 1803, "text": "shubham_singh" }, { "code": null, "e": 1838, "s": 1817, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 1848, "s": 1838, "text": "PHP-array" }, { "code": null, "e": 1861, "s": 1848, "text": "PHP-function" }, { "code": null, "e": 1865, "s": 1861, "text": "PHP" }, { "code": null, "e": 1882, "s": 1865, "text": "Web Technologies" }, { "code": null, "e": 1886, "s": 1882, "text": "PHP" }, { "code": null, "e": 1984, "s": 1886, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2024, "s": 1984, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2069, "s": 2024, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 2096, "s": 2069, "text": "Comparing two dates in PHP" }, { "code": null, "e": 2132, "s": 2096, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 2180, "s": 2132, "text": "How to get parameters from a URL string in PHP?" }, { "code": null, "e": 2213, "s": 2180, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2275, "s": 2213, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2336, "s": 2275, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2386, "s": 2336, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Find the longest path in a matrix with given constraints
28 Jun, 2022 Given a n*n matrix where all numbers are distinct, find the maximum length path (starting from any cell) such that all cells along the path are in increasing order with a difference of 1. We can move in 4 directions from a given cell (i, j), i.e., we can move to (i+1, j) or (i, j+1) or (i-1, j) or (i, j-1) with the condition that the adjacent cells have a difference of 1. Example: Input: mat[][] = {{1, 2, 9} {5, 3, 8} {4, 6, 7}} Output: 4 The longest path is 6-7-8-9. The idea is simple, we calculate longest path beginning with every cell. Once we have computed longest for all cells, we return maximum of all longest paths. One important observation in this approach is many overlapping sub-problems. Therefore this problem can be optimally solved using Dynamic Programming. Below is Dynamic Programming based implementation that uses a lookup table dp[][] to check if a problem is already solved or not. C++ Java Python3 Javascript C# // C++ program to find the longest path in a matrix// with given constraints#include <bits/stdc++.h>#define n 3using namespace std; // Returns length of the longest path beginning with// mat[i][j]. This function mainly uses lookup table// dp[n][n]int findLongestFromACell(int i, int j, int mat[n][n], int dp[n][n]){ if (i < 0 || i >= n || j < 0 || j >= n) return 0; // If this subproblem is already solved if (dp[i][j] != -1) return dp[i][j]; // To store the path lengths in all the four directions int x = INT_MIN, y = INT_MIN, z = INT_MIN, w = INT_MIN; // Since all numbers are unique and in range from 1 to // n*n, there is atmost one possible direction from any // cell if (j < n - 1 && ((mat[i][j] + 1) == mat[i][j + 1])) x = 1 + findLongestFromACell(i, j + 1, mat, dp); if (j > 0 && (mat[i][j] + 1 == mat[i][j - 1])) y = 1 + findLongestFromACell(i, j - 1, mat, dp); if (i > 0 && (mat[i][j] + 1 == mat[i - 1][j])) z = 1 + findLongestFromACell(i - 1, j, mat, dp); if (i < n - 1 && (mat[i][j] + 1 == mat[i + 1][j])) w = 1 + findLongestFromACell(i + 1, j, mat, dp); // If none of the adjacent fours is one greater we will // take 1 otherwise we will pick maximum from all the // four directions return dp[i][j] = max({x, y, z, w, 1});} // Returns length of the longest path beginning with any// cellint finLongestOverAll(int mat[n][n]){ int result = 1; // Initialize result // Create a lookup table and fill all entries in it as // -1 int dp[n][n]; memset(dp, -1, sizeof dp); // Compute longest path beginning from all cells for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (dp[i][j] == -1) findLongestFromACell(i, j, mat, dp); // Update result if needed result = max(result, dp[i][j]); } } return result;} // Driver programint main(){ int mat[n][n] = { { 1, 2, 9 }, { 5, 3, 8 }, { 4, 6, 7 } }; cout << "Length of the longest path is " << finLongestOverAll(mat); return 0;} // Java program to find the longest path in a matrix// with given constraints class GFG { public static int n = 3; // Function that returns length of the longest path // beginning with mat[i][j] // This function mainly uses lookup table dp[n][n] static int findLongestFromACell(int i, int j, int mat[][], int dp[][]) { // Base case if (i < 0 || i >= n || j < 0 || j >= n) return 0; // If this subproblem is already solved if (dp[i][j] != -1) return dp[i][j]; // To store the path lengths in all the four // directions int x = Integer.MIN_VALUE, y = Integer.MIN_VALUE, z = Integer.MIN_VALUE, w = Integer.MIN_VALUE; // Since all numbers are unique and in range from 1 // to n*n, there is atmost one possible direction // from any cell if (j < n - 1 && ((mat[i][j] + 1) == mat[i][j + 1])) x = dp[i][j] = 1 + findLongestFromACell(i, j + 1, mat, dp); if (j > 0 && (mat[i][j] + 1 == mat[i][j - 1])) y = dp[i][j] = 1 + findLongestFromACell(i, j - 1, mat, dp); if (i > 0 && (mat[i][j] + 1 == mat[i - 1][j])) z = dp[i][j] = 1 + findLongestFromACell(i - 1, j, mat, dp); if (i < n - 1 && (mat[i][j] + 1 == mat[i + 1][j])) w = dp[i][j] = 1 + findLongestFromACell(i + 1, j, mat, dp); // If none of the adjacent fours is one greater we // will take 1 otherwise we will pick maximum from // all the four directions return dp[i][j] = Math.max( x, Math.max(y, Math.max(z, Math.max(w, 1)))); } // Function that returns length of the longest path // beginning with any cell static int finLongestOverAll(int mat[][]) { // Initialize result int result = 1; // Create a lookup table and fill all entries in it // as -1 int[][] dp = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) dp[i][j] = -1; // Compute longest path beginning from all cells for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (dp[i][j] == -1) findLongestFromACell(i, j, mat, dp); // Update result if needed result = Math.max(result, dp[i][j]); } } return result; } // driver program public static void main(String[] args) { int mat[][] = { { 1, 2, 9 }, { 5, 3, 8 }, { 4, 6, 7 } }; System.out.println("Length of the longest path is " + finLongestOverAll(mat)); }} // Contributed by Pramod Kumar # Python3 program to find the longest path in a matrix# with given constraints n = 3# Returns length of the longest path beginning with mat[i][j].# This function mainly uses lookup table dp[n][n] def findLongestFromACell(i, j, mat, dp): # Base case if (i < 0 or i >= n or j < 0 or j >= n): return 0 # If this subproblem is already solved if (dp[i][j] != -1): return dp[i][j] # To store the path lengths in all the four directions x, y, z, w = -1, -1, -1, -1 # Since all numbers are unique and in range from 1 to n * n, # there is atmost one possible direction from any cell if (j < n-1 and ((mat[i][j] + 1) == mat[i][j + 1])): x = 1 + findLongestFromACell(i, j + 1, mat, dp) if (j > 0 and (mat[i][j] + 1 == mat[i][j-1])): y = 1 + findLongestFromACell(i, j-1, mat, dp) if (i > 0 and (mat[i][j] + 1 == mat[i-1][j])): z = 1 + findLongestFromACell(i-1, j, mat, dp) if (i < n-1 and (mat[i][j] + 1 == mat[i + 1][j])): w = 1 + findLongestFromACell(i + 1, j, mat, dp) # If none of the adjacent fours is one greater we will take 1 # otherwise we will pick maximum from all the four directions dp[i][j] = max(x, max(y, max(z, max(w, 1)))) return dp[i][j] # Returns length of the longest path beginning with any celldef finLongestOverAll(mat): result = 1 # Initialize result # Create a lookup table and fill all entries in it as -1 dp = [[-1 for i in range(n)]for i in range(n)] # Compute longest path beginning from all cells for i in range(n): for j in range(n): if (dp[i][j] == -1): findLongestFromACell(i, j, mat, dp) # Update result if needed result = max(result, dp[i][j]) return result # Driver programmat = [[1, 2, 9], [5, 3, 8], [4, 6, 7]]print("Length of the longest path is ", finLongestOverAll(mat)) # this code is improved by sahilshelangia <script>// JavaScript program to find the longest path in a matrix// with given constraintslet n = 3; // Returns length of the longest path beginning with mat[i][j].// This function mainly uses lookup table dp[n][n]function findLongestFromACell( i, j, mat, dp){ if (i < 0 || i >= n || j < 0 || j >= n) return 0; // If this subproblem is already solved if (dp[i][j] != -1) return dp[i][j]; // To store the path lengths in all the four directions let x,y,z,w; x = -1; y = -1; z = -1 w = -1; // Since all numbers are unique and in range from 1 to n*n, // there is atmost one possible direction from any cell if (j < n - 1 && ((mat[i][j] + 1) == mat[i][j + 1])) x = 1 + findLongestFromACell(i, j + 1, mat, dp); if (j > 0 && (mat[i][j] + 1 == mat[i][j - 1])) y = 1 + findLongestFromACell(i, j - 1, mat, dp); if (i > 0 && (mat[i][j] + 1 == mat[i - 1][j])) z = 1 + findLongestFromACell(i - 1, j, mat, dp); if (i < n - 1 && (mat[i][j] + 1 == mat[i + 1][j])) w = 1 + findLongestFromACell(i + 1, j, mat, dp); // If none of the adjacent fours is one greater we will take 1 // otherwise we will pick maximum from all the four directions dp[i][j] = Math.max(x, Math.max(y, Math.max(z, Math.max(w, 1)))); return dp[i][j];} // Returns length of the longest path beginning with any cellfunction finLongestOverAll( mat){ let result = 1; // Initialize result // Create a lookup table and fill all entries in it as -1 var dp = []; for( var y = 0; y < n; y++ ) { dp[ y ] = []; for( var x = 0; x < n; x++ ) { dp[ y ][ x ] = -1; }} // Compute longest path beginning from all cells for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { if (dp[i][j] == -1) findLongestFromACell(i, j, mat, dp); // Update result if needed result = Math.max(result, dp[i][j]); } } return result;} // Driver programlet mat = [[ 1, 2, 9 ], [ 5, 3, 8 ], [ 4, 6, 7 ]]; document.write("Length of the longest path is ");document.write( finLongestOverAll(mat)); </script> // C# program to find the longest path// in a matrix with given constraintsusing System; class GFG { public static int n = 3; // Function that returns length of // the longest path beginning with mat[i][j] // This function mainly uses lookup // table dp[n][n] public static int findLongestFromACell(int i, int j, int[][] mat, int[][] dp) { // Base case if (i < 0 || i >= n || j < 0 || j >= n) { return 0; } // If this subproblem is // already solved if (dp[i][j] != -1) { return dp[i][j]; } // To store the path lengths in all the four // directions int x = int.MinValue, y = int.MinValue, z = int.MinValue, w = int.MinValue; // Since all numbers are unique and // in range from 1 to n*n, there is // atmost one possible direction // from any cell if (j < n - 1 && ((mat[i][j] + 1) == mat[i][j + 1])) { x = dp[i][j] = 1 + findLongestFromACell(i, j + 1, mat, dp); } if (j > 0 && (mat[i][j] + 1 == mat[i][j - 1])) { y = dp[i][j] = 1 + findLongestFromACell(i, j - 1, mat, dp); } if (i > 0 && (mat[i][j] + 1 == mat[i - 1][j])) { z = dp[i][j] = 1 + findLongestFromACell(i - 1, j, mat, dp); } if (i < n - 1 && (mat[i][j] + 1 == mat[i + 1][j])) { w = dp[i][j] = 1 + findLongestFromACell(i + 1, j, mat, dp); } // If none of the adjacent fours is one greater we // will take 1 otherwise we will pick maximum from // all the four directions dp[i][j] = Math.Max( x, Math.Max(y, Math.Max(z, Math.Max(w, 1)))); return dp[i][j]; } // Function that returns length of the // longest path beginning with any cell public static int finLongestOverAll(int[][] mat) { // Initialize result int result = 1; // Create a lookup table and fill // all entries in it as -1 int[][] dp = RectangularArrays.ReturnRectangularIntArray( n, n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dp[i][j] = -1; } } // Compute longest path beginning // from all cells for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (dp[i][j] == -1) { findLongestFromACell(i, j, mat, dp); } // Update result if needed result = Math.Max(result, dp[i][j]); } } return result; } public static class RectangularArrays { public static int[][] ReturnRectangularIntArray( int size1, int size2) { int[][] newArray = new int[size1][]; for (int array1 = 0; array1 < size1; array1++) { newArray[array1] = new int[size2]; } return newArray; } } // Driver Code public static void Main(string[] args) { int[][] mat = new int[][] { new int[] { 1, 2, 9 }, new int[] { 5, 3, 8 }, new int[] { 4, 6, 7 } }; Console.WriteLine("Length of the longest path is " + finLongestOverAll(mat)); }} // This code is contributed by Shrikant13 Length of the longest path is 4 Time complexity of the above solution is O(n2). It may seem more at first look. If we take a closer look, we can notice that all values of dp[i][j] are computed only once.Auxiliary Space: O(N x N), This article is contributed by Aarti_Rathi and Ekta Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sahilshelangia shrikanth13 MOHNEESHGARG gp6 Jaspreet Singh rohitsingh07052 atharvakango sksusha8853 codewithshinchan hardikkoriintern Amazon Samsung Dynamic Programming Matrix Amazon Samsung Dynamic Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Largest Sum Contiguous Subarray Program for Fibonacci numbers Longest Palindromic Substring | Set 1 Longest Increasing Subsequence | DP-3 Find if there is a path between two vertices in an undirected graph Print a given matrix in spiral form Program to find largest element in an array Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7 Find the number of islands | Set 1 (Using DFS)
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2022" }, { "code": null, "e": 429, "s": 54, "text": "Given a n*n matrix where all numbers are distinct, find the maximum length path (starting from any cell) such that all cells along the path are in increasing order with a difference of 1. We can move in 4 directions from a given cell (i, j), i.e., we can move to (i+1, j) or (i, j+1) or (i-1, j) or (i, j-1) with the condition that the adjacent cells have a difference of 1." }, { "code": null, "e": 439, "s": 429, "text": "Example: " }, { "code": null, "e": 567, "s": 439, "text": "Input: mat[][] = {{1, 2, 9}\n {5, 3, 8}\n {4, 6, 7}}\nOutput: 4\nThe longest path is 6-7-8-9. " }, { "code": null, "e": 877, "s": 567, "text": "The idea is simple, we calculate longest path beginning with every cell. Once we have computed longest for all cells, we return maximum of all longest paths. One important observation in this approach is many overlapping sub-problems. Therefore this problem can be optimally solved using Dynamic Programming. " }, { "code": null, "e": 1007, "s": 877, "text": "Below is Dynamic Programming based implementation that uses a lookup table dp[][] to check if a problem is already solved or not." }, { "code": null, "e": 1011, "s": 1007, "text": "C++" }, { "code": null, "e": 1016, "s": 1011, "text": "Java" }, { "code": null, "e": 1024, "s": 1016, "text": "Python3" }, { "code": null, "e": 1035, "s": 1024, "text": "Javascript" }, { "code": null, "e": 1038, "s": 1035, "text": "C#" }, { "code": "// C++ program to find the longest path in a matrix// with given constraints#include <bits/stdc++.h>#define n 3using namespace std; // Returns length of the longest path beginning with// mat[i][j]. This function mainly uses lookup table// dp[n][n]int findLongestFromACell(int i, int j, int mat[n][n], int dp[n][n]){ if (i < 0 || i >= n || j < 0 || j >= n) return 0; // If this subproblem is already solved if (dp[i][j] != -1) return dp[i][j]; // To store the path lengths in all the four directions int x = INT_MIN, y = INT_MIN, z = INT_MIN, w = INT_MIN; // Since all numbers are unique and in range from 1 to // n*n, there is atmost one possible direction from any // cell if (j < n - 1 && ((mat[i][j] + 1) == mat[i][j + 1])) x = 1 + findLongestFromACell(i, j + 1, mat, dp); if (j > 0 && (mat[i][j] + 1 == mat[i][j - 1])) y = 1 + findLongestFromACell(i, j - 1, mat, dp); if (i > 0 && (mat[i][j] + 1 == mat[i - 1][j])) z = 1 + findLongestFromACell(i - 1, j, mat, dp); if (i < n - 1 && (mat[i][j] + 1 == mat[i + 1][j])) w = 1 + findLongestFromACell(i + 1, j, mat, dp); // If none of the adjacent fours is one greater we will // take 1 otherwise we will pick maximum from all the // four directions return dp[i][j] = max({x, y, z, w, 1});} // Returns length of the longest path beginning with any// cellint finLongestOverAll(int mat[n][n]){ int result = 1; // Initialize result // Create a lookup table and fill all entries in it as // -1 int dp[n][n]; memset(dp, -1, sizeof dp); // Compute longest path beginning from all cells for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (dp[i][j] == -1) findLongestFromACell(i, j, mat, dp); // Update result if needed result = max(result, dp[i][j]); } } return result;} // Driver programint main(){ int mat[n][n] = { { 1, 2, 9 }, { 5, 3, 8 }, { 4, 6, 7 } }; cout << \"Length of the longest path is \" << finLongestOverAll(mat); return 0;}", "e": 3166, "s": 1038, "text": null }, { "code": "// Java program to find the longest path in a matrix// with given constraints class GFG { public static int n = 3; // Function that returns length of the longest path // beginning with mat[i][j] // This function mainly uses lookup table dp[n][n] static int findLongestFromACell(int i, int j, int mat[][], int dp[][]) { // Base case if (i < 0 || i >= n || j < 0 || j >= n) return 0; // If this subproblem is already solved if (dp[i][j] != -1) return dp[i][j]; // To store the path lengths in all the four // directions int x = Integer.MIN_VALUE, y = Integer.MIN_VALUE, z = Integer.MIN_VALUE, w = Integer.MIN_VALUE; // Since all numbers are unique and in range from 1 // to n*n, there is atmost one possible direction // from any cell if (j < n - 1 && ((mat[i][j] + 1) == mat[i][j + 1])) x = dp[i][j] = 1 + findLongestFromACell(i, j + 1, mat, dp); if (j > 0 && (mat[i][j] + 1 == mat[i][j - 1])) y = dp[i][j] = 1 + findLongestFromACell(i, j - 1, mat, dp); if (i > 0 && (mat[i][j] + 1 == mat[i - 1][j])) z = dp[i][j] = 1 + findLongestFromACell(i - 1, j, mat, dp); if (i < n - 1 && (mat[i][j] + 1 == mat[i + 1][j])) w = dp[i][j] = 1 + findLongestFromACell(i + 1, j, mat, dp); // If none of the adjacent fours is one greater we // will take 1 otherwise we will pick maximum from // all the four directions return dp[i][j] = Math.max( x, Math.max(y, Math.max(z, Math.max(w, 1)))); } // Function that returns length of the longest path // beginning with any cell static int finLongestOverAll(int mat[][]) { // Initialize result int result = 1; // Create a lookup table and fill all entries in it // as -1 int[][] dp = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) dp[i][j] = -1; // Compute longest path beginning from all cells for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (dp[i][j] == -1) findLongestFromACell(i, j, mat, dp); // Update result if needed result = Math.max(result, dp[i][j]); } } return result; } // driver program public static void main(String[] args) { int mat[][] = { { 1, 2, 9 }, { 5, 3, 8 }, { 4, 6, 7 } }; System.out.println(\"Length of the longest path is \" + finLongestOverAll(mat)); }} // Contributed by Pramod Kumar", "e": 6043, "s": 3166, "text": null }, { "code": "# Python3 program to find the longest path in a matrix# with given constraints n = 3# Returns length of the longest path beginning with mat[i][j].# This function mainly uses lookup table dp[n][n] def findLongestFromACell(i, j, mat, dp): # Base case if (i < 0 or i >= n or j < 0 or j >= n): return 0 # If this subproblem is already solved if (dp[i][j] != -1): return dp[i][j] # To store the path lengths in all the four directions x, y, z, w = -1, -1, -1, -1 # Since all numbers are unique and in range from 1 to n * n, # there is atmost one possible direction from any cell if (j < n-1 and ((mat[i][j] + 1) == mat[i][j + 1])): x = 1 + findLongestFromACell(i, j + 1, mat, dp) if (j > 0 and (mat[i][j] + 1 == mat[i][j-1])): y = 1 + findLongestFromACell(i, j-1, mat, dp) if (i > 0 and (mat[i][j] + 1 == mat[i-1][j])): z = 1 + findLongestFromACell(i-1, j, mat, dp) if (i < n-1 and (mat[i][j] + 1 == mat[i + 1][j])): w = 1 + findLongestFromACell(i + 1, j, mat, dp) # If none of the adjacent fours is one greater we will take 1 # otherwise we will pick maximum from all the four directions dp[i][j] = max(x, max(y, max(z, max(w, 1)))) return dp[i][j] # Returns length of the longest path beginning with any celldef finLongestOverAll(mat): result = 1 # Initialize result # Create a lookup table and fill all entries in it as -1 dp = [[-1 for i in range(n)]for i in range(n)] # Compute longest path beginning from all cells for i in range(n): for j in range(n): if (dp[i][j] == -1): findLongestFromACell(i, j, mat, dp) # Update result if needed result = max(result, dp[i][j]) return result # Driver programmat = [[1, 2, 9], [5, 3, 8], [4, 6, 7]]print(\"Length of the longest path is \", finLongestOverAll(mat)) # this code is improved by sahilshelangia", "e": 7974, "s": 6043, "text": null }, { "code": "<script>// JavaScript program to find the longest path in a matrix// with given constraintslet n = 3; // Returns length of the longest path beginning with mat[i][j].// This function mainly uses lookup table dp[n][n]function findLongestFromACell( i, j, mat, dp){ if (i < 0 || i >= n || j < 0 || j >= n) return 0; // If this subproblem is already solved if (dp[i][j] != -1) return dp[i][j]; // To store the path lengths in all the four directions let x,y,z,w; x = -1; y = -1; z = -1 w = -1; // Since all numbers are unique and in range from 1 to n*n, // there is atmost one possible direction from any cell if (j < n - 1 && ((mat[i][j] + 1) == mat[i][j + 1])) x = 1 + findLongestFromACell(i, j + 1, mat, dp); if (j > 0 && (mat[i][j] + 1 == mat[i][j - 1])) y = 1 + findLongestFromACell(i, j - 1, mat, dp); if (i > 0 && (mat[i][j] + 1 == mat[i - 1][j])) z = 1 + findLongestFromACell(i - 1, j, mat, dp); if (i < n - 1 && (mat[i][j] + 1 == mat[i + 1][j])) w = 1 + findLongestFromACell(i + 1, j, mat, dp); // If none of the adjacent fours is one greater we will take 1 // otherwise we will pick maximum from all the four directions dp[i][j] = Math.max(x, Math.max(y, Math.max(z, Math.max(w, 1)))); return dp[i][j];} // Returns length of the longest path beginning with any cellfunction finLongestOverAll( mat){ let result = 1; // Initialize result // Create a lookup table and fill all entries in it as -1 var dp = []; for( var y = 0; y < n; y++ ) { dp[ y ] = []; for( var x = 0; x < n; x++ ) { dp[ y ][ x ] = -1; }} // Compute longest path beginning from all cells for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { if (dp[i][j] == -1) findLongestFromACell(i, j, mat, dp); // Update result if needed result = Math.max(result, dp[i][j]); } } return result;} // Driver programlet mat = [[ 1, 2, 9 ], [ 5, 3, 8 ], [ 4, 6, 7 ]]; document.write(\"Length of the longest path is \");document.write( finLongestOverAll(mat)); </script>", "e": 10143, "s": 7974, "text": null }, { "code": "// C# program to find the longest path// in a matrix with given constraintsusing System; class GFG { public static int n = 3; // Function that returns length of // the longest path beginning with mat[i][j] // This function mainly uses lookup // table dp[n][n] public static int findLongestFromACell(int i, int j, int[][] mat, int[][] dp) { // Base case if (i < 0 || i >= n || j < 0 || j >= n) { return 0; } // If this subproblem is // already solved if (dp[i][j] != -1) { return dp[i][j]; } // To store the path lengths in all the four // directions int x = int.MinValue, y = int.MinValue, z = int.MinValue, w = int.MinValue; // Since all numbers are unique and // in range from 1 to n*n, there is // atmost one possible direction // from any cell if (j < n - 1 && ((mat[i][j] + 1) == mat[i][j + 1])) { x = dp[i][j] = 1 + findLongestFromACell(i, j + 1, mat, dp); } if (j > 0 && (mat[i][j] + 1 == mat[i][j - 1])) { y = dp[i][j] = 1 + findLongestFromACell(i, j - 1, mat, dp); } if (i > 0 && (mat[i][j] + 1 == mat[i - 1][j])) { z = dp[i][j] = 1 + findLongestFromACell(i - 1, j, mat, dp); } if (i < n - 1 && (mat[i][j] + 1 == mat[i + 1][j])) { w = dp[i][j] = 1 + findLongestFromACell(i + 1, j, mat, dp); } // If none of the adjacent fours is one greater we // will take 1 otherwise we will pick maximum from // all the four directions dp[i][j] = Math.Max( x, Math.Max(y, Math.Max(z, Math.Max(w, 1)))); return dp[i][j]; } // Function that returns length of the // longest path beginning with any cell public static int finLongestOverAll(int[][] mat) { // Initialize result int result = 1; // Create a lookup table and fill // all entries in it as -1 int[][] dp = RectangularArrays.ReturnRectangularIntArray( n, n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dp[i][j] = -1; } } // Compute longest path beginning // from all cells for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (dp[i][j] == -1) { findLongestFromACell(i, j, mat, dp); } // Update result if needed result = Math.Max(result, dp[i][j]); } } return result; } public static class RectangularArrays { public static int[][] ReturnRectangularIntArray( int size1, int size2) { int[][] newArray = new int[size1][]; for (int array1 = 0; array1 < size1; array1++) { newArray[array1] = new int[size2]; } return newArray; } } // Driver Code public static void Main(string[] args) { int[][] mat = new int[][] { new int[] { 1, 2, 9 }, new int[] { 5, 3, 8 }, new int[] { 4, 6, 7 } }; Console.WriteLine(\"Length of the longest path is \" + finLongestOverAll(mat)); }} // This code is contributed by Shrikant13", "e": 13746, "s": 10143, "text": null }, { "code": null, "e": 13778, "s": 13746, "text": "Length of the longest path is 4" }, { "code": null, "e": 13976, "s": 13778, "text": "Time complexity of the above solution is O(n2). It may seem more at first look. If we take a closer look, we can notice that all values of dp[i][j] are computed only once.Auxiliary Space: O(N x N)," }, { "code": null, "e": 14159, "s": 13976, "text": "This article is contributed by Aarti_Rathi and Ekta Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 14174, "s": 14159, "text": "sahilshelangia" }, { "code": null, "e": 14186, "s": 14174, "text": "shrikanth13" }, { "code": null, "e": 14199, "s": 14186, "text": "MOHNEESHGARG" }, { "code": null, "e": 14203, "s": 14199, "text": "gp6" }, { "code": null, "e": 14218, "s": 14203, "text": "Jaspreet Singh" }, { "code": null, "e": 14234, "s": 14218, "text": "rohitsingh07052" }, { "code": null, "e": 14247, "s": 14234, "text": "atharvakango" }, { "code": null, "e": 14259, "s": 14247, "text": "sksusha8853" }, { "code": null, "e": 14276, "s": 14259, "text": "codewithshinchan" }, { "code": null, "e": 14293, "s": 14276, "text": "hardikkoriintern" }, { "code": null, "e": 14300, "s": 14293, "text": "Amazon" }, { "code": null, "e": 14308, "s": 14300, "text": "Samsung" }, { "code": null, "e": 14328, "s": 14308, "text": "Dynamic Programming" }, { "code": null, "e": 14335, "s": 14328, "text": "Matrix" }, { "code": null, "e": 14342, "s": 14335, "text": "Amazon" }, { "code": null, "e": 14350, "s": 14342, "text": "Samsung" }, { "code": null, "e": 14370, "s": 14350, "text": "Dynamic Programming" }, { "code": null, "e": 14377, "s": 14370, "text": "Matrix" }, { "code": null, "e": 14475, "s": 14377, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14507, "s": 14475, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 14537, "s": 14507, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 14575, "s": 14537, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 14613, "s": 14575, "text": "Longest Increasing Subsequence | DP-3" }, { "code": null, "e": 14681, "s": 14613, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 14717, "s": 14681, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 14761, "s": 14717, "text": "Program to find largest element in an array" }, { "code": null, "e": 14792, "s": 14761, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 14816, "s": 14792, "text": "Sudoku | Backtracking-7" } ]
Comparison of Inheritance in C++ and Java
22 Nov, 2021 The purpose of inheritance is the same in C++ and Java. Inheritance is used in both languages for reusing code and/or creating an ‘is-a’ relationship. The following examples will demonstrate the differences between Java and C++ that provide support for inheritance. 1) In Java, all classes inherit from the Object class directly or indirectly. Therefore, there is always a single inheritance tree of classes in Java, and the Object Class is the root of the tree. In Java, when creating a class it automatically inherits from the Object Class. In C++ however, there is a forest of classes; when we create a class that doesn’t inherit from another, we create a new tree in a forest. Following the Java example shows that the Test class automatically inherits from the Object class. Java class Test { // members of test}class Main { public static void main(String[] args) { Test t = new Test(); System.out.println("t is instanceof Object: " + (t instanceof Object)); }} t is instanceof Object: true 2) In Java, members of the grandparent class are not directly accessible. (Refer to this article for more details). 3) The meaning of protected member access specifier is somewhat different in Java. In Java, protected members of a class “A” are accessible in other class “B” of the same package, even if B doesn’t inherit from A (they both have to be in the same package). For example, in the following program, protected members of A are accessible in B. Java class A { protected int x = 10, y = 20;} class B { public static void main(String args[]) { A a = new A(); System.out.println(a.x + " " + a.y); }} 10 20 4) Java uses ‘extends’ keywords for inheritance. Unlike C++, Java doesn’t provide an inheritance specifier like public, protected, or private. Therefore, we cannot change the protection level of members of the base class in Java, if some data member is public or protected in the base class then it remains public or protected in the derived class. Like C++, private members of a base class are not accessible in a derived class. Unlike C++, in Java, we don’t have to remember those rules of inheritance which are a combination of base class access specifier and inheritance specifier. 5) In Java, methods are virtual by default. In C++, we explicitly use virtual keywords (Refer to this article for more details). 6) Java uses a separate keyword interface for interfaces and abstract keywords for abstract classes and abstract functions. Following is a Java abstract class example, Java // An abstract class exampleabstract class myAbstractClass { // An abstract method abstract void myAbstractFun(); // A normal method void fun() { System.out.println("Inside My fun"); }} public class myClass extends myAbstractClass { public void myAbstractFun() { System.out.println("Inside My fun"); }} Following is a Java interface example, Java // An interface examplepublic interface myInterface { // myAbstractFun() is public // and abstract, even if we // don't use these keywords void myAbstractFun(); // is same as public abstract void myAbstractFun()} // Note the implements keyword also.public class myClass implements myInterface { public void myAbstractFun() { System.out.println("Inside My fun"); }} 7) Unlike C++, Java doesn’t support multiple inheritances. A class cannot inherit from more than one class. However, A class can implement multiple interfaces. 8) In C++, the default constructor of the parent class is automatically called, but if we want to call a parameterized constructor of a parent class, we must use the Initializer list. Like C++, the default constructor of the parent class is automatically called in Java, but if we want to call parameterized constructor then we must use super to call the parent constructor. See the following Java example. Java package main; class Base { private int b; Base(int x) { b = x; System.out.println("Base constructor called"); }} class Derived extends Base { private int d; Derived(int x, int y) { // Calling parent class parameterized constructor // Call to parent constructor must be the first line // in a Derived class super(x); d = y; System.out.println("Derived constructor called"); }} class Main { public static void main(String[] args) { Derived obj = new Derived(1, 2); }} Output Base constructor called Derived constructor called Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. BacchusJax anikaseth98 23603vaibhav2021 anshikajain26 cpp-inheritance java-inheritance Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java How to iterate any Map in Java Stream In Java Singleton Class in Java Initialize an ArrayList in Java Initializing a List in Java Generics in Java Java Programming Examples
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Nov, 2021" }, { "code": null, "e": 319, "s": 52, "text": "The purpose of inheritance is the same in C++ and Java. Inheritance is used in both languages for reusing code and/or creating an ‘is-a’ relationship. The following examples will demonstrate the differences between Java and C++ that provide support for inheritance. " }, { "code": null, "e": 735, "s": 319, "text": "1) In Java, all classes inherit from the Object class directly or indirectly. Therefore, there is always a single inheritance tree of classes in Java, and the Object Class is the root of the tree. In Java, when creating a class it automatically inherits from the Object Class. In C++ however, there is a forest of classes; when we create a class that doesn’t inherit from another, we create a new tree in a forest. " }, { "code": null, "e": 835, "s": 735, "text": "Following the Java example shows that the Test class automatically inherits from the Object class. " }, { "code": null, "e": 840, "s": 835, "text": "Java" }, { "code": "class Test { // members of test}class Main { public static void main(String[] args) { Test t = new Test(); System.out.println(\"t is instanceof Object: \" + (t instanceof Object)); }}", "e": 1074, "s": 840, "text": null }, { "code": null, "e": 1103, "s": 1074, "text": "t is instanceof Object: true" }, { "code": null, "e": 1221, "s": 1103, "text": "2) In Java, members of the grandparent class are not directly accessible. (Refer to this article for more details). " }, { "code": null, "e": 1478, "s": 1221, "text": "3) The meaning of protected member access specifier is somewhat different in Java. In Java, protected members of a class “A” are accessible in other class “B” of the same package, even if B doesn’t inherit from A (they both have to be in the same package)." }, { "code": null, "e": 1562, "s": 1478, "text": "For example, in the following program, protected members of A are accessible in B. " }, { "code": null, "e": 1567, "s": 1562, "text": "Java" }, { "code": "class A { protected int x = 10, y = 20;} class B { public static void main(String args[]) { A a = new A(); System.out.println(a.x + \" \" + a.y); }}", "e": 1740, "s": 1567, "text": null }, { "code": null, "e": 1746, "s": 1740, "text": "10 20" }, { "code": null, "e": 2177, "s": 1746, "text": "4) Java uses ‘extends’ keywords for inheritance. Unlike C++, Java doesn’t provide an inheritance specifier like public, protected, or private. Therefore, we cannot change the protection level of members of the base class in Java, if some data member is public or protected in the base class then it remains public or protected in the derived class. Like C++, private members of a base class are not accessible in a derived class. " }, { "code": null, "e": 2334, "s": 2177, "text": "Unlike C++, in Java, we don’t have to remember those rules of inheritance which are a combination of base class access specifier and inheritance specifier. " }, { "code": null, "e": 2463, "s": 2334, "text": "5) In Java, methods are virtual by default. In C++, we explicitly use virtual keywords (Refer to this article for more details)." }, { "code": null, "e": 2587, "s": 2463, "text": "6) Java uses a separate keyword interface for interfaces and abstract keywords for abstract classes and abstract functions." }, { "code": null, "e": 2631, "s": 2587, "text": "Following is a Java abstract class example," }, { "code": null, "e": 2636, "s": 2631, "text": "Java" }, { "code": "// An abstract class exampleabstract class myAbstractClass { // An abstract method abstract void myAbstractFun(); // A normal method void fun() { System.out.println(\"Inside My fun\"); }} public class myClass extends myAbstractClass { public void myAbstractFun() { System.out.println(\"Inside My fun\"); }}", "e": 2969, "s": 2636, "text": null }, { "code": null, "e": 3010, "s": 2969, "text": "Following is a Java interface example, " }, { "code": null, "e": 3015, "s": 3010, "text": "Java" }, { "code": "// An interface examplepublic interface myInterface { // myAbstractFun() is public // and abstract, even if we // don't use these keywords void myAbstractFun(); // is same as public abstract void myAbstractFun()} // Note the implements keyword also.public class myClass implements myInterface { public void myAbstractFun() { System.out.println(\"Inside My fun\"); }}", "e": 3415, "s": 3015, "text": null }, { "code": null, "e": 3575, "s": 3415, "text": "7) Unlike C++, Java doesn’t support multiple inheritances. A class cannot inherit from more than one class. However, A class can implement multiple interfaces." }, { "code": null, "e": 3982, "s": 3575, "text": "8) In C++, the default constructor of the parent class is automatically called, but if we want to call a parameterized constructor of a parent class, we must use the Initializer list. Like C++, the default constructor of the parent class is automatically called in Java, but if we want to call parameterized constructor then we must use super to call the parent constructor. See the following Java example." }, { "code": null, "e": 3987, "s": 3982, "text": "Java" }, { "code": "package main; class Base { private int b; Base(int x) { b = x; System.out.println(\"Base constructor called\"); }} class Derived extends Base { private int d; Derived(int x, int y) { // Calling parent class parameterized constructor // Call to parent constructor must be the first line // in a Derived class super(x); d = y; System.out.println(\"Derived constructor called\"); }} class Main { public static void main(String[] args) { Derived obj = new Derived(1, 2); }}", "e": 4549, "s": 3987, "text": null }, { "code": null, "e": 4556, "s": 4549, "text": "Output" }, { "code": null, "e": 4607, "s": 4556, "text": "Base constructor called\nDerived constructor called" }, { "code": null, "e": 4732, "s": 4607, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4743, "s": 4732, "text": "BacchusJax" }, { "code": null, "e": 4755, "s": 4743, "text": "anikaseth98" }, { "code": null, "e": 4772, "s": 4755, "text": "23603vaibhav2021" }, { "code": null, "e": 4786, "s": 4772, "text": "anshikajain26" }, { "code": null, "e": 4802, "s": 4786, "text": "cpp-inheritance" }, { "code": null, "e": 4819, "s": 4802, "text": "java-inheritance" }, { "code": null, "e": 4824, "s": 4819, "text": "Java" }, { "code": null, "e": 4829, "s": 4824, "text": "Java" }, { "code": null, "e": 4927, "s": 4829, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4971, "s": 4927, "text": "Split() String method in Java with examples" }, { "code": null, "e": 5007, "s": 4971, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 5032, "s": 5007, "text": "Reverse a string in Java" }, { "code": null, "e": 5063, "s": 5032, "text": "How to iterate any Map in Java" }, { "code": null, "e": 5078, "s": 5063, "text": "Stream In Java" }, { "code": null, "e": 5102, "s": 5078, "text": "Singleton Class in Java" }, { "code": null, "e": 5134, "s": 5102, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 5162, "s": 5134, "text": "Initializing a List in Java" }, { "code": null, "e": 5179, "s": 5162, "text": "Generics in Java" } ]
Coin Change | BFS Approach
31 May, 2022 Given an integer X and an array arr[] of length N consisting of positive integers, the task is to pick minimum number of integers from the array such that they sum up to N. Any number can be chosen infinite number of times. If no answer exists then print -1.Examples: Input: X = 7, arr[] = {3, 5, 4} Output: 2 The minimum number elements will be 2 as 3 and 4 can be selected to reach 7. Input: X = 4, arr[] = {5} Output: -1 Approach: We have already seen how to solve this problem using dynamic-programming approach in this article.Here, we will see a slightly different approach to solve this problem using BFS. Before that, let’s go ahead and define a state. A state SX can be defined as the minimum number of integers we would need to take from array to get a total of X.Now, if we start looking at each state as a node in a graph such that each node is connected to (SX – arr[0], SX – arr[1], ... SX – arr[N – 1]). Thus, we have to find the shortest path from state N to 0 in an unweighted and this can be done using BFS. BFS works here because the graph is unweighted.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 find the minimum number// of integers requiredint minNumbers(int x, int* arr, int n){ // Queue for BFS queue<int> q; // Base value in queue q.push(x); // Boolean array to check if a number has been // visited before unordered_set<int> v; // Variable to store depth of BFS int d = 0; // BFS algorithm while (q.size()) { // Size of queue int s = q.size(); while (s--) { // Front most element of the queue int c = q.front(); // Base case if (!c) return d; q.pop(); if (v.find(c) != v.end() or c < 0) continue; // Setting current state as visited v.insert(c); // Pushing the required states in queue for (int i = 0; i < n; i++) q.push(c - arr[i]); } d++; } // If no possible solution return -1;} // Driver codeint main(){ int arr[] = { 3, 3, 4 }; int n = sizeof(arr) / sizeof(int); int x = 7; cout << minNumbers(x, arr, n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function to find the minimum number// of integers requiredstatic int minNumbers(int x, int []arr, int n){ // Queue for BFS Queue<Integer> q = new LinkedList<>(); // Base value in queue q.add(x); // Boolean array to check if // a number has been visited before HashSet<Integer> v = new HashSet<Integer>(); // Variable to store depth of BFS int d = 0; // BFS algorithm while (q.size() > 0) { // Size of queue int s = q.size(); while (s-- > 0) { // Front most element of the queue int c = q.peek(); // Base case if (c == 0) return d; q.remove(); if (v.contains(c) || c < 0) continue; // Setting current state as visited v.add(c); // Pushing the required states in queue for (int i = 0; i < n; i++) q.add(c - arr[i]); } d++; } // If no possible solution return -1;} // Driver codepublic static void main(String[] args){ int arr[] = { 3, 3, 4 }; int n = arr.length; int x = 7; System.out.println(minNumbers(x, arr, n));}} // This code is contributed by Rajput-Ji # Python3 implementation of the approach # Function to find the minimum number# of integers requireddef minNumbers(x, arr, n) : q = [] # Base value in queue q.append(x) v = set([]) d = 0 while (len(q) > 0) : s = len(q) while (s) : s -= 1 c = q[0] #print(q) if (c == 0) : return d q.pop(0) if ((c in v) or c < 0) : continue # Setting current state as visited v.add(c) # Pushing the required states in queue for i in range(n) : q.append(c - arr[i]) d += 1 #print() #print(d,c) # If no possible solution return -1 arr = [ 1, 4,6 ]n = len(arr)x = 20print(minNumbers(x, arr, n)) # This code is contributed by divyeshrabadiya07# Improved by nishant.k108 // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to find the minimum number// of integers requiredstatic int minNumbers(int x, int []arr, int n){ // Queue for BFS Queue<int> q = new Queue<int>(); // Base value in queue q.Enqueue(x); // Boolean array to check if // a number has been visited before HashSet<int> v = new HashSet<int>(); // Variable to store depth of BFS int d = 0; // BFS algorithm while (q.Count > 0) { // Size of queue int s = q.Count; while (s-- > 0) { // Front most element of the queue int c = q.Peek(); // Base case if (c == 0) return d; q.Dequeue(); if (v.Contains(c) || c < 0) continue; // Setting current state as visited v.Add(c); // Pushing the required states in queue for (int i = 0; i < n; i++) q.Enqueue(c - arr[i]); } d++; } // If no possible solution return -1;} // Driver codepublic static void Main(String[] args){ int []arr = { 3, 3, 4 }; int n = arr.Length; int x = 7; Console.WriteLine(minNumbers(x, arr, n));}} // This code is contributed by Rajput-Ji <script> // Javascript implementation of the approach // Function to find the minimum number// of integers requiredfunction minNumbers(x, arr, n){ // Queue for BFS var q = []; // Base value in queue q.push(x); // Boolean array to check if a number has been // visited before var v = new Set(); // Variable to store depth of BFS var d = 0; // BFS algorithm while (q.length!=0) { // Size of queue var s = q.length; while (s--) { // Front most element of the queue var c = q[0]; // Base case if (!c) return d; q.shift(); if (v.has(c) || c < 0) continue; // Setting current state as visited v.add(c); // Pushing the required states in queue for (var i = 0; i < n; i++) q.push(c - arr[i]); } d++; } // If no possible solution return -1;} // Driver codevar arr = [3, 3, 4];var n = arr.length;var x = 7;document.write(minNumbers(x, arr, n)); // This code is contributed by rrrtnx.</script> 2 Time complexity: O(N * X)Auxiliary Space: O(N), since N extra space has been taken. Rajput-Ji divyeshrabadiya07 NishantKumar37 pankajsharmagfg rrrtnx rishavnitro BFS Algorithms Dynamic Programming Mathematical Searching Searching Dynamic Programming Mathematical BFS Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n31 May, 2022" }, { "code": null, "e": 321, "s": 52, "text": "Given an integer X and an array arr[] of length N consisting of positive integers, the task is to pick minimum number of integers from the array such that they sum up to N. Any number can be chosen infinite number of times. If no answer exists then print -1.Examples: " }, { "code": null, "e": 440, "s": 321, "text": "Input: X = 7, arr[] = {3, 5, 4} Output: 2 The minimum number elements will be 2 as 3 and 4 can be selected to reach 7." }, { "code": null, "e": 480, "s": 440, "text": "Input: X = 4, arr[] = {5} Output: -1 " }, { "code": null, "e": 1181, "s": 480, "text": "Approach: We have already seen how to solve this problem using dynamic-programming approach in this article.Here, we will see a slightly different approach to solve this problem using BFS. Before that, let’s go ahead and define a state. A state SX can be defined as the minimum number of integers we would need to take from array to get a total of X.Now, if we start looking at each state as a node in a graph such that each node is connected to (SX – arr[0], SX – arr[1], ... SX – arr[N – 1]). Thus, we have to find the shortest path from state N to 0 in an unweighted and this can be done using BFS. BFS works here because the graph is unweighted.Below is the implementation of the above approach: " }, { "code": null, "e": 1185, "s": 1181, "text": "C++" }, { "code": null, "e": 1190, "s": 1185, "text": "Java" }, { "code": null, "e": 1198, "s": 1190, "text": "Python3" }, { "code": null, "e": 1201, "s": 1198, "text": "C#" }, { "code": null, "e": 1212, "s": 1201, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum number// of integers requiredint minNumbers(int x, int* arr, int n){ // Queue for BFS queue<int> q; // Base value in queue q.push(x); // Boolean array to check if a number has been // visited before unordered_set<int> v; // Variable to store depth of BFS int d = 0; // BFS algorithm while (q.size()) { // Size of queue int s = q.size(); while (s--) { // Front most element of the queue int c = q.front(); // Base case if (!c) return d; q.pop(); if (v.find(c) != v.end() or c < 0) continue; // Setting current state as visited v.insert(c); // Pushing the required states in queue for (int i = 0; i < n; i++) q.push(c - arr[i]); } d++; } // If no possible solution return -1;} // Driver codeint main(){ int arr[] = { 3, 3, 4 }; int n = sizeof(arr) / sizeof(int); int x = 7; cout << minNumbers(x, arr, n); return 0;}", "e": 2400, "s": 1212, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to find the minimum number// of integers requiredstatic int minNumbers(int x, int []arr, int n){ // Queue for BFS Queue<Integer> q = new LinkedList<>(); // Base value in queue q.add(x); // Boolean array to check if // a number has been visited before HashSet<Integer> v = new HashSet<Integer>(); // Variable to store depth of BFS int d = 0; // BFS algorithm while (q.size() > 0) { // Size of queue int s = q.size(); while (s-- > 0) { // Front most element of the queue int c = q.peek(); // Base case if (c == 0) return d; q.remove(); if (v.contains(c) || c < 0) continue; // Setting current state as visited v.add(c); // Pushing the required states in queue for (int i = 0; i < n; i++) q.add(c - arr[i]); } d++; } // If no possible solution return -1;} // Driver codepublic static void main(String[] args){ int arr[] = { 3, 3, 4 }; int n = arr.length; int x = 7; System.out.println(minNumbers(x, arr, n));}} // This code is contributed by Rajput-Ji", "e": 3695, "s": 2400, "text": null }, { "code": "# Python3 implementation of the approach # Function to find the minimum number# of integers requireddef minNumbers(x, arr, n) : q = [] # Base value in queue q.append(x) v = set([]) d = 0 while (len(q) > 0) : s = len(q) while (s) : s -= 1 c = q[0] #print(q) if (c == 0) : return d q.pop(0) if ((c in v) or c < 0) : continue # Setting current state as visited v.add(c) # Pushing the required states in queue for i in range(n) : q.append(c - arr[i]) d += 1 #print() #print(d,c) # If no possible solution return -1 arr = [ 1, 4,6 ]n = len(arr)x = 20print(minNumbers(x, arr, n)) # This code is contributed by divyeshrabadiya07# Improved by nishant.k108", "e": 4591, "s": 3695, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to find the minimum number// of integers requiredstatic int minNumbers(int x, int []arr, int n){ // Queue for BFS Queue<int> q = new Queue<int>(); // Base value in queue q.Enqueue(x); // Boolean array to check if // a number has been visited before HashSet<int> v = new HashSet<int>(); // Variable to store depth of BFS int d = 0; // BFS algorithm while (q.Count > 0) { // Size of queue int s = q.Count; while (s-- > 0) { // Front most element of the queue int c = q.Peek(); // Base case if (c == 0) return d; q.Dequeue(); if (v.Contains(c) || c < 0) continue; // Setting current state as visited v.Add(c); // Pushing the required states in queue for (int i = 0; i < n; i++) q.Enqueue(c - arr[i]); } d++; } // If no possible solution return -1;} // Driver codepublic static void Main(String[] args){ int []arr = { 3, 3, 4 }; int n = arr.Length; int x = 7; Console.WriteLine(minNumbers(x, arr, n));}} // This code is contributed by Rajput-Ji", "e": 5907, "s": 4591, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to find the minimum number// of integers requiredfunction minNumbers(x, arr, n){ // Queue for BFS var q = []; // Base value in queue q.push(x); // Boolean array to check if a number has been // visited before var v = new Set(); // Variable to store depth of BFS var d = 0; // BFS algorithm while (q.length!=0) { // Size of queue var s = q.length; while (s--) { // Front most element of the queue var c = q[0]; // Base case if (!c) return d; q.shift(); if (v.has(c) || c < 0) continue; // Setting current state as visited v.add(c); // Pushing the required states in queue for (var i = 0; i < n; i++) q.push(c - arr[i]); } d++; } // If no possible solution return -1;} // Driver codevar arr = [3, 3, 4];var n = arr.length;var x = 7;document.write(minNumbers(x, arr, n)); // This code is contributed by rrrtnx.</script>", "e": 7033, "s": 5907, "text": null }, { "code": null, "e": 7035, "s": 7033, "text": "2" }, { "code": null, "e": 7121, "s": 7037, "text": "Time complexity: O(N * X)Auxiliary Space: O(N), since N extra space has been taken." }, { "code": null, "e": 7131, "s": 7121, "text": "Rajput-Ji" }, { "code": null, "e": 7149, "s": 7131, "text": "divyeshrabadiya07" }, { "code": null, "e": 7164, "s": 7149, "text": "NishantKumar37" }, { "code": null, "e": 7180, "s": 7164, "text": "pankajsharmagfg" }, { "code": null, "e": 7187, "s": 7180, "text": "rrrtnx" }, { "code": null, "e": 7199, "s": 7187, "text": "rishavnitro" }, { "code": null, "e": 7203, "s": 7199, "text": "BFS" }, { "code": null, "e": 7214, "s": 7203, "text": "Algorithms" }, { "code": null, "e": 7234, "s": 7214, "text": "Dynamic Programming" }, { "code": null, "e": 7247, "s": 7234, "text": "Mathematical" }, { "code": null, "e": 7257, "s": 7247, "text": "Searching" }, { "code": null, "e": 7267, "s": 7257, "text": "Searching" }, { "code": null, "e": 7287, "s": 7267, "text": "Dynamic Programming" }, { "code": null, "e": 7300, "s": 7287, "text": "Mathematical" }, { "code": null, "e": 7304, "s": 7300, "text": "BFS" }, { "code": null, "e": 7315, "s": 7304, "text": "Algorithms" } ]
Python | Check if two lists are identical
24 Nov, 2018 This article deals with the task of ways to check if two unordered list contains exact similar elements in exact similar position, i.e to check if two lists are exactly equal. This is quite a useful utility and can be used in day-day programming. Method 1 : Using list.sort() and == operatorsort() coupled with == operator can achieve this task. We first sort the list, so that if both the lists are identical, then they have elements at the same position. But this doesn’t take into account the ordering of elements in list. # Python 3 code to demonstrate # check if list are identical# using sort() + == operator # initializing lists test_list1 = [1, 2, 4, 3, 5]test_list2 = [1, 2, 4, 3, 5] # printing listsprint ("The first list is : " + str(test_list1))print ("The second list is : " + str(test_list2)) # sorting both the liststest_list1.sort()test_list2.sort() # using == to check if # lists are equalif test_list1 == test_list2: print ("The lists are identical")else : print ("The lists are not identical") Output : The first list is : [1, 2, 4, 3, 5] The second list is : [1, 2, 4, 3, 5] The lists are identical Method 2 : Using collections.Counter()Using Counter(), we usually are able to get frequency of each element in list, checking for it, for both the list, we can check if two lists are identical or not. But this method also ignores the ordering of the elements in the list and only takes into account the frequency of elements. # Python 3 code to demonstrate # check if list are identical# using collections.Counter()import collections # initializing lists test_list1 = [1, 2, 4, 3, 5]test_list2 = [1, 2, 4, 3, 5] # printing listsprint ("The first list is : " + str(test_list1))print ("The second list is : " + str(test_list2)) # using collections.Counter() to check if # lists are equalif collections.Counter(test_list1) == collections.Counter(test_list2): print ("The lists are identical")else : print ("The lists are not identical") Output : The first list is : [1, 2, 4, 3, 5] The second list is : [1, 2, 4, 3, 5] The lists are identical Method 3 : Using sum() + zip() + len()Using sum() + zip(), we can get sum of one of the list as summation of 1 if both the index in two lists have equal elements, and then compare that number with size of other list. This also requires first to check if two lists are equal before this computation. It also checks for the order. # Python 3 code to demonstrate # check if list are identical# using sum() + zip() + len() # initializing lists test_list1 = [1, 2, 4, 3, 5]test_list2 = [1, 2, 4, 3, 5] # printing listsprint ("The first list is : " + str(test_list1))print ("The second list is : " + str(test_list2)) # using sum() + zip() + len() to check if # lists are equalif len(test_list1)== len(test_list2) and len(test_list1) == sum([1 for i, j in zip(test_list1, test_list2) if i == j]): print ("The lists are identical")else : print ("The lists are not identical") Output : The first list is : [1, 2, 4, 3, 5] The second list is : [1, 2, 4, 3, 5] The lists are identical Method 4 : Using reduce() + map()Carefully coupling power of map() to hash values and utility of reduce(), we can achieve this task of checking for equality of two lists to be identical. This also takes into account the ordering of the list. # Python 3 code to demonstrate # check if list are identical# using map() + reduce()import functools # initializing lists test_list1 = [1, 2, 4, 3, 5]test_list2 = [1, 2, 4, 3, 5] # printing listsprint ("The first list is : " + str(test_list1))print ("The second list is : " + str(test_list2)) # using map() + reduce() to check if # lists are equalif functools.reduce(lambda i, j : i and j, map(lambda m, k: m == k, test_list1, test_list2), True) : print ("The lists are identical")else : print ("The lists are not identical") Output : The first list is : [1, 2, 4, 3, 5] The second list is : [1, 2, 4, 3, 5] The lists are identical Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Nov, 2018" }, { "code": null, "e": 275, "s": 28, "text": "This article deals with the task of ways to check if two unordered list contains exact similar elements in exact similar position, i.e to check if two lists are exactly equal. This is quite a useful utility and can be used in day-day programming." }, { "code": null, "e": 554, "s": 275, "text": "Method 1 : Using list.sort() and == operatorsort() coupled with == operator can achieve this task. We first sort the list, so that if both the lists are identical, then they have elements at the same position. But this doesn’t take into account the ordering of elements in list." }, { "code": "# Python 3 code to demonstrate # check if list are identical# using sort() + == operator # initializing lists test_list1 = [1, 2, 4, 3, 5]test_list2 = [1, 2, 4, 3, 5] # printing listsprint (\"The first list is : \" + str(test_list1))print (\"The second list is : \" + str(test_list2)) # sorting both the liststest_list1.sort()test_list2.sort() # using == to check if # lists are equalif test_list1 == test_list2: print (\"The lists are identical\")else : print (\"The lists are not identical\")", "e": 1051, "s": 554, "text": null }, { "code": null, "e": 1060, "s": 1051, "text": "Output :" }, { "code": null, "e": 1158, "s": 1060, "text": "The first list is : [1, 2, 4, 3, 5]\nThe second list is : [1, 2, 4, 3, 5]\nThe lists are identical\n" }, { "code": null, "e": 1484, "s": 1158, "text": "Method 2 : Using collections.Counter()Using Counter(), we usually are able to get frequency of each element in list, checking for it, for both the list, we can check if two lists are identical or not. But this method also ignores the ordering of the elements in the list and only takes into account the frequency of elements." }, { "code": "# Python 3 code to demonstrate # check if list are identical# using collections.Counter()import collections # initializing lists test_list1 = [1, 2, 4, 3, 5]test_list2 = [1, 2, 4, 3, 5] # printing listsprint (\"The first list is : \" + str(test_list1))print (\"The second list is : \" + str(test_list2)) # using collections.Counter() to check if # lists are equalif collections.Counter(test_list1) == collections.Counter(test_list2): print (\"The lists are identical\")else : print (\"The lists are not identical\")", "e": 2001, "s": 1484, "text": null }, { "code": null, "e": 2010, "s": 2001, "text": "Output :" }, { "code": null, "e": 2108, "s": 2010, "text": "The first list is : [1, 2, 4, 3, 5]\nThe second list is : [1, 2, 4, 3, 5]\nThe lists are identical\n" }, { "code": null, "e": 2437, "s": 2108, "text": "Method 3 : Using sum() + zip() + len()Using sum() + zip(), we can get sum of one of the list as summation of 1 if both the index in two lists have equal elements, and then compare that number with size of other list. This also requires first to check if two lists are equal before this computation. It also checks for the order." }, { "code": "# Python 3 code to demonstrate # check if list are identical# using sum() + zip() + len() # initializing lists test_list1 = [1, 2, 4, 3, 5]test_list2 = [1, 2, 4, 3, 5] # printing listsprint (\"The first list is : \" + str(test_list1))print (\"The second list is : \" + str(test_list2)) # using sum() + zip() + len() to check if # lists are equalif len(test_list1)== len(test_list2) and len(test_list1) == sum([1 for i, j in zip(test_list1, test_list2) if i == j]): print (\"The lists are identical\")else : print (\"The lists are not identical\")", "e": 2985, "s": 2437, "text": null }, { "code": null, "e": 2994, "s": 2985, "text": "Output :" }, { "code": null, "e": 3092, "s": 2994, "text": "The first list is : [1, 2, 4, 3, 5]\nThe second list is : [1, 2, 4, 3, 5]\nThe lists are identical\n" }, { "code": null, "e": 3334, "s": 3092, "text": "Method 4 : Using reduce() + map()Carefully coupling power of map() to hash values and utility of reduce(), we can achieve this task of checking for equality of two lists to be identical. This also takes into account the ordering of the list." }, { "code": "# Python 3 code to demonstrate # check if list are identical# using map() + reduce()import functools # initializing lists test_list1 = [1, 2, 4, 3, 5]test_list2 = [1, 2, 4, 3, 5] # printing listsprint (\"The first list is : \" + str(test_list1))print (\"The second list is : \" + str(test_list2)) # using map() + reduce() to check if # lists are equalif functools.reduce(lambda i, j : i and j, map(lambda m, k: m == k, test_list1, test_list2), True) : print (\"The lists are identical\")else : print (\"The lists are not identical\")", "e": 3870, "s": 3334, "text": null }, { "code": null, "e": 3879, "s": 3870, "text": "Output :" }, { "code": null, "e": 3977, "s": 3879, "text": "The first list is : [1, 2, 4, 3, 5]\nThe second list is : [1, 2, 4, 3, 5]\nThe lists are identical\n" }, { "code": null, "e": 3998, "s": 3977, "text": "Python list-programs" }, { "code": null, "e": 4010, "s": 3998, "text": "python-list" }, { "code": null, "e": 4017, "s": 4010, "text": "Python" }, { "code": null, "e": 4029, "s": 4017, "text": "python-list" }, { "code": null, "e": 4127, "s": 4029, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4145, "s": 4127, "text": "Python Dictionary" }, { "code": null, "e": 4187, "s": 4145, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4209, "s": 4187, "text": "Enumerate() in Python" }, { "code": null, "e": 4244, "s": 4209, "text": "Read a file line by line in Python" }, { "code": null, "e": 4270, "s": 4244, "text": "Python String | replace()" }, { "code": null, "e": 4302, "s": 4270, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4331, "s": 4302, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4358, "s": 4331, "text": "Python Classes and Objects" }, { "code": null, "e": 4388, "s": 4358, "text": "Iterate over a list in Python" } ]
Spring Boot – CRUD Operations using MySQL Database
24 Dec, 2021 CRUD stands for Create, Read/Retrieve, Update and Delete and these are the four basic operations that we perform on persistence storage. CRUD is data-oriented and the standardized use of HTTP methods. HTTP has a few methods which work as CRUD operations and do note they are very vital from a developmental point perspective in programming that also does helps us relate better web development and also aids us while dealing with databases. So, standard CRUD Operations is as follows: POST: Creates a new resource GET: Reads/Retrieve a resource PUT: Updates an existing resource DELETE: Deletes a resource As the name suggests CREATE Operation: Performs the INSERT statement to create a new record. READ Operation: Reads table records based on the input parameter. UPDATE Operation: Executes an update statement on the table. It is based on the input parameter. DELETE Operation: Deletes a specified row in the table. It is also based on the input parameter. So in this article, we are going to perform some basic CRUD Operations by creating a Spring Boot Application and using the MySQL Database. So here is a brief explanation of What’s Spring Boot and What’s MySQL Database. Spring Boot Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because it’s a rapid production-ready environment that enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. MySQL Database MySQL is an RDBMS (Relational Database Management System) based on the SQL (Structured Query Language), which is the popular language for accessing and managing the records in the database. MySQL is open-source and free software under the GNU license. It is supported by Oracle Company. The data in a MySQL database are stored in tables. A table is a collection of related data, and it consists of columns and rows. Some of the features of MySQL are listed below: It is a database system used on the webIt runs on a serverIt is ideal for both small and large applicationsIt is very fast, reliable, and easy to useIt uses standard SQLIt is free to download and use It is a database system used on the web It runs on a server It is ideal for both small and large applications It is very fast, reliable, and easy to use It uses standard SQL It is free to download and use So to connect and perform CRUD operation with the MySQL DB with Spring Boot application we have to just configure it inside the application.properties file as follows: # Configuration for MySQL Database spring.jpa.hibernate.ddl-auto=update spring.datasource.url = jdbc:mysql://localhost:3306/schooldb (Datasource URL of your DB and "schooldb", here is your schema name) spring.datasource.username=amiya559 (Your MySQL Workbench user name) spring.datasource.password=password.123 (Your MySQL Workbench password) spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.show-sql:true JpaRepository is a JPA (Java Persistence API) specific extension of Repository. It contains the full API of CrudRepository and PagingAndSortingRepository. So it contains API for basic CRUD operations and also API for pagination and sorting. Syntax: public interface JpaRepository<T,ID> extends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T> Where T: Domain type that repository manages (Generally the Entity/Model class name) ID: Type of the id of the entity that repository manages (Generally the wrapper class of your @Id that is created inside the Entity/Model class) Illustration: public interface DepartmentRepository extends JpaRepository<Department, Long> {} Example: We will be having a Spring Boot application that manages a Department entity with JpaRepository. The data is saved in the MySQL database. We use a RESTful controller. Step 1: Create a Spring Boot project with say it be IntelliJ Step 2: Add the following dependency as listed below as follows: Spring Web MySQL Database Lombok Spring Data JPA Below is the complete code for the pom.xml file. XML <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.5</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.amiya</groupId> <artifactId>Spring-Boot-Demo-Project</artifactId> <version>1.0.0-SNAPSHOT</version> <name>Spring-Boot-Demo-Project</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Dependency for MySQL Database --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project> Step 3: Create 4 packages as listed and create some classes and interfaces inside these packages as seen in the below image as shown: entity repository service controller Note: Green Rounded Icon ‘I’ Buttons are Interface Blue Rounded Icon ‘C’ Buttons are Classes Step 4: Inside the entity package It is done via creating a simple POJO class inside the Department.java file. Java // Java Program to Illustrate Department File // Importing package module to code fragmentpackage com.amiya.springbootdemoproject.entity; // Importing required classesimport lombok.AllArgsConstructor;import lombok.Builder;import lombok.Data;import lombok.NoArgsConstructor; import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id; // Annotations@Entity@Data@NoArgsConstructor@AllArgsConstructor@Builder // Classpublic class Department { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long departmentId; private String departmentName; private String departmentAddress; private String departmentCode;} Step 5: Inside the repository package Create a simple interface and name the interface as DepartmentRepository. This interface is going to extend the JpaRepository as we have discussed above. Example Java // Java Program to Illustrate DepartmentRepository File // Importing package module to this codepackage com.amiya.springbootdemoproject.repository;// Importing required classesimport com.amiya.springbootdemoproject.entity.Department;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.stereotype.Repository; // Annotation@Repository // Interfacepublic interface DepartmentRepository extends JpaRepository<Department, Long> {} Step 6: Inside the service package Example 1-A Inside the package create one interface named as DepartmentService and one class named as DepartmentServiceImpl. Java // Java Program to Illustrate DepartmentService File // Importing package to this code fragmentpackage com.amiya.springbootdemoproject.service;import com.amiya.springbootdemoproject.entity.Department;// Importing required classesimport java.util.List; // Interfacepublic interface DepartmentService { // Save operation Department saveDepartment(Department department); // Read operation List<Department> fetchDepartmentList(); // Update operation Department updateDepartment(Department department, Long departmentId); // Delete operation void deleteDepartmentById(Long departmentId);} Example 1-B Java // Java Program to Illustrate DepartmentServiceImpl File // Importing package module to this codepackage com.amiya.springbootdemoproject.service; import com.amiya.springbootdemoproject.entity.Department;import com.amiya.springbootdemoproject.repository.DepartmentRepository;// Importing required classesimport java.util.List;import java.util.Objects;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service; // Annotation@Service // Classpublic class DepartmentServiceImpl implements DepartmentService { @Autowired private DepartmentRepository departmentRepository; // Save operation @Override public Department saveDepartment(Department department) { return departmentRepository.save(department); } // Read operation @Override public List<Department> fetchDepartmentList() { return (List<Department>) departmentRepository.findAll(); } // Update operation @Override public Department updateDepartment(Department department, Long departmentId) { Department depDB = departmentRepository.findById(departmentId) .get(); if (Objects.nonNull(department.getDepartmentName()) && !"".equalsIgnoreCase( department.getDepartmentName())) { depDB.setDepartmentName( department.getDepartmentName()); } if (Objects.nonNull( department.getDepartmentAddress()) && !"".equalsIgnoreCase( department.getDepartmentAddress())) { depDB.setDepartmentAddress( department.getDepartmentAddress()); } if (Objects.nonNull(department.getDepartmentCode()) && !"".equalsIgnoreCase( department.getDepartmentCode())) { depDB.setDepartmentCode( department.getDepartmentCode()); } return departmentRepository.save(depDB); } // Delete operation @Override public void deleteDepartmentById(Long departmentId) { departmentRepository.deleteById(departmentId); }} Step 7: Inside the controller package Inside the package create one class named as DepartmentController. Java // Java Program to Illustrate DepartmentController File // Importing package module to this codepackage com.amiya.springbootdemoproject.controller; import com.amiya.springbootdemoproject.entity.Department;import com.amiya.springbootdemoproject.service.DepartmentService;import java.util.List;import javax.validation.Valid;// Importing required classesimport org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*; // Annotation@RestController // Classpublic class DepartmentController { // Annotation @Autowired private DepartmentService departmentService; // Save operation @PostMapping("/departments") public Department saveDepartment( @Valid @RequestBody Department department) { return departmentService.saveDepartment(department); } // Read operation @GetMapping("/departments") public List<Department> fetchDepartmentList() { return departmentService.fetchDepartmentList(); } // Update operation @PutMapping("/departments/{id}") public Department updateDepartment(@RequestBody Department department, @PathVariable("id") Long departmentId) { return departmentService.updateDepartment( department, departmentId); } // Delete operation @DeleteMapping("/departments/{id}") public String deleteDepartmentById(@PathVariable("id") Long departmentId) { departmentService.deleteDepartmentById( departmentId); return "Deleted Successfully"; }} Step 8: Below is the code for the application.properties file server.port=8082 # Configuration for MySQL Database spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://localhost:3306/schooldb spring.datasource.username=amiya559 spring.datasource.password=password.123 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.show-sql:true Now run your application and let’s test the endpoints in Postman and also refer to our H2 Database. Endpoint 1: POST – http://localhost:8082/departments/ Endpoint 2: GET – http://localhost:8082/departments/ Endpoint 3: PUT – http://localhost:8082/departments/1 Endpoint 4: DELETE – http://localhost:8082/departments/1 MySQL Workbench will appear as shown below: arorakashish0911 Java-Spring-Boot mysql Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. List Interface in Java with Examples Different ways of Reading a text file in Java Constructors in Java Strings in Java HashMap containsKey() Method in Java How to Create Array of Objects in Java? Hashtable in Java Compare two Strings in Java HashSet in Java How to remove an element from ArrayList in Java?
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2021" }, { "code": null, "e": 470, "s": 28, "text": "CRUD stands for Create, Read/Retrieve, Update and Delete and these are the four basic operations that we perform on persistence storage. CRUD is data-oriented and the standardized use of HTTP methods. HTTP has a few methods which work as CRUD operations and do note they are very vital from a developmental point perspective in programming that also does helps us relate better web development and also aids us while dealing with databases. " }, { "code": null, "e": 514, "s": 470, "text": "So, standard CRUD Operations is as follows:" }, { "code": null, "e": 543, "s": 514, "text": "POST: Creates a new resource" }, { "code": null, "e": 574, "s": 543, "text": "GET: Reads/Retrieve a resource" }, { "code": null, "e": 608, "s": 574, "text": "PUT: Updates an existing resource" }, { "code": null, "e": 635, "s": 608, "text": "DELETE: Deletes a resource" }, { "code": null, "e": 657, "s": 635, "text": "As the name suggests " }, { "code": null, "e": 729, "s": 657, "text": "CREATE Operation: Performs the INSERT statement to create a new record." }, { "code": null, "e": 795, "s": 729, "text": "READ Operation: Reads table records based on the input parameter." }, { "code": null, "e": 892, "s": 795, "text": "UPDATE Operation: Executes an update statement on the table. It is based on the input parameter." }, { "code": null, "e": 989, "s": 892, "text": "DELETE Operation: Deletes a specified row in the table. It is also based on the input parameter." }, { "code": null, "e": 1209, "s": 989, "text": "So in this article, we are going to perform some basic CRUD Operations by creating a Spring Boot Application and using the MySQL Database. So here is a brief explanation of What’s Spring Boot and What’s MySQL Database. " }, { "code": null, "e": 1221, "s": 1209, "text": "Spring Boot" }, { "code": null, "e": 1643, "s": 1221, "text": "Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because it’s a rapid production-ready environment that enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time." }, { "code": null, "e": 1658, "s": 1643, "text": "MySQL Database" }, { "code": null, "e": 2122, "s": 1658, "text": "MySQL is an RDBMS (Relational Database Management System) based on the SQL (Structured Query Language), which is the popular language for accessing and managing the records in the database. MySQL is open-source and free software under the GNU license. It is supported by Oracle Company. The data in a MySQL database are stored in tables. A table is a collection of related data, and it consists of columns and rows. Some of the features of MySQL are listed below:" }, { "code": null, "e": 2322, "s": 2122, "text": "It is a database system used on the webIt runs on a serverIt is ideal for both small and large applicationsIt is very fast, reliable, and easy to useIt uses standard SQLIt is free to download and use" }, { "code": null, "e": 2362, "s": 2322, "text": "It is a database system used on the web" }, { "code": null, "e": 2382, "s": 2362, "text": "It runs on a server" }, { "code": null, "e": 2432, "s": 2382, "text": "It is ideal for both small and large applications" }, { "code": null, "e": 2475, "s": 2432, "text": "It is very fast, reliable, and easy to use" }, { "code": null, "e": 2496, "s": 2475, "text": "It uses standard SQL" }, { "code": null, "e": 2527, "s": 2496, "text": "It is free to download and use" }, { "code": null, "e": 2695, "s": 2527, "text": "So to connect and perform CRUD operation with the MySQL DB with Spring Boot application we have to just configure it inside the application.properties file as follows:" }, { "code": null, "e": 3128, "s": 2695, "text": "# Configuration for MySQL Database\n\nspring.jpa.hibernate.ddl-auto=update\n\nspring.datasource.url = jdbc:mysql://localhost:3306/schooldb \n(Datasource URL of your DB and \"schooldb\", here is your schema name)\n\nspring.datasource.username=amiya559 (Your MySQL Workbench user name)\nspring.datasource.password=password.123 (Your MySQL Workbench password)\nspring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver\nspring.jpa.show-sql:true" }, { "code": null, "e": 3369, "s": 3128, "text": "JpaRepository is a JPA (Java Persistence API) specific extension of Repository. It contains the full API of CrudRepository and PagingAndSortingRepository. So it contains API for basic CRUD operations and also API for pagination and sorting." }, { "code": null, "e": 3377, "s": 3369, "text": "Syntax:" }, { "code": null, "e": 3483, "s": 3377, "text": "public interface JpaRepository<T,ID> extends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T> " }, { "code": null, "e": 3489, "s": 3483, "text": "Where" }, { "code": null, "e": 3568, "s": 3489, "text": "T: Domain type that repository manages (Generally the Entity/Model class name)" }, { "code": null, "e": 3713, "s": 3568, "text": "ID: Type of the id of the entity that repository manages (Generally the wrapper class of your @Id that is created inside the Entity/Model class)" }, { "code": null, "e": 3727, "s": 3713, "text": "Illustration:" }, { "code": null, "e": 3808, "s": 3727, "text": "public interface DepartmentRepository extends JpaRepository<Department, Long> {}" }, { "code": null, "e": 3984, "s": 3808, "text": "Example: We will be having a Spring Boot application that manages a Department entity with JpaRepository. The data is saved in the MySQL database. We use a RESTful controller." }, { "code": null, "e": 4045, "s": 3984, "text": "Step 1: Create a Spring Boot project with say it be IntelliJ" }, { "code": null, "e": 4110, "s": 4045, "text": "Step 2: Add the following dependency as listed below as follows:" }, { "code": null, "e": 4121, "s": 4110, "text": "Spring Web" }, { "code": null, "e": 4136, "s": 4121, "text": "MySQL Database" }, { "code": null, "e": 4143, "s": 4136, "text": "Lombok" }, { "code": null, "e": 4159, "s": 4143, "text": "Spring Data JPA" }, { "code": null, "e": 4208, "s": 4159, "text": "Below is the complete code for the pom.xml file." }, { "code": null, "e": 4212, "s": 4208, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.5</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.amiya</groupId> <artifactId>Spring-Boot-Demo-Project</artifactId> <version>1.0.0-SNAPSHOT</version> <name>Spring-Boot-Demo-Project</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Dependency for MySQL Database --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project>", "e": 6724, "s": 4212, "text": null }, { "code": null, "e": 6859, "s": 6724, "text": " Step 3: Create 4 packages as listed and create some classes and interfaces inside these packages as seen in the below image as shown:" }, { "code": null, "e": 6866, "s": 6859, "text": "entity" }, { "code": null, "e": 6877, "s": 6866, "text": "repository" }, { "code": null, "e": 6885, "s": 6877, "text": "service" }, { "code": null, "e": 6896, "s": 6885, "text": "controller" }, { "code": null, "e": 6902, "s": 6896, "text": "Note:" }, { "code": null, "e": 6947, "s": 6902, "text": "Green Rounded Icon ‘I’ Buttons are Interface" }, { "code": null, "e": 6989, "s": 6947, "text": "Blue Rounded Icon ‘C’ Buttons are Classes" }, { "code": null, "e": 7023, "s": 6989, "text": "Step 4: Inside the entity package" }, { "code": null, "e": 7101, "s": 7023, "text": "It is done via creating a simple POJO class inside the Department.java file. " }, { "code": null, "e": 7106, "s": 7101, "text": "Java" }, { "code": "// Java Program to Illustrate Department File // Importing package module to code fragmentpackage com.amiya.springbootdemoproject.entity; // Importing required classesimport lombok.AllArgsConstructor;import lombok.Builder;import lombok.Data;import lombok.NoArgsConstructor; import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id; // Annotations@Entity@Data@NoArgsConstructor@AllArgsConstructor@Builder // Classpublic class Department { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long departmentId; private String departmentName; private String departmentAddress; private String departmentCode;}", "e": 7823, "s": 7106, "text": null }, { "code": null, "e": 7862, "s": 7823, "text": " Step 5: Inside the repository package" }, { "code": null, "e": 8018, "s": 7862, "text": "Create a simple interface and name the interface as DepartmentRepository. This interface is going to extend the JpaRepository as we have discussed above. " }, { "code": null, "e": 8027, "s": 8018, "text": "Example " }, { "code": null, "e": 8032, "s": 8027, "text": "Java" }, { "code": "// Java Program to Illustrate DepartmentRepository File // Importing package module to this codepackage com.amiya.springbootdemoproject.repository;// Importing required classesimport com.amiya.springbootdemoproject.entity.Department;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.stereotype.Repository; // Annotation@Repository // Interfacepublic interface DepartmentRepository extends JpaRepository<Department, Long> {}", "e": 8497, "s": 8032, "text": null }, { "code": null, "e": 8533, "s": 8497, "text": " Step 6: Inside the service package" }, { "code": null, "e": 8660, "s": 8533, "text": "Example 1-A Inside the package create one interface named as DepartmentService and one class named as DepartmentServiceImpl. " }, { "code": null, "e": 8665, "s": 8660, "text": "Java" }, { "code": "// Java Program to Illustrate DepartmentService File // Importing package to this code fragmentpackage com.amiya.springbootdemoproject.service;import com.amiya.springbootdemoproject.entity.Department;// Importing required classesimport java.util.List; // Interfacepublic interface DepartmentService { // Save operation Department saveDepartment(Department department); // Read operation List<Department> fetchDepartmentList(); // Update operation Department updateDepartment(Department department, Long departmentId); // Delete operation void deleteDepartmentById(Long departmentId);}", "e": 9309, "s": 8665, "text": null }, { "code": null, "e": 9324, "s": 9309, "text": " Example 1-B " }, { "code": null, "e": 9329, "s": 9324, "text": "Java" }, { "code": "// Java Program to Illustrate DepartmentServiceImpl File // Importing package module to this codepackage com.amiya.springbootdemoproject.service; import com.amiya.springbootdemoproject.entity.Department;import com.amiya.springbootdemoproject.repository.DepartmentRepository;// Importing required classesimport java.util.List;import java.util.Objects;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service; // Annotation@Service // Classpublic class DepartmentServiceImpl implements DepartmentService { @Autowired private DepartmentRepository departmentRepository; // Save operation @Override public Department saveDepartment(Department department) { return departmentRepository.save(department); } // Read operation @Override public List<Department> fetchDepartmentList() { return (List<Department>) departmentRepository.findAll(); } // Update operation @Override public Department updateDepartment(Department department, Long departmentId) { Department depDB = departmentRepository.findById(departmentId) .get(); if (Objects.nonNull(department.getDepartmentName()) && !\"\".equalsIgnoreCase( department.getDepartmentName())) { depDB.setDepartmentName( department.getDepartmentName()); } if (Objects.nonNull( department.getDepartmentAddress()) && !\"\".equalsIgnoreCase( department.getDepartmentAddress())) { depDB.setDepartmentAddress( department.getDepartmentAddress()); } if (Objects.nonNull(department.getDepartmentCode()) && !\"\".equalsIgnoreCase( department.getDepartmentCode())) { depDB.setDepartmentCode( department.getDepartmentCode()); } return departmentRepository.save(depDB); } // Delete operation @Override public void deleteDepartmentById(Long departmentId) { departmentRepository.deleteById(departmentId); }}", "e": 11487, "s": 9329, "text": null }, { "code": null, "e": 11526, "s": 11487, "text": " Step 7: Inside the controller package" }, { "code": null, "e": 11594, "s": 11526, "text": "Inside the package create one class named as DepartmentController. " }, { "code": null, "e": 11599, "s": 11594, "text": "Java" }, { "code": "// Java Program to Illustrate DepartmentController File // Importing package module to this codepackage com.amiya.springbootdemoproject.controller; import com.amiya.springbootdemoproject.entity.Department;import com.amiya.springbootdemoproject.service.DepartmentService;import java.util.List;import javax.validation.Valid;// Importing required classesimport org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*; // Annotation@RestController // Classpublic class DepartmentController { // Annotation @Autowired private DepartmentService departmentService; // Save operation @PostMapping(\"/departments\") public Department saveDepartment( @Valid @RequestBody Department department) { return departmentService.saveDepartment(department); } // Read operation @GetMapping(\"/departments\") public List<Department> fetchDepartmentList() { return departmentService.fetchDepartmentList(); } // Update operation @PutMapping(\"/departments/{id}\") public Department updateDepartment(@RequestBody Department department, @PathVariable(\"id\") Long departmentId) { return departmentService.updateDepartment( department, departmentId); } // Delete operation @DeleteMapping(\"/departments/{id}\") public String deleteDepartmentById(@PathVariable(\"id\") Long departmentId) { departmentService.deleteDepartmentById( departmentId); return \"Deleted Successfully\"; }}", "e": 13184, "s": 11599, "text": null }, { "code": null, "e": 13248, "s": 13184, "text": " Step 8: Below is the code for the application.properties file " }, { "code": null, "e": 13559, "s": 13248, "text": "server.port=8082\n\n# Configuration for MySQL Database\nspring.jpa.hibernate.ddl-auto=update\nspring.datasource.url=jdbc:mysql://localhost:3306/schooldb\nspring.datasource.username=amiya559\nspring.datasource.password=password.123\nspring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver\nspring.jpa.show-sql:true" }, { "code": null, "e": 13660, "s": 13559, "text": "Now run your application and let’s test the endpoints in Postman and also refer to our H2 Database. " }, { "code": null, "e": 13715, "s": 13660, "text": "Endpoint 1: POST – http://localhost:8082/departments/ " }, { "code": null, "e": 13769, "s": 13715, "text": "Endpoint 2: GET – http://localhost:8082/departments/ " }, { "code": null, "e": 13824, "s": 13769, "text": "Endpoint 3: PUT – http://localhost:8082/departments/1 " }, { "code": null, "e": 13882, "s": 13824, "text": "Endpoint 4: DELETE – http://localhost:8082/departments/1 " }, { "code": null, "e": 13927, "s": 13882, "text": "MySQL Workbench will appear as shown below: " }, { "code": null, "e": 13946, "s": 13929, "text": "arorakashish0911" }, { "code": null, "e": 13963, "s": 13946, "text": "Java-Spring-Boot" }, { "code": null, "e": 13969, "s": 13963, "text": "mysql" }, { "code": null, "e": 13974, "s": 13969, "text": "Java" }, { "code": null, "e": 13979, "s": 13974, "text": "Java" }, { "code": null, "e": 14077, "s": 13979, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14114, "s": 14077, "text": "List Interface in Java with Examples" }, { "code": null, "e": 14160, "s": 14114, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 14181, "s": 14160, "text": "Constructors in Java" }, { "code": null, "e": 14197, "s": 14181, "text": "Strings in Java" }, { "code": null, "e": 14234, "s": 14197, "text": "HashMap containsKey() Method in Java" }, { "code": null, "e": 14274, "s": 14234, "text": "How to Create Array of Objects in Java?" }, { "code": null, "e": 14292, "s": 14274, "text": "Hashtable in Java" }, { "code": null, "e": 14320, "s": 14292, "text": "Compare two Strings in Java" }, { "code": null, "e": 14336, "s": 14320, "text": "HashSet in Java" } ]
File Searching using Python
21 Feb, 2022 There may be many instances when you want to search a system.Suppose while writing an mp3 player you may want to have all the ‘.mp3’ files present. Well here’s how to do it in a simple way. This code searches all the folders in the file it’s being run. If you want some other kinds of files just change the extension. Python3 # Python code to search .mp3 files in current# folder (We can change file type/name and path# according to the requirements.import os # This is to get the directory that the program# is currently running in.dir_path = os.path.dirname(os.path.realpath(__file__)) for root, dirs, files in os.walk(dir_path): for file in files: # change the extension from '.mp3' to # the one of your choice. if file.endswith('.mp3'): print (root+'/'+str(file)) os is not an external library in python. So I feel this is the simplest and the best way to do this.This article is contributed by soumith kumar. 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. avtarkumar719 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Feb, 2022" }, { "code": null, "e": 371, "s": 52, "text": "There may be many instances when you want to search a system.Suppose while writing an mp3 player you may want to have all the ‘.mp3’ files present. Well here’s how to do it in a simple way. This code searches all the folders in the file it’s being run. If you want some other kinds of files just change the extension. " }, { "code": null, "e": 379, "s": 371, "text": "Python3" }, { "code": "# Python code to search .mp3 files in current# folder (We can change file type/name and path# according to the requirements.import os # This is to get the directory that the program# is currently running in.dir_path = os.path.dirname(os.path.realpath(__file__)) for root, dirs, files in os.walk(dir_path): for file in files: # change the extension from '.mp3' to # the one of your choice. if file.endswith('.mp3'): print (root+'/'+str(file))", "e": 857, "s": 379, "text": null }, { "code": null, "e": 1379, "s": 857, "text": "os is not an external library in python. So I feel this is the simplest and the best way to do this.This article is contributed by soumith kumar. 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": 1393, "s": 1379, "text": "avtarkumar719" }, { "code": null, "e": 1408, "s": 1393, "text": "python-utility" }, { "code": null, "e": 1415, "s": 1408, "text": "Python" }, { "code": null, "e": 1513, "s": 1415, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1531, "s": 1513, "text": "Python Dictionary" }, { "code": null, "e": 1573, "s": 1531, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1595, "s": 1573, "text": "Enumerate() in Python" }, { "code": null, "e": 1630, "s": 1595, "text": "Read a file line by line in Python" }, { "code": null, "e": 1656, "s": 1630, "text": "Python String | replace()" }, { "code": null, "e": 1688, "s": 1656, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1717, "s": 1688, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1744, "s": 1717, "text": "Python Classes and Objects" }, { "code": null, "e": 1774, "s": 1744, "text": "Iterate over a list in Python" } ]
Finding minimum vertex cover size of a graph using binary search
04 Jul, 2022 A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either ‘u’ or ‘v’ is in vertex cover. There may be a lot of vertex covers possible for a graph. Problem Find the size of the minimum size vertex cover, that is, cardinality of a vertex cover with minimum cardinality, for an undirected connected graph with V vertices and m edges. Examples: Input: V = 6, E = 6 6 / / 1 -----5 /|\ 3 | \ \ | \ 2 4 Output: Minimum vertex cover size = 2 Consider subset of vertices {1, 2}, every edge in above graph is either incident on vertex 1 or 2. Hence the minimum vertex cover = {1, 2}, the size of which is 2. Input: V = 6, E = 7 2 ---- 4 ---- 6 /| | 1 | | \| | 3 ---- 5 Output: Minimum vertex cover size = 3 Consider subset of vertices {2, 3, 4}, every edge in above graph is either incident on vertex 2, 3 or 4. Hence the minimum size of a vertex cover can be 3. Method 1 (Naive) We can check in O(E + V) time if a given subset of vertices is a vertex cover or not, using the following algorithm. Generate all 2V subsets of vertices in graph and do following for every subset. 1. edges_covered = 0 2. for each vertex in current subset 3. for all edges emerging out of current vertex 4. if the edge is not already marked visited 5. mark the edge visited 6. edges_covered++ 7. if edges_covered is equal to total number edges 8. return size of current subset An upper bound on time complexity of this solution is O((E + V) * 2V) Method 2 (Binary Search) If we generate 2V subsets first by generating VCV subsets, then VC(V-1) subsets, and so on upto VC0 subsets(2V = VCV + VC(V-1) + ... + VC1 + VC0). Our objective is now to find the minimum k such that at least one subset of size ‘k’ amongst VCk subsets is a vertex cover [ We know that if minimum size vertex cover is of size k, then there will exist a vertex cover of all sizes more than k. That is, there will be a vertex cover of size k + 1, k + 2, k + 3, ..., n. ] Now let’s imagine a boolean array of size n and call it isCover[]. So if the answer of the question; “Does a vertex cover of size x exist?” is yes, we put a ‘1’ at xth position, otherwise ‘0’. The array isCover[] will look like: The array is sorted and hence binary searchable, as no index before k will have a ‘1’, and every index after k(inclusive) will have a ‘1’, so k is the answer. So we can apply Binary Search to find the minimum size vertex set that covers all edges (this problem is equivalent to finding last 1 in isCover[]). Now the problem is how to generate all subsets of a given size. The idea is to use Gosper’s hack. What is Gosper’s Hack? Gosper’s hack is a technique to get the next number with same number of bits set. So we set the first x bits from right and generate next number with x bits set until the number is less than 2V. In this way, we can generate all VCx numbers with x bits set. CPP int set = (1 << k) - 1;int limit = (1 << V);while (set < limit){ // Do your stuff with current set doStuff(set); // Gosper's hack: int c = set & -set; int r = set + c; set = (((r^set) >>> 2) / c) | r;} Source : StackExchange We use gosper’s hack to generate all subsets of size x(0 < x <= V), that is, to check whether we have a ‘1’ or ‘0’ at any index x in isCover[] array. C++ Java Python3 C# // A C++ program to find size of minimum vertex// cover using Binary Search#include<bits/stdc++.h>#define maxn 25 using namespace std; // Global array to store the graph// Note: since the array is global, all the// elements are 0 initiallybool gr[maxn][maxn]; // Returns true if there is a possible subset// of size 'k' that can be a vertex coverbool isCover(int V, int k, int E){ // Set has first 'k' bits high initially int set = (1 << k) - 1; int limit = (1 << V); // to mark the edges covered in each subset // of size 'k' bool vis[maxn][maxn]; while (set < limit) { // Reset visited array for every subset // of vertices memset(vis, 0, sizeof vis); // set counter for number of edges covered // from this subset of vertices to zero int cnt = 0; // selected vertex cover is the indices // where 'set' has its bit high for (int j = 1, v = 1 ; j < limit ; j = j << 1, v++) { if (set & j) { // Mark all edges emerging out of this // vertex visited for (int k = 1 ; k <= V ; k++) { if (gr[v][k] && !vis[v][k]) { vis[v][k] = 1; vis[k][v] = 1; cnt++; } } } } // If the current subset covers all the edges if (cnt == E) return true; // Generate previous combination with k bits high // set & -set = (1 << last bit high in set) int c = set & -set; int r = set + c; set = (((r^set) >> 2) / c) | r; } return false;} // Returns answer to graph stored in gr[][]int findMinCover(int n, int m){ // Binary search the answer int left = 1, right = n; while (right > left) { int mid = (left + right) >> 1; if (isCover(n, mid, m) == false) left = mid + 1; else right = mid; } // at the end of while loop both left and // right will be equal,/ as when they are // not, the while loop won't exit the minimum // size vertex cover = left = right return left;} // Inserts an edge in the graphvoid insertEdge(int u, int v){ gr[u][v] = 1; gr[v][u] = 1; // Undirected graph} // Driver codeint main(){ /* 6 / 1 ----- 5 vertex cover = {1, 2} /|\ 3 | \ \ | \ 2 4 */ int V = 6, E = 6; insertEdge(1, 2); insertEdge(2, 3); insertEdge(1, 3); insertEdge(1, 4); insertEdge(1, 5); insertEdge(1, 6); cout << "Minimum size of a vertex cover = " << findMinCover(V, E) << endl; // Let us create another graph memset(gr, 0, sizeof gr); /* 2 ---- 4 ---- 6 /| | 1 | | vertex cover = {2, 3, 4} \ | | 3 ---- 5 */ V = 6, E = 7; insertEdge(1, 2); insertEdge(1, 3); insertEdge(2, 3); insertEdge(2, 4); insertEdge(3, 5); insertEdge(4, 5); insertEdge(4, 6); cout << "Minimum size of a vertex cover = " << findMinCover(V, E) << endl; return 0;} // A Java program to find size of minimum vertex// cover using Binary Searchclass GFG{ static final int maxn = 25; // Global array to store the graph// Note: since the array is global, all the// elements are 0 initiallystatic boolean [][]gr = new boolean[maxn][maxn]; // Returns true if there is a possible subset// of size 'k' that can be a vertex coverstatic boolean isCover(int V, int k, int E){ // Set has first 'k' bits high initially int set = (1 << k) - 1; int limit = (1 << V); // to mark the edges covered in each subset // of size 'k' boolean [][]vis = new boolean[maxn][maxn];; while (set < limit) { // Reset visited array for every subset // of vertices for(int i = 0; i < maxn; i++) { for(int j = 0; j < maxn; j++) { vis[i][j] = false; } } // set counter for number of edges covered // from this subset of vertices to zero int cnt = 0; // selected vertex cover is the indices // where 'set' has its bit high for (int j = 1, v = 1 ; j < limit ; j = j << 1, v++) { if ((set & j) != 0) { // Mark all edges emerging out of this // vertex visited for (int co = 1 ; co <= V ; co++) { if (gr[v][co] && !vis[v][co]) { vis[v][co] = true; vis[co][v] = true; cnt++; } } } } // If the current subset covers all the edges if (cnt == E) return true; // Generate previous combination with k bits high // set & -set = (1 << last bit high in set) int co = set & -set; int ro = set + co; set = (((ro^set) >> 2) / co) | ro; } return false;} // Returns answer to graph stored in gr[][]static int findMinCover(int n, int m){ // Binary search the answer int left = 1, right = n; while (right > left) { int mid = (left + right) >> 1; if (isCover(n, mid, m) == false) left = mid + 1; else right = mid; } // at the end of while loop both left and // right will be equal,/ as when they are // not, the while loop won't exit the minimum // size vertex cover = left = right return left;} // Inserts an edge in the graphstatic void insertEdge(int u, int v){ gr[u][v] = true; gr[v][u] = true; // Undirected graph} // Driver codepublic static void main(String[] args){ /* 6 / 1 ----- 5 vertex cover = {1, 2} /|\ 3 | \ \ | \ 2 4 */ int V = 6, E = 6; insertEdge(1, 2); insertEdge(2, 3); insertEdge(1, 3); insertEdge(1, 4); insertEdge(1, 5); insertEdge(1, 6); System.out.print("Minimum size of a vertex cover = " + findMinCover(V, E) +"\n"); // Let us create another graph for(int i = 0; i < maxn; i++) { for(int j = 0; j < maxn; j++) { gr[i][j] = false; } } /* 2 ---- 4 ---- 6 /| | 1 | | vertex cover = {2, 3, 4} \ | | 3 ---- 5 */ V = 6; E = 7; insertEdge(1, 2); insertEdge(1, 3); insertEdge(2, 3); insertEdge(2, 4); insertEdge(3, 5); insertEdge(4, 5); insertEdge(4, 6); System.out.print("Minimum size of a vertex cover = " + findMinCover(V, E) +"\n"); }} // This code is contributed by Rajput-Ji # A Python3 program to find size of minimum# vertex cover using Binary Search # Returns true if there is a possible subSet# of size 'k' that can be a vertex coverdef isCover(V, k, E): # Set has first 'k' bits high initially Set = (1 << k) - 1 limit = (1 << V) # to mark the edges covered in each # subSet of size 'k' vis = [[None] * maxn for i in range(maxn)] while (Set < limit): # ReSet visited array for every # subSet of vertices vis = [[0] * maxn for i in range(maxn)] # Set counter for number of edges covered # from this subSet of vertices to zero cnt = 0 # selected vertex cover is the # indices where 'Set' has its bit high j = 1 v = 1 while(j < limit): if (Set & j): # Mark all edges emerging out of # this vertex visited for k in range(1, V + 1): if (gr[v][k] and not vis[v][k]): vis[v][k] = 1 vis[k][v] = 1 cnt += 1 j = j << 1 v += 1 # If the current subSet covers all the edges if (cnt == E): return True # Generate previous combination with k bits high # Set & -Set = (1 << last bit high in Set) c = Set & -Set r = Set + c Set = (((r ^ Set) >> 2) // c) | r return False # Returns answer to graph stored in gr[][]def findMinCover(n, m): # Binary search the answer left = 1 right = n while (right > left): mid = (left + right) >> 1 if (isCover(n, mid, m) == False): left = mid + 1 else: right = mid # at the end of while loop both left and # right will be equal,/ as when they are # not, the while loop won't exit the # minimum size vertex cover = left = right return left # Inserts an edge in the graphdef insertEdge(u, v): gr[u][v] = 1 gr[v][u] = 1 # Undirected graph # Driver codemaxn = 25 # Global array to store the graph# Note: since the array is global, # all the elements are 0 initiallygr = [[None] * maxn for i in range(maxn)] ## 6# /# 1 ----- 5 vertex cover = {1, 2}# /|\# 3 | \# \ | \# 2 4V = 6E = 6insertEdge(1, 2)insertEdge(2, 3)insertEdge(1, 3)insertEdge(1, 4)insertEdge(1, 5)insertEdge(1, 6)print("Minimum size of a vertex cover = ", findMinCover(V, E)) # Let us create another graphgr = [[0] * maxn for i in range(maxn)] ## 2 ---- 4 ---- 6# /| |# 1 | | vertex cover = {2, 3, 4}# \ | |# 3 ---- 5V = 6E = 7insertEdge(1, 2)insertEdge(1, 3)insertEdge(2, 3)insertEdge(2, 4)insertEdge(3, 5)insertEdge(4, 5)insertEdge(4, 6)print("Minimum size of a vertex cover = ", findMinCover(V, E)) # This code is contributed by PranchalK // A C# program to find size of minimum vertex// cover using Binary Searchusing System; class GFG{ static readonly int maxn = 25; // Global array to store the graph// Note: since the array is global, all the// elements are 0 initiallystatic bool [,]gr = new bool[maxn, maxn]; // Returns true if there is a possible subset// of size 'k' that can be a vertex coverstatic bool isCover(int V, int k, int E){ // Set has first 'k' bits high initially int set = (1 << k) - 1; int limit = (1 << V); // to mark the edges covered in each subset // of size 'k' bool [,]vis = new bool[maxn, maxn];; while (set < limit) { // Reset visited array for every subset // of vertices for(int i = 0; i < maxn; i++) { for(int j = 0; j < maxn; j++) { vis[i, j] = false; } } // set counter for number of edges covered // from this subset of vertices to zero int cnt = 0; // selected vertex cover is the indices // where 'set' has its bit high for (int j = 1, v = 1 ; j < limit ; j = j << 1, v++) { if ((set & j) != 0) { // Mark all edges emerging out of this // vertex visited for (int co = 1 ; co <= V ; co++) { if (gr[v, co] && !vis[v, co]) { vis[v, co] = true; vis[co, v] = true; cnt++; } } } } // If the current subset covers all the edges if (cnt == E) return true; // Generate previous combination with k bits high // set & -set = (1 << last bit high in set) int cO = set & -set; int rO = set + cO; set = (((rO^set) >> 2) / cO) | rO; } return false;} // Returns answer to graph stored in gr[,]static int findMinCover(int n, int m){ // Binary search the answer int left = 1, right = n; while (right > left) { int mid = (left + right) >> 1; if (isCover(n, mid, m) == false) left = mid + 1; else right = mid; } // at the end of while loop both left and // right will be equal,/ as when they are // not, the while loop won't exit the minimum // size vertex cover = left = right return left;} // Inserts an edge in the graphstatic void insertEdge(int u, int v){ gr[u, v] = true; gr[v, u] = true; // Undirected graph} // Driver codepublic static void Main(String[] args){ /* 6 / 1 ----- 5 vertex cover = {1, 2} /|\ 3 | \ \ | \ 2 4 */ int V = 6, E = 6; insertEdge(1, 2); insertEdge(2, 3); insertEdge(1, 3); insertEdge(1, 4); insertEdge(1, 5); insertEdge(1, 6); Console.Write("Minimum size of a vertex cover = " + findMinCover(V, E) +"\n"); // Let us create another graph for(int i = 0; i < maxn; i++) { for(int j = 0; j < maxn; j++) { gr[i,j] = false; } } /* 2 ---- 4 ---- 6 /| | 1 | | vertex cover = {2, 3, 4} \ | | 3 ---- 5 */ V = 6; E = 7; insertEdge(1, 2); insertEdge(1, 3); insertEdge(2, 3); insertEdge(2, 4); insertEdge(3, 5); insertEdge(4, 5); insertEdge(4, 6); Console.Write("Minimum size of a vertex cover = " + findMinCover(V, E) +"\n"); }} // This code is contributed by Rajput-Ji Minimum size of a vertex cover = 2 Minimum size of a vertex cover = 3 Conclusion: Time Complexity : O (E * ( VCV/2 + VCV/4 + VCV/8 +...upto VCk ) ) These terms are not more than log(V) in worst case. Note: Gosper’s hack works for upto V = 31 only, if we take ‘long long int’ instead of ‘int’ it can work upto V = 63. This article is contributed by Saumye Malhotra . 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. PranchalKatiyar Akanksha_Rai Rajput-Ji hardikkoriintern Binary Search Graph Graph Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Topological Sorting Find if there is a path between two vertices in a directed graph Detect Cycle in a Directed Graph Introduction to Data Structures Floyd Warshall Algorithm | DP-16 Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) What is Data Structure: Types, Classifications and Applications Bellman–Ford Algorithm | DP-23 Find if there is a path between two vertices in an undirected graph Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jul, 2022" }, { "code": null, "e": 263, "s": 54, "text": "A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either ‘u’ or ‘v’ is in vertex cover. There may be a lot of vertex covers possible for a graph. " }, { "code": null, "e": 448, "s": 263, "text": "Problem Find the size of the minimum size vertex cover, that is, cardinality of a vertex cover with minimum cardinality, for an undirected connected graph with V vertices and m edges. " }, { "code": null, "e": 458, "s": 448, "text": "Examples:" }, { "code": null, "e": 1129, "s": 458, "text": "Input: V = 6, E = 6\n 6\n /\n /\n 1 -----5\n /|\\\n 3 | \\\n \\ | \\\n 2 4\nOutput: Minimum vertex cover size = 2\nConsider subset of vertices {1, 2}, every edge \nin above graph is either incident on vertex 1 \nor 2. Hence the minimum vertex cover = {1, 2}, \nthe size of which is 2.\n\nInput: V = 6, E = 7\n 2 ---- 4 ---- 6\n /| |\n 1 | |\n \\| |\n 3 ---- 5\nOutput: Minimum vertex cover size = 3\nConsider subset of vertices {2, 3, 4}, every\nedge in above graph is either incident on \nvertex 2, 3 or 4. Hence the minimum size of\na vertex cover can be 3." }, { "code": null, "e": 1263, "s": 1129, "text": "Method 1 (Naive) We can check in O(E + V) time if a given subset of vertices is a vertex cover or not, using the following algorithm." }, { "code": null, "e": 1665, "s": 1263, "text": "Generate all 2V subsets of vertices in graph and\ndo following for every subset.\n 1. edges_covered = 0\n 2. for each vertex in current subset\n 3. for all edges emerging out of current vertex\n 4. if the edge is not already marked visited\n 5. mark the edge visited\n 6. edges_covered++\n 7. if edges_covered is equal to total number edges\n 8. return size of current subset" }, { "code": null, "e": 1738, "s": 1665, "text": "An upper bound on time complexity of this solution is O((E + V) * 2V) " }, { "code": null, "e": 2460, "s": 1738, "text": "Method 2 (Binary Search) If we generate 2V subsets first by generating VCV subsets, then VC(V-1) subsets, and so on upto VC0 subsets(2V = VCV + VC(V-1) + ... + VC1 + VC0). Our objective is now to find the minimum k such that at least one subset of size ‘k’ amongst VCk subsets is a vertex cover [ We know that if minimum size vertex cover is of size k, then there will exist a vertex cover of all sizes more than k. That is, there will be a vertex cover of size k + 1, k + 2, k + 3, ..., n. ] Now let’s imagine a boolean array of size n and call it isCover[]. So if the answer of the question; “Does a vertex cover of size x exist?” is yes, we put a ‘1’ at xth position, otherwise ‘0’. The array isCover[] will look like:" }, { "code": null, "e": 2867, "s": 2460, "text": "The array is sorted and hence binary searchable, as no index before k will have a ‘1’, and every index after k(inclusive) will have a ‘1’, so k is the answer. So we can apply Binary Search to find the minimum size vertex set that covers all edges (this problem is equivalent to finding last 1 in isCover[]). Now the problem is how to generate all subsets of a given size. The idea is to use Gosper’s hack. " }, { "code": null, "e": 3148, "s": 2867, "text": "What is Gosper’s Hack? Gosper’s hack is a technique to get the next number with same number of bits set. So we set the first x bits from right and generate next number with x bits set until the number is less than 2V. In this way, we can generate all VCx numbers with x bits set. " }, { "code": null, "e": 3152, "s": 3148, "text": "CPP" }, { "code": "int set = (1 << k) - 1;int limit = (1 << V);while (set < limit){ // Do your stuff with current set doStuff(set); // Gosper's hack: int c = set & -set; int r = set + c; set = (((r^set) >>> 2) / c) | r;}", "e": 3373, "s": 3152, "text": null }, { "code": null, "e": 3547, "s": 3373, "text": "Source : StackExchange We use gosper’s hack to generate all subsets of size x(0 < x <= V), that is, to check whether we have a ‘1’ or ‘0’ at any index x in isCover[] array. " }, { "code": null, "e": 3551, "s": 3547, "text": "C++" }, { "code": null, "e": 3556, "s": 3551, "text": "Java" }, { "code": null, "e": 3564, "s": 3556, "text": "Python3" }, { "code": null, "e": 3567, "s": 3564, "text": "C#" }, { "code": "// A C++ program to find size of minimum vertex// cover using Binary Search#include<bits/stdc++.h>#define maxn 25 using namespace std; // Global array to store the graph// Note: since the array is global, all the// elements are 0 initiallybool gr[maxn][maxn]; // Returns true if there is a possible subset// of size 'k' that can be a vertex coverbool isCover(int V, int k, int E){ // Set has first 'k' bits high initially int set = (1 << k) - 1; int limit = (1 << V); // to mark the edges covered in each subset // of size 'k' bool vis[maxn][maxn]; while (set < limit) { // Reset visited array for every subset // of vertices memset(vis, 0, sizeof vis); // set counter for number of edges covered // from this subset of vertices to zero int cnt = 0; // selected vertex cover is the indices // where 'set' has its bit high for (int j = 1, v = 1 ; j < limit ; j = j << 1, v++) { if (set & j) { // Mark all edges emerging out of this // vertex visited for (int k = 1 ; k <= V ; k++) { if (gr[v][k] && !vis[v][k]) { vis[v][k] = 1; vis[k][v] = 1; cnt++; } } } } // If the current subset covers all the edges if (cnt == E) return true; // Generate previous combination with k bits high // set & -set = (1 << last bit high in set) int c = set & -set; int r = set + c; set = (((r^set) >> 2) / c) | r; } return false;} // Returns answer to graph stored in gr[][]int findMinCover(int n, int m){ // Binary search the answer int left = 1, right = n; while (right > left) { int mid = (left + right) >> 1; if (isCover(n, mid, m) == false) left = mid + 1; else right = mid; } // at the end of while loop both left and // right will be equal,/ as when they are // not, the while loop won't exit the minimum // size vertex cover = left = right return left;} // Inserts an edge in the graphvoid insertEdge(int u, int v){ gr[u][v] = 1; gr[v][u] = 1; // Undirected graph} // Driver codeint main(){ /* 6 / 1 ----- 5 vertex cover = {1, 2} /|\\ 3 | \\ \\ | \\ 2 4 */ int V = 6, E = 6; insertEdge(1, 2); insertEdge(2, 3); insertEdge(1, 3); insertEdge(1, 4); insertEdge(1, 5); insertEdge(1, 6); cout << \"Minimum size of a vertex cover = \" << findMinCover(V, E) << endl; // Let us create another graph memset(gr, 0, sizeof gr); /* 2 ---- 4 ---- 6 /| | 1 | | vertex cover = {2, 3, 4} \\ | | 3 ---- 5 */ V = 6, E = 7; insertEdge(1, 2); insertEdge(1, 3); insertEdge(2, 3); insertEdge(2, 4); insertEdge(3, 5); insertEdge(4, 5); insertEdge(4, 6); cout << \"Minimum size of a vertex cover = \" << findMinCover(V, E) << endl; return 0;}", "e": 6772, "s": 3567, "text": null }, { "code": "// A Java program to find size of minimum vertex// cover using Binary Searchclass GFG{ static final int maxn = 25; // Global array to store the graph// Note: since the array is global, all the// elements are 0 initiallystatic boolean [][]gr = new boolean[maxn][maxn]; // Returns true if there is a possible subset// of size 'k' that can be a vertex coverstatic boolean isCover(int V, int k, int E){ // Set has first 'k' bits high initially int set = (1 << k) - 1; int limit = (1 << V); // to mark the edges covered in each subset // of size 'k' boolean [][]vis = new boolean[maxn][maxn];; while (set < limit) { // Reset visited array for every subset // of vertices for(int i = 0; i < maxn; i++) { for(int j = 0; j < maxn; j++) { vis[i][j] = false; } } // set counter for number of edges covered // from this subset of vertices to zero int cnt = 0; // selected vertex cover is the indices // where 'set' has its bit high for (int j = 1, v = 1 ; j < limit ; j = j << 1, v++) { if ((set & j) != 0) { // Mark all edges emerging out of this // vertex visited for (int co = 1 ; co <= V ; co++) { if (gr[v][co] && !vis[v][co]) { vis[v][co] = true; vis[co][v] = true; cnt++; } } } } // If the current subset covers all the edges if (cnt == E) return true; // Generate previous combination with k bits high // set & -set = (1 << last bit high in set) int co = set & -set; int ro = set + co; set = (((ro^set) >> 2) / co) | ro; } return false;} // Returns answer to graph stored in gr[][]static int findMinCover(int n, int m){ // Binary search the answer int left = 1, right = n; while (right > left) { int mid = (left + right) >> 1; if (isCover(n, mid, m) == false) left = mid + 1; else right = mid; } // at the end of while loop both left and // right will be equal,/ as when they are // not, the while loop won't exit the minimum // size vertex cover = left = right return left;} // Inserts an edge in the graphstatic void insertEdge(int u, int v){ gr[u][v] = true; gr[v][u] = true; // Undirected graph} // Driver codepublic static void main(String[] args){ /* 6 / 1 ----- 5 vertex cover = {1, 2} /|\\ 3 | \\ \\ | \\ 2 4 */ int V = 6, E = 6; insertEdge(1, 2); insertEdge(2, 3); insertEdge(1, 3); insertEdge(1, 4); insertEdge(1, 5); insertEdge(1, 6); System.out.print(\"Minimum size of a vertex cover = \" + findMinCover(V, E) +\"\\n\"); // Let us create another graph for(int i = 0; i < maxn; i++) { for(int j = 0; j < maxn; j++) { gr[i][j] = false; } } /* 2 ---- 4 ---- 6 /| | 1 | | vertex cover = {2, 3, 4} \\ | | 3 ---- 5 */ V = 6; E = 7; insertEdge(1, 2); insertEdge(1, 3); insertEdge(2, 3); insertEdge(2, 4); insertEdge(3, 5); insertEdge(4, 5); insertEdge(4, 6); System.out.print(\"Minimum size of a vertex cover = \" + findMinCover(V, E) +\"\\n\"); }} // This code is contributed by Rajput-Ji", "e": 10319, "s": 6772, "text": null }, { "code": "# A Python3 program to find size of minimum# vertex cover using Binary Search # Returns true if there is a possible subSet# of size 'k' that can be a vertex coverdef isCover(V, k, E): # Set has first 'k' bits high initially Set = (1 << k) - 1 limit = (1 << V) # to mark the edges covered in each # subSet of size 'k' vis = [[None] * maxn for i in range(maxn)] while (Set < limit): # ReSet visited array for every # subSet of vertices vis = [[0] * maxn for i in range(maxn)] # Set counter for number of edges covered # from this subSet of vertices to zero cnt = 0 # selected vertex cover is the # indices where 'Set' has its bit high j = 1 v = 1 while(j < limit): if (Set & j): # Mark all edges emerging out of # this vertex visited for k in range(1, V + 1): if (gr[v][k] and not vis[v][k]): vis[v][k] = 1 vis[k][v] = 1 cnt += 1 j = j << 1 v += 1 # If the current subSet covers all the edges if (cnt == E): return True # Generate previous combination with k bits high # Set & -Set = (1 << last bit high in Set) c = Set & -Set r = Set + c Set = (((r ^ Set) >> 2) // c) | r return False # Returns answer to graph stored in gr[][]def findMinCover(n, m): # Binary search the answer left = 1 right = n while (right > left): mid = (left + right) >> 1 if (isCover(n, mid, m) == False): left = mid + 1 else: right = mid # at the end of while loop both left and # right will be equal,/ as when they are # not, the while loop won't exit the # minimum size vertex cover = left = right return left # Inserts an edge in the graphdef insertEdge(u, v): gr[u][v] = 1 gr[v][u] = 1 # Undirected graph # Driver codemaxn = 25 # Global array to store the graph# Note: since the array is global, # all the elements are 0 initiallygr = [[None] * maxn for i in range(maxn)] ## 6# /# 1 ----- 5 vertex cover = {1, 2}# /|\\# 3 | \\# \\ | \\# 2 4V = 6E = 6insertEdge(1, 2)insertEdge(2, 3)insertEdge(1, 3)insertEdge(1, 4)insertEdge(1, 5)insertEdge(1, 6)print(\"Minimum size of a vertex cover = \", findMinCover(V, E)) # Let us create another graphgr = [[0] * maxn for i in range(maxn)] ## 2 ---- 4 ---- 6# /| |# 1 | | vertex cover = {2, 3, 4}# \\ | |# 3 ---- 5V = 6E = 7insertEdge(1, 2)insertEdge(1, 3)insertEdge(2, 3)insertEdge(2, 4)insertEdge(3, 5)insertEdge(4, 5)insertEdge(4, 6)print(\"Minimum size of a vertex cover = \", findMinCover(V, E)) # This code is contributed by PranchalK", "e": 13207, "s": 10319, "text": null }, { "code": "// A C# program to find size of minimum vertex// cover using Binary Searchusing System; class GFG{ static readonly int maxn = 25; // Global array to store the graph// Note: since the array is global, all the// elements are 0 initiallystatic bool [,]gr = new bool[maxn, maxn]; // Returns true if there is a possible subset// of size 'k' that can be a vertex coverstatic bool isCover(int V, int k, int E){ // Set has first 'k' bits high initially int set = (1 << k) - 1; int limit = (1 << V); // to mark the edges covered in each subset // of size 'k' bool [,]vis = new bool[maxn, maxn];; while (set < limit) { // Reset visited array for every subset // of vertices for(int i = 0; i < maxn; i++) { for(int j = 0; j < maxn; j++) { vis[i, j] = false; } } // set counter for number of edges covered // from this subset of vertices to zero int cnt = 0; // selected vertex cover is the indices // where 'set' has its bit high for (int j = 1, v = 1 ; j < limit ; j = j << 1, v++) { if ((set & j) != 0) { // Mark all edges emerging out of this // vertex visited for (int co = 1 ; co <= V ; co++) { if (gr[v, co] && !vis[v, co]) { vis[v, co] = true; vis[co, v] = true; cnt++; } } } } // If the current subset covers all the edges if (cnt == E) return true; // Generate previous combination with k bits high // set & -set = (1 << last bit high in set) int cO = set & -set; int rO = set + cO; set = (((rO^set) >> 2) / cO) | rO; } return false;} // Returns answer to graph stored in gr[,]static int findMinCover(int n, int m){ // Binary search the answer int left = 1, right = n; while (right > left) { int mid = (left + right) >> 1; if (isCover(n, mid, m) == false) left = mid + 1; else right = mid; } // at the end of while loop both left and // right will be equal,/ as when they are // not, the while loop won't exit the minimum // size vertex cover = left = right return left;} // Inserts an edge in the graphstatic void insertEdge(int u, int v){ gr[u, v] = true; gr[v, u] = true; // Undirected graph} // Driver codepublic static void Main(String[] args){ /* 6 / 1 ----- 5 vertex cover = {1, 2} /|\\ 3 | \\ \\ | \\ 2 4 */ int V = 6, E = 6; insertEdge(1, 2); insertEdge(2, 3); insertEdge(1, 3); insertEdge(1, 4); insertEdge(1, 5); insertEdge(1, 6); Console.Write(\"Minimum size of a vertex cover = \" + findMinCover(V, E) +\"\\n\"); // Let us create another graph for(int i = 0; i < maxn; i++) { for(int j = 0; j < maxn; j++) { gr[i,j] = false; } } /* 2 ---- 4 ---- 6 /| | 1 | | vertex cover = {2, 3, 4} \\ | | 3 ---- 5 */ V = 6; E = 7; insertEdge(1, 2); insertEdge(1, 3); insertEdge(2, 3); insertEdge(2, 4); insertEdge(3, 5); insertEdge(4, 5); insertEdge(4, 6); Console.Write(\"Minimum size of a vertex cover = \" + findMinCover(V, E) +\"\\n\"); }} // This code is contributed by Rajput-Ji", "e": 16753, "s": 13207, "text": null }, { "code": null, "e": 16823, "s": 16753, "text": "Minimum size of a vertex cover = 2\nMinimum size of a vertex cover = 3" }, { "code": null, "e": 16954, "s": 16823, "text": "Conclusion: Time Complexity : O (E * ( VCV/2 + VCV/4 + VCV/8 +...upto VCk ) ) These terms are not more than log(V) in worst case. " }, { "code": null, "e": 17120, "s": 16954, "text": "Note: Gosper’s hack works for upto V = 31 only, if we take ‘long long int’ instead of ‘int’ it can work upto V = 63. This article is contributed by Saumye Malhotra ." }, { "code": null, "e": 17371, "s": 17120, "text": "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." }, { "code": null, "e": 17387, "s": 17371, "text": "PranchalKatiyar" }, { "code": null, "e": 17400, "s": 17387, "text": "Akanksha_Rai" }, { "code": null, "e": 17410, "s": 17400, "text": "Rajput-Ji" }, { "code": null, "e": 17427, "s": 17410, "text": "hardikkoriintern" }, { "code": null, "e": 17441, "s": 17427, "text": "Binary Search" }, { "code": null, "e": 17447, "s": 17441, "text": "Graph" }, { "code": null, "e": 17453, "s": 17447, "text": "Graph" }, { "code": null, "e": 17467, "s": 17453, "text": "Binary Search" }, { "code": null, "e": 17565, "s": 17467, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 17585, "s": 17565, "text": "Topological Sorting" }, { "code": null, "e": 17650, "s": 17585, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 17683, "s": 17650, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 17715, "s": 17683, "text": "Introduction to Data Structures" }, { "code": null, "e": 17748, "s": 17715, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 17823, "s": 17748, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 17887, "s": 17823, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 17918, "s": 17887, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 17986, "s": 17918, "text": "Find if there is a path between two vertices in an undirected graph" } ]
Program to calculate Surface Area of Ellipsoid
17 Aug, 2021 Given the length of the three semi-axes as A, B, and C, the task is to find the surface area of the given Ellipsoid. Ellipsoid is a closed surface of which all plane cross-sections are either ellipses or circles. An ellipsoid is symmetrical about the three mutually perpendicular axes that intersect at the center. It is a three-dimensional, closed geometric shape, all planar sections of which are ellipses or circles. An ellipsoid has three independent axes, and is usually specified by the lengths a, b, c of the three semi-axes. If an ellipsoid is made by rotating an ellipse about one of its axes, then two axes of the ellipsoid are the same, and it is called an ellipsoid of revolution, or spheroid. If the lengths of all three of its axes are the same, it is a sphere. Examples: Input: A = 1, B = 1, C = 1Output: 12.57 Input: A = 11, B = 12, C = 13Output: 1807.89 Approach: The given problem can be solved by using the formula for Surface Area of the Ellipsoid as: Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <iomanip>#include <iostream>#include <math.h>using namespace std; // Function to find the surface area of// the given Ellipsoidvoid findArea(double a, double b, double c){ // Formula to find surface area // of an Ellipsoid double area = 4 * 3.141592653 * pow((pow(a * b, 1.6) + pow(a * c, 1.6) + pow(b * c, 1.6)) / 3, 1 / 1.6); // Print the area cout << fixed << setprecision(2) << area;} // Driver Codeint main(){ double A = 11, B = 12, C = 13; findArea(A, B, C); return 0;} // Java program of the above approachimport java.util.*; class GFG{ // Function to find the surface area of// the given Ellipsoidstatic void findArea(double a, double b, double c){ // Formula to find surface area // of an Ellipsoid double area = 4 * 3.141592653 * Math.pow((Math.pow(a * b, 1.6) + Math.pow(a * c, 1.6) + Math.pow(b * c, 1.6)) / 3, 1 / 1.6); // Print the area System.out.print(String.format("%.2f", area));} // Driver Codepublic static void main(String[] args){ double A = 11, B = 12, C = 13; findArea(A, B, C);}} // This code is contributed by code_hunt # Python3 program for the above approachfrom math import pow # Function to find the surface area of# the given Ellipsoiddef findArea(a, b, c): # Formula to find surface area # of an Ellipsoid area = (4 * 3.141592653 * pow((pow(a * b, 1.6) + pow(a * c, 1.6) + pow(b * c, 1.6)) / 3, 1 / 1.6)) # Print the area print("{:.2f}".format(round(area, 2))) # Driver Codeif __name__ == '__main__': A = 11 B = 12 C = 13 findArea(A, B, C) # This code is contributed by SURENDRA_GANGWAR // C# program of the above approachusing System; class GFG{ // Function to find the surface area of// the given Ellipsoidstatic void findArea(double a, double b, double c){ // Formula to find surface area // of an Ellipsoid double area = 4 * 3.141592653 * Math.Pow((Math.Pow(a * b, 1.6) + Math.Pow(a * c, 1.6) + Math.Pow(b * c, 1.6)) / 3, 1 / 1.6); // Print the area Console.Write(Math.Round(area, 2));} // Driver Codepublic static void Main(String[] args){ double A = 11, B = 12, C = 13; findArea(A, B, C);}} // This code is contributed by shivanisinghss2110 <script> // JavaScript Program to implement // the above approach // Function to find the surface area of // the given Ellipsoid function findArea(a, b, c) { // Formula to find surface area // of an Ellipsoid let area = 4 * 3.141592653 * Math.pow((Math.pow(a * b, 1.6) + Math.pow(a * c, 1.6) + Math.pow(b * c, 1.6)) / 3, 1 / 1.6); // Print the area document.write(area.toPrecision(6)); } // Driver Code let A = 11, B = 12, C = 13; findArea(A, B, C); // This code is contributed by Potta Lokesh </script> 1807.89 Time Complexity: O(1)Auxiliary Space: O(1) SURENDRA_GANGWAR lokeshpotta20 code_hunt shivanisinghss2110 area-volume-programs Mensuration 3D Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum Manhattan distance between a distinct pair from N coordinates Total area of two overlapping rectangles Largest area possible after removal of a series of horizontal & vertical bars Program to find line passing through 2 Points Orientation of 3 ordered points Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Aug, 2021" }, { "code": null, "e": 145, "s": 28, "text": "Given the length of the three semi-axes as A, B, and C, the task is to find the surface area of the given Ellipsoid." }, { "code": null, "e": 448, "s": 145, "text": "Ellipsoid is a closed surface of which all plane cross-sections are either ellipses or circles. An ellipsoid is symmetrical about the three mutually perpendicular axes that intersect at the center. It is a three-dimensional, closed geometric shape, all planar sections of which are ellipses or circles." }, { "code": null, "e": 804, "s": 448, "text": "An ellipsoid has three independent axes, and is usually specified by the lengths a, b, c of the three semi-axes. If an ellipsoid is made by rotating an ellipse about one of its axes, then two axes of the ellipsoid are the same, and it is called an ellipsoid of revolution, or spheroid. If the lengths of all three of its axes are the same, it is a sphere." }, { "code": null, "e": 814, "s": 804, "text": "Examples:" }, { "code": null, "e": 854, "s": 814, "text": "Input: A = 1, B = 1, C = 1Output: 12.57" }, { "code": null, "e": 899, "s": 854, "text": "Input: A = 11, B = 12, C = 13Output: 1807.89" }, { "code": null, "e": 1000, "s": 899, "text": "Approach: The given problem can be solved by using the formula for Surface Area of the Ellipsoid as:" }, { "code": null, "e": 1051, "s": 1000, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1055, "s": 1051, "text": "C++" }, { "code": null, "e": 1060, "s": 1055, "text": "Java" }, { "code": null, "e": 1068, "s": 1060, "text": "Python3" }, { "code": null, "e": 1071, "s": 1068, "text": "C#" }, { "code": null, "e": 1082, "s": 1071, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <iomanip>#include <iostream>#include <math.h>using namespace std; // Function to find the surface area of// the given Ellipsoidvoid findArea(double a, double b, double c){ // Formula to find surface area // of an Ellipsoid double area = 4 * 3.141592653 * pow((pow(a * b, 1.6) + pow(a * c, 1.6) + pow(b * c, 1.6)) / 3, 1 / 1.6); // Print the area cout << fixed << setprecision(2) << area;} // Driver Codeint main(){ double A = 11, B = 12, C = 13; findArea(A, B, C); return 0;}", "e": 1731, "s": 1082, "text": null }, { "code": "// Java program of the above approachimport java.util.*; class GFG{ // Function to find the surface area of// the given Ellipsoidstatic void findArea(double a, double b, double c){ // Formula to find surface area // of an Ellipsoid double area = 4 * 3.141592653 * Math.pow((Math.pow(a * b, 1.6) + Math.pow(a * c, 1.6) + Math.pow(b * c, 1.6)) / 3, 1 / 1.6); // Print the area System.out.print(String.format(\"%.2f\", area));} // Driver Codepublic static void main(String[] args){ double A = 11, B = 12, C = 13; findArea(A, B, C);}} // This code is contributed by code_hunt", "e": 2383, "s": 1731, "text": null }, { "code": "# Python3 program for the above approachfrom math import pow # Function to find the surface area of# the given Ellipsoiddef findArea(a, b, c): # Formula to find surface area # of an Ellipsoid area = (4 * 3.141592653 * pow((pow(a * b, 1.6) + pow(a * c, 1.6) + pow(b * c, 1.6)) / 3, 1 / 1.6)) # Print the area print(\"{:.2f}\".format(round(area, 2))) # Driver Codeif __name__ == '__main__': A = 11 B = 12 C = 13 findArea(A, B, C) # This code is contributed by SURENDRA_GANGWAR", "e": 2914, "s": 2383, "text": null }, { "code": "// C# program of the above approachusing System; class GFG{ // Function to find the surface area of// the given Ellipsoidstatic void findArea(double a, double b, double c){ // Formula to find surface area // of an Ellipsoid double area = 4 * 3.141592653 * Math.Pow((Math.Pow(a * b, 1.6) + Math.Pow(a * c, 1.6) + Math.Pow(b * c, 1.6)) / 3, 1 / 1.6); // Print the area Console.Write(Math.Round(area, 2));} // Driver Codepublic static void Main(String[] args){ double A = 11, B = 12, C = 13; findArea(A, B, C);}} // This code is contributed by shivanisinghss2110", "e": 3556, "s": 2914, "text": null }, { "code": "<script> // JavaScript Program to implement // the above approach // Function to find the surface area of // the given Ellipsoid function findArea(a, b, c) { // Formula to find surface area // of an Ellipsoid let area = 4 * 3.141592653 * Math.pow((Math.pow(a * b, 1.6) + Math.pow(a * c, 1.6) + Math.pow(b * c, 1.6)) / 3, 1 / 1.6); // Print the area document.write(area.toPrecision(6)); } // Driver Code let A = 11, B = 12, C = 13; findArea(A, B, C); // This code is contributed by Potta Lokesh </script>", "e": 4257, "s": 3556, "text": null }, { "code": null, "e": 4265, "s": 4257, "text": "1807.89" }, { "code": null, "e": 4310, "s": 4267, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 4327, "s": 4310, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 4341, "s": 4327, "text": "lokeshpotta20" }, { "code": null, "e": 4351, "s": 4341, "text": "code_hunt" }, { "code": null, "e": 4370, "s": 4351, "text": "shivanisinghss2110" }, { "code": null, "e": 4391, "s": 4370, "text": "area-volume-programs" }, { "code": null, "e": 4406, "s": 4391, "text": "Mensuration 3D" }, { "code": null, "e": 4416, "s": 4406, "text": "Geometric" }, { "code": null, "e": 4429, "s": 4416, "text": "Mathematical" }, { "code": null, "e": 4442, "s": 4429, "text": "Mathematical" }, { "code": null, "e": 4452, "s": 4442, "text": "Geometric" }, { "code": null, "e": 4550, "s": 4452, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4620, "s": 4550, "text": "Maximum Manhattan distance between a distinct pair from N coordinates" }, { "code": null, "e": 4661, "s": 4620, "text": "Total area of two overlapping rectangles" }, { "code": null, "e": 4739, "s": 4661, "text": "Largest area possible after removal of a series of horizontal & vertical bars" }, { "code": null, "e": 4785, "s": 4739, "text": "Program to find line passing through 2 Points" }, { "code": null, "e": 4817, "s": 4785, "text": "Orientation of 3 ordered points" }, { "code": null, "e": 4847, "s": 4817, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 4890, "s": 4847, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 4950, "s": 4890, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 4965, "s": 4950, "text": "C++ Data Types" } ]
ReactJS UI Ant Design Form Component
30 Jun, 2021 Ant Design Library has this component pre-built, and it is very easy to integrate as well. Form Component is used when the user needs to create an instance or collect information. We can use the following approach in ReactJS to use the Ant Design Form Component. Form Props: colon: It is used to configure the default value of colon for Form.Item. component: It is used to set the Form rendering element. fields: It is used to denote the control of form fields through state management. form: It is used to denote the form control instance created by Form.useForm(). initialValues: It is used to set value by Form initialization or reset. labelAlign: It is used to denote the text-align of the label of all items. labelCol: It is used to denote the Label layout, like <Col> component. layout: It is used to denote the form layout. name: It is used to denote the Form name. preserve: It is used to keep field value even when the field removed. requiredMark: It is used for the Required mark style. scrollToFirstError: It is used for the Auto scroll to the first failed field when submitting. size: It is used to set field component size. validateMessages: It is used for the Validation prompt template. validateTrigger: It is used to denote the config field validate trigger. wrapperCol: It is used to denote the layout for input controls. onFieldsChange: It is a callback function that is triggered when the field updated. onFinish: It is a callback function that is triggered after submitting the form and verifying data successfully. onFinishFailed: It is a callback function that is triggered after submitting the form and verifying data failed. onValuesChange: It is a callback function that is triggered when the value updated. Form.Item Props: colon: It is used with label, whether to display color(:) after label text. dependencies: It is used to Set the dependency field. extra: It is used to denote the extra prompt message. getValueFromEvent: It is used to specify how to get value from the event or other onChange arguments. getValueProps: It is used to get the Additional props with subcomponent. hasFeedback: It is used with validate status and this option specifies the validation status icon. help: It is used to denote the prompt message. hidden: It is used to indicate whether to hide Form.Item or not. htmlFor: It is used to set sub-label htmlFor. initialValue: It is used to configure sub default value. label: It is used to denote the Label text. labelAlign: It is used to denote the text-align of the label. labelCol: It is used to denote the layout of the label. messageVariables: It is used to denote the default validate field info. name: It is used to denote the name. normalize: It is used to normalize value from the component value before passing to the Form instance. noStyle: It is used as a pure field control. preserve: It is used to keep field value even when the field removed. required: It is used to display the required style. and it is generated by the validation rule. rules: It is used to denote the rules for field validation. shouldUpdate: It is used for the custom field update logic. tooltip: It is used to configure tooltip info. trigger: It is used to indicate when to collect the value of the children node. validateFirst: It is used to indicate whether to stop validate on the first rule of error for this field. validateStatus: It is used to denote the validation status. validateTrigger: It is used to indicate when to validate the value of the children node. valuePropName: It is used to denote the props of the children node. wrapperCol: It is used to denote the layout for input controls. Form.List Props: children: It is a render function. initialValue: It is used to denote a config sub default value. name: It is used to denote the field name. rules: It is used for the validation rules. Form.ErrorList Props: errors: It is used to denote the error list. Form.Provider Props: onFormChange: It is a callback function that is triggered when a subform field updates function. onFormFinish: It is a callback function that is triggered when a subform submits. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd Step 3: After creating the ReactJS application, Install the required module using the following command: npm install antd Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react'import "antd/dist/antd.css";import { Form, Button, Input } from 'antd'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Form Component</h4> <Form name="basicform" onFinishFailed={() => alert('Failed to submit')} onFinish={() => alert('Form Submitted')} initialValues={{ remember: true }} > <Form.Item label="Enter username" name="Username" rules={[{ required: true, message: 'Please enter username' }]} > <Input /> </Form.Item> <Form.Item> <Button type="success" htmlType="submit"> Submit Username </Button> </Form.Item> </Form> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://ant.design/components/form/ ReactJS-Ant Design JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2021" }, { "code": null, "e": 291, "s": 28, "text": "Ant Design Library has this component pre-built, and it is very easy to integrate as well. Form Component is used when the user needs to create an instance or collect information. We can use the following approach in ReactJS to use the Ant Design Form Component." }, { "code": null, "e": 303, "s": 291, "text": "Form Props:" }, { "code": null, "e": 376, "s": 303, "text": "colon: It is used to configure the default value of colon for Form.Item." }, { "code": null, "e": 433, "s": 376, "text": "component: It is used to set the Form rendering element." }, { "code": null, "e": 515, "s": 433, "text": "fields: It is used to denote the control of form fields through state management." }, { "code": null, "e": 595, "s": 515, "text": "form: It is used to denote the form control instance created by Form.useForm()." }, { "code": null, "e": 667, "s": 595, "text": "initialValues: It is used to set value by Form initialization or reset." }, { "code": null, "e": 742, "s": 667, "text": "labelAlign: It is used to denote the text-align of the label of all items." }, { "code": null, "e": 813, "s": 742, "text": "labelCol: It is used to denote the Label layout, like <Col> component." }, { "code": null, "e": 859, "s": 813, "text": "layout: It is used to denote the form layout." }, { "code": null, "e": 901, "s": 859, "text": "name: It is used to denote the Form name." }, { "code": null, "e": 971, "s": 901, "text": "preserve: It is used to keep field value even when the field removed." }, { "code": null, "e": 1025, "s": 971, "text": "requiredMark: It is used for the Required mark style." }, { "code": null, "e": 1119, "s": 1025, "text": "scrollToFirstError: It is used for the Auto scroll to the first failed field when submitting." }, { "code": null, "e": 1165, "s": 1119, "text": "size: It is used to set field component size." }, { "code": null, "e": 1230, "s": 1165, "text": "validateMessages: It is used for the Validation prompt template." }, { "code": null, "e": 1303, "s": 1230, "text": "validateTrigger: It is used to denote the config field validate trigger." }, { "code": null, "e": 1367, "s": 1303, "text": "wrapperCol: It is used to denote the layout for input controls." }, { "code": null, "e": 1451, "s": 1367, "text": "onFieldsChange: It is a callback function that is triggered when the field updated." }, { "code": null, "e": 1564, "s": 1451, "text": "onFinish: It is a callback function that is triggered after submitting the form and verifying data successfully." }, { "code": null, "e": 1677, "s": 1564, "text": "onFinishFailed: It is a callback function that is triggered after submitting the form and verifying data failed." }, { "code": null, "e": 1761, "s": 1677, "text": "onValuesChange: It is a callback function that is triggered when the value updated." }, { "code": null, "e": 1778, "s": 1761, "text": "Form.Item Props:" }, { "code": null, "e": 1854, "s": 1778, "text": "colon: It is used with label, whether to display color(:) after label text." }, { "code": null, "e": 1908, "s": 1854, "text": "dependencies: It is used to Set the dependency field." }, { "code": null, "e": 1962, "s": 1908, "text": "extra: It is used to denote the extra prompt message." }, { "code": null, "e": 2064, "s": 1962, "text": "getValueFromEvent: It is used to specify how to get value from the event or other onChange arguments." }, { "code": null, "e": 2137, "s": 2064, "text": "getValueProps: It is used to get the Additional props with subcomponent." }, { "code": null, "e": 2236, "s": 2137, "text": "hasFeedback: It is used with validate status and this option specifies the validation status icon." }, { "code": null, "e": 2283, "s": 2236, "text": "help: It is used to denote the prompt message." }, { "code": null, "e": 2348, "s": 2283, "text": "hidden: It is used to indicate whether to hide Form.Item or not." }, { "code": null, "e": 2394, "s": 2348, "text": "htmlFor: It is used to set sub-label htmlFor." }, { "code": null, "e": 2451, "s": 2394, "text": "initialValue: It is used to configure sub default value." }, { "code": null, "e": 2495, "s": 2451, "text": "label: It is used to denote the Label text." }, { "code": null, "e": 2557, "s": 2495, "text": "labelAlign: It is used to denote the text-align of the label." }, { "code": null, "e": 2613, "s": 2557, "text": "labelCol: It is used to denote the layout of the label." }, { "code": null, "e": 2685, "s": 2613, "text": "messageVariables: It is used to denote the default validate field info." }, { "code": null, "e": 2722, "s": 2685, "text": "name: It is used to denote the name." }, { "code": null, "e": 2825, "s": 2722, "text": "normalize: It is used to normalize value from the component value before passing to the Form instance." }, { "code": null, "e": 2870, "s": 2825, "text": "noStyle: It is used as a pure field control." }, { "code": null, "e": 2940, "s": 2870, "text": "preserve: It is used to keep field value even when the field removed." }, { "code": null, "e": 3036, "s": 2940, "text": "required: It is used to display the required style. and it is generated by the validation rule." }, { "code": null, "e": 3096, "s": 3036, "text": "rules: It is used to denote the rules for field validation." }, { "code": null, "e": 3156, "s": 3096, "text": "shouldUpdate: It is used for the custom field update logic." }, { "code": null, "e": 3203, "s": 3156, "text": "tooltip: It is used to configure tooltip info." }, { "code": null, "e": 3283, "s": 3203, "text": "trigger: It is used to indicate when to collect the value of the children node." }, { "code": null, "e": 3389, "s": 3283, "text": "validateFirst: It is used to indicate whether to stop validate on the first rule of error for this field." }, { "code": null, "e": 3449, "s": 3389, "text": "validateStatus: It is used to denote the validation status." }, { "code": null, "e": 3538, "s": 3449, "text": "validateTrigger: It is used to indicate when to validate the value of the children node." }, { "code": null, "e": 3606, "s": 3538, "text": "valuePropName: It is used to denote the props of the children node." }, { "code": null, "e": 3670, "s": 3606, "text": "wrapperCol: It is used to denote the layout for input controls." }, { "code": null, "e": 3687, "s": 3670, "text": "Form.List Props:" }, { "code": null, "e": 3722, "s": 3687, "text": "children: It is a render function." }, { "code": null, "e": 3785, "s": 3722, "text": "initialValue: It is used to denote a config sub default value." }, { "code": null, "e": 3828, "s": 3785, "text": "name: It is used to denote the field name." }, { "code": null, "e": 3872, "s": 3828, "text": "rules: It is used for the validation rules." }, { "code": null, "e": 3896, "s": 3874, "text": "Form.ErrorList Props:" }, { "code": null, "e": 3941, "s": 3896, "text": "errors: It is used to denote the error list." }, { "code": null, "e": 3962, "s": 3941, "text": "Form.Provider Props:" }, { "code": null, "e": 4059, "s": 3962, "text": "onFormChange: It is a callback function that is triggered when a subform field updates function." }, { "code": null, "e": 4141, "s": 4059, "text": "onFormFinish: It is a callback function that is triggered when a subform submits." }, { "code": null, "e": 4191, "s": 4141, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 4286, "s": 4191, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 4350, "s": 4286, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 4382, "s": 4350, "text": "npx create-react-app foldername" }, { "code": null, "e": 4495, "s": 4382, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 4595, "s": 4495, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 4609, "s": 4595, "text": "cd foldername" }, { "code": null, "e": 4730, "s": 4609, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd" }, { "code": null, "e": 4835, "s": 4730, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 4852, "s": 4835, "text": "npm install antd" }, { "code": null, "e": 4904, "s": 4852, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 4922, "s": 4904, "text": "Project Structure" }, { "code": null, "e": 5052, "s": 4922, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 5059, "s": 5052, "text": "App.js" }, { "code": "import React from 'react'import \"antd/dist/antd.css\";import { Form, Button, Input } from 'antd'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Form Component</h4> <Form name=\"basicform\" onFinishFailed={() => alert('Failed to submit')} onFinish={() => alert('Form Submitted')} initialValues={{ remember: true }} > <Form.Item label=\"Enter username\" name=\"Username\" rules={[{ required: true, message: 'Please enter username' }]} > <Input /> </Form.Item> <Form.Item> <Button type=\"success\" htmlType=\"submit\"> Submit Username </Button> </Form.Item> </Form> </div> );}", "e": 5997, "s": 5059, "text": null }, { "code": null, "e": 6110, "s": 5997, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 6120, "s": 6110, "text": "npm start" }, { "code": null, "e": 6219, "s": 6120, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 6266, "s": 6219, "text": "Reference: https://ant.design/components/form/" }, { "code": null, "e": 6285, "s": 6266, "text": "ReactJS-Ant Design" }, { "code": null, "e": 6296, "s": 6285, "text": "JavaScript" }, { "code": null, "e": 6304, "s": 6296, "text": "ReactJS" }, { "code": null, "e": 6321, "s": 6304, "text": "Web Technologies" } ]
Python Program for Sum the digits of a given number
11 Aug, 2021 Given a number and the task is to find sum of digits of this number in Python. Examples: Input : n = 87 Output : 15 Input : n = 111 Output : 3 Below are the methods to sum of the digits. Method-1: Using str() and int() methods.: The str() method is used to convert the number to string. The int() method is used to convert the string digit to an integer. Convert the number to string and iterate over each digit in the string and after converting each digit to integer and add to the sum of the digits in each iteration. Python3 # Python program to# compute sum of digits in # number. # Function to get sum of digits def getSum(n): sum = 0 for digit in str(n): sum += int(digit) return sum n = 12345print(getSum(n)) Output: 15 Method-2: Using sum() methods.: The sum() method is used to sum of numbers in the list. Convert the number to string using str() and strip the string and convert to list of number using strip() and map() method resp. Then find the sum using the sum() method. Python3 # Python program to# compute sum of digits in # number. # Function to get sum of digits def getSum(n): strr = str(n) list_of_number = list(map(int, strr.strip())) return sum(list_of_number) n = 12345print(getSum(n)) Output: 15 Method-3: Using General Approach: Get the number Declare a variable to store the sum and set it to 0 Repeat the next two steps till the number is not 0 Get the rightmost digit of the number with help of remainder ‘%’ operator by dividing it with 10 and add it to sum. Divide the number by 10 with help of ‘//’ operator Print or return the sum A. Iterative Approach: Python3 # Python 3 program to# compute sum of digits in # number. # Function to get sum of digits def getSum(n): sum = 0 while (n != 0): sum = sum + (n % 10) n = n//10 return sum n = 12345print(getSum(n)) Output: 15 B. Recursive Approach: Python3 # Python program to compute# sum of digits in number. def sumDigits(no): return 0 if no == 0 else int(no % 10) + sumDigits(int(no / 10)) # Driver coden = 12345print(sumDigits(n)) Output: 15 sagar0719kumar Picked Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python | Split string into list of characters
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Aug, 2021" }, { "code": null, "e": 144, "s": 53, "text": "Given a number and the task is to find sum of digits of this number in Python. Examples: " }, { "code": null, "e": 198, "s": 144, "text": "Input : n = 87 Output : 15 Input : n = 111 Output : 3" }, { "code": null, "e": 412, "s": 198, "text": " Below are the methods to sum of the digits. Method-1: Using str() and int() methods.: The str() method is used to convert the number to string. The int() method is used to convert the string digit to an integer. " }, { "code": null, "e": 579, "s": 412, "text": "Convert the number to string and iterate over each digit in the string and after converting each digit to integer and add to the sum of the digits in each iteration. " }, { "code": null, "e": 587, "s": 579, "text": "Python3" }, { "code": "# Python program to# compute sum of digits in # number. # Function to get sum of digits def getSum(n): sum = 0 for digit in str(n): sum += int(digit) return sum n = 12345print(getSum(n))", "e": 803, "s": 587, "text": null }, { "code": null, "e": 811, "s": 803, "text": "Output:" }, { "code": null, "e": 814, "s": 811, "text": "15" }, { "code": null, "e": 902, "s": 814, "text": "Method-2: Using sum() methods.: The sum() method is used to sum of numbers in the list." }, { "code": null, "e": 1073, "s": 902, "text": "Convert the number to string using str() and strip the string and convert to list of number using strip() and map() method resp. Then find the sum using the sum() method." }, { "code": null, "e": 1081, "s": 1073, "text": "Python3" }, { "code": "# Python program to# compute sum of digits in # number. # Function to get sum of digits def getSum(n): strr = str(n) list_of_number = list(map(int, strr.strip())) return sum(list_of_number) n = 12345print(getSum(n))", "e": 1315, "s": 1081, "text": null }, { "code": null, "e": 1323, "s": 1315, "text": "Output:" }, { "code": null, "e": 1326, "s": 1323, "text": "15" }, { "code": null, "e": 1361, "s": 1326, "text": "Method-3: Using General Approach: " }, { "code": null, "e": 1376, "s": 1361, "text": "Get the number" }, { "code": null, "e": 1428, "s": 1376, "text": "Declare a variable to store the sum and set it to 0" }, { "code": null, "e": 1479, "s": 1428, "text": "Repeat the next two steps till the number is not 0" }, { "code": null, "e": 1595, "s": 1479, "text": "Get the rightmost digit of the number with help of remainder ‘%’ operator by dividing it with 10 and add it to sum." }, { "code": null, "e": 1646, "s": 1595, "text": "Divide the number by 10 with help of ‘//’ operator" }, { "code": null, "e": 1670, "s": 1646, "text": "Print or return the sum" }, { "code": null, "e": 1693, "s": 1670, "text": "A. Iterative Approach:" }, { "code": null, "e": 1701, "s": 1693, "text": "Python3" }, { "code": "# Python 3 program to# compute sum of digits in # number. # Function to get sum of digits def getSum(n): sum = 0 while (n != 0): sum = sum + (n % 10) n = n//10 return sum n = 12345print(getSum(n))", "e": 1943, "s": 1701, "text": null }, { "code": null, "e": 1951, "s": 1943, "text": "Output:" }, { "code": null, "e": 1954, "s": 1951, "text": "15" }, { "code": null, "e": 1977, "s": 1954, "text": "B. Recursive Approach:" }, { "code": null, "e": 1985, "s": 1977, "text": "Python3" }, { "code": "# Python program to compute# sum of digits in number. def sumDigits(no): return 0 if no == 0 else int(no % 10) + sumDigits(int(no / 10)) # Driver coden = 12345print(sumDigits(n))", "e": 2172, "s": 1985, "text": null }, { "code": null, "e": 2180, "s": 2172, "text": "Output:" }, { "code": null, "e": 2183, "s": 2180, "text": "15" }, { "code": null, "e": 2198, "s": 2183, "text": "sagar0719kumar" }, { "code": null, "e": 2205, "s": 2198, "text": "Picked" }, { "code": null, "e": 2212, "s": 2205, "text": "Python" }, { "code": null, "e": 2228, "s": 2212, "text": "Python Programs" }, { "code": null, "e": 2326, "s": 2228, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2368, "s": 2326, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2390, "s": 2368, "text": "Enumerate() in Python" }, { "code": null, "e": 2416, "s": 2390, "text": "Python String | replace()" }, { "code": null, "e": 2448, "s": 2416, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2477, "s": 2448, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2499, "s": 2477, "text": "Defaultdict in Python" }, { "code": null, "e": 2538, "s": 2499, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2576, "s": 2538, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2625, "s": 2576, "text": "Python | Convert string dictionary to dictionary" } ]
How to validate if input date (end date) in input field must be after a given date (start date) using express-validator ?
11 Jan, 2022 In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In certain cases, we want the user to type a date that must come after some given date(Ex. ‘end date’ must be after ‘start date’) and based on that we give the user access to the request or deny the request access. We can also validate these input fields using express-validator middleware. Command to install express-validator: npm install express-validator Steps to use express-validator to implement the logic: Install express-validator middleware. Create a validator.js file to code all the validation logic. Use custom validator to validate and fetch the start date as request body. Convert the date strings to a valid date and compare them according to requirement. Use the validation name(validateInputField) in the routes as a middleware as an array of validations. Destructure ‘validationResult’ function from express-validator to use it to find any errors. If error occurs redirect to the same page passing the error information. If error list is empty, give access to the user for the subsequent request. Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql. Example: This example illustrates how to validate a input field to only allow a date after a given date. Filename – index.js Javascript const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateEndDate } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/project', [validateEndDate], async (req, res) => { const errors = validationResult(req) if (!errors.isEmpty()) { console.log(errors) return res.send(formTemplet({errors})) } const {name, domain, sdate, edate, } = req.body // Fetch year, month, day of respective dates const [sd, sm, sy] = sdate.split('/') const [ed, em, ey] = edate.split('/') // New record await repo.create({ 'Project Name': name, 'Project Domain': domain, 'Start Date': new Date(sy, sm-1, sd).toDateString(), 'End Date': new Date(ey, em-1, ed).toDateString() }) res.send('<strong>Project details stored ' + 'successfully in the datebase</strong>')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)}) Filename – repository.js: This file contains all the logic to create a local database and interact with it. Javascript // Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where data are going to store if (!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is // created with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json') Filename – form.js: This file contains logic to show the form to submit project data with start and end date. Javascript const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return ` <!DOCTYPE html> <html> <head> <link rel='stylesheet'href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns{ margin-top: 100px; } .button{ margin-top : 10px } </style> </head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/project' method='POST'> <div> <div> <label class='label' id='name'>Project Name</label> </div> <input class='input' type='text' name='name' placeholder='Project Name' for='name'> </div> <div> <div> <label class='label' id='domain'>Project Domain</label> </div> <input class='input' type='text' name='domain' placeholder='Project Domain' for='base64data'> </div> <div> <div> <label class='label' id='sdate'>Start Date</label> </div> <input class='input' type='text' name='sdate' placeholder='dd/mm/yyyy' for='sdate'> </div> <div> <div> <label class='label' id='edate'>End Date</label> </div> <input class='input' type='text' name='edate' placeholder='dd/mm/yyyy' for='edate'> <p class="help is-danger">${getError(errors, 'edate')}</p> </div> <div> <button class='button is-primary'>Submit</button> </div> </form> </div> </div> </div> </body> </html> `} Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to accept only a date after a given date). Javascript const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateEndDate : check('edate') // To delete leading and trailing space .trim() // Custom validator .custom((edate, {req}) => { // Fetch year, month and day of respective dates const [sd, sm, sy] = req.body.sdate.split('/') const [ed, em, ey] = edate.split('/') // Constructing dates from given string date input const startDate = new Date(sy, sm, sd) const endDate = new Date(ey, em, ed) // Validate end date so that it must after start date if (endDate <= startDate) { throw new Error('End date of project must be after start date') } return true }) } Filename – package.json package.json file Database: Database Output: Attempt to submit form when end date comes before start date Response when an attempt to submit the form where end date comes before start date Attempt to submit form when end date comes after start date Response when attempt to submit the form where end date comes after start date Database after successful form submission: Database after successful submission of form Note: We have used some Bulma classes(CSS framework) in the signup.js file to design the content. clintra simmytarika5 Express.js Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function Installation of Node.js on Windows JWT Authentication with Node.js How to use an ES6 import in Node.js? 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 ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jan, 2022" }, { "code": null, "e": 539, "s": 28, "text": "In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In certain cases, we want the user to type a date that must come after some given date(Ex. ‘end date’ must be after ‘start date’) and based on that we give the user access to the request or deny the request access. We can also validate these input fields using express-validator middleware." }, { "code": null, "e": 577, "s": 539, "text": "Command to install express-validator:" }, { "code": null, "e": 607, "s": 577, "text": "npm install express-validator" }, { "code": null, "e": 662, "s": 607, "text": "Steps to use express-validator to implement the logic:" }, { "code": null, "e": 700, "s": 662, "text": "Install express-validator middleware." }, { "code": null, "e": 761, "s": 700, "text": "Create a validator.js file to code all the validation logic." }, { "code": null, "e": 836, "s": 761, "text": "Use custom validator to validate and fetch the start date as request body." }, { "code": null, "e": 920, "s": 836, "text": "Convert the date strings to a valid date and compare them according to requirement." }, { "code": null, "e": 1022, "s": 920, "text": "Use the validation name(validateInputField) in the routes as a middleware as an array of validations." }, { "code": null, "e": 1115, "s": 1022, "text": "Destructure ‘validationResult’ function from express-validator to use it to find any errors." }, { "code": null, "e": 1188, "s": 1115, "text": "If error occurs redirect to the same page passing the error information." }, { "code": null, "e": 1264, "s": 1188, "text": "If error list is empty, give access to the user for the subsequent request." }, { "code": null, "e": 1430, "s": 1264, "text": "Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql." }, { "code": null, "e": 1535, "s": 1430, "text": "Example: This example illustrates how to validate a input field to only allow a date after a given date." }, { "code": null, "e": 1555, "s": 1535, "text": "Filename – index.js" }, { "code": null, "e": 1566, "s": 1555, "text": "Javascript" }, { "code": "const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateEndDate } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/project', [validateEndDate], async (req, res) => { const errors = validationResult(req) if (!errors.isEmpty()) { console.log(errors) return res.send(formTemplet({errors})) } const {name, domain, sdate, edate, } = req.body // Fetch year, month, day of respective dates const [sd, sm, sy] = sdate.split('/') const [ed, em, ey] = edate.split('/') // New record await repo.create({ 'Project Name': name, 'Project Domain': domain, 'Start Date': new Date(sy, sm-1, sd).toDateString(), 'End Date': new Date(ey, em-1, ed).toDateString() }) res.send('<strong>Project details stored ' + 'successfully in the datebase</strong>')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})", "e": 2913, "s": 1566, "text": null }, { "code": null, "e": 3021, "s": 2913, "text": "Filename – repository.js: This file contains all the logic to create a local database and interact with it." }, { "code": null, "e": 3032, "s": 3021, "text": "Javascript" }, { "code": "// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where data are going to store if (!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is // created with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')", "e": 4175, "s": 3032, "text": null }, { "code": null, "e": 4285, "s": 4175, "text": "Filename – form.js: This file contains logic to show the form to submit project data with start and end date." }, { "code": null, "e": 4296, "s": 4285, "text": "Javascript" }, { "code": "const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return ` <!DOCTYPE html> <html> <head> <link rel='stylesheet'href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns{ margin-top: 100px; } .button{ margin-top : 10px } </style> </head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/project' method='POST'> <div> <div> <label class='label' id='name'>Project Name</label> </div> <input class='input' type='text' name='name' placeholder='Project Name' for='name'> </div> <div> <div> <label class='label' id='domain'>Project Domain</label> </div> <input class='input' type='text' name='domain' placeholder='Project Domain' for='base64data'> </div> <div> <div> <label class='label' id='sdate'>Start Date</label> </div> <input class='input' type='text' name='sdate' placeholder='dd/mm/yyyy' for='sdate'> </div> <div> <div> <label class='label' id='edate'>End Date</label> </div> <input class='input' type='text' name='edate' placeholder='dd/mm/yyyy' for='edate'> <p class=\"help is-danger\">${getError(errors, 'edate')}</p> </div> <div> <button class='button is-primary'>Submit</button> </div> </form> </div> </div> </div> </body> </html> `}", "e": 6368, "s": 4296, "text": null }, { "code": null, "e": 6511, "s": 6368, "text": "Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to accept only a date after a given date)." }, { "code": null, "e": 6522, "s": 6511, "text": "Javascript" }, { "code": "const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateEndDate : check('edate') // To delete leading and trailing space .trim() // Custom validator .custom((edate, {req}) => { // Fetch year, month and day of respective dates const [sd, sm, sy] = req.body.sdate.split('/') const [ed, em, ey] = edate.split('/') // Constructing dates from given string date input const startDate = new Date(sy, sm, sd) const endDate = new Date(ey, em, ed) // Validate end date so that it must after start date if (endDate <= startDate) { throw new Error('End date of project must be after start date') } return true }) }", "e": 7263, "s": 6522, "text": null }, { "code": null, "e": 7287, "s": 7263, "text": "Filename – package.json" }, { "code": null, "e": 7305, "s": 7287, "text": "package.json file" }, { "code": null, "e": 7315, "s": 7305, "text": "Database:" }, { "code": null, "e": 7324, "s": 7315, "text": "Database" }, { "code": null, "e": 7332, "s": 7324, "text": "Output:" }, { "code": null, "e": 7393, "s": 7332, "text": "Attempt to submit form when end date comes before start date" }, { "code": null, "e": 7476, "s": 7393, "text": "Response when an attempt to submit the form where end date comes before start date" }, { "code": null, "e": 7536, "s": 7476, "text": "Attempt to submit form when end date comes after start date" }, { "code": null, "e": 7615, "s": 7536, "text": "Response when attempt to submit the form where end date comes after start date" }, { "code": null, "e": 7658, "s": 7615, "text": "Database after successful form submission:" }, { "code": null, "e": 7703, "s": 7658, "text": "Database after successful submission of form" }, { "code": null, "e": 7801, "s": 7703, "text": "Note: We have used some Bulma classes(CSS framework) in the signup.js file to design the content." }, { "code": null, "e": 7809, "s": 7801, "text": "clintra" }, { "code": null, "e": 7822, "s": 7809, "text": "simmytarika5" }, { "code": null, "e": 7833, "s": 7822, "text": "Express.js" }, { "code": null, "e": 7846, "s": 7833, "text": "Node.js-Misc" }, { "code": null, "e": 7854, "s": 7846, "text": "Node.js" }, { "code": null, "e": 7871, "s": 7854, "text": "Web Technologies" }, { "code": null, "e": 7969, "s": 7871, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8023, "s": 7969, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 8063, "s": 8023, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 8098, "s": 8063, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 8130, "s": 8098, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 8167, "s": 8130, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 8229, "s": 8167, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 8290, "s": 8229, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 8340, "s": 8290, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 8383, "s": 8340, "text": "How to fetch data from an API in ReactJS ?" } ]
How to use Mat-Dialog in Angular ?
26 Oct, 2020 Introduction:Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. Installation syntax: ng add @angular/material Approach: First we need to import ‘MatDialog’ from ‘@angular/material/dialog’ and we need to create an instance for it in the constructor. Using this instance we can open the dialog box component. Now create a separate component for the dialog and write code as per the requirements. In the dialog component, we need to create an instance of ‘MatDialogRef’ which we should import from ‘@angular/material/dialog’. Import ‘MatDialogModule’ from ‘@angular/material’ in app.module.ts file. Make sure that you are mentioning the Dialog component in entryComponents array in the module file. Implementation of code: app.component.html: <button mat-raised-button (click)="openDialog()"> Pick one</button><br> <span *ngIf="animal"> You choose: <i>{{animal}}</i><span> app.component.ts: import { Component } from '@angular/core';import { MatDialog } from '@angular/material'; import { ExampleDialogComponent } from './example-dialog'; @Component({ selector: 'app-root', templateUrl: 'app.component.html',})export class AppComponent { animal: string; name: string; constructor(public dialog: MatDialog) {} openDialog(): void { let dialogRef = this.dialog.open(ExampleDialogComponent, { width: '250px', data: { name: this.name, animal: this.animal } }); dialogRef.afterClosed().subscribe(result => { this.animal = result; }); } } app.module.ts: import { CommonModule } from '@angular/common';import { NgModule } from '@angular/core';import { FormsModule } from '@angular/forms';import { MatButtonModule, MatCommonModule, MatFormFieldModule, MatInputModule,} from '@angular/material'; import { AppComponent } from './example.component';import { ExampleDialogModule } from './example-dialog'; @NgModule({ declarations: [AppComponent], exports: [AppComponent], imports: [ ExampleDialogModule, CommonModule, FormsModule, MatButtonModule, MatCommonModule, MatFormFieldModule, MatInputModule, ],})export class AppModule {} example-dialog.component.html: <h1 mat-dialog-title>Welcome user</h1><div mat-dialog-content> <p>What's your favorite animal?</p> <mat-form-field> <input matInput [(ngModel)]="data.animal"> </mat-form-field></div><div mat-dialog-actions> <button mat-button (click)="onCancel()">No Thanks</button> <button mat-button [mat-dialog-close]="data.animal" cdkFocusInitial>Ok</button></div> example-dialog.component.ts: import { Component, Inject } from '@angular/core';import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; @Component({ selector: 'app-example-dialog', templateUrl: 'example-dialog.component.html',})export class ExampleDialogComponent { constructor( public dialogRef: MatDialogRef<ExampleDialogComponent>, @Inject(MAT_DIALOG_DATA) public data: any) { } onCancel(): void { this.dialogRef.close(); } } example-dialog.module.ts: import { NgModule } from '@angular/core';import { FormsModule } from '@angular/forms';import { MatButtonModule, MatCommonModule, MatDialogModule, MatFormFieldModule, MatInputModule,} from '@angular/material'; import { ExampleDialogComponent } from './example-dialog.component'; @NgModule({ declarations: [ExampleDialogComponent], entryComponents: [ExampleDialogComponent], imports: [ FormsModule, MatButtonModule, MatCommonModule, MatDialogModule, MatFormFieldModule, MatInputModule, ],})export class ExampleDialogModule {} Output: Output when the dialog box is opened: Output when the entered value is displayed on the screen: AngularJS-Misc Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Oct, 2020" }, { "code": null, "e": 360, "s": 54, "text": "Introduction:Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it." }, { "code": null, "e": 381, "s": 360, "text": "Installation syntax:" }, { "code": "ng add @angular/material", "e": 406, "s": 381, "text": null }, { "code": null, "e": 416, "s": 406, "text": "Approach:" }, { "code": null, "e": 545, "s": 416, "text": "First we need to import ‘MatDialog’ from ‘@angular/material/dialog’ and we need to create an instance for it in the constructor." }, { "code": null, "e": 603, "s": 545, "text": "Using this instance we can open the dialog box component." }, { "code": null, "e": 690, "s": 603, "text": "Now create a separate component for the dialog and write code as per the requirements." }, { "code": null, "e": 820, "s": 690, "text": "In the dialog component, we need to create an instance of ‘MatDialogRef’ which we should import from ‘@angular/material/dialog’." }, { "code": null, "e": 893, "s": 820, "text": "Import ‘MatDialogModule’ from ‘@angular/material’ in app.module.ts file." }, { "code": null, "e": 993, "s": 893, "text": "Make sure that you are mentioning the Dialog component in entryComponents array in the module file." }, { "code": null, "e": 1037, "s": 993, "text": "Implementation of code: app.component.html:" }, { "code": "<button mat-raised-button (click)=\"openDialog()\"> Pick one</button><br> <span *ngIf=\"animal\"> You choose: <i>{{animal}}</i><span>", "e": 1174, "s": 1037, "text": null }, { "code": null, "e": 1192, "s": 1174, "text": "app.component.ts:" }, { "code": "import { Component } from '@angular/core';import { MatDialog } from '@angular/material'; import { ExampleDialogComponent } from './example-dialog'; @Component({ selector: 'app-root', templateUrl: 'app.component.html',})export class AppComponent { animal: string; name: string; constructor(public dialog: MatDialog) {} openDialog(): void { let dialogRef = this.dialog.open(ExampleDialogComponent, { width: '250px', data: { name: this.name, animal: this.animal } }); dialogRef.afterClosed().subscribe(result => { this.animal = result; }); } }", "e": 1778, "s": 1192, "text": null }, { "code": null, "e": 1793, "s": 1778, "text": "app.module.ts:" }, { "code": "import { CommonModule } from '@angular/common';import { NgModule } from '@angular/core';import { FormsModule } from '@angular/forms';import { MatButtonModule, MatCommonModule, MatFormFieldModule, MatInputModule,} from '@angular/material'; import { AppComponent } from './example.component';import { ExampleDialogModule } from './example-dialog'; @NgModule({ declarations: [AppComponent], exports: [AppComponent], imports: [ ExampleDialogModule, CommonModule, FormsModule, MatButtonModule, MatCommonModule, MatFormFieldModule, MatInputModule, ],})export class AppModule {}", "e": 2396, "s": 1793, "text": null }, { "code": null, "e": 2427, "s": 2396, "text": "example-dialog.component.html:" }, { "code": "<h1 mat-dialog-title>Welcome user</h1><div mat-dialog-content> <p>What's your favorite animal?</p> <mat-form-field> <input matInput [(ngModel)]=\"data.animal\"> </mat-form-field></div><div mat-dialog-actions> <button mat-button (click)=\"onCancel()\">No Thanks</button> <button mat-button [mat-dialog-close]=\"data.animal\" cdkFocusInitial>Ok</button></div>", "e": 2800, "s": 2427, "text": null }, { "code": null, "e": 2829, "s": 2800, "text": "example-dialog.component.ts:" }, { "code": "import { Component, Inject } from '@angular/core';import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; @Component({ selector: 'app-example-dialog', templateUrl: 'example-dialog.component.html',})export class ExampleDialogComponent { constructor( public dialogRef: MatDialogRef<ExampleDialogComponent>, @Inject(MAT_DIALOG_DATA) public data: any) { } onCancel(): void { this.dialogRef.close(); } }", "e": 3259, "s": 2829, "text": null }, { "code": null, "e": 3285, "s": 3259, "text": "example-dialog.module.ts:" }, { "code": "import { NgModule } from '@angular/core';import { FormsModule } from '@angular/forms';import { MatButtonModule, MatCommonModule, MatDialogModule, MatFormFieldModule, MatInputModule,} from '@angular/material'; import { ExampleDialogComponent } from './example-dialog.component'; @NgModule({ declarations: [ExampleDialogComponent], entryComponents: [ExampleDialogComponent], imports: [ FormsModule, MatButtonModule, MatCommonModule, MatDialogModule, MatFormFieldModule, MatInputModule, ],})export class ExampleDialogModule {}", "e": 3838, "s": 3285, "text": null }, { "code": null, "e": 3846, "s": 3838, "text": "Output:" }, { "code": null, "e": 3884, "s": 3846, "text": "Output when the dialog box is opened:" }, { "code": null, "e": 3942, "s": 3884, "text": "Output when the entered value is displayed on the screen:" }, { "code": null, "e": 3957, "s": 3942, "text": "AngularJS-Misc" }, { "code": null, "e": 3964, "s": 3957, "text": "Picked" }, { "code": null, "e": 3974, "s": 3964, "text": "AngularJS" }, { "code": null, "e": 3991, "s": 3974, "text": "Web Technologies" } ]
Touch module in Python
21 Apr, 2020 In Python, the Touch module is used to create any file on any specified directory. The touch module is equivalent to linux command ‘touch‘ or to the windows’ cmd command ‘ type null > ‘. Installation: This module does not come built-in with Python. To install this module type the below command in the terminal. pip install touch Example 1: In this example, we will create a file inside a same directory. import touch touch.touch("success.java") Output: Example 2: In this example, we will create a file in a different directory. Here we create a file in “testm” folder. import touch touch.touch("testm / success2.java") Output: Example 3: In this example, we will create a multiple files at the same time. For this, we need to pass the file name in a list. import touch touch.touch(["testm / success100.java", "success10.cpp"]) Output: python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Apr, 2020" }, { "code": null, "e": 241, "s": 54, "text": "In Python, the Touch module is used to create any file on any specified directory. The touch module is equivalent to linux command ‘touch‘ or to the windows’ cmd command ‘ type null > ‘." }, { "code": null, "e": 255, "s": 241, "text": "Installation:" }, { "code": null, "e": 366, "s": 255, "text": "This module does not come built-in with Python. To install this module type the below command in the terminal." }, { "code": null, "e": 384, "s": 366, "text": "pip install touch" }, { "code": null, "e": 459, "s": 384, "text": "Example 1: In this example, we will create a file inside a same directory." }, { "code": "import touch touch.touch(\"success.java\")", "e": 501, "s": 459, "text": null }, { "code": null, "e": 509, "s": 501, "text": "Output:" }, { "code": null, "e": 626, "s": 509, "text": "Example 2: In this example, we will create a file in a different directory. Here we create a file in “testm” folder." }, { "code": "import touch touch.touch(\"testm / success2.java\")", "e": 677, "s": 626, "text": null }, { "code": null, "e": 685, "s": 677, "text": "Output:" }, { "code": null, "e": 814, "s": 685, "text": "Example 3: In this example, we will create a multiple files at the same time. For this, we need to pass the file name in a list." }, { "code": "import touch touch.touch([\"testm / success100.java\", \"success10.cpp\"])", "e": 886, "s": 814, "text": null }, { "code": null, "e": 894, "s": 886, "text": "Output:" }, { "code": null, "e": 909, "s": 894, "text": "python-modules" }, { "code": null, "e": 916, "s": 909, "text": "Python" } ]
Time Durations in Golang
10 Sep, 2021 Operations related to time and date are a crucial part of software development (example log keeping). Go standard library provides a time package that has many functions and methods to deal with date and time. The operating system measures two types of time “Wall clock” time and “Monotonic” time. Wall clock time is used to tell time whereas monotonic clock time is used to measure time. Go time package provides functionalities to measure and manipulate both clocks. Golang has time.Time datatype to deal with wall clock time and time.Duration to deal with monotonic time. The first basic method is time.Now() which returns the current date and time up to nanosecond precision. The value returned has datatype time.Time, which is a struct. According to Golang’s official documentation “A Time represents an instant in time with nanosecond precision.” Go package main import ( "fmt" "time") func main() { // Returns current time. t := time.Now() fmt.Println(t)} Output: 2020-04-29 00:37:36.849599502 +0530 IST m=+0.000166550 In Go any variable which is declared but not initialized is by default set to its zero value. The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC, which is impossible in a real-life scenario. IsZero method can also be used to check whether a Time variable is initialized or not. Go package main import ( "fmt" "time") func main() { var t time.Time fmt.Println(t) fmt.Println(t.IsZero())} Output: 0001-01-01 00:00:00 +0000 UTC true time.Time datatype has a base type structure that contains time, date, location, timezone, and monotonic time. Go time package has methods to extract individual parts from time instant (like date, time, day, location, etc). Go package main import ( "fmt" "time") func main() { t := time.Now() fmt.Println(t) // We can get individual values // of hour, minute, seconds, // nanoseconds from time.Time // datatype // Returns wall clock time // from time.Time datatype fmt.Println(t.Clock()) fmt.Println(t.Hour()) fmt.Println(t.Minute()) fmt.Println(t.Second()) fmt.Println(t.Nanosecond()) fmt.Println("---------------------------------") // We can get individual values // of day, month, year, yearday, // and weekday from time.Time // datatype // Returns date from // time.Time datatype fmt.Println(t.Date()) fmt.Println(t.Day()) fmt.Println(t.Month()) fmt.Println(t.Year()) fmt.Println(t.YearDay()) fmt.Println(t.Weekday()) // week number fmt.Println(t.ISOWeek()) fmt.Println("---------------------------------") // current time in string formats fmt.Println(t.String()) // nanoseconds passed // from 1 january 1970 fmt.Println(t.Unix()) // prints abbreviated timezone and // its offset in seconds from // east of UTC fmt.Println(t.Zone()) // prints nanoseconds // elapsed from 1 january 1970 fmt.Println(t.UnixNano())} Output: 2020-04-29 17:54:25.643755713 +0530 IST m=+0.000064065 17 54 25 17 54 25 643755713 --------------------------------- 2020 April 29 29 April 2020 120 Wednesday 2020 18 --------------------------------- 2020-04-29 17:54:25.643755713 +0530 IST m=+0.000064065 1588163065 IST 19800 1588163065643755713 Golang == operator compares not only time instant but also the Location and the monotonic clock reading. time.Duration has a base type int64. Duration represents the elapsed time between two instants as an int64 nanosecond count”. The maximum possible nanosecond representation is up to 290 years. type Duration int64 Conversion of various duration instances: const ( Nanosecond Duration = 1 Microsecond = 1000 * Nanosecond Millisecond = 1000 * Microsecond Second = 1000 * Millisecond Minute = 60 * Second Hour = 60 * Minute ) Go package main import ( "fmt" "time") func main() { // random duration in nanoseconds var d time.Duration = 1000000000 // converts d in hour fmt.Println(d.Hours()) // converts d in minutes fmt.Println(d.Minutes()) // converts d in seconds fmt.Println(d.Seconds()) // converts d in milliseconds fmt.Println(d.Milliseconds()) // converts d in microseconds fmt.Println(d.Microseconds()) // string representation go d fmt.Println(d.String())} Output: 0.0002777777777777778 0.016666666666666666 1 1000 1000000 1s simranarora5sos GoLang-time Picked Go Language Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Sep, 2021" }, { "code": null, "e": 906, "s": 52, "text": "Operations related to time and date are a crucial part of software development (example log keeping). Go standard library provides a time package that has many functions and methods to deal with date and time. The operating system measures two types of time “Wall clock” time and “Monotonic” time. Wall clock time is used to tell time whereas monotonic clock time is used to measure time. Go time package provides functionalities to measure and manipulate both clocks. Golang has time.Time datatype to deal with wall clock time and time.Duration to deal with monotonic time. The first basic method is time.Now() which returns the current date and time up to nanosecond precision. The value returned has datatype time.Time, which is a struct. According to Golang’s official documentation “A Time represents an instant in time with nanosecond precision.” " }, { "code": null, "e": 909, "s": 906, "text": "Go" }, { "code": "package main import ( \"fmt\" \"time\") func main() { // Returns current time. t := time.Now() fmt.Println(t)}", "e": 1032, "s": 909, "text": null }, { "code": null, "e": 1040, "s": 1032, "text": "Output:" }, { "code": null, "e": 1096, "s": 1040, "text": "2020-04-29 00:37:36.849599502 +0530 IST m=+0.000166550 " }, { "code": null, "e": 1397, "s": 1096, "text": "In Go any variable which is declared but not initialized is by default set to its zero value. The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC, which is impossible in a real-life scenario. IsZero method can also be used to check whether a Time variable is initialized or not. " }, { "code": null, "e": 1400, "s": 1397, "text": "Go" }, { "code": "package main import ( \"fmt\" \"time\") func main() { var t time.Time fmt.Println(t) fmt.Println(t.IsZero())}", "e": 1521, "s": 1400, "text": null }, { "code": null, "e": 1529, "s": 1521, "text": "Output:" }, { "code": null, "e": 1566, "s": 1529, "text": "0001-01-01 00:00:00 +0000 UTC \ntrue " }, { "code": null, "e": 1791, "s": 1566, "text": "time.Time datatype has a base type structure that contains time, date, location, timezone, and monotonic time. Go time package has methods to extract individual parts from time instant (like date, time, day, location, etc). " }, { "code": null, "e": 1794, "s": 1791, "text": "Go" }, { "code": "package main import ( \"fmt\" \"time\") func main() { t := time.Now() fmt.Println(t) // We can get individual values // of hour, minute, seconds, // nanoseconds from time.Time // datatype // Returns wall clock time // from time.Time datatype fmt.Println(t.Clock()) fmt.Println(t.Hour()) fmt.Println(t.Minute()) fmt.Println(t.Second()) fmt.Println(t.Nanosecond()) fmt.Println(\"---------------------------------\") // We can get individual values // of day, month, year, yearday, // and weekday from time.Time // datatype // Returns date from // time.Time datatype fmt.Println(t.Date()) fmt.Println(t.Day()) fmt.Println(t.Month()) fmt.Println(t.Year()) fmt.Println(t.YearDay()) fmt.Println(t.Weekday()) // week number fmt.Println(t.ISOWeek()) fmt.Println(\"---------------------------------\") // current time in string formats fmt.Println(t.String()) // nanoseconds passed // from 1 january 1970 fmt.Println(t.Unix()) // prints abbreviated timezone and // its offset in seconds from // east of UTC fmt.Println(t.Zone()) // prints nanoseconds // elapsed from 1 january 1970 fmt.Println(t.UnixNano())}", "e": 3027, "s": 1794, "text": null }, { "code": null, "e": 3035, "s": 3027, "text": "Output:" }, { "code": null, "e": 3332, "s": 3035, "text": "2020-04-29 17:54:25.643755713 +0530 IST m=+0.000064065\n17 54 25\n17\n54\n25\n643755713\n---------------------------------\n2020 April 29\n29\nApril\n2020\n120\nWednesday\n2020 18\n---------------------------------\n2020-04-29 17:54:25.643755713 +0530 IST m=+0.000064065\n1588163065\nIST 19800\n1588163065643755713" }, { "code": null, "e": 3437, "s": 3332, "text": "Golang == operator compares not only time instant but also the Location and the monotonic clock reading." }, { "code": null, "e": 3631, "s": 3437, "text": "time.Duration has a base type int64. Duration represents the elapsed time between two instants as an int64 nanosecond count”. The maximum possible nanosecond representation is up to 290 years. " }, { "code": null, "e": 3651, "s": 3631, "text": "type Duration int64" }, { "code": null, "e": 3694, "s": 3651, "text": "Conversion of various duration instances: " }, { "code": null, "e": 3948, "s": 3694, "text": "const (\n Nanosecond Duration = 1\n Microsecond = 1000 * Nanosecond\n Millisecond = 1000 * Microsecond\n Second = 1000 * Millisecond\n Minute = 60 * Second\n Hour = 60 * Minute\n)" }, { "code": null, "e": 3951, "s": 3948, "text": "Go" }, { "code": "package main import ( \"fmt\" \"time\") func main() { // random duration in nanoseconds var d time.Duration = 1000000000 // converts d in hour fmt.Println(d.Hours()) // converts d in minutes fmt.Println(d.Minutes()) // converts d in seconds fmt.Println(d.Seconds()) // converts d in milliseconds fmt.Println(d.Milliseconds()) // converts d in microseconds fmt.Println(d.Microseconds()) // string representation go d fmt.Println(d.String())}", "e": 4443, "s": 3951, "text": null }, { "code": null, "e": 4451, "s": 4443, "text": "Output:" }, { "code": null, "e": 4512, "s": 4451, "text": "0.0002777777777777778\n0.016666666666666666\n1\n1000\n1000000\n1s" }, { "code": null, "e": 4530, "s": 4514, "text": "simranarora5sos" }, { "code": null, "e": 4542, "s": 4530, "text": "GoLang-time" }, { "code": null, "e": 4549, "s": 4542, "text": "Picked" }, { "code": null, "e": 4561, "s": 4549, "text": "Go Language" }, { "code": null, "e": 4577, "s": 4561, "text": "Write From Home" } ]
How to create copy to clipboard button ?
16 Nov, 2021 In this article, we will discuss how to create a copy to the clipboard button. There are multiple scenarios in web development where we have to give user functionality to copy certain data into a clipboard using a button. Whether it is a sample of code or it is the User’s own information, we can create a copy button to copy data to the clipboard using the navigator.clipboard.writeText() function. This function writes the data fed to it as a parameter into the clipboard. We can use this to copy any text to the clipboard. First, we select the text to copy to the clipboard whether it is from a div or from an input box using document.getElementById() or any other suitable function. Then we store the value of that text in a variable and pass that variable as an argument to navigator.clipboard.writeText() function to copy it to clipboard. Syntax: navigator.clipboard.writeText( <text> ) Where <text>: determines string variable to be copied. Example 1: Here we have added a copy to clipboard button to a div with text in it to copy the sample text into the clipboard. HTML <!DOCTYPE html><html> <head> <style> body { margin: 100px; } #textbox { width: 40vw; height: 30vh; position: absolute; margin-left: 50px; margin-top: 20px; } button { width: 70px; height: 40px; margin-top: 120px; margin-left: 50px; background-color: green; color: white; border-radius: 10px; box-shadow: grey; position: absolute; } #sample { width: 70vw; margin: 50px; background-color: green; color: white; padding: 20px; font-size: x-large; position: absolute; } h1 { margin-left: 50px; margin-top: 160px; } </style></head> <body> <div id="sample"> Geeksforgeeks is best learning platform. </div> <br /> <button onclick="copyText()">Copy</button> <br /> <h1>Copied Text:</h1><br /> <textarea id="textbox"></textarea> <script> function copyText() { /* Copy text into clipboard */ navigator.clipboard.writeText ("Geeksforgeeks is best learning platform."); } </script></body> </html> Output: Output Example 2: Here, we have copied text from a text area where user can write their own text and then copy it to the clipboard, and that text is shown on the lower band also. HTML <!DOCTYPE html><html> <head> <style> #textbox { width: 70vw; height: 30vh; } button { width: 70px; height: 40px; background-color: green; color: white; border-radius: 10px; box-shadow: grey; } #clipboard { width: 70vw; margin: 50px; background-color: green; color: white; padding: 20px; font-size: x-large; } </style></head> <body> <center> <textarea id="textbox"></textarea><br /> <button onclick="copyText()">Copy</button> <br /> <h1>Copied Text:</h1><br /> <span id="clipboard">NA</span> </center> <script> function copyText() { /* Select text area by id*/ var Text = document.getElementById("textbox"); /* Select the text inside text area. */ Text.select(); /* Copy selected text into clipboard */ navigator.clipboard.writeText(Text.value); /* Set the copied text as text for div with id clipboard */ document.getElementById("clipboard") .innerHTML = Text.value; } </script></body> </html> Output: Output CSS-Properties CSS-Questions HTML-Questions JavaScript-Questions Picked CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Form validation using jQuery Design a web page using HTML and CSS 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 ? HTTP headers | Content-Type
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Nov, 2021" }, { "code": null, "e": 107, "s": 28, "text": "In this article, we will discuss how to create a copy to the clipboard button." }, { "code": null, "e": 554, "s": 107, "text": "There are multiple scenarios in web development where we have to give user functionality to copy certain data into a clipboard using a button. Whether it is a sample of code or it is the User’s own information, we can create a copy button to copy data to the clipboard using the navigator.clipboard.writeText() function. This function writes the data fed to it as a parameter into the clipboard. We can use this to copy any text to the clipboard." }, { "code": null, "e": 873, "s": 554, "text": "First, we select the text to copy to the clipboard whether it is from a div or from an input box using document.getElementById() or any other suitable function. Then we store the value of that text in a variable and pass that variable as an argument to navigator.clipboard.writeText() function to copy it to clipboard." }, { "code": null, "e": 883, "s": 875, "text": "Syntax:" }, { "code": null, "e": 923, "s": 883, "text": "navigator.clipboard.writeText( <text> )" }, { "code": null, "e": 929, "s": 923, "text": "Where" }, { "code": null, "e": 978, "s": 929, "text": "<text>: determines string variable to be copied." }, { "code": null, "e": 1104, "s": 978, "text": "Example 1: Here we have added a copy to clipboard button to a div with text in it to copy the sample text into the clipboard." }, { "code": null, "e": 1109, "s": 1104, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> body { margin: 100px; } #textbox { width: 40vw; height: 30vh; position: absolute; margin-left: 50px; margin-top: 20px; } button { width: 70px; height: 40px; margin-top: 120px; margin-left: 50px; background-color: green; color: white; border-radius: 10px; box-shadow: grey; position: absolute; } #sample { width: 70vw; margin: 50px; background-color: green; color: white; padding: 20px; font-size: x-large; position: absolute; } h1 { margin-left: 50px; margin-top: 160px; } </style></head> <body> <div id=\"sample\"> Geeksforgeeks is best learning platform. </div> <br /> <button onclick=\"copyText()\">Copy</button> <br /> <h1>Copied Text:</h1><br /> <textarea id=\"textbox\"></textarea> <script> function copyText() { /* Copy text into clipboard */ navigator.clipboard.writeText (\"Geeksforgeeks is best learning platform.\"); } </script></body> </html>", "e": 2453, "s": 1109, "text": null }, { "code": null, "e": 2461, "s": 2453, "text": "Output:" }, { "code": null, "e": 2468, "s": 2461, "text": "Output" }, { "code": null, "e": 2640, "s": 2468, "text": "Example 2: Here, we have copied text from a text area where user can write their own text and then copy it to the clipboard, and that text is shown on the lower band also." }, { "code": null, "e": 2645, "s": 2640, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> #textbox { width: 70vw; height: 30vh; } button { width: 70px; height: 40px; background-color: green; color: white; border-radius: 10px; box-shadow: grey; } #clipboard { width: 70vw; margin: 50px; background-color: green; color: white; padding: 20px; font-size: x-large; } </style></head> <body> <center> <textarea id=\"textbox\"></textarea><br /> <button onclick=\"copyText()\">Copy</button> <br /> <h1>Copied Text:</h1><br /> <span id=\"clipboard\">NA</span> </center> <script> function copyText() { /* Select text area by id*/ var Text = document.getElementById(\"textbox\"); /* Select the text inside text area. */ Text.select(); /* Copy selected text into clipboard */ navigator.clipboard.writeText(Text.value); /* Set the copied text as text for div with id clipboard */ document.getElementById(\"clipboard\") .innerHTML = Text.value; } </script></body> </html>", "e": 3938, "s": 2645, "text": null }, { "code": null, "e": 3946, "s": 3938, "text": "Output:" }, { "code": null, "e": 3953, "s": 3946, "text": "Output" }, { "code": null, "e": 3968, "s": 3953, "text": "CSS-Properties" }, { "code": null, "e": 3982, "s": 3968, "text": "CSS-Questions" }, { "code": null, "e": 3997, "s": 3982, "text": "HTML-Questions" }, { "code": null, "e": 4018, "s": 3997, "text": "JavaScript-Questions" }, { "code": null, "e": 4025, "s": 4018, "text": "Picked" }, { "code": null, "e": 4029, "s": 4025, "text": "CSS" }, { "code": null, "e": 4034, "s": 4029, "text": "HTML" }, { "code": null, "e": 4045, "s": 4034, "text": "JavaScript" }, { "code": null, "e": 4062, "s": 4045, "text": "Web Technologies" }, { "code": null, "e": 4067, "s": 4062, "text": "HTML" }, { "code": null, "e": 4165, "s": 4067, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4204, "s": 4165, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 4243, "s": 4204, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 4282, "s": 4243, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 4311, "s": 4282, "text": "Form validation using jQuery" }, { "code": null, "e": 4348, "s": 4311, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 4372, "s": 4348, "text": "REST API (Introduction)" }, { "code": null, "e": 4425, "s": 4372, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 4485, "s": 4425, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 4546, "s": 4485, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
What does the @ prefix do on string literals in C#?
The @prefix states hat you don't need to escape special characters in the string following to the symbol. The following statement @"D:\new" is equal to: "D:\\new" The @ prefix is also used if you want to have large strings and want it to be displayed across multiple lines. The following is an example showing multi-line string − Live Demo using System; namespace Demo { class Program { static void Main(string[] args) { string str = @"Welcome User, Kindly wait for the image to load"; Console.WriteLine(str); } } } Welcome User, Kindly wait for the image to load
[ { "code": null, "e": 1168, "s": 1062, "text": "The @prefix states hat you don't need to escape special characters in the string following to the symbol." }, { "code": null, "e": 1192, "s": 1168, "text": "The following statement" }, { "code": null, "e": 1202, "s": 1192, "text": "@\"D:\\new\"" }, { "code": null, "e": 1215, "s": 1202, "text": "is equal to:" }, { "code": null, "e": 1225, "s": 1215, "text": "\"D:\\\\new\"" }, { "code": null, "e": 1392, "s": 1225, "text": "The @ prefix is also used if you want to have large strings and want it to be displayed across multiple lines. The following is an example showing multi-line string −" }, { "code": null, "e": 1403, "s": 1392, "text": " Live Demo" }, { "code": null, "e": 1637, "s": 1403, "text": "using System;\n\nnamespace Demo {\n\n class Program {\n\n static void Main(string[] args) {\n string str = @\"Welcome User,\n Kindly wait for the image to\n load\";\n\n Console.WriteLine(str);\n }\n }\n}" }, { "code": null, "e": 1685, "s": 1637, "text": "Welcome User,\nKindly wait for the image to\nload" } ]
Gradio: graphical interfaces for Machine Learning models | by Pier Paolo Ippolito | Towards Data Science
1 2 3 4 5 6 7 8 9 10 Powered by Play.ht Create audio with Play.ht Create Audio Narrations with Play.ht Creating Machine Learning models is nowadays becoming increasingly easy thanks to many open-source and proprietary based services (e.g. Python, R, SAS). Although, practitioners might always find it difficult to efficiently create interfaces to test and share their completed model to colleagues or stakeholders. One possible solution to this problem is Gradio, a free open-source Python package which helps you to create models user interfaces which you can effortlessly share with a link to colleagues and friends. Gradio can be easily installed by using the following command: !pip install gradio Gradio is perfectly compatible with many Machine Learning frameworks (e.g. TensorFlow, PyTorch, etc...) and can be used even for arbitrary general-purpose Python scripts. I will now walk you through different examples of how Gradio can be integrated into your Machine Learning workflow. All the code used for this article is available in this Google Colab notebook and my GitHub account. In this example, we are going to create an interface to load images to test a Computer Vision model. In this case, we are going to use PyTorch and the Alexnet pre-trained model, but this experiment can be recreated for any other model and framework. In order to create a Gradio interface we just need to call the interface function and pass three parameters: fn: a function which is automatically called by interacting with the user interface in order to create a prediction for our model, provided some form of input. inputs: to inform Gradio what type of input we are expecting to get from the user interface (e.g. images, text, audio data, numerical data). outputs: to inform Gradio what type of output is going to be returned by our prediction function. In this way, Gradio can understand how the output can best be represented on the user interface. Once created our interface we then just need to launch it (Figure 1). When launching the interface we can then decide if to pass extra parameters such as share or debug as true. These parameters can in fact be used to embed our Gradio interface not just on our notebook but also as a sharable webpage and to make it easier to debug our system during testing. Sharable links, remains although active just for 6 hours. Generating text in order to predict the conclusion of a sentence or to generate narratives is currently a topic of great interest, especially thanks to the advent of Natural Language Processing (NLP) Transformers. In this example, I am going to create a user interface for the GTP2 HuggingFace pre-trained model I introduced in a my previous article about NLP. Finally, in this example, I am going to show how Gradio can be used for classical Machine Learning problems involving multiple types of input data. In this example, the Kaggle Heart Disease UCI dataset is going to be used as our dataset. All the data pre-processing steps are available in this Google Colab notebook and on my GitHub account. Gradio, can be certainly be considered to be a great tool in order to create interfaces for Machine Learning project when creating and testing models, although in order to incorporate your model in a production and stable environment alternative solutions might be necessary such as: ONNX (Open Neural Network Exchange Format) Flask and Heroku Tensorflow.js Dash by Plotly Tkinter A full list of the different facilities and GUI interfaces provided by Gradio is available on the official Gradio Documentation page. If you have any question, feel free to leave a comment in the comment section below. I hope you enjoyed this article, thank you for reading! If you want to keep updated with my latest articles and projects follow me on Medium and subscribe to my mailing list. These are some of my contacts details:
[ { "code": null, "e": 174, "s": 172, "text": "1" }, { "code": null, "e": 176, "s": 174, "text": "2" }, { "code": null, "e": 178, "s": 176, "text": "3" }, { "code": null, "e": 180, "s": 178, "text": "4" }, { "code": null, "e": 182, "s": 180, "text": "5" }, { "code": null, "e": 184, "s": 182, "text": "6" }, { "code": null, "e": 186, "s": 184, "text": "7" }, { "code": null, "e": 188, "s": 186, "text": "8" }, { "code": null, "e": 190, "s": 188, "text": "9" }, { "code": null, "e": 193, "s": 190, "text": "10" }, { "code": null, "e": 212, "s": 193, "text": "Powered by Play.ht" }, { "code": null, "e": 238, "s": 212, "text": "Create audio with Play.ht" }, { "code": null, "e": 275, "s": 238, "text": "Create Audio Narrations with Play.ht" }, { "code": null, "e": 587, "s": 275, "text": "Creating Machine Learning models is nowadays becoming increasingly easy thanks to many open-source and proprietary based services (e.g. Python, R, SAS). Although, practitioners might always find it difficult to efficiently create interfaces to test and share their completed model to colleagues or stakeholders." }, { "code": null, "e": 791, "s": 587, "text": "One possible solution to this problem is Gradio, a free open-source Python package which helps you to create models user interfaces which you can effortlessly share with a link to colleagues and friends." }, { "code": null, "e": 854, "s": 791, "text": "Gradio can be easily installed by using the following command:" }, { "code": null, "e": 874, "s": 854, "text": "!pip install gradio" }, { "code": null, "e": 1045, "s": 874, "text": "Gradio is perfectly compatible with many Machine Learning frameworks (e.g. TensorFlow, PyTorch, etc...) and can be used even for arbitrary general-purpose Python scripts." }, { "code": null, "e": 1262, "s": 1045, "text": "I will now walk you through different examples of how Gradio can be integrated into your Machine Learning workflow. All the code used for this article is available in this Google Colab notebook and my GitHub account." }, { "code": null, "e": 1512, "s": 1262, "text": "In this example, we are going to create an interface to load images to test a Computer Vision model. In this case, we are going to use PyTorch and the Alexnet pre-trained model, but this experiment can be recreated for any other model and framework." }, { "code": null, "e": 1621, "s": 1512, "text": "In order to create a Gradio interface we just need to call the interface function and pass three parameters:" }, { "code": null, "e": 1781, "s": 1621, "text": "fn: a function which is automatically called by interacting with the user interface in order to create a prediction for our model, provided some form of input." }, { "code": null, "e": 1922, "s": 1781, "text": "inputs: to inform Gradio what type of input we are expecting to get from the user interface (e.g. images, text, audio data, numerical data)." }, { "code": null, "e": 2117, "s": 1922, "text": "outputs: to inform Gradio what type of output is going to be returned by our prediction function. In this way, Gradio can understand how the output can best be represented on the user interface." }, { "code": null, "e": 2534, "s": 2117, "text": "Once created our interface we then just need to launch it (Figure 1). When launching the interface we can then decide if to pass extra parameters such as share or debug as true. These parameters can in fact be used to embed our Gradio interface not just on our notebook but also as a sharable webpage and to make it easier to debug our system during testing. Sharable links, remains although active just for 6 hours." }, { "code": null, "e": 2895, "s": 2534, "text": "Generating text in order to predict the conclusion of a sentence or to generate narratives is currently a topic of great interest, especially thanks to the advent of Natural Language Processing (NLP) Transformers. In this example, I am going to create a user interface for the GTP2 HuggingFace pre-trained model I introduced in a my previous article about NLP." }, { "code": null, "e": 3237, "s": 2895, "text": "Finally, in this example, I am going to show how Gradio can be used for classical Machine Learning problems involving multiple types of input data. In this example, the Kaggle Heart Disease UCI dataset is going to be used as our dataset. All the data pre-processing steps are available in this Google Colab notebook and on my GitHub account." }, { "code": null, "e": 3521, "s": 3237, "text": "Gradio, can be certainly be considered to be a great tool in order to create interfaces for Machine Learning project when creating and testing models, although in order to incorporate your model in a production and stable environment alternative solutions might be necessary such as:" }, { "code": null, "e": 3564, "s": 3521, "text": "ONNX (Open Neural Network Exchange Format)" }, { "code": null, "e": 3581, "s": 3564, "text": "Flask and Heroku" }, { "code": null, "e": 3595, "s": 3581, "text": "Tensorflow.js" }, { "code": null, "e": 3610, "s": 3595, "text": "Dash by Plotly" }, { "code": null, "e": 3618, "s": 3610, "text": "Tkinter" }, { "code": null, "e": 3837, "s": 3618, "text": "A full list of the different facilities and GUI interfaces provided by Gradio is available on the official Gradio Documentation page. If you have any question, feel free to leave a comment in the comment section below." }, { "code": null, "e": 3893, "s": 3837, "text": "I hope you enjoyed this article, thank you for reading!" } ]
Monthly Spot Price Prediction - Time Series Analysis by State Space Method | by Sarit Maitra | Towards Data Science
ERROR: type should be string, got "https://sarit-maitra.medium.com/membership\nSARIMAX application to original series have the advantages e.g. interpret-ability of model parameters. The objective here is to develop a Seasonal Autoregressive Integrated Moving Average with external variables (SARIMAX) model which tries to account all the effects due to the price influencing factors, to forecast the monthly spot price at Henry Hub. Natural gas price is a random variable which follows a stochastic process with a random trend.\nThe ability to predict trends is more useful rather than point forecasts in a complex system like stock market. We can predict trends with greater confidence and reliability, rather than the values or levels of these quantities.\nHere, our time series forecasting model will use the past price and other variables e.g. climate, storage etc. to predict their future values Natural Gas. Our time series are influenced by lot of external factors. SARIMAX has the capability to incorporate both seasonal and non-seasonal factors in a multiplicative model. Therefore, when the time series exhibits a seasonal variation, the SARIMAX model is usually applied.\nSARIMAX model is a SARIMA model with external variables, called SARIMAX (p,d,q) (P,D,Q)S (X), where X is the vector of external variables.\nData related to prices, consumption, reserves, storage, productions, pipelines etc., and climate data including cooling/heating degree days, extreme maximum/minimum temperature, mean temperature, and mean maximum/minimum temperature for New Orleans, LA. All these data were combined together in a single file as an input data file.\nWe can see that our time-series has more than one time-dependent variable. Each variable depends on its past values and also has some dependency on other variables. We will use this dependency here to predict future values.\nSARIMAX is an example of a fully fledged model created using the state space back-end for estimation. SARIMAX model consists of five iterative steps-\nModel identification where we identify order of differencing (d), order of seasonal differencing (D), seasonal length (S), non-seasonal autoregressive order (p), seasonal autoregressive order (P), non-seasonal moving average order (q), and seasonal moving average order (Q).Parameter estimation where parameters of the identified model from step 1 are estimated.The fitness of model is diagnosed using Ljung-Box Q statistic to check the adequacy. If the residuals are not normally distributed, we need go to step 4. Otherwise, proceed to step 5.Inclusion of external variables: The relevant external variables are included into the SARIMA model using linear regression.The diagnosed model is validated using out-sample. The validated model is used for forecasting the future values.\nModel identification where we identify order of differencing (d), order of seasonal differencing (D), seasonal length (S), non-seasonal autoregressive order (p), seasonal autoregressive order (P), non-seasonal moving average order (q), and seasonal moving average order (Q).\nParameter estimation where parameters of the identified model from step 1 are estimated.\nThe fitness of model is diagnosed using Ljung-Box Q statistic to check the adequacy. If the residuals are not normally distributed, we need go to step 4. Otherwise, proceed to step 5.\nInclusion of external variables: The relevant external variables are included into the SARIMA model using linear regression.\nThe diagnosed model is validated using out-sample. The validated model is used for forecasting the future values.\nplt.figure()plt.subplot(211)plot_acf(df['hh_sp'], ax=plt.gca())plt.subplot(212)plot_pacf(df['hh_sp'], ax=plt.gca())plt.xlabel('Lag')plt.tight_layout()plt.show()\ndf = data.copy()df.set_index('Date', inplace=True)print(df.info())df = df.astype(float)res = sm.tsa.seasonal_decompose(df['hh_sp'],freq=12)fig = res.plot()fig.set_figheight(8)fig.set_figwidth(15)plt.show()\nFrom the trend plot, we do not observe any clear trend which follows somewhat stochastic movement here (random walk with drift).\nWe can see here that, just differencing is not helping to normalize the data set.\ndf.isnull().sum()def fill_missing(df):for row in range(df.shape[0]):for col in range(df.shape[1]):if np.isnan(df[row,col]):df[row,col]= df[row-1, col]fill_missing(df.values)np.isnan(df).sum()fill_missing(df.values)np.isnan(df).sum()\nWe have used feature ranking with recursive feature elimination and cross- validated selection of the best number of features using linear regression as the model.\nThe feature ranking, such that ranking_[i] corresponds to the ranking position of the i-th feature. Selected (i.e., estimated best) features are assigned rank 1.\ny = df['hh_sp']X = df.drop(['hh_sp'], axis=1)names=pd.DataFrame(X.columns)lin_reg = LinearRegression()mod = RFECV(lin_reg, step=1, cv=20) mod_fit = mod.fit(X,y) rankings=pd.DataFrame(mod_fit.ranking_, index=names) #Make it into data framerankings.rename(columns ={0: 'Rank'}, inplace=True)rankings.transpose()\n14 features are selected for inclusion in the model\nLet us define our target; we will project next 5 months spot price.\ndf['target'] = df['hh_sp'].shift(-5)df.dropna(inplace=True)n = df.drop(['target'], axis=1) # storing in a dataframe for future usedataset = df[['im_pr','ex_pr','prod_mp','prod_liq','prod_dng','imp_tot','imp_pip','ImpLiq', 'mean_max_txt', 'mean_min_txt', 'mean_txt', 'mean_max_lat', 'mean_min_lat','mean_lat', 'target' ]]dataset.describe()\nX = np.array(dataset.drop(['target'], 1))y = np.array(dataset['target'])tscv = TimeSeriesSplit(max_train_size=None, n_splits=5)for train_samples, test_samples in tscv.split(X):#print(\"TRAIN:\", train_samples, \"TEST:\", test_samples)X_train, X_test = X[train_samples], X[test_samples]y_train, y_test = y[train_samples], y[test_samples]print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)feature_names = ['im_pr','ex_pr','prod_mp','prod_liq','prod_dng','imp_tot','imp_pip','ImpLiq','mean_max_tx', 'mean_min_txt', 'mean_txt', 'mean_max_lat', 'mean_min_lat','mean_lat' ]X_train = pd.DataFrame(data=X_train, columns=feature_names)X_train.index = dataset[:186].indexy_train = pd.DataFrame(y_train, columns = ['target'])y_train.index = X_train.indexX_test = pd.DataFrame(data=X_test, columns=feature_names)X_test.index = dataset[186:].indexy_test = pd.DataFrame(y_test, columns = ['target'])y_test.index = X_test.index\nKnowing that, stock price in general follow random walk; the first stage is to generate a set of changes or differences for each of the variables, since spot price can be explained by reference to the unexpected changes in the set of chosen variables rather than their levels. The unexpected value of a variable can be defined as the difference between the actual value of the variable and its expected value. The entire change in the variables from one period to the next is the unexpected change\nThe advantage of series being stationary is that, the effect of a shock will ease out gradually compared to non-stationary system where effect of shock is permanent.\nWhether or not to use differencing partially conditional maximum likelihood estimation. If True, differencing is performed prior to estimation, which discards the first sD+d initial rows but results in a smaller state-space formulation. See the Notes section for important details about interpreting results when this option is used. If False, the full SARIMAX model is put in state-space form so that all data points can be used in estimation. Default is False.\nAs we know that, SARIMAX combines the ARIMA model with the ability to perform the same auto-regression, differencing, and moving average modeling at the seasonal level. Let us estimate the parameters using maximum likelihood method.\n# Fit auto_arima functionstepwise_fit = auto_arima(y_train_tran, X_train_tran, start_p = 1, start_q = 1, max_p = 7, max_q = 7, m = 12, start_P = 0, seasonal = True,d = None, D = 1, trace = True, error_action ='ignore', suppress_warnings = True, stepwise = True) # To print the summarystepwise_fit.summary()\nThe p-values of the parameters of the model shows that the seasonal and non-seasonal AR and MA values are not significant at 5% level .\nHere, exogenous variables are given as parallel input sequences that have observations at the same time steps as the endogenous series.\n# fit modelmodel = sm.tsa.statespace.SARIMAX( endog = y_train_tran, exog = X_train_tran, order = (0, 0, 0), seasonal_order = (2, 1, 1, 12), enforce_invertibility = False, enforce_stationarity = False)model_fit = model.fit(disp = False)model_fit.summary()\nThis tests the null hypothesis of all the slope parameters being jointly zero. The p-value of zero attached to the test statistic shows that this null hypothesis should be rejected. Here, all our parameters are having p> 0.05 and therefore null hypothesis cannot be rejected.\nThe model is diagnosed using the Ljung-Box Q statistic which indicates that the residuals are not white noise. The null hypothesis of the Box Ljung Test, H0, is that our model does not show lack of fit.\nDiagnostic plots help us determine visually how our model is fitting the data and if any of the basic assumptions of an SARIMAX model are being violated.\nWe can see that, the underlying error distribution is Gaussian with constant mean and standard deviation of parametric assumptions.\n# Fit a local level modelendog = ytest_tranlocal_model = sm.tsa.UnobservedComponents(endog, 'local level')# Fit the model via maximum likelihoodresult = local_model.fit()# result is an instance of the Unobserved Components Results classprint(result.summary())# Show a plot of the estimated level and trend component seriesfig = result.plot_components()plt.tight_layout()\nX_test_tran = np.log(X_test).diff()Xtest_tran = X_test_tran.copy()Xtest_tran = Xtest_tran[~Xtest_tran.isin([np.nan, np.inf, -np.inf]).any(1)]Xtest_tran.describe()y_test_log = np.log(y_test['target']).dropna()y_test_tran = y_test_log.diff().dropna()ytest_tran = y_test_tran.copy()#ytest_tran = ytest_tran[~ytest_tran.isin([np.nan, np.inf, -np.inf]).any(1)]ytest_tran.describe()\nrebuilt = pred.cumsum().fillna(0)print('\\nCumsum:\\n', rebuilt.tail())rebuilt_further = rebuilt + y_test_log[-1:] # last value of test setprint('\\nDe-difference:\\n',rebuilt_further.tail())original = np.exp(rebuilt_further)print('\\nOriginal form:\\n',original.tail())\nWe had shifted our target variables to 5 periods (months); therefore, above should be future 5 months forecast. Let us do some data manipulation to get future dates as shown below.\nIt can be noticed that, setting up monthly frequency by fault shows future all dates are end of month instead 15 as per original data set. Well, this can also be fixed to synchronize with original data.\n# Graphfig, ax = plt.subplots(figsize=(10,5))ax.set(title='Henry Hub Spot price', xlabel='Date', ylabel='USD / Mbtu')# Plot data pointsy_test.plot(ax=ax, label='Observed')# Plot predictionsoriginal.plot(ax=ax, style='r--', label='One-step-ahead forecast')legend = ax.legend(loc='best')\nMoreover, it is also possible to get the the confidence interval between upper and lower level of predicted price and draw confidence interval plot too.\nIt is always a good idea to start with a simple model and test whether it is good enough for its purpose. Applying iterative modeling approach we can add features gradually. Comparing results of successive models provides a form of internal validation, so we can catch conceptual, mathematical, and software errors. By adding and removing features, we can tell which ones have the biggest effect on the results, and which can be ignored.\nThe important assumption of time series forecasting is the current price is a function of the demand and past price. However, the relation is not just straight forward; demand also depends on climatic condition, import/export price etc. A set of 14 variables are found through recursive feature elimination methods. These variables are found to be important to determine monthly Natural Gas spot price. SARIMAX model is used here for price forecasting, which has a distinct advantage in its explanation of the outlying data. Based on prediction, we could see that SARIMAX prediction can follow the pattern of actual data smoothly.\nI can be reached here."
[ { "code": null, "e": 214, "s": 171, "text": "https://sarit-maitra.medium.com/membership" }, { "code": null, "e": 663, "s": 214, "text": "SARIMAX application to original series have the advantages e.g. interpret-ability of model parameters. The objective here is to develop a Seasonal Autoregressive Integrated Moving Average with external variables (SARIMAX) model which tries to account all the effects due to the price influencing factors, to forecast the monthly spot price at Henry Hub. Natural gas price is a random variable which follows a stochastic process with a random trend." }, { "code": null, "e": 892, "s": 663, "text": "The ability to predict trends is more useful rather than point forecasts in a complex system like stock market. We can predict trends with greater confidence and reliability, rather than the values or levels of these quantities." }, { "code": null, "e": 1315, "s": 892, "text": "Here, our time series forecasting model will use the past price and other variables e.g. climate, storage etc. to predict their future values Natural Gas. Our time series are influenced by lot of external factors. SARIMAX has the capability to incorporate both seasonal and non-seasonal factors in a multiplicative model. Therefore, when the time series exhibits a seasonal variation, the SARIMAX model is usually applied." }, { "code": null, "e": 1454, "s": 1315, "text": "SARIMAX model is a SARIMA model with external variables, called SARIMAX (p,d,q) (P,D,Q)S (X), where X is the vector of external variables." }, { "code": null, "e": 1786, "s": 1454, "text": "Data related to prices, consumption, reserves, storage, productions, pipelines etc., and climate data including cooling/heating degree days, extreme maximum/minimum temperature, mean temperature, and mean maximum/minimum temperature for New Orleans, LA. All these data were combined together in a single file as an input data file." }, { "code": null, "e": 2010, "s": 1786, "text": "We can see that our time-series has more than one time-dependent variable. Each variable depends on its past values and also has some dependency on other variables. We will use this dependency here to predict future values." }, { "code": null, "e": 2160, "s": 2010, "text": "SARIMAX is an example of a fully fledged model created using the state space back-end for estimation. SARIMAX model consists of five iterative steps-" }, { "code": null, "e": 2943, "s": 2160, "text": "Model identification where we identify order of differencing (d), order of seasonal differencing (D), seasonal length (S), non-seasonal autoregressive order (p), seasonal autoregressive order (P), non-seasonal moving average order (q), and seasonal moving average order (Q).Parameter estimation where parameters of the identified model from step 1 are estimated.The fitness of model is diagnosed using Ljung-Box Q statistic to check the adequacy. If the residuals are not normally distributed, we need go to step 4. Otherwise, proceed to step 5.Inclusion of external variables: The relevant external variables are included into the SARIMA model using linear regression.The diagnosed model is validated using out-sample. The validated model is used for forecasting the future values." }, { "code": null, "e": 3218, "s": 2943, "text": "Model identification where we identify order of differencing (d), order of seasonal differencing (D), seasonal length (S), non-seasonal autoregressive order (p), seasonal autoregressive order (P), non-seasonal moving average order (q), and seasonal moving average order (Q)." }, { "code": null, "e": 3307, "s": 3218, "text": "Parameter estimation where parameters of the identified model from step 1 are estimated." }, { "code": null, "e": 3491, "s": 3307, "text": "The fitness of model is diagnosed using Ljung-Box Q statistic to check the adequacy. If the residuals are not normally distributed, we need go to step 4. Otherwise, proceed to step 5." }, { "code": null, "e": 3616, "s": 3491, "text": "Inclusion of external variables: The relevant external variables are included into the SARIMA model using linear regression." }, { "code": null, "e": 3730, "s": 3616, "text": "The diagnosed model is validated using out-sample. The validated model is used for forecasting the future values." }, { "code": null, "e": 3891, "s": 3730, "text": "plt.figure()plt.subplot(211)plot_acf(df['hh_sp'], ax=plt.gca())plt.subplot(212)plot_pacf(df['hh_sp'], ax=plt.gca())plt.xlabel('Lag')plt.tight_layout()plt.show()" }, { "code": null, "e": 4097, "s": 3891, "text": "df = data.copy()df.set_index('Date', inplace=True)print(df.info())df = df.astype(float)res = sm.tsa.seasonal_decompose(df['hh_sp'],freq=12)fig = res.plot()fig.set_figheight(8)fig.set_figwidth(15)plt.show()" }, { "code": null, "e": 4226, "s": 4097, "text": "From the trend plot, we do not observe any clear trend which follows somewhat stochastic movement here (random walk with drift)." }, { "code": null, "e": 4308, "s": 4226, "text": "We can see here that, just differencing is not helping to normalize the data set." }, { "code": null, "e": 4541, "s": 4308, "text": "df.isnull().sum()def fill_missing(df):for row in range(df.shape[0]):for col in range(df.shape[1]):if np.isnan(df[row,col]):df[row,col]= df[row-1, col]fill_missing(df.values)np.isnan(df).sum()fill_missing(df.values)np.isnan(df).sum()" }, { "code": null, "e": 4705, "s": 4541, "text": "We have used feature ranking with recursive feature elimination and cross- validated selection of the best number of features using linear regression as the model." }, { "code": null, "e": 4867, "s": 4705, "text": "The feature ranking, such that ranking_[i] corresponds to the ranking position of the i-th feature. Selected (i.e., estimated best) features are assigned rank 1." }, { "code": null, "e": 5178, "s": 4867, "text": "y = df['hh_sp']X = df.drop(['hh_sp'], axis=1)names=pd.DataFrame(X.columns)lin_reg = LinearRegression()mod = RFECV(lin_reg, step=1, cv=20) mod_fit = mod.fit(X,y) rankings=pd.DataFrame(mod_fit.ranking_, index=names) #Make it into data framerankings.rename(columns ={0: 'Rank'}, inplace=True)rankings.transpose()" }, { "code": null, "e": 5230, "s": 5178, "text": "14 features are selected for inclusion in the model" }, { "code": null, "e": 5298, "s": 5230, "text": "Let us define our target; we will project next 5 months spot price." }, { "code": null, "e": 5637, "s": 5298, "text": "df['target'] = df['hh_sp'].shift(-5)df.dropna(inplace=True)n = df.drop(['target'], axis=1) # storing in a dataframe for future usedataset = df[['im_pr','ex_pr','prod_mp','prod_liq','prod_dng','imp_tot','imp_pip','ImpLiq', 'mean_max_txt', 'mean_min_txt', 'mean_txt', 'mean_max_lat', 'mean_min_lat','mean_lat', 'target' ]]dataset.describe()" }, { "code": null, "e": 6558, "s": 5637, "text": "X = np.array(dataset.drop(['target'], 1))y = np.array(dataset['target'])tscv = TimeSeriesSplit(max_train_size=None, n_splits=5)for train_samples, test_samples in tscv.split(X):#print(\"TRAIN:\", train_samples, \"TEST:\", test_samples)X_train, X_test = X[train_samples], X[test_samples]y_train, y_test = y[train_samples], y[test_samples]print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)feature_names = ['im_pr','ex_pr','prod_mp','prod_liq','prod_dng','imp_tot','imp_pip','ImpLiq','mean_max_tx', 'mean_min_txt', 'mean_txt', 'mean_max_lat', 'mean_min_lat','mean_lat' ]X_train = pd.DataFrame(data=X_train, columns=feature_names)X_train.index = dataset[:186].indexy_train = pd.DataFrame(y_train, columns = ['target'])y_train.index = X_train.indexX_test = pd.DataFrame(data=X_test, columns=feature_names)X_test.index = dataset[186:].indexy_test = pd.DataFrame(y_test, columns = ['target'])y_test.index = X_test.index" }, { "code": null, "e": 7056, "s": 6558, "text": "Knowing that, stock price in general follow random walk; the first stage is to generate a set of changes or differences for each of the variables, since spot price can be explained by reference to the unexpected changes in the set of chosen variables rather than their levels. The unexpected value of a variable can be defined as the difference between the actual value of the variable and its expected value. The entire change in the variables from one period to the next is the unexpected change" }, { "code": null, "e": 7222, "s": 7056, "text": "The advantage of series being stationary is that, the effect of a shock will ease out gradually compared to non-stationary system where effect of shock is permanent." }, { "code": null, "e": 7685, "s": 7222, "text": "Whether or not to use differencing partially conditional maximum likelihood estimation. If True, differencing is performed prior to estimation, which discards the first sD+d initial rows but results in a smaller state-space formulation. See the Notes section for important details about interpreting results when this option is used. If False, the full SARIMAX model is put in state-space form so that all data points can be used in estimation. Default is False." }, { "code": null, "e": 7918, "s": 7685, "text": "As we know that, SARIMAX combines the ARIMA model with the ability to perform the same auto-regression, differencing, and moving average modeling at the seasonal level. Let us estimate the parameters using maximum likelihood method." }, { "code": null, "e": 8392, "s": 7918, "text": "# Fit auto_arima functionstepwise_fit = auto_arima(y_train_tran, X_train_tran, start_p = 1, start_q = 1, max_p = 7, max_q = 7, m = 12, start_P = 0, seasonal = True,d = None, D = 1, trace = True, error_action ='ignore', suppress_warnings = True, stepwise = True) # To print the summarystepwise_fit.summary()" }, { "code": null, "e": 8528, "s": 8392, "text": "The p-values of the parameters of the model shows that the seasonal and non-seasonal AR and MA values are not significant at 5% level ." }, { "code": null, "e": 8664, "s": 8528, "text": "Here, exogenous variables are given as parallel input sequences that have observations at the same time steps as the endogenous series." }, { "code": null, "e": 9022, "s": 8664, "text": "# fit modelmodel = sm.tsa.statespace.SARIMAX( endog = y_train_tran, exog = X_train_tran, order = (0, 0, 0), seasonal_order = (2, 1, 1, 12), enforce_invertibility = False, enforce_stationarity = False)model_fit = model.fit(disp = False)model_fit.summary()" }, { "code": null, "e": 9298, "s": 9022, "text": "This tests the null hypothesis of all the slope parameters being jointly zero. The p-value of zero attached to the test statistic shows that this null hypothesis should be rejected. Here, all our parameters are having p> 0.05 and therefore null hypothesis cannot be rejected." }, { "code": null, "e": 9501, "s": 9298, "text": "The model is diagnosed using the Ljung-Box Q statistic which indicates that the residuals are not white noise. The null hypothesis of the Box Ljung Test, H0, is that our model does not show lack of fit." }, { "code": null, "e": 9655, "s": 9501, "text": "Diagnostic plots help us determine visually how our model is fitting the data and if any of the basic assumptions of an SARIMAX model are being violated." }, { "code": null, "e": 9787, "s": 9655, "text": "We can see that, the underlying error distribution is Gaussian with constant mean and standard deviation of parametric assumptions." }, { "code": null, "e": 10158, "s": 9787, "text": "# Fit a local level modelendog = ytest_tranlocal_model = sm.tsa.UnobservedComponents(endog, 'local level')# Fit the model via maximum likelihoodresult = local_model.fit()# result is an instance of the Unobserved Components Results classprint(result.summary())# Show a plot of the estimated level and trend component seriesfig = result.plot_components()plt.tight_layout()" }, { "code": null, "e": 10535, "s": 10158, "text": "X_test_tran = np.log(X_test).diff()Xtest_tran = X_test_tran.copy()Xtest_tran = Xtest_tran[~Xtest_tran.isin([np.nan, np.inf, -np.inf]).any(1)]Xtest_tran.describe()y_test_log = np.log(y_test['target']).dropna()y_test_tran = y_test_log.diff().dropna()ytest_tran = y_test_tran.copy()#ytest_tran = ytest_tran[~ytest_tran.isin([np.nan, np.inf, -np.inf]).any(1)]ytest_tran.describe()" }, { "code": null, "e": 10800, "s": 10535, "text": "rebuilt = pred.cumsum().fillna(0)print('\\nCumsum:\\n', rebuilt.tail())rebuilt_further = rebuilt + y_test_log[-1:] # last value of test setprint('\\nDe-difference:\\n',rebuilt_further.tail())original = np.exp(rebuilt_further)print('\\nOriginal form:\\n',original.tail())" }, { "code": null, "e": 10981, "s": 10800, "text": "We had shifted our target variables to 5 periods (months); therefore, above should be future 5 months forecast. Let us do some data manipulation to get future dates as shown below." }, { "code": null, "e": 11184, "s": 10981, "text": "It can be noticed that, setting up monthly frequency by fault shows future all dates are end of month instead 15 as per original data set. Well, this can also be fixed to synchronize with original data." }, { "code": null, "e": 11470, "s": 11184, "text": "# Graphfig, ax = plt.subplots(figsize=(10,5))ax.set(title='Henry Hub Spot price', xlabel='Date', ylabel='USD / Mbtu')# Plot data pointsy_test.plot(ax=ax, label='Observed')# Plot predictionsoriginal.plot(ax=ax, style='r--', label='One-step-ahead forecast')legend = ax.legend(loc='best')" }, { "code": null, "e": 11623, "s": 11470, "text": "Moreover, it is also possible to get the the confidence interval between upper and lower level of predicted price and draw confidence interval plot too." }, { "code": null, "e": 12061, "s": 11623, "text": "It is always a good idea to start with a simple model and test whether it is good enough for its purpose. Applying iterative modeling approach we can add features gradually. Comparing results of successive models provides a form of internal validation, so we can catch conceptual, mathematical, and software errors. By adding and removing features, we can tell which ones have the biggest effect on the results, and which can be ignored." }, { "code": null, "e": 12692, "s": 12061, "text": "The important assumption of time series forecasting is the current price is a function of the demand and past price. However, the relation is not just straight forward; demand also depends on climatic condition, import/export price etc. A set of 14 variables are found through recursive feature elimination methods. These variables are found to be important to determine monthly Natural Gas spot price. SARIMAX model is used here for price forecasting, which has a distinct advantage in its explanation of the outlying data. Based on prediction, we could see that SARIMAX prediction can follow the pattern of actual data smoothly." } ]
Flipkart Interview | Set 3 - GeeksforGeeks
27 Sep, 2021 Recently I appeared for Flipkart Interview. I would like to share my experience. Round-1: Telephonic (45 mins) Given an array of n distinct integers sorted in ascending order. Find an index i s.t ar[i] = i. Return -1 if no such index exists. Note that integers in array can be negative. Article Link: https://www.geeksforgeeks.org/find-a-fixed-point-in-a-given-array/Practice Link: https://practice.geeksforgeeks.org/problems/value-equal-to-index-value1330/1 Design a stack which holds an integer value such that getMinimum() function should return the minimum element in the stack. FOLLOW UP: Implement popMin() function which would pop minimum element from the original stack. O(1) implementation was required. (Hint: Use LinkedList to implement stack and store address of minimum element node in min-stack) Article Link: https://www.geeksforgeeks.org/design-a-stack-that-supports-getmin-in-o1-time-and-o1-extra-space/Practice Link: https://practice.geeksforgeeks.org/problems/special-stack/1 Print an organisational hierarchy. Naveen manages Satish Satish manages Anushree Satish manages Sandeep Gurinder manages Naveen Gurinder->Naveen Naveen->Satish Satish->Anushree,Sandeep Anushree-> Sandeep-> Given an array of n distinct integers sorted in ascending order. Find an index i s.t ar[i] = i. Return -1 if no such index exists. Note that integers in array can be negative. Article Link: https://www.geeksforgeeks.org/find-a-fixed-point-in-a-given-array/Practice Link: https://practice.geeksforgeeks.org/problems/value-equal-to-index-value1330/1 Design a stack which holds an integer value such that getMinimum() function should return the minimum element in the stack. FOLLOW UP: Implement popMin() function which would pop minimum element from the original stack. O(1) implementation was required. (Hint: Use LinkedList to implement stack and store address of minimum element node in min-stack) Article Link: https://www.geeksforgeeks.org/design-a-stack-that-supports-getmin-in-o1-time-and-o1-extra-space/Practice Link: https://practice.geeksforgeeks.org/problems/special-stack/1 Print an organisational hierarchy. Naveen manages Satish Satish manages Anushree Satish manages Sandeep Gurinder manages Naveen Gurinder->Naveen Naveen->Satish Satish->Anushree,Sandeep Anushree-> Sandeep-> Gurinder->Naveen Naveen->Satish Satish->Anushree,Sandeep Anushree-> Sandeep-> Round-2: Telephonic (30 mins) Given an array which is first strictly increasing and then strictly decreasing. Find an element in this array. Discussions on various approaches and their complexities.Article Link: https://www.geeksforgeeks.org/find-element-bitonic-array/Practice Link: https://practice.geeksforgeeks.org/problems/maximum-value-in-a-bitonic-array3001/1 Round-3: In-House Coding(1 Hour 45 mins) Write a running code in any language to implement the famous tic-tac-toe game. First, there was a discussion on various approaches and basic functions which would be required to implement the same. Then I was asked to code. I was given 1 hour 15 mins to code this. I had to design this game as per following: Game has 3 modes: Human Vs Human, Human Vs Computer and Computer Vs Computer. Initially start with a 3X3 grid, but it can be generalised to NXN grid. So don’t hardcode any variable. Minimise Code Redundancy and try to make it as modular as possible. Try to use abstraction and expose a lesser number of functions(APIs) to the outside world. Try to cover maximum number of edge cases, like when to abort the game, draw condition, win condition, overwriting the existing value in grid etc) Round-4: Data Structure and Problem Solving(1 Hour) Given a sorted and rotated array. Find an element in this array. (Famous Problem) This was an interesting problem. Given a set of intervals like 5-10, 15-20, 25-40, 30-45, 50-100. Find the ith smallest number in these intervals. Assume there are no duplicate numbers.e.g: 1st smallest number = 5 6th smallest number = 10 7th smallest number = 15 and so on. I told him that we would first sort the interval on basis of starting numbers. Then merge overlapping intervals to get a set of non-overlapping intervals like 5-10, 15-20, 25-45, 50-100. Now we can find the ith smallest number after finding the appropriate interval. FOLLOW UP: He then modified this question to accommodate duplicate numbers also.Suppose we have intervals like 5-10, 8-12. Then total numbers in these two intervals would be: {5,6,7,8,8,9,9,10,10,11,12} So, 1st smallest number: 5 4th smallest number: 8 5th smallest number: 8 (here is the change since now we have duplicate elements also) and so on. Given a dictionary of 50,000 words. Given a phrase without spaces, add spaces to make it a proper sentence.e.g: input: thequickbrownfoxjumpoverlazydog output: the quick brown fox jump over lazy dog Given a sorted and rotated array. Find an element in this array. (Famous Problem) This was an interesting problem. Given a set of intervals like 5-10, 15-20, 25-40, 30-45, 50-100. Find the ith smallest number in these intervals. Assume there are no duplicate numbers.e.g: 1st smallest number = 5 6th smallest number = 10 7th smallest number = 15 and so on. I told him that we would first sort the interval on basis of starting numbers. Then merge overlapping intervals to get a set of non-overlapping intervals like 5-10, 15-20, 25-45, 50-100. Now we can find the ith smallest number after finding the appropriate interval. FOLLOW UP: He then modified this question to accommodate duplicate numbers also.Suppose we have intervals like 5-10, 8-12. Then total numbers in these two intervals would be: {5,6,7,8,8,9,9,10,10,11,12} So, 1st smallest number: 5 4th smallest number: 8 5th smallest number: 8 (here is the change since now we have duplicate elements also) and so on. e.g: 1st smallest number = 5 6th smallest number = 10 7th smallest number = 15 and so on. I told him that we would first sort the interval on basis of starting numbers. Then merge overlapping intervals to get a set of non-overlapping intervals like 5-10, 15-20, 25-45, 50-100. Now we can find the ith smallest number after finding the appropriate interval. FOLLOW UP: He then modified this question to accommodate duplicate numbers also. Suppose we have intervals like 5-10, 8-12. Then total numbers in these two intervals would be: {5,6,7,8,8,9,9,10,10,11,12} So, 1st smallest number: 5 4th smallest number: 8 5th smallest number: 8 (here is the change since now we have duplicate elements also) and so on. Given a dictionary of 50,000 words. Given a phrase without spaces, add spaces to make it a proper sentence.e.g: input: thequickbrownfoxjumpoverlazydog output: the quick brown fox jump over lazy dog e.g: input: thequickbrownfoxjumpoverlazydog output: the quick brown fox jump over lazy dog FOLLOW UP Questions: Worst case complexity of finding a word in HASHMAP given we have ‘B’ buckets and total of 50,000 words. ( Ans: O(50,000/B) ) Complexity of finding a word in TRIE. (Ans: O(Word Length) ) Advantages of TRIE over HASHMAP and some similar discussion. Worst case complexity of finding a word in HASHMAP given we have ‘B’ buckets and total of 50,000 words. ( Ans: O(50,000/B) ) Complexity of finding a word in TRIE. (Ans: O(Word Length) ) Advantages of TRIE over HASHMAP and some similar discussion. Round-5: Hiring Manager Round(45 mins) He asked me lots of questions regarding my current company projects. Questions: My role in current project. Most Challenging work in your company. What technologies you learnt last year? and several similar questions. My role in current project. Most Challenging work in your company. What technologies you learnt last year? and several similar questions. Round-6: HR Round (10 mins) Common HR questions like why Flipkart, Why should we hire you etc. 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. All Practice Problems for Flipkart ! Flipkart Interview Experiences Flipkart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Amazon Interview Experience for SDE-1 (On-Campus) Difference between ANN, CNN and RNN Amazon Interview Experience for SDE-1 Amazon Interview Experience (Off-Campus) 2022 Amazon Interview Experience for SDE-1 Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 Microsoft Interview Experience for Internship (Via Engage) Infosys DSE Interview Experience 2021 Zoho Interview | Set 1 (On-Campus) Infosys Interview Experience for DSE - System Engineer | On-Campus 2022
[ { "code": null, "e": 24994, "s": 24966, "text": "\n27 Sep, 2021" }, { "code": null, "e": 25076, "s": 24994, "text": "Recently I appeared for Flipkart Interview. I would like to share my experience. " }, { "code": null, "e": 25110, "s": 25078, "text": "Round-1: Telephonic (45 mins) " }, { "code": null, "e": 26200, "s": 25110, "text": "Given an array of n distinct integers sorted in ascending order. Find an index i s.t ar[i] = i. Return -1 if no such index exists. Note that integers in array can be negative. Article Link: https://www.geeksforgeeks.org/find-a-fixed-point-in-a-given-array/Practice Link: https://practice.geeksforgeeks.org/problems/value-equal-to-index-value1330/1 Design a stack which holds an integer value such that getMinimum() function should return the minimum element in the stack. FOLLOW UP: Implement popMin() function which would pop minimum element from the original stack. O(1) implementation was required. (Hint: Use LinkedList to implement stack and store address of minimum element node in min-stack) Article Link: https://www.geeksforgeeks.org/design-a-stack-that-supports-getmin-in-o1-time-and-o1-extra-space/Practice Link: https://practice.geeksforgeeks.org/problems/special-stack/1 Print an organisational hierarchy. Naveen manages Satish Satish manages Anushree Satish manages Sandeep Gurinder manages Naveen Gurinder->Naveen Naveen->Satish Satish->Anushree,Sandeep Anushree-> Sandeep->" }, { "code": null, "e": 26549, "s": 26200, "text": "Given an array of n distinct integers sorted in ascending order. Find an index i s.t ar[i] = i. Return -1 if no such index exists. Note that integers in array can be negative. Article Link: https://www.geeksforgeeks.org/find-a-fixed-point-in-a-given-array/Practice Link: https://practice.geeksforgeeks.org/problems/value-equal-to-index-value1330/1 " }, { "code": null, "e": 27086, "s": 26549, "text": "Design a stack which holds an integer value such that getMinimum() function should return the minimum element in the stack. FOLLOW UP: Implement popMin() function which would pop minimum element from the original stack. O(1) implementation was required. (Hint: Use LinkedList to implement stack and store address of minimum element node in min-stack) Article Link: https://www.geeksforgeeks.org/design-a-stack-that-supports-getmin-in-o1-time-and-o1-extra-space/Practice Link: https://practice.geeksforgeeks.org/problems/special-stack/1 " }, { "code": null, "e": 27292, "s": 27086, "text": "Print an organisational hierarchy. Naveen manages Satish Satish manages Anushree Satish manages Sandeep Gurinder manages Naveen Gurinder->Naveen Naveen->Satish Satish->Anushree,Sandeep Anushree-> Sandeep->" }, { "code": null, "e": 27370, "s": 27292, "text": "Gurinder->Naveen Naveen->Satish Satish->Anushree,Sandeep Anushree-> Sandeep->" }, { "code": null, "e": 27402, "s": 27370, "text": "Round-2: Telephonic (30 mins) " }, { "code": null, "e": 27739, "s": 27402, "text": "Given an array which is first strictly increasing and then strictly decreasing. Find an element in this array. Discussions on various approaches and their complexities.Article Link: https://www.geeksforgeeks.org/find-element-bitonic-array/Practice Link: https://practice.geeksforgeeks.org/problems/maximum-value-in-a-bitonic-array3001/1" }, { "code": null, "e": 28091, "s": 27739, "text": "Round-3: In-House Coding(1 Hour 45 mins) Write a running code in any language to implement the famous tic-tac-toe game. First, there was a discussion on various approaches and basic functions which would be required to implement the same. Then I was asked to code. I was given 1 hour 15 mins to code this. I had to design this game as per following: " }, { "code": null, "e": 28170, "s": 28091, "text": "Game has 3 modes: Human Vs Human, Human Vs Computer and Computer Vs Computer. " }, { "code": null, "e": 28275, "s": 28170, "text": "Initially start with a 3X3 grid, but it can be generalised to NXN grid. So don’t hardcode any variable. " }, { "code": null, "e": 28344, "s": 28275, "text": "Minimise Code Redundancy and try to make it as modular as possible. " }, { "code": null, "e": 28436, "s": 28344, "text": "Try to use abstraction and expose a lesser number of functions(APIs) to the outside world. " }, { "code": null, "e": 28583, "s": 28436, "text": "Try to cover maximum number of edge cases, like when to abort the game, draw condition, win condition, overwriting the existing value in grid etc)" }, { "code": null, "e": 28637, "s": 28583, "text": "Round-4: Data Structure and Problem Solving(1 Hour) " }, { "code": null, "e": 29863, "s": 28637, "text": "Given a sorted and rotated array. Find an element in this array. (Famous Problem) This was an interesting problem. Given a set of intervals like 5-10, 15-20, 25-40, 30-45, 50-100. Find the ith smallest number in these intervals. Assume there are no duplicate numbers.e.g: 1st smallest number = 5\n 6th smallest number = 10\n 7th smallest number = 15 and so on. I told him that we would first sort the interval on basis of starting numbers. Then merge overlapping intervals to get a set of non-overlapping intervals like 5-10, 15-20, 25-45, 50-100. Now we can find the ith smallest number after finding the appropriate interval. FOLLOW UP: He then modified this question to accommodate duplicate numbers also.Suppose we have intervals like 5-10, 8-12. \nThen total numbers in these two intervals would be: {5,6,7,8,8,9,9,10,10,11,12} \n So, 1st smallest number: 5\n 4th smallest number: 8\n 5th smallest number: 8 (here is the \nchange since now we have duplicate elements also) and so on. \nGiven a dictionary of 50,000 words. Given a phrase without spaces, add spaces to make it a proper sentence.e.g: input: thequickbrownfoxjumpoverlazydog\n output: the quick brown fox jump over lazy dog" }, { "code": null, "e": 29946, "s": 29863, "text": "Given a sorted and rotated array. Find an element in this array. (Famous Problem) " }, { "code": null, "e": 30888, "s": 29946, "text": "This was an interesting problem. Given a set of intervals like 5-10, 15-20, 25-40, 30-45, 50-100. Find the ith smallest number in these intervals. Assume there are no duplicate numbers.e.g: 1st smallest number = 5\n 6th smallest number = 10\n 7th smallest number = 15 and so on. I told him that we would first sort the interval on basis of starting numbers. Then merge overlapping intervals to get a set of non-overlapping intervals like 5-10, 15-20, 25-45, 50-100. Now we can find the ith smallest number after finding the appropriate interval. FOLLOW UP: He then modified this question to accommodate duplicate numbers also.Suppose we have intervals like 5-10, 8-12. \nThen total numbers in these two intervals would be: {5,6,7,8,8,9,9,10,10,11,12} \n So, 1st smallest number: 5\n 4th smallest number: 8\n 5th smallest number: 8 (here is the \nchange since now we have duplicate elements also) and so on. \n" }, { "code": null, "e": 30992, "s": 30888, "text": "e.g: 1st smallest number = 5\n 6th smallest number = 10\n 7th smallest number = 15 and so on. " }, { "code": null, "e": 31260, "s": 30992, "text": "I told him that we would first sort the interval on basis of starting numbers. Then merge overlapping intervals to get a set of non-overlapping intervals like 5-10, 15-20, 25-45, 50-100. Now we can find the ith smallest number after finding the appropriate interval. " }, { "code": null, "e": 31341, "s": 31260, "text": "FOLLOW UP: He then modified this question to accommodate duplicate numbers also." }, { "code": null, "e": 31648, "s": 31341, "text": "Suppose we have intervals like 5-10, 8-12. \nThen total numbers in these two intervals would be: {5,6,7,8,8,9,9,10,10,11,12} \n So, 1st smallest number: 5\n 4th smallest number: 8\n 5th smallest number: 8 (here is the \nchange since now we have duplicate elements also) and so on. \n" }, { "code": null, "e": 31851, "s": 31648, "text": "Given a dictionary of 50,000 words. Given a phrase without spaces, add spaces to make it a proper sentence.e.g: input: thequickbrownfoxjumpoverlazydog\n output: the quick brown fox jump over lazy dog" }, { "code": null, "e": 31947, "s": 31851, "text": "e.g: input: thequickbrownfoxjumpoverlazydog\n output: the quick brown fox jump over lazy dog" }, { "code": null, "e": 31970, "s": 31947, "text": "FOLLOW UP Questions: " }, { "code": null, "e": 32217, "s": 31970, "text": "Worst case complexity of finding a word in HASHMAP given we have ‘B’ buckets and total of 50,000 words. ( Ans: O(50,000/B) ) Complexity of finding a word in TRIE. (Ans: O(Word Length) ) Advantages of TRIE over HASHMAP and some similar discussion." }, { "code": null, "e": 32343, "s": 32217, "text": "Worst case complexity of finding a word in HASHMAP given we have ‘B’ buckets and total of 50,000 words. ( Ans: O(50,000/B) ) " }, { "code": null, "e": 32405, "s": 32343, "text": "Complexity of finding a word in TRIE. (Ans: O(Word Length) ) " }, { "code": null, "e": 32466, "s": 32405, "text": "Advantages of TRIE over HASHMAP and some similar discussion." }, { "code": null, "e": 32587, "s": 32466, "text": "Round-5: Hiring Manager Round(45 mins) He asked me lots of questions regarding my current company projects. Questions: " }, { "code": null, "e": 32727, "s": 32587, "text": "My role in current project. Most Challenging work in your company. What technologies you learnt last year? and several similar questions." }, { "code": null, "e": 32757, "s": 32727, "text": "My role in current project. " }, { "code": null, "e": 32798, "s": 32757, "text": "Most Challenging work in your company. " }, { "code": null, "e": 32869, "s": 32798, "text": "What technologies you learnt last year? and several similar questions." }, { "code": null, "e": 32899, "s": 32869, "text": "Round-6: HR Round (10 mins) " }, { "code": null, "e": 32966, "s": 32899, "text": "Common HR questions like why Flipkart, Why should we hire you etc." }, { "code": null, "e": 33189, "s": 32966, "text": "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": 33229, "s": 33191, "text": "All Practice Problems for Flipkart ! " }, { "code": null, "e": 33242, "s": 33233, "text": "Flipkart" }, { "code": null, "e": 33264, "s": 33242, "text": "Interview Experiences" }, { "code": null, "e": 33273, "s": 33264, "text": "Flipkart" }, { "code": null, "e": 33371, "s": 33273, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33380, "s": 33371, "text": "Comments" }, { "code": null, "e": 33393, "s": 33380, "text": "Old Comments" }, { "code": null, "e": 33443, "s": 33393, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 33479, "s": 33443, "text": "Difference between ANN, CNN and RNN" }, { "code": null, "e": 33517, "s": 33479, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 33563, "s": 33517, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 33601, "s": 33563, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 33666, "s": 33601, "text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022" }, { "code": null, "e": 33725, "s": 33666, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 33763, "s": 33725, "text": "Infosys DSE Interview Experience 2021" }, { "code": null, "e": 33798, "s": 33763, "text": "Zoho Interview | Set 1 (On-Campus)" } ]
Sqoop - List Tables
This chapter describes how to list out the tables of a particular database in MySQL database server using Sqoop. Sqoop list-tables tool parses and executes the ‘SHOW TABLES’ query against a particular database. Thereafter, it lists out the present tables in a database. The following syntax is used for Sqoop list-tables command. $ sqoop list-tables (generic-args) (list-tables-args) $ sqoop-list-tables (generic-args) (list-tables-args) The following command is used to list all the tables in the userdb database of MySQL database server. $ sqoop list-tables \ --connect jdbc:mysql://localhost/userdb \ --username root If the command is executes successfully, then it will display the list of tables in the userdb database as follows. ... 13/05/31 16:45:58 INFO manager.MySQLManager: Preparing to use a MySQL streaming resultset. emp emp_add emp_contact 50 Lectures 4 hours Navdeep Kaur Print Add Notes Bookmark this page
[ { "code": null, "e": 2057, "s": 1787, "text": "This chapter describes how to list out the tables of a particular database in MySQL database server using Sqoop. Sqoop list-tables tool parses and executes the ‘SHOW TABLES’ query against a particular database. Thereafter, it lists out the present tables in a database." }, { "code": null, "e": 2117, "s": 2057, "text": "The following syntax is used for Sqoop list-tables command." }, { "code": null, "e": 2226, "s": 2117, "text": "$ sqoop list-tables (generic-args) (list-tables-args) \n$ sqoop-list-tables (generic-args) (list-tables-args)" }, { "code": null, "e": 2328, "s": 2226, "text": "The following command is used to list all the tables in the userdb database of MySQL database server." }, { "code": null, "e": 2408, "s": 2328, "text": "$ sqoop list-tables \\\n--connect jdbc:mysql://localhost/userdb \\\n--username root" }, { "code": null, "e": 2524, "s": 2408, "text": "If the command is executes successfully, then it will display the list of tables in the userdb database as follows." }, { "code": null, "e": 2645, "s": 2524, "text": "...\n13/05/31 16:45:58 INFO manager.MySQLManager: Preparing to use a MySQL streaming resultset.\n\nemp\nemp_add\nemp_contact\n" }, { "code": null, "e": 2678, "s": 2645, "text": "\n 50 Lectures \n 4 hours \n" }, { "code": null, "e": 2692, "s": 2678, "text": " Navdeep Kaur" }, { "code": null, "e": 2699, "s": 2692, "text": " Print" }, { "code": null, "e": 2710, "s": 2699, "text": " Add Notes" } ]
Detecting Objects in Flutter. Using tflite and SSD-MobileNet | by Rupak Karki | Towards Data Science
In this guide, we will be developing an application in Flutter using the tflite package and a pre-trained SSD-MobileNet model, capable of detecting objects in images and real-time camera stream. This application is capable of detecting objects offline. We will also be able to take pictures from within the app and feed it to the model for detection. github.com Please note that I am no longer maintaining this project because of my busy schedule. Breaking changes introduced in the recent version of Flutter and dependencies may break the app. But you’re free to fork the repo and change things your way. Thanks! Setup Flutter on your machine if you haven’t already. This guide in the Flutter website is a great place to start. After setting up Flutter, create a new project by typing the following in your terminal. $ flutter create object_detection$ cd object_detection You can now open your project in your favorite editor. In your pubspec.yaml file, under the dependencies section add the following to install the required packages. image_picker: ^0.6.7tflite: ^1.1.1camera: ^0.5.8+7 We use the image_picker for picking images from gallery, tflite for running our model, and the camera package for controlling the camera. You can read more about them on pub.dev. In your app level build.gradle file (/android/app), under the android block, add the following lines to make sure Flutter does not compress your models or the tflite package. aaptOptions { noCompress 'tflite' noCompress 'lite'} You can download the SSD-MobileNet model and its labels from the GitHub repo mentioned above or from anywhere and place them in your project. Then, in your pubspec.yaml file add your assets. assets: - assets/models/ssd_mobilenet.tflite - assets/models/labels.txt The main function of this app is created in such a way that all the cameras are initialized right after the application starts. Then, the camera descriptions are passed on to all the classes that require it. To detect objects in images, we first need to load the model using the Tflite.loadModel method available in the tflite package. Then, we need to get the images from either our gallery or take one from within the app by launching the camera. The camera package provides the getImage method that can be used to do both. After the image is loaded, we feed it into our model using the Tflite.detectObjectOnImage method. This method returns the detected class, confidence and points of interests that will help us draw bounding boxes around the objects. The basic idea of drawing bounding boxes around the detected object is to use the POIs from the model and the image dimensions. Using Stack widget, we can place the bounding boxes on top of the image. Inside a Positioned widget, we place a Container that has borders all around it. We can also display the detected class and its accuracy as percentage by simply adding a Text widget and converting the confidence to percentage. The Static Image detection page has two Floating Action Buttons. Using one, we can pick images directly from the gallery and run our model on it. Using another, a camera is opened and we can take picture and feed it to our model. Detecting objects in real time is somewhat similar to detecting objects in images. Each frame in the video stream is treated as an image and the model is run on it. The model spits out results per frame and the bounding boxes are redrawn over and over on top of the image stream. The camera controller object in the camera plugin has a method called startImageStream that can be used to feed frames to our model. Inside this method we can call the Tflite.detectObjectOnFrame method that takes the camera stream and runs it through our model. The rest of the method is the same i.e. the model returns detectedClass, confidence and the POIs and we use them to draw bounding boxes on top of the camera stream. We developed an application capable of detecting objects using Flutter, the tflite package and a pre-trained model. The application is not perfect and may not work on all the images. We can improve this by training our own model that can detect more classes with increased accuracy or use some other powerful model. Despite this hurdle, the application performs really good at images and videos lit well. This is a really good project for someone who is looking to combine their knowledge of Machine Learning and Flutter. We can also use Google’s Teachable Machine to train models to classify or detect specific types of images. The tflite plugin currently only supports SSD-MobileNet and YOLO for object detection. You can check out the project repo here. If there are any issues, feel free to open issues or create a PR. Any feedback or suggestions are welcome and encouraged. You can also look at my portfolio here.
[ { "code": null, "e": 522, "s": 171, "text": "In this guide, we will be developing an application in Flutter using the tflite package and a pre-trained SSD-MobileNet model, capable of detecting objects in images and real-time camera stream. This application is capable of detecting objects offline. We will also be able to take pictures from within the app and feed it to the model for detection." }, { "code": null, "e": 533, "s": 522, "text": "github.com" }, { "code": null, "e": 785, "s": 533, "text": "Please note that I am no longer maintaining this project because of my busy schedule. Breaking changes introduced in the recent version of Flutter and dependencies may break the app. But you’re free to fork the repo and change things your way. Thanks!" }, { "code": null, "e": 989, "s": 785, "text": "Setup Flutter on your machine if you haven’t already. This guide in the Flutter website is a great place to start. After setting up Flutter, create a new project by typing the following in your terminal." }, { "code": null, "e": 1044, "s": 989, "text": "$ flutter create object_detection$ cd object_detection" }, { "code": null, "e": 1099, "s": 1044, "text": "You can now open your project in your favorite editor." }, { "code": null, "e": 1209, "s": 1099, "text": "In your pubspec.yaml file, under the dependencies section add the following to install the required packages." }, { "code": null, "e": 1260, "s": 1209, "text": "image_picker: ^0.6.7tflite: ^1.1.1camera: ^0.5.8+7" }, { "code": null, "e": 1439, "s": 1260, "text": "We use the image_picker for picking images from gallery, tflite for running our model, and the camera package for controlling the camera. You can read more about them on pub.dev." }, { "code": null, "e": 1614, "s": 1439, "text": "In your app level build.gradle file (/android/app), under the android block, add the following lines to make sure Flutter does not compress your models or the tflite package." }, { "code": null, "e": 1669, "s": 1614, "text": "aaptOptions { noCompress 'tflite' noCompress 'lite'}" }, { "code": null, "e": 1860, "s": 1669, "text": "You can download the SSD-MobileNet model and its labels from the GitHub repo mentioned above or from anywhere and place them in your project. Then, in your pubspec.yaml file add your assets." }, { "code": null, "e": 1934, "s": 1860, "text": "assets: - assets/models/ssd_mobilenet.tflite - assets/models/labels.txt" }, { "code": null, "e": 2142, "s": 1934, "text": "The main function of this app is created in such a way that all the cameras are initialized right after the application starts. Then, the camera descriptions are passed on to all the classes that require it." }, { "code": null, "e": 2460, "s": 2142, "text": "To detect objects in images, we first need to load the model using the Tflite.loadModel method available in the tflite package. Then, we need to get the images from either our gallery or take one from within the app by launching the camera. The camera package provides the getImage method that can be used to do both." }, { "code": null, "e": 2691, "s": 2460, "text": "After the image is loaded, we feed it into our model using the Tflite.detectObjectOnImage method. This method returns the detected class, confidence and points of interests that will help us draw bounding boxes around the objects." }, { "code": null, "e": 2819, "s": 2691, "text": "The basic idea of drawing bounding boxes around the detected object is to use the POIs from the model and the image dimensions." }, { "code": null, "e": 3119, "s": 2819, "text": "Using Stack widget, we can place the bounding boxes on top of the image. Inside a Positioned widget, we place a Container that has borders all around it. We can also display the detected class and its accuracy as percentage by simply adding a Text widget and converting the confidence to percentage." }, { "code": null, "e": 3349, "s": 3119, "text": "The Static Image detection page has two Floating Action Buttons. Using one, we can pick images directly from the gallery and run our model on it. Using another, a camera is opened and we can take picture and feed it to our model." }, { "code": null, "e": 3629, "s": 3349, "text": "Detecting objects in real time is somewhat similar to detecting objects in images. Each frame in the video stream is treated as an image and the model is run on it. The model spits out results per frame and the bounding boxes are redrawn over and over on top of the image stream." }, { "code": null, "e": 4056, "s": 3629, "text": "The camera controller object in the camera plugin has a method called startImageStream that can be used to feed frames to our model. Inside this method we can call the Tflite.detectObjectOnFrame method that takes the camera stream and runs it through our model. The rest of the method is the same i.e. the model returns detectedClass, confidence and the POIs and we use them to draw bounding boxes on top of the camera stream." }, { "code": null, "e": 4372, "s": 4056, "text": "We developed an application capable of detecting objects using Flutter, the tflite package and a pre-trained model. The application is not perfect and may not work on all the images. We can improve this by training our own model that can detect more classes with increased accuracy or use some other powerful model." }, { "code": null, "e": 4685, "s": 4372, "text": "Despite this hurdle, the application performs really good at images and videos lit well. This is a really good project for someone who is looking to combine their knowledge of Machine Learning and Flutter. We can also use Google’s Teachable Machine to train models to classify or detect specific types of images." }, { "code": null, "e": 4772, "s": 4685, "text": "The tflite plugin currently only supports SSD-MobileNet and YOLO for object detection." }, { "code": null, "e": 4935, "s": 4772, "text": "You can check out the project repo here. If there are any issues, feel free to open issues or create a PR. Any feedback or suggestions are welcome and encouraged." } ]
Hadoop – getmerge Command
29 Jun, 2020 Hadoop -getmerge command is used to merge multiple files in an HDFS(Hadoop Distributed File System) and then put it into one single output file in our local file system. We want to merge the 2 files present inside are HDFS i.e. file1.txt and file2.txt, into a single file output.txt in our local file system. Step 1: Let’s see the content of file1.txt and file2.txt that are available in our HDFS. You can see the content of File1.txt in the below image: Content of File2.txt In this case, we have copied both of these files inside my HDFS in Hadoop_File folder. If you don’t know how to make the directory and copy files to HDFS then follow below command to do so. Making Hadoop_Files directory in our HDFShdfs dfs -mkdir /Hadoop_File hdfs dfs -mkdir /Hadoop_File Copying files to HDFShdfs dfs -copyFromLocal /home/dikshant/Documents/hadoop_file/file1.txt /home/dikshant/Documents/hadoop_file/file2.txt /Hadoop_File hdfs dfs -copyFromLocal /home/dikshant/Documents/hadoop_file/file1.txt /home/dikshant/Documents/hadoop_file/file2.txt /Hadoop_File Below is the Image showing this file inside my /Hadoop_File directory in HDFS. Step 2: Now it’s time to use -getmerge command to merge these files into a single output file in our local file system for that follow the below procedure. Syntax: hdfs dfs -getmerge -nl /path1 /path2 ..../path n /destination -nl is used for adding new line. this will add a new line between the content of these n files. In this case we have merge it to /hadoop_file folder inside my /Documents folder. hdfs dfs -getmerge -nl /Hadoop_File/file1.txt /Hadoop_File/file2.txt /home/dikshant/Documents/hadoop_file/output.txt Now let’s see whether the file get merged in output.txt file or not. In the above image, you can easily see that the file is merged successfully in our output.txt file. Hadoop Hadoop Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jun, 2020" }, { "code": null, "e": 198, "s": 28, "text": "Hadoop -getmerge command is used to merge multiple files in an HDFS(Hadoop Distributed File System) and then put it into one single output file in our local file system." }, { "code": null, "e": 337, "s": 198, "text": "We want to merge the 2 files present inside are HDFS i.e. file1.txt and file2.txt, into a single file output.txt in our local file system." }, { "code": null, "e": 483, "s": 337, "text": "Step 1: Let’s see the content of file1.txt and file2.txt that are available in our HDFS. You can see the content of File1.txt in the below image:" }, { "code": null, "e": 504, "s": 483, "text": "Content of File2.txt" }, { "code": null, "e": 694, "s": 504, "text": "In this case, we have copied both of these files inside my HDFS in Hadoop_File folder. If you don’t know how to make the directory and copy files to HDFS then follow below command to do so." }, { "code": null, "e": 764, "s": 694, "text": "Making Hadoop_Files directory in our HDFShdfs dfs -mkdir /Hadoop_File" }, { "code": null, "e": 793, "s": 764, "text": "hdfs dfs -mkdir /Hadoop_File" }, { "code": null, "e": 945, "s": 793, "text": "Copying files to HDFShdfs dfs -copyFromLocal /home/dikshant/Documents/hadoop_file/file1.txt /home/dikshant/Documents/hadoop_file/file2.txt /Hadoop_File" }, { "code": null, "e": 1076, "s": 945, "text": "hdfs dfs -copyFromLocal /home/dikshant/Documents/hadoop_file/file1.txt /home/dikshant/Documents/hadoop_file/file2.txt /Hadoop_File" }, { "code": null, "e": 1155, "s": 1076, "text": "Below is the Image showing this file inside my /Hadoop_File directory in HDFS." }, { "code": null, "e": 1311, "s": 1155, "text": "Step 2: Now it’s time to use -getmerge command to merge these files into a single output file in our local file system for that follow the below procedure." }, { "code": null, "e": 1319, "s": 1311, "text": "Syntax:" }, { "code": null, "e": 1381, "s": 1319, "text": "hdfs dfs -getmerge -nl /path1 /path2 ..../path n /destination" }, { "code": null, "e": 1559, "s": 1381, "text": "-nl is used for adding new line. this will add a new line between the content of these n files. In this case we have merge it to /hadoop_file folder inside my /Documents folder." }, { "code": null, "e": 1676, "s": 1559, "text": "hdfs dfs -getmerge -nl /Hadoop_File/file1.txt /Hadoop_File/file2.txt /home/dikshant/Documents/hadoop_file/output.txt" }, { "code": null, "e": 1745, "s": 1676, "text": "Now let’s see whether the file get merged in output.txt file or not." }, { "code": null, "e": 1845, "s": 1745, "text": "In the above image, you can easily see that the file is merged successfully in our output.txt file." }, { "code": null, "e": 1852, "s": 1845, "text": "Hadoop" }, { "code": null, "e": 1859, "s": 1852, "text": "Hadoop" } ]
Implicit Type Conversion in C with Examples
25 Nov, 2019 Prerequisite: Data Types, Type Conversion Implicit Type Conversion is also known as ‘automatic type conversion‘. It is done by the compiler on its own, without any external trigger from the user. It generally takes place when in an expression more than one data type is present. In such condition type conversion (type promotion) takes place to avoid loss of data. All the data types of the variables are upgraded to the data type of the variable with the largest data type. There are many ways in which the Implicit Type Conversion occurs in C, such as: Conversion RankA rank can be assigned to the integer and floating-point arithmetic type, from 1 to 9. This scale is theoretically accurate but the actual implementation is not this easy. A long double real has a higher rank than long real and a short integer has a higher rank than a character as shown in the figure. Conversions in Assignment ExpressionsThere are two operands and an assignment operator in an assignment operation. The difference in rank decides the promotion and demotion of the right expression to equalize the rank of left and right expression. Promoting implies that the right expression is of lower rank. Demoting implies that the right expression is of higher rank. PromotionPromotion does not create any problems. The rank of right expression is promoted to the rank of left expression. The value of the expression is the value of the right expression after the promotion.Examples:bool x = true; char y = ‘X’; int i = 123; Long double d = 1234.5; y = x; // value of y is SOH (ASCII 1) i = y; // value of i is 88 d = x; // value of d is 1.0 d = i; // value of d is 1234.0 *Here SOH is Start of Header Examples: bool x = true; char y = ‘X’; int i = 123; Long double d = 1234.5; y = x; // value of y is SOH (ASCII 1) i = y; // value of i is 88 d = x; // value of d is 1.0 d = i; // value of d is 1234.0 *Here SOH is Start of Header DemotionDemotion may or may not create problems. If the size of the variable of the left expression can accommodate the value of the expression, no problem arises but the results can be a bit different from those expected. Any real or integer value can be assigned to the Boolean variable. If the value of the right expression is zero, it implies false(0) is stored. And if the value is something other than zero, i.e. either positive or negative, it implies true(1) is stored.When an integer or real value is assigned to a character variable, the least significant byte of the number is converted to a character and stored. When a real value is stored in an integer variable only integer part is assigned and the fraction is dropped. But if the integer value is greater than the maximum value that can be stored, then unpredictable results are obtained.Likewise, if a long double value is stored in a float type variable then the results are valid only if the value fits otherwise very large values become invalid.Examples:bool b = false; char c = ‘X’; short s = 98; int j = INT_MAX; int k = 88; b = c; // value of b is 1 (true) s = j; // value of s is unpredictable c = k + 1; // demotion: value of c is ‘Y’ When an integer or real value is assigned to a character variable, the least significant byte of the number is converted to a character and stored. When a real value is stored in an integer variable only integer part is assigned and the fraction is dropped. But if the integer value is greater than the maximum value that can be stored, then unpredictable results are obtained. Likewise, if a long double value is stored in a float type variable then the results are valid only if the value fits otherwise very large values become invalid.Examples: bool b = false; char c = ‘X’; short s = 98; int j = INT_MAX; int k = 88; b = c; // value of b is 1 (true) s = j; // value of s is unpredictable c = k + 1; // demotion: value of c is ‘Y’ Conversions in other Binary ExpressionsThere are different set of rules for other binary expressions and they become complicated sometimes so summarising them as steps:The operand with the higher rank is determined using the ranking as shown in above figure.The lower-ranked operand is elevated to the rank defined in step 1.The operation is performed with the expression value having the type of the promoted rank.Examples:bool x = true; char y = ‘X’; int i = 123; short s = 98; long double d = 1234.5678; x + y; // b is promoted, result is ‘Y’ (‘X’ + 1) i * s; // result is an int d * c; // result is long double The operand with the higher rank is determined using the ranking as shown in above figure.The lower-ranked operand is elevated to the rank defined in step 1.The operation is performed with the expression value having the type of the promoted rank. The operand with the higher rank is determined using the ranking as shown in above figure. The lower-ranked operand is elevated to the rank defined in step 1. The operation is performed with the expression value having the type of the promoted rank. Examples: bool x = true; char y = ‘X’; int i = 123; short s = 98; long double d = 1234.5678; x + y; // b is promoted, result is ‘Y’ (‘X’ + 1) i * s; // result is an int d * c; // result is long double Below is an example to demonstrate Implicit Type Conversion of numeric types for a better understanding. // C program to demonstrate Implicit// Type Conversion of numeric types #include <stdbool.h>#include <stdio.h> int main(void){ // Local Declarations bool b = true; char c = 'X'; float d = 1234.5; int i = 123; short s = 98; // Statements printf("bool + char is char: %c\n", b + c); printf("int * short is int: %d\n", i * s); printf("float * char is float: %f\n", d * c); // bool promoted to char c = c + b; // char promoted to float d = d + c; b = false; // float demoted to bool b = -d; printf("\nAfter execution \n"); printf("char + true: %c\n", c); printf("float + char: %f\n", d); printf("bool = -float: %d\n", b); return 0;} bool + char is char: Y int * short is int: 12054 float * char is float: 108636.000000 After execution char + true: Y float + char: 1323.500000 bool = -float: 1 C Language 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, 2019" }, { "code": null, "e": 94, "s": 52, "text": "Prerequisite: Data Types, Type Conversion" }, { "code": null, "e": 527, "s": 94, "text": "Implicit Type Conversion is also known as ‘automatic type conversion‘. It is done by the compiler on its own, without any external trigger from the user. It generally takes place when in an expression more than one data type is present. In such condition type conversion (type promotion) takes place to avoid loss of data. All the data types of the variables are upgraded to the data type of the variable with the largest data type." }, { "code": null, "e": 607, "s": 527, "text": "There are many ways in which the Implicit Type Conversion occurs in C, such as:" }, { "code": null, "e": 925, "s": 607, "text": "Conversion RankA rank can be assigned to the integer and floating-point arithmetic type, from 1 to 9. This scale is theoretically accurate but the actual implementation is not this easy. A long double real has a higher rank than long real and a short integer has a higher rank than a character as shown in the figure." }, { "code": null, "e": 1297, "s": 925, "text": "Conversions in Assignment ExpressionsThere are two operands and an assignment operator in an assignment operation. The difference in rank decides the promotion and demotion of the right expression to equalize the rank of left and right expression. Promoting implies that the right expression is of lower rank. Demoting implies that the right expression is of higher rank." }, { "code": null, "e": 1765, "s": 1297, "text": "PromotionPromotion does not create any problems. The rank of right expression is promoted to the rank of left expression. The value of the expression is the value of the right expression after the promotion.Examples:bool x = true;\nchar y = ‘X’;\nint i = 123;\nLong double d = 1234.5;\n\ny = x; // value of y is SOH (ASCII 1)\ni = y; // value of i is 88\nd = x; // value of d is 1.0\nd = i; // value of d is 1234.0\n\n*Here SOH is Start of Header\n" }, { "code": null, "e": 1775, "s": 1765, "text": "Examples:" }, { "code": null, "e": 2027, "s": 1775, "text": "bool x = true;\nchar y = ‘X’;\nint i = 123;\nLong double d = 1234.5;\n\ny = x; // value of y is SOH (ASCII 1)\ni = y; // value of i is 88\nd = x; // value of d is 1.0\nd = i; // value of d is 1234.0\n\n*Here SOH is Start of Header\n" }, { "code": null, "e": 3253, "s": 2027, "text": "DemotionDemotion may or may not create problems. If the size of the variable of the left expression can accommodate the value of the expression, no problem arises but the results can be a bit different from those expected. Any real or integer value can be assigned to the Boolean variable. If the value of the right expression is zero, it implies false(0) is stored. And if the value is something other than zero, i.e. either positive or negative, it implies true(1) is stored.When an integer or real value is assigned to a character variable, the least significant byte of the number is converted to a character and stored. When a real value is stored in an integer variable only integer part is assigned and the fraction is dropped. But if the integer value is greater than the maximum value that can be stored, then unpredictable results are obtained.Likewise, if a long double value is stored in a float type variable then the results are valid only if the value fits otherwise very large values become invalid.Examples:bool b = false;\nchar c = ‘X’;\nshort s = 98;\nint j = INT_MAX;\nint k = 88;\n\nb = c; // value of b is 1 (true)\ns = j; // value of s is unpredictable\nc = k + 1; // demotion: value of c is ‘Y’\n" }, { "code": null, "e": 3631, "s": 3253, "text": "When an integer or real value is assigned to a character variable, the least significant byte of the number is converted to a character and stored. When a real value is stored in an integer variable only integer part is assigned and the fraction is dropped. But if the integer value is greater than the maximum value that can be stored, then unpredictable results are obtained." }, { "code": null, "e": 3802, "s": 3631, "text": "Likewise, if a long double value is stored in a float type variable then the results are valid only if the value fits otherwise very large values become invalid.Examples:" }, { "code": null, "e": 4004, "s": 3802, "text": "bool b = false;\nchar c = ‘X’;\nshort s = 98;\nint j = INT_MAX;\nint k = 88;\n\nb = c; // value of b is 1 (true)\ns = j; // value of s is unpredictable\nc = k + 1; // demotion: value of c is ‘Y’\n" }, { "code": null, "e": 4655, "s": 4004, "text": "Conversions in other Binary ExpressionsThere are different set of rules for other binary expressions and they become complicated sometimes so summarising them as steps:The operand with the higher rank is determined using the ranking as shown in above figure.The lower-ranked operand is elevated to the rank defined in step 1.The operation is performed with the expression value having the type of the promoted rank.Examples:bool x = true;\nchar y = ‘X’;\nint i = 123;\nshort s = 98;\nlong double d = 1234.5678;\n\nx + y; // b is promoted, result is ‘Y’ (‘X’ + 1)\ni * s; // result is an int\nd * c; // result is long double\n" }, { "code": null, "e": 4903, "s": 4655, "text": "The operand with the higher rank is determined using the ranking as shown in above figure.The lower-ranked operand is elevated to the rank defined in step 1.The operation is performed with the expression value having the type of the promoted rank." }, { "code": null, "e": 4994, "s": 4903, "text": "The operand with the higher rank is determined using the ranking as shown in above figure." }, { "code": null, "e": 5062, "s": 4994, "text": "The lower-ranked operand is elevated to the rank defined in step 1." }, { "code": null, "e": 5153, "s": 5062, "text": "The operation is performed with the expression value having the type of the promoted rank." }, { "code": null, "e": 5163, "s": 5153, "text": "Examples:" }, { "code": null, "e": 5390, "s": 5163, "text": "bool x = true;\nchar y = ‘X’;\nint i = 123;\nshort s = 98;\nlong double d = 1234.5678;\n\nx + y; // b is promoted, result is ‘Y’ (‘X’ + 1)\ni * s; // result is an int\nd * c; // result is long double\n" }, { "code": null, "e": 5495, "s": 5390, "text": "Below is an example to demonstrate Implicit Type Conversion of numeric types for a better understanding." }, { "code": "// C program to demonstrate Implicit// Type Conversion of numeric types #include <stdbool.h>#include <stdio.h> int main(void){ // Local Declarations bool b = true; char c = 'X'; float d = 1234.5; int i = 123; short s = 98; // Statements printf(\"bool + char is char: %c\\n\", b + c); printf(\"int * short is int: %d\\n\", i * s); printf(\"float * char is float: %f\\n\", d * c); // bool promoted to char c = c + b; // char promoted to float d = d + c; b = false; // float demoted to bool b = -d; printf(\"\\nAfter execution \\n\"); printf(\"char + true: %c\\n\", c); printf(\"float + char: %f\\n\", d); printf(\"bool = -float: %d\\n\", b); return 0;}", "e": 6226, "s": 5495, "text": null }, { "code": null, "e": 6409, "s": 6226, "text": "bool + char is char: Y\nint * short is int: 12054\nfloat * char is float: 108636.000000\n\nAfter execution \nchar + true: Y\nfloat + char: 1323.500000\nbool = -float: 1\n" }, { "code": null, "e": 6420, "s": 6409, "text": "C Language" } ]
Different ways to create objects in Java
13 Jun, 2022 There are several ways by which we can create objects of a class in java as we all know a class provides the blueprint for objects, you create an object from a class. This concept is under-rated and sometimes proves to be beneficial as this concept is bypassed by many programmers and sometimes even do ask from interview perceptive. Methods: There are many different ways to create objects in Java. Let us list them later discussing later taking individually with the help of programs to illustrate internal working by which we can create objects in Java. Using new keywordUsing new instanceUsing clone() methodUsing deserializationUsing newInstance() method of Constructor class Using new keyword Using new instance Using clone() method Using deserialization Using newInstance() method of Constructor class Let us discuss them one by one and implement the same by appending a clean java program for the same. Method 1: Using new keyword Using the new keyword in java is the most basic way to create an object. This is the most common way to create an object in java. Almost 99% of objects are created in this way. By using this method we can call any constructor we want to call (no argument or parameterized constructors). Example Java // Java program to Illustrate Creation of Object// Using new keyword // Main classclass GFG { // Declaring and initializing string // Custom input string String name = "GeeksForGeeks"; // Main driver method public static void main(String[] args) { // As usual and most generic used we will // be creating object of class inside main() // using new keyword GFG obj = new GFG(); // Print and display the object System.out.println(obj.name); }} GeeksForGeeks Method 2: Using new instance If we know the name of the class & if it has a public default constructor we can create an object Class.forName. We can use it to create the Object of a Class. Class.forName actually loads the Class in Java but doesn’t create any Object. To create an Object of the Class you have to use the new Instance Method of the Class. Example Java // Java program to Illustrate Creation of Object// Using new Instance // Main classclass GFG { // Declaring and initializing string String name = "GeeksForGeeks"; // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { Class cls = Class.forName("GFG"); // Creating object of main class // using instance method GFG obj = (GFG)cls.newInstance(); // Print and display System.out.println(obj.name); } // Catch block to handle the exceptions // Catch block 1 // Handling ClassNotFound Exception catch (ClassNotFoundException e) { // Display the exception along with line number // using printStacktrace() method e.printStackTrace(); } // Catch block 2 // Handling InstantiationException catch (InstantiationException e) { e.printStackTrace(); } // Catch block 2 // Handling IllegalAccessException catch (IllegalAccessException e) { e.printStackTrace(); } }} Output: GeeksForGeeks Method 3: Using clone() method Whenever clone() is called on any object, the JVM actually creates a new object and copies all content of the previous object into it. Creating an object using the clone method does not invoke any constructor. In order to use the clone() method on an object we need to implement Cloneable and define the clone() method in it. Example Java // Java program to Illustrate Creation of Object// Using clone() method // Main class// Implementing Cloneable interfaceclass GFG implements Cloneable { // Method 1 @Override protected Object clone() throws CloneNotSupportedException { // Super() keyword refers to parent class return super.clone(); } // Declaring and initializing string String name = "GeeksForGeeks"; // Method 2 // main driver method public static void main(String[] args) { GFG obj1 = new GFG(); // Try block to check for exceptions try { // Using the clone() method GFG obj2 = (GFG)obj1.clone(); // Print and display the main class object // as created above System.out.println(obj2.name); } // Catch block to handle the exceptions catch (CloneNotSupportedException e) { // Display the exception // using printStackTrace() method e.printStackTrace(); } }} GeeksForGeeks Note: Here we are creating the clone of an existing Object and not any new Object. Class need to implement Cloneable Interface otherwise it will throw CloneNotSupportedException. Method 4: Using deserialization Whenever we serialize and then deserialize an object, JVM creates a separate object. In deserialization, JVM doesn’t use any constructor to create the object. To deserialize an object we need to implement the Serializable interface in the class. Example 1 Java // Java Program Illustrate Serializing an Object // Importing input output classesimport java.io.*; // Main class// Implementing the Serializable interfaceclass GFG implements Serializable { // Member variables private String name; GFG(String name) { // This keyword refers to current object itself this.name = name; } // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating object of class in main() method GFG d = new GFG("GeeksForGeeks"); FileOutputStream f = new FileOutputStream("file.txt"); ObjectOutputStream oos = new ObjectOutputStream(f); oos.writeObject(d); oos.close(); // Freeing up memory resources f.close(); } // Catch block to handle the exceptiona catch (Exception e) { // Display the exception along with line number // using printStacktrace() method e.printStackTrace(); } }} Output: GeeksForGeeks Object of DeserializationExample class is serialized using writeObject() method and written to file.txt file. Example 2 Java // Java Program Illustrate Creation of Object// Using Deserialization // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { GFG d; // Creating FileInputStream class object FileInputStream f = new FileInputStream("file.txt"); // Creating ObjectInputStream class object ObjectInputStream oos = new ObjectInputStream(f); d = (DeserializationExample)oos.readObject(); } // Catch block to handle the exceptions catch (Exception e) { // Display the exception on console // using printStacjtrace() method e.printStackTrace(); } System.out.println(d.name); }} Output: GeeksForGeeks Method 5: Using newInstance() method of the constructor class This is similar to the newInstance() method of a class. There is one newInstance() method in the java.lang.reflect.Constructor class which we can use to create objects. It can also call the parameterized constructor, and private constructor by using this newInstance() method. Both newInstance() methods are known as reflective ways to create objects. In fact newInstance() method of Class internally uses newInstance() method of Constructor class. Example Java // Java program to illustrate creation of Object// using newInstance() method of Constructor class // Importing required classes from java.lang packageimport java.lang.reflect.*; // Main classclass GFG { // Member variables of this class private String name; // Constructor of this class GFG() {} // Method 1 // To set name ofthe string public void setName(String name) { // This method refers to current object itself this.name = name; } // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { Constructor<GFG> constructor = GFG.class.getDeclaredConstructor(); GFG r = constructor.newInstance(); // Custom passing r.setName("GeeksForGeeks"); System.out.println(r.name); } // Catch block to handle the exceptions catch (Exception e) { // Display the exception on console // using printStackTrace() method e.printStackTrace(); } }} Output: GeeksForGeeks This article is contributed by Saket Kumar. 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 if you want to share more information about the topic discussed above. ShreyasWaghmare solankimayank sagartomar9927 anikakapoor praticecoder nnr223442 adnanirshad158 simmytarika5 harshiiash2008 varshagumber28 Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples For-each loop in Java Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jun, 2022" }, { "code": null, "e": 388, "s": 54, "text": "There are several ways by which we can create objects of a class in java as we all know a class provides the blueprint for objects, you create an object from a class. This concept is under-rated and sometimes proves to be beneficial as this concept is bypassed by many programmers and sometimes even do ask from interview perceptive." }, { "code": null, "e": 398, "s": 388, "text": "Methods: " }, { "code": null, "e": 612, "s": 398, "text": "There are many different ways to create objects in Java. Let us list them later discussing later taking individually with the help of programs to illustrate internal working by which we can create objects in Java." }, { "code": null, "e": 736, "s": 612, "text": "Using new keywordUsing new instanceUsing clone() methodUsing deserializationUsing newInstance() method of Constructor class" }, { "code": null, "e": 754, "s": 736, "text": "Using new keyword" }, { "code": null, "e": 773, "s": 754, "text": "Using new instance" }, { "code": null, "e": 794, "s": 773, "text": "Using clone() method" }, { "code": null, "e": 816, "s": 794, "text": "Using deserialization" }, { "code": null, "e": 864, "s": 816, "text": "Using newInstance() method of Constructor class" }, { "code": null, "e": 966, "s": 864, "text": "Let us discuss them one by one and implement the same by appending a clean java program for the same." }, { "code": null, "e": 994, "s": 966, "text": "Method 1: Using new keyword" }, { "code": null, "e": 1281, "s": 994, "text": "Using the new keyword in java is the most basic way to create an object. This is the most common way to create an object in java. Almost 99% of objects are created in this way. By using this method we can call any constructor we want to call (no argument or parameterized constructors)." }, { "code": null, "e": 1289, "s": 1281, "text": "Example" }, { "code": null, "e": 1294, "s": 1289, "text": "Java" }, { "code": "// Java program to Illustrate Creation of Object// Using new keyword // Main classclass GFG { // Declaring and initializing string // Custom input string String name = \"GeeksForGeeks\"; // Main driver method public static void main(String[] args) { // As usual and most generic used we will // be creating object of class inside main() // using new keyword GFG obj = new GFG(); // Print and display the object System.out.println(obj.name); }}", "e": 1802, "s": 1294, "text": null }, { "code": null, "e": 1816, "s": 1802, "text": "GeeksForGeeks" }, { "code": null, "e": 1845, "s": 1816, "text": "Method 2: Using new instance" }, { "code": null, "e": 2170, "s": 1845, "text": "If we know the name of the class & if it has a public default constructor we can create an object Class.forName. We can use it to create the Object of a Class. Class.forName actually loads the Class in Java but doesn’t create any Object. To create an Object of the Class you have to use the new Instance Method of the Class." }, { "code": null, "e": 2178, "s": 2170, "text": "Example" }, { "code": null, "e": 2183, "s": 2178, "text": "Java" }, { "code": "// Java program to Illustrate Creation of Object// Using new Instance // Main classclass GFG { // Declaring and initializing string String name = \"GeeksForGeeks\"; // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { Class cls = Class.forName(\"GFG\"); // Creating object of main class // using instance method GFG obj = (GFG)cls.newInstance(); // Print and display System.out.println(obj.name); } // Catch block to handle the exceptions // Catch block 1 // Handling ClassNotFound Exception catch (ClassNotFoundException e) { // Display the exception along with line number // using printStacktrace() method e.printStackTrace(); } // Catch block 2 // Handling InstantiationException catch (InstantiationException e) { e.printStackTrace(); } // Catch block 2 // Handling IllegalAccessException catch (IllegalAccessException e) { e.printStackTrace(); } }}", "e": 3350, "s": 2183, "text": null }, { "code": null, "e": 3359, "s": 3350, "text": "Output: " }, { "code": null, "e": 3373, "s": 3359, "text": "GeeksForGeeks" }, { "code": null, "e": 3405, "s": 3373, "text": "Method 3: Using clone() method" }, { "code": null, "e": 3731, "s": 3405, "text": "Whenever clone() is called on any object, the JVM actually creates a new object and copies all content of the previous object into it. Creating an object using the clone method does not invoke any constructor. In order to use the clone() method on an object we need to implement Cloneable and define the clone() method in it." }, { "code": null, "e": 3739, "s": 3731, "text": "Example" }, { "code": null, "e": 3744, "s": 3739, "text": "Java" }, { "code": "// Java program to Illustrate Creation of Object// Using clone() method // Main class// Implementing Cloneable interfaceclass GFG implements Cloneable { // Method 1 @Override protected Object clone() throws CloneNotSupportedException { // Super() keyword refers to parent class return super.clone(); } // Declaring and initializing string String name = \"GeeksForGeeks\"; // Method 2 // main driver method public static void main(String[] args) { GFG obj1 = new GFG(); // Try block to check for exceptions try { // Using the clone() method GFG obj2 = (GFG)obj1.clone(); // Print and display the main class object // as created above System.out.println(obj2.name); } // Catch block to handle the exceptions catch (CloneNotSupportedException e) { // Display the exception // using printStackTrace() method e.printStackTrace(); } }}", "e": 4774, "s": 3744, "text": null }, { "code": null, "e": 4788, "s": 4774, "text": "GeeksForGeeks" }, { "code": null, "e": 4796, "s": 4788, "text": "Note: " }, { "code": null, "e": 4873, "s": 4796, "text": "Here we are creating the clone of an existing Object and not any new Object." }, { "code": null, "e": 4969, "s": 4873, "text": "Class need to implement Cloneable Interface otherwise it will throw CloneNotSupportedException." }, { "code": null, "e": 5001, "s": 4969, "text": "Method 4: Using deserialization" }, { "code": null, "e": 5247, "s": 5001, "text": "Whenever we serialize and then deserialize an object, JVM creates a separate object. In deserialization, JVM doesn’t use any constructor to create the object. To deserialize an object we need to implement the Serializable interface in the class." }, { "code": null, "e": 5257, "s": 5247, "text": "Example 1" }, { "code": null, "e": 5262, "s": 5257, "text": "Java" }, { "code": "// Java Program Illustrate Serializing an Object // Importing input output classesimport java.io.*; // Main class// Implementing the Serializable interfaceclass GFG implements Serializable { // Member variables private String name; GFG(String name) { // This keyword refers to current object itself this.name = name; } // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating object of class in main() method GFG d = new GFG(\"GeeksForGeeks\"); FileOutputStream f = new FileOutputStream(\"file.txt\"); ObjectOutputStream oos = new ObjectOutputStream(f); oos.writeObject(d); oos.close(); // Freeing up memory resources f.close(); } // Catch block to handle the exceptiona catch (Exception e) { // Display the exception along with line number // using printStacktrace() method e.printStackTrace(); } }}", "e": 6359, "s": 5262, "text": null }, { "code": null, "e": 6368, "s": 6359, "text": "Output: " }, { "code": null, "e": 6382, "s": 6368, "text": "GeeksForGeeks" }, { "code": null, "e": 6492, "s": 6382, "text": "Object of DeserializationExample class is serialized using writeObject() method and written to file.txt file." }, { "code": null, "e": 6502, "s": 6492, "text": "Example 2" }, { "code": null, "e": 6507, "s": 6502, "text": "Java" }, { "code": "// Java Program Illustrate Creation of Object// Using Deserialization // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { GFG d; // Creating FileInputStream class object FileInputStream f = new FileInputStream(\"file.txt\"); // Creating ObjectInputStream class object ObjectInputStream oos = new ObjectInputStream(f); d = (DeserializationExample)oos.readObject(); } // Catch block to handle the exceptions catch (Exception e) { // Display the exception on console // using printStacjtrace() method e.printStackTrace(); } System.out.println(d.name); }}", "e": 7392, "s": 6507, "text": null }, { "code": null, "e": 7401, "s": 7392, "text": "Output: " }, { "code": null, "e": 7415, "s": 7401, "text": "GeeksForGeeks" }, { "code": null, "e": 7477, "s": 7415, "text": "Method 5: Using newInstance() method of the constructor class" }, { "code": null, "e": 7927, "s": 7477, "text": "This is similar to the newInstance() method of a class. There is one newInstance() method in the java.lang.reflect.Constructor class which we can use to create objects. It can also call the parameterized constructor, and private constructor by using this newInstance() method. Both newInstance() methods are known as reflective ways to create objects. In fact newInstance() method of Class internally uses newInstance() method of Constructor class. " }, { "code": null, "e": 7935, "s": 7927, "text": "Example" }, { "code": null, "e": 7940, "s": 7935, "text": "Java" }, { "code": "// Java program to illustrate creation of Object// using newInstance() method of Constructor class // Importing required classes from java.lang packageimport java.lang.reflect.*; // Main classclass GFG { // Member variables of this class private String name; // Constructor of this class GFG() {} // Method 1 // To set name ofthe string public void setName(String name) { // This method refers to current object itself this.name = name; } // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { Constructor<GFG> constructor = GFG.class.getDeclaredConstructor(); GFG r = constructor.newInstance(); // Custom passing r.setName(\"GeeksForGeeks\"); System.out.println(r.name); } // Catch block to handle the exceptions catch (Exception e) { // Display the exception on console // using printStackTrace() method e.printStackTrace(); } }}", "e": 9027, "s": 7940, "text": null }, { "code": null, "e": 9036, "s": 9027, "text": "Output: " }, { "code": null, "e": 9050, "s": 9036, "text": "GeeksForGeeks" }, { "code": null, "e": 9473, "s": 9050, "text": "This article is contributed by Saket Kumar. 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 if you want to share more information about the topic discussed above." }, { "code": null, "e": 9489, "s": 9473, "text": "ShreyasWaghmare" }, { "code": null, "e": 9503, "s": 9489, "text": "solankimayank" }, { "code": null, "e": 9518, "s": 9503, "text": "sagartomar9927" }, { "code": null, "e": 9530, "s": 9518, "text": "anikakapoor" }, { "code": null, "e": 9543, "s": 9530, "text": "praticecoder" }, { "code": null, "e": 9553, "s": 9543, "text": "nnr223442" }, { "code": null, "e": 9568, "s": 9553, "text": "adnanirshad158" }, { "code": null, "e": 9581, "s": 9568, "text": "simmytarika5" }, { "code": null, "e": 9596, "s": 9581, "text": "harshiiash2008" }, { "code": null, "e": 9611, "s": 9596, "text": "varshagumber28" }, { "code": null, "e": 9616, "s": 9611, "text": "Java" }, { "code": null, "e": 9621, "s": 9616, "text": "Java" }, { "code": null, "e": 9719, "s": 9621, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9734, "s": 9719, "text": "Arrays in Java" }, { "code": null, "e": 9778, "s": 9734, "text": "Split() String method in Java with examples" }, { "code": null, "e": 9814, "s": 9778, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 9836, "s": 9814, "text": "For-each loop in Java" }, { "code": null, "e": 9861, "s": 9836, "text": "Reverse a string in Java" }, { "code": null, "e": 9912, "s": 9861, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 9943, "s": 9912, "text": "How to iterate any Map in Java" }, { "code": null, "e": 9962, "s": 9943, "text": "Interfaces in Java" }, { "code": null, "e": 9992, "s": 9962, "text": "HashMap in Java with Examples" } ]
Concept of Isolates in Dart
20 Jul, 2020 Dart was traditionally designed to create single-page applications. And we also know that most computers, even mobile platforms, have multi-core CPUs. To take advantage of all those cores, developers traditionally use shared-memory threads running concurrently. However, shared-state concurrency is error-prone and can lead to complicated code. Instead of threads, all Dart code runs inside of isolates. Each isolate has its own memory heap, ensuring that no isolate’s state is accessible from any other isolate. The isolates and threads are different than each other as in threads memory are shared whereas in isolates it is not. Moreover isolates talk to each other via passing messages. To use isolates you have to add import 'dart:isolate'; statement in your program code. To create an isolate we make use of .spawn() method in Dart. Syntax: Isolate isolate_name = await Isolate.spawn( parameter ); This parameter represents the port that will receive the message back. To destroy the isolate we make use of .kill() method in Dart. Syntax: isolate_name.kill( parameters ); We generally use spawn() and kill() together in a single program. Example: Creating an isolate in Dart. Dart // importing dart libraries import 'dart:io';import 'dart:async';import 'dart:isolate'; // Creating geek isolateIsolate geek; void start_geek_process() async { // port for isolate to receive messages. ReceivePort geekReceive= ReceivePort(); // Starting an isolate geek = await Isolate.spawn(gfg, geekReceive.sendPort);} void gfg(SendPort sendPort) { int counter = 0; // Printing Output message after every 2 sec. Timer.periodic(new Duration(seconds: 2), (Timer t) { // Increasing the counter counter++; //Printing the output message stdout.writeln('Welcome to GeeksForGeeks $counter'); });} void stop_geek_process() { // Checking the isolate with null if (geek != null) { stdout.writeln('--------------Stopping Geek Isolate--------------'); // Killing the isolate geek.kill(priority: Isolate.immediate); // Setting the isolate to null geek = null; } } // Main Functionvoid main() async { stdout.writeln('--------------Starting Geek Isolate--------------'); // Starting the isolate with start_geek_process await start_geek_process(); stdout.writeln('Press enter key to quit'); // Whenever enter is hit the program is stopped await stdin.first; // Calling the stop_geek_process stop_geek_process(); // Printing the goodbye message stdout.writeln('GoodBye Geek!'); // Exiting the program. exit(0);} Output: --------------Starting Geek Isolate-------------- Press enter key to quit Welcome to GeeksForGeeks 1 Welcome to GeeksForGeeks 2 Welcome to GeeksForGeeks 3 Welcome to GeeksForGeeks 4 Welcome to GeeksForGeeks 5 Welcome to GeeksForGeeks 6 Welcome to GeeksForGeeks 7 --------------Stopping Geek Isolate-------------- GoodBye Geek! Hitting enter after seventh output. Dart-Exception-Handling Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jul, 2020" }, { "code": null, "e": 541, "s": 28, "text": "Dart was traditionally designed to create single-page applications. And we also know that most computers, even mobile platforms, have multi-core CPUs. To take advantage of all those cores, developers traditionally use shared-memory threads running concurrently. However, shared-state concurrency is error-prone and can lead to complicated code. Instead of threads, all Dart code runs inside of isolates. Each isolate has its own memory heap, ensuring that no isolate’s state is accessible from any other isolate." }, { "code": null, "e": 718, "s": 541, "text": "The isolates and threads are different than each other as in threads memory are shared whereas in isolates it is not. Moreover isolates talk to each other via passing messages." }, { "code": null, "e": 806, "s": 718, "text": "To use isolates you have to add import 'dart:isolate'; statement in your program code.\n" }, { "code": null, "e": 867, "s": 806, "text": "To create an isolate we make use of .spawn() method in Dart." }, { "code": null, "e": 933, "s": 867, "text": "Syntax: Isolate isolate_name = await Isolate.spawn( parameter );\n" }, { "code": null, "e": 1004, "s": 933, "text": "This parameter represents the port that will receive the message back." }, { "code": null, "e": 1066, "s": 1004, "text": "To destroy the isolate we make use of .kill() method in Dart." }, { "code": null, "e": 1108, "s": 1066, "text": "Syntax: isolate_name.kill( parameters );\n" }, { "code": null, "e": 1174, "s": 1108, "text": "We generally use spawn() and kill() together in a single program." }, { "code": null, "e": 1213, "s": 1174, "text": "Example: Creating an isolate in Dart." }, { "code": null, "e": 1218, "s": 1213, "text": "Dart" }, { "code": "// importing dart libraries import 'dart:io';import 'dart:async';import 'dart:isolate'; // Creating geek isolateIsolate geek; void start_geek_process() async { // port for isolate to receive messages. ReceivePort geekReceive= ReceivePort(); // Starting an isolate geek = await Isolate.spawn(gfg, geekReceive.sendPort);} void gfg(SendPort sendPort) { int counter = 0; // Printing Output message after every 2 sec. Timer.periodic(new Duration(seconds: 2), (Timer t) { // Increasing the counter counter++; //Printing the output message stdout.writeln('Welcome to GeeksForGeeks $counter'); });} void stop_geek_process() { // Checking the isolate with null if (geek != null) { stdout.writeln('--------------Stopping Geek Isolate--------------'); // Killing the isolate geek.kill(priority: Isolate.immediate); // Setting the isolate to null geek = null; } } // Main Functionvoid main() async { stdout.writeln('--------------Starting Geek Isolate--------------'); // Starting the isolate with start_geek_process await start_geek_process(); stdout.writeln('Press enter key to quit'); // Whenever enter is hit the program is stopped await stdin.first; // Calling the stop_geek_process stop_geek_process(); // Printing the goodbye message stdout.writeln('GoodBye Geek!'); // Exiting the program. exit(0);}", "e": 2624, "s": 1218, "text": null }, { "code": null, "e": 2632, "s": 2624, "text": "Output:" }, { "code": null, "e": 2961, "s": 2632, "text": "--------------Starting Geek Isolate--------------\nPress enter key to quit\nWelcome to GeeksForGeeks 1\nWelcome to GeeksForGeeks 2\nWelcome to GeeksForGeeks 3\nWelcome to GeeksForGeeks 4\nWelcome to GeeksForGeeks 5\nWelcome to GeeksForGeeks 6\nWelcome to GeeksForGeeks 7\n\n--------------Stopping Geek Isolate--------------\nGoodBye Geek!\n" }, { "code": null, "e": 2997, "s": 2961, "text": "Hitting enter after seventh output." }, { "code": null, "e": 3021, "s": 2997, "text": "Dart-Exception-Handling" }, { "code": null, "e": 3026, "s": 3021, "text": "Dart" } ]
Implement Splash Screen and Authentication in Social Media Android App
13 Jun, 2022 This is the Part 1 of “Build a Social Media App on Android Studio” tutorial, and we are going to cover the following functionalities in this article: Creating a Splash Screen Authentication Part:Registration, andLogin Registration, and Login 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: Connect your app to firebase Go to the Tools > Firebase > Authentication and connect your app to firebase and also add the firebase authentication SDK to your app like the following image. Then go to the Firebase Console > Authentication > Sign-in method and Enable the Email/Password. Step 3: Create 4 new empty activities Go to the package name > right-click > New > Activity > Empty Activity and name the activity as SplashScreen, RegistrationActivity, LoginActivity, and DashboardActivity. You may also refer to this article How to create new empty activity in android studio. Step 4: Working with the SplashScreen Activity Navigate to the app > res > layout > activity_splash_screen.xml and add the below code to that file. Below is the code for the activity_splash_screen.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout 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:background="@drawable/background_color" tools:context=".SplashScreen"> </androidx.constraintlayout.widget.ConstraintLayout> Working with the SplashScreen.java file. Here we are checking that if the user is null then go to LoginActivity. Else move to DashboardActivity. new Handler().postDelayed(new Runnable() { @Override public void run() { FirebaseUser user=mAuth.getCurrentUser(); if(user==null){ Intent intent = new Intent(SplashScreen.this, LoginActivity.class); startActivity(intent); finish(); } else { Intent mainIntent= new Intent(SplashScreen.this, DashboardActivity.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(mainIntent); finish(); } } },1000); Below is the code for the SplashScreen.java file. Java package com.example.socialmediaapp; import android.content.Intent;import android.os.Bundle;import android.os.Handler; import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser; public class SplashScreen extends AppCompatActivity { FirebaseUser currentUser; private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_screen); mAuth = FirebaseAuth.getInstance(); if (mAuth != null) { currentUser = mAuth.getCurrentUser(); } new Handler().postDelayed(new Runnable() { @Override public void run() { FirebaseUser user = mAuth.getCurrentUser(); if (user == null) { Intent intent = new Intent(SplashScreen.this, LoginActivity.class); startActivity(intent); finish(); } else { Intent mainIntent = new Intent(SplashScreen.this, DashboardActivity.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(mainIntent); finish(); } } }, 1000); }} Step 5: Working with the RegistrationActivity Activity Navigate to the app > res > layout > activity_registration.xml and add the below code to that file. Below is the code for the activity_registration.xml file. Here we have created three EditText for the name, email and password and one Button to Register user. 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=".RegistrationActivity"> <TextView android:id="@+id/teacher" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginTop="50dp" android:gravity="center" android:text="Sign Up Here" android:textColor="@color/colorBlack" android:textSize="28sp" android:textStyle="bold|italic" /> <TextView android:id="@+id/names" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/teacher" android:layout_marginStart="35dp" android:layout_marginTop="120dp" android:text="Name" android:textColor="@color/colorBlack" /> <EditText android:id="@+id/register_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/names" android:layout_alignParentStart="true" android:layout_marginLeft="30dp" android:layout_marginTop="10dp" android:layout_marginRight="30dp" android:background="@drawable/edit" android:drawableStart="@drawable/name" android:hint="Your Name..." android:inputType="text" android:padding="8dp" /> <TextView android:id="@+id/email" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/register_name" android:layout_marginStart="35dp" android:layout_marginTop="10dp" android:text="Email" android:textColor="@color/colorBlack" /> <EditText android:id="@+id/register_email" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/email" android:layout_alignParentStart="true" android:layout_marginLeft="30dp" android:layout_marginTop="10dp" android:layout_marginRight="30dp" android:background="@drawable/edit" android:drawableStart="@drawable/ic_email" android:hint="Email..." android:inputType="textEmailAddress" android:padding="8dp" /> <TextView android:id="@+id/pass" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/register_email" android:layout_marginStart="35dp" android:layout_marginTop="10dp" android:text="Password" android:textColor="@color/colorBlack" /> <EditText android:id="@+id/register_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/pass" android:layout_alignParentStart="true" android:layout_marginLeft="30dp" android:layout_marginTop="10dp" android:layout_marginRight="30dp" android:background="@drawable/edit" android:drawableStart="@drawable/password" android:hint="Password..." android:inputType="textPassword" android:padding="8dp" /> <Button android:id="@+id/register_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/register_password" android:layout_marginLeft="30dp" android:layout_marginTop="30dp" android:layout_marginRight="30dp" android:background="@drawable/buttonss" android:padding="4dp" android:text="Create Account" android:textAllCaps="false" android:textColor="@android:color/background_light" android:textSize="24sp" /> <TextView android:id="@+id/homepage" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/register_button" android:layout_centerHorizontal="true" android:layout_marginStart="15dp" android:layout_marginTop="20dp" android:layout_marginEnd="23dp" android:text=" Already Have a Account?Sign In" android:textAlignment="center" android:textColor="@color/colorBlack" android:textSize="17sp" android:textStyle="bold" /> </RelativeLayout> Working with the RegistrationActivity.java file. Creating a user with the email and password written by the user. If it fails then we will be showing the error. mAuth.createUserWithEmailAndPassword(emaill, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()){ progressDialog.dismiss(); } else { progressDialog.dismiss(); Toast.makeText(RegistrationActivity.this,"Error",Toast.LENGTH_LONG).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { progressDialog.dismiss(); Toast.makeText(RegistrationActivity.this,"Error Occurred",Toast.LENGTH_LONG).show(); } }); Below is the code for the RegistrationActivity.java file. Java package com.example.socialmediaapp; import android.app.ProgressDialog;import android.content.Intent;import android.os.Bundle;import android.util.Patterns;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.ActionBar;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.Task;import com.google.firebase.auth.AuthResult;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase; import java.util.HashMap; public class RegistrationActivity extends AppCompatActivity { private EditText email, password, name; private Button mRegister; private TextView existaccount; private ProgressDialog progressDialog; private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registration); ActionBar actionBar = getSupportActionBar(); actionBar.setTitle("Create Account"); actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); email = findViewById(R.id.register_email); name = findViewById(R.id.register_name); password = findViewById(R.id.register_password); mRegister = findViewById(R.id.register_button); existaccount = findViewById(R.id.homepage); mAuth = FirebaseAuth.getInstance(); progressDialog = new ProgressDialog(this); progressDialog.setMessage("Register"); mRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String emaill = email.getText().toString().trim(); String uname = name.getText().toString().trim(); String pass = password.getText().toString().trim(); if (!Patterns.EMAIL_ADDRESS.matcher(emaill).matches()) { email.setError("Invalid Email"); email.setFocusable(true); } else if (pass.length() < 6) { password.setError("Length Must be greater than 6 character"); password.setFocusable(true); } else { registerUser(emaill, pass, uname); } } }); existaccount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(RegistrationActivity.this, LoginActivity.class)); } }); } private void registerUser(String emaill, final String pass, final String uname) { progressDialog.show(); mAuth.createUserWithEmailAndPassword(emaill, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { progressDialog.dismiss(); FirebaseUser user = mAuth.getCurrentUser(); String email = user.getEmail(); String uid = user.getUid(); HashMap<Object, String> hashMap = new HashMap<>(); hashMap.put("email", email); hashMap.put("uid", uid); hashMap.put("name", uname); hashMap.put("onlineStatus", "online"); hashMap.put("typingTo", "noOne"); hashMap.put("image", ""); FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference reference = database.getReference("Users"); reference.child(uid).setValue(hashMap); Toast.makeText(RegistrationActivity.this, "Registered User " + user.getEmail(), Toast.LENGTH_LONG).show(); Intent mainIntent = new Intent(RegistrationActivity.this, DashboardActivity.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(mainIntent); finish(); } else { progressDialog.dismiss(); Toast.makeText(RegistrationActivity.this, "Error", Toast.LENGTH_LONG).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { progressDialog.dismiss(); Toast.makeText(RegistrationActivity.this, "Error Occurred", Toast.LENGTH_LONG).show(); } }); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return super.onSupportNavigateUp(); }} Step 6: Working with the LoginActivity Activity Navigate to the app > res > layout > activity_login.xml and add the below code to that file. Below is the code for the activity_login.xml file. Here We are creating two EditText for email and password and one Button to Login. 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" tools:context=".LoginActivity"> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentStart="true" android:layout_alignParentTop="true"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/welcom" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="120dp" android:layout_marginTop="50dp" android:text="Welcome!" android:textColor="@color/colorBlack" android:textSize="30sp" android:textStyle="italic|bold" /> <TextView android:id="@+id/email" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/welcom" android:layout_marginStart="35dp" android:layout_marginTop="120dp" android:text="Email" android:textColor="@color/colorBlack" /> <EditText android:id="@+id/login_email" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/email" android:layout_alignParentStart="true" android:layout_marginLeft="30dp" android:layout_marginTop="5dp" android:layout_marginRight="30dp" android:background="@drawable/edit" android:drawableStart="@drawable/ic_email" android:hint="Email..." android:inputType="textEmailAddress" android:padding="8dp" /> <TextView android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/login_email" android:layout_marginStart="32dp" android:layout_marginTop="20dp" android:text="Password" android:textColor="@color/colorBlack" /> <EditText android:id="@+id/login_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/password" android:layout_alignParentStart="true" android:layout_marginLeft="30dp" android:layout_marginTop="5dp" android:layout_marginRight="30dp" android:background="@drawable/edit" android:drawableStart="@drawable/password" android:hint="Password..." android:inputType="textPassword" android:padding="8dp" /> <TextView android:id="@+id/forgetp" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/login_password" android:layout_marginStart="210dp" android:layout_marginTop="15dp" android:layout_marginEnd="23dp" android:text="Forget Password?" android:textAlignment="center" android:textColor="@color/colorPrimaryDark" android:textSize="17sp" android:textStyle="bold" /> <Button android:id="@+id/login_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/forgetp" android:layout_marginLeft="30dp" android:layout_marginTop="15dp" android:layout_marginRight="30dp" android:background="@drawable/buttonss" android:padding="4dp" android:text="Login" android:textAllCaps="false" android:textColor="@android:color/background_light" android:textSize="24sp" /> <TextView android:id="@+id/needs_new_account" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/login_button" android:layout_centerHorizontal="true" android:layout_marginStart="15dp" android:layout_marginTop="20dp" android:layout_marginEnd="23dp" android:text="Need new Account?Sign Up Here" android:textAlignment="center" android:textColor="@color/colorPrimary" android:textSize="17sp" android:textStyle="bold" /> </RelativeLayout> </ScrollView> </LinearLayout> Working with the LoginActivity.java file. Signing in user with the email and password written by the user. If it fails then we will be showing the error. mAuth.signInWithEmailAndPassword(emaill, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { loadingBar.dismiss(); } else { loadingBar.dismiss(); Toast.makeText(LoginActivity.this,"Login Failed",Toast.LENGTH_LONG).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { loadingBar.dismiss(); Toast.makeText(LoginActivity.this,"Error Occurred",Toast.LENGTH_LONG).show(); } }); Below is the code for the LoginActivity.java file. Java package com.example.socialmediaapp; import android.app.AlertDialog;import android.app.ProgressDialog;import android.content.DialogInterface;import android.content.Intent;import android.os.Bundle;import android.text.InputType;import android.util.Patterns;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.ActionBar;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.Task;import com.google.firebase.auth.AuthResult;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase; import java.util.HashMap; public class LoginActivity extends AppCompatActivity { private EditText email, password, name; private Button mlogin; private TextView newdnewaccount, reocverpass; FirebaseUser currentUser; private ProgressDialog loadingBar; private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ActionBar actionBar = getSupportActionBar(); actionBar.setTitle("Create Account"); actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); // initialising the layout items email = findViewById(R.id.login_email); password = findViewById(R.id.login_password); newdnewaccount = findViewById(R.id.needs_new_account); reocverpass = findViewById(R.id.forgetp); mAuth = FirebaseAuth.getInstance(); mlogin = findViewById(R.id.login_button); loadingBar = new ProgressDialog(this); mAuth = FirebaseAuth.getInstance(); // checking if user is null or not if (mAuth != null) { currentUser = mAuth.getCurrentUser(); } mlogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String emaill = email.getText().toString().trim(); String pass = password.getText().toString().trim(); // if format of email doesn't matches return null if (!Patterns.EMAIL_ADDRESS.matcher(emaill).matches()) { email.setError("Invalid Email"); email.setFocusable(true); } else { loginUser(emaill, pass); } } }); // If new account then move to Registration Activity newdnewaccount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(LoginActivity.this, RegistrationActivity.class)); } }); // Recover Your Password using email reocverpass.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showRecoverPasswordDialog(); } }); } private void showRecoverPasswordDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Recover Password"); LinearLayout linearLayout = new LinearLayout(this); final EditText emailet = new EditText(this);//write your registered email emailet.setText("Email"); emailet.setMinEms(16); emailet.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); linearLayout.addView(emailet); linearLayout.setPadding(10, 10, 10, 10); builder.setView(linearLayout); builder.setPositiveButton("Recover", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String emaill = emailet.getText().toString().trim(); beginRecovery(emaill);//send a mail on the mail to recover password } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } private void beginRecovery(String emaill) { loadingBar.setMessage("Sending Email...."); loadingBar.setCanceledOnTouchOutside(false); loadingBar.show(); // send reset password email mAuth.sendPasswordResetEmail(emaill).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { loadingBar.dismiss(); if (task.isSuccessful()) { Toast.makeText(LoginActivity.this, "Done sent", Toast.LENGTH_LONG).show(); } else { Toast.makeText(LoginActivity.this, "Error Occurred", Toast.LENGTH_LONG).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { loadingBar.dismiss(); Toast.makeText(LoginActivity.this, "Error Failed", Toast.LENGTH_LONG).show(); } }); } private void loginUser(String emaill, String pass) { loadingBar.setMessage("Logging In...."); loadingBar.show(); // sign in with email and password after authenticating mAuth.signInWithEmailAndPassword(emaill, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { loadingBar.dismiss(); FirebaseUser user = mAuth.getCurrentUser(); if (task.getResult().getAdditionalUserInfo().isNewUser()) { String email = user.getEmail(); String uid = user.getUid(); HashMap<Object, String> hashMap = new HashMap<>(); hashMap.put("email", email); hashMap.put("uid", uid); hashMap.put("name", ""); hashMap.put("onlineStatus", "online"); hashMap.put("typingTo", "noOne"); hashMap.put("phone", ""); hashMap.put("image", ""); hashMap.put("cover", ""); FirebaseDatabase database = FirebaseDatabase.getInstance(); // store the value in Database in "Users" Node DatabaseReference reference = database.getReference("Users"); // storing the value in Firebase reference.child(uid).setValue(hashMap); } Toast.makeText(LoginActivity.this, "Registered User " + user.getEmail(), Toast.LENGTH_LONG).show(); Intent mainIntent = new Intent(LoginActivity.this, DashboardActivity.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(mainIntent); finish(); } else { loadingBar.dismiss(); Toast.makeText(LoginActivity.this, "Login Failed", Toast.LENGTH_LONG).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { loadingBar.dismiss(); Toast.makeText(LoginActivity.this, "Error Occurred", Toast.LENGTH_LONG).show(); } }); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return super.onSupportNavigateUp(); }} Step 7: Working with the AndroidManifest.xml file Navigate to the AndroidManifest.xml file and add the below permission for getting internet permission in the app. <uses-permission android:name=”android.permission.INTERNET”/> Also, make the SplashScreen Acticty as the welcome screen. Refer to the following code <activity android:name=".SplashScreen"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> 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="com.example.socialmediaapp"> <uses-permission android:name="android.permission.INTERNET" /> <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/Theme.SocialMediaApp"> <activity android:name=".DashboardActivity"></activity> <activity android:name=".LoginActivity" /> <activity android:name=".RegistrationActivity" /> <activity android:name=".SplashScreen"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Step 8: Working with the colors.xml file Go to the app > res > values > colors.xml file and use the following color XML <?xml version="1.0" encoding="utf-8"?><resources> <color name="colorPrimary">#CC2E76BE</color> <color name="colorPrimaryDark">#CC073D74</color> <color name="colorAccent">#0A527E</color> <color name="colorBlack">#000000</color> <color name="colorWhite">#fff</color> <color name="colorGray">#F5F1F1</color> <color name="colorgray01">#959595</color> <color name="colorGray02">#f5f0f0</color> <color name="colorGreen">#17581A</color> <color name="colorRed">#F4511E</color> <color name="btnRed">#E61313</color> <color name="btnedit">#2CA7E0</color> <color name="neutral">#0a1b97</color> <color name="colordrawer">#2B2C2E</color></resources> Registration: Login: After successfully authenticated the admin can see the users in the firebase console like the following For all the drawable file used in this article please refer to this link: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing Below is the file structure after performing these operations: Note: In this part, there is nothing to do with the DashboardActivity. adnanirshad158 germanshephered48 avtarkumar719 nnr223442 nikhatkhan11 Firebase Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jun, 2022" }, { "code": null, "e": 204, "s": 54, "text": "This is the Part 1 of “Build a Social Media App on Android Studio” tutorial, and we are going to cover the following functionalities in this article:" }, { "code": null, "e": 229, "s": 204, "text": "Creating a Splash Screen" }, { "code": null, "e": 272, "s": 229, "text": "Authentication Part:Registration, andLogin" }, { "code": null, "e": 290, "s": 272, "text": "Registration, and" }, { "code": null, "e": 296, "s": 290, "text": "Login" }, { "code": null, "e": 325, "s": 296, "text": "Step 1: Create a New Project" }, { "code": null, "e": 487, "s": 325, "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": 525, "s": 487, "text": "Step 2: Connect your app to firebase " }, { "code": null, "e": 685, "s": 525, "text": "Go to the Tools > Firebase > Authentication and connect your app to firebase and also add the firebase authentication SDK to your app like the following image." }, { "code": null, "e": 782, "s": 685, "text": "Then go to the Firebase Console > Authentication > Sign-in method and Enable the Email/Password." }, { "code": null, "e": 820, "s": 782, "text": "Step 3: Create 4 new empty activities" }, { "code": null, "e": 1077, "s": 820, "text": "Go to the package name > right-click > New > Activity > Empty Activity and name the activity as SplashScreen, RegistrationActivity, LoginActivity, and DashboardActivity. You may also refer to this article How to create new empty activity in android studio." }, { "code": null, "e": 1124, "s": 1077, "text": "Step 4: Working with the SplashScreen Activity" }, { "code": null, "e": 1285, "s": 1124, "text": "Navigate to the app > res > layout > activity_splash_screen.xml and add the below code to that file. Below is the code for the activity_splash_screen.xml file. " }, { "code": null, "e": 1289, "s": 1285, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout 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:background=\"@drawable/background_color\" tools:context=\".SplashScreen\"> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 1708, "s": 1289, "text": null }, { "code": null, "e": 1854, "s": 1708, "text": "Working with the SplashScreen.java file. Here we are checking that if the user is null then go to LoginActivity. Else move to DashboardActivity. " }, { "code": null, "e": 2568, "s": 1854, "text": "new Handler().postDelayed(new Runnable() {\n @Override\n public void run() {\n FirebaseUser user=mAuth.getCurrentUser();\n if(user==null){\n Intent intent = new Intent(SplashScreen.this, LoginActivity.class);\n startActivity(intent);\n finish();\n }\n else {\n Intent mainIntent= new Intent(SplashScreen.this, DashboardActivity.class);\n mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);\n startActivity(mainIntent);\n finish();\n }\n }\n },1000);" }, { "code": null, "e": 2618, "s": 2568, "text": "Below is the code for the SplashScreen.java file." }, { "code": null, "e": 2623, "s": 2618, "text": "Java" }, { "code": "package com.example.socialmediaapp; import android.content.Intent;import android.os.Bundle;import android.os.Handler; import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser; public class SplashScreen extends AppCompatActivity { FirebaseUser currentUser; private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_screen); mAuth = FirebaseAuth.getInstance(); if (mAuth != null) { currentUser = mAuth.getCurrentUser(); } new Handler().postDelayed(new Runnable() { @Override public void run() { FirebaseUser user = mAuth.getCurrentUser(); if (user == null) { Intent intent = new Intent(SplashScreen.this, LoginActivity.class); startActivity(intent); finish(); } else { Intent mainIntent = new Intent(SplashScreen.this, DashboardActivity.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(mainIntent); finish(); } } }, 1000); }}", "e": 4000, "s": 2623, "text": null }, { "code": null, "e": 4055, "s": 4000, "text": "Step 5: Working with the RegistrationActivity Activity" }, { "code": null, "e": 4316, "s": 4055, "text": "Navigate to the app > res > layout > activity_registration.xml and add the below code to that file. Below is the code for the activity_registration.xml file. Here we have created three EditText for the name, email and password and one Button to Register user." }, { "code": null, "e": 4320, "s": 4316, "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=\".RegistrationActivity\"> <TextView android:id=\"@+id/teacher\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_alignParentStart=\"true\" android:layout_alignParentTop=\"true\" android:layout_marginTop=\"50dp\" android:gravity=\"center\" android:text=\"Sign Up Here\" android:textColor=\"@color/colorBlack\" android:textSize=\"28sp\" android:textStyle=\"bold|italic\" /> <TextView android:id=\"@+id/names\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/teacher\" android:layout_marginStart=\"35dp\" android:layout_marginTop=\"120dp\" android:text=\"Name\" android:textColor=\"@color/colorBlack\" /> <EditText android:id=\"@+id/register_name\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/names\" android:layout_alignParentStart=\"true\" android:layout_marginLeft=\"30dp\" android:layout_marginTop=\"10dp\" android:layout_marginRight=\"30dp\" android:background=\"@drawable/edit\" android:drawableStart=\"@drawable/name\" android:hint=\"Your Name...\" android:inputType=\"text\" android:padding=\"8dp\" /> <TextView android:id=\"@+id/email\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/register_name\" android:layout_marginStart=\"35dp\" android:layout_marginTop=\"10dp\" android:text=\"Email\" android:textColor=\"@color/colorBlack\" /> <EditText android:id=\"@+id/register_email\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/email\" android:layout_alignParentStart=\"true\" android:layout_marginLeft=\"30dp\" android:layout_marginTop=\"10dp\" android:layout_marginRight=\"30dp\" android:background=\"@drawable/edit\" android:drawableStart=\"@drawable/ic_email\" android:hint=\"Email...\" android:inputType=\"textEmailAddress\" android:padding=\"8dp\" /> <TextView android:id=\"@+id/pass\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/register_email\" android:layout_marginStart=\"35dp\" android:layout_marginTop=\"10dp\" android:text=\"Password\" android:textColor=\"@color/colorBlack\" /> <EditText android:id=\"@+id/register_password\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/pass\" android:layout_alignParentStart=\"true\" android:layout_marginLeft=\"30dp\" android:layout_marginTop=\"10dp\" android:layout_marginRight=\"30dp\" android:background=\"@drawable/edit\" android:drawableStart=\"@drawable/password\" android:hint=\"Password...\" android:inputType=\"textPassword\" android:padding=\"8dp\" /> <Button android:id=\"@+id/register_button\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/register_password\" android:layout_marginLeft=\"30dp\" android:layout_marginTop=\"30dp\" android:layout_marginRight=\"30dp\" android:background=\"@drawable/buttonss\" android:padding=\"4dp\" android:text=\"Create Account\" android:textAllCaps=\"false\" android:textColor=\"@android:color/background_light\" android:textSize=\"24sp\" /> <TextView android:id=\"@+id/homepage\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/register_button\" android:layout_centerHorizontal=\"true\" android:layout_marginStart=\"15dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"23dp\" android:text=\" Already Have a Account?Sign In\" android:textAlignment=\"center\" android:textColor=\"@color/colorBlack\" android:textSize=\"17sp\" android:textStyle=\"bold\" /> </RelativeLayout>", "e": 8818, "s": 4320, "text": null }, { "code": null, "e": 8979, "s": 8818, "text": "Working with the RegistrationActivity.java file. Creating a user with the email and password written by the user. If it fails then we will be showing the error." }, { "code": null, "e": 9789, "s": 8979, "text": "mAuth.createUserWithEmailAndPassword(emaill, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {\n @Override\n public void onComplete(@NonNull Task<AuthResult> task) {\n if (task.isSuccessful()){\n progressDialog.dismiss();\n }\n else {\n progressDialog.dismiss();\n Toast.makeText(RegistrationActivity.this,\"Error\",Toast.LENGTH_LONG).show();\n }\n }\n }).addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception e) {\n progressDialog.dismiss();\n Toast.makeText(RegistrationActivity.this,\"Error Occurred\",Toast.LENGTH_LONG).show();\n }\n });" }, { "code": null, "e": 9847, "s": 9789, "text": "Below is the code for the RegistrationActivity.java file." }, { "code": null, "e": 9852, "s": 9847, "text": "Java" }, { "code": "package com.example.socialmediaapp; import android.app.ProgressDialog;import android.content.Intent;import android.os.Bundle;import android.util.Patterns;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.ActionBar;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.Task;import com.google.firebase.auth.AuthResult;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase; import java.util.HashMap; public class RegistrationActivity extends AppCompatActivity { private EditText email, password, name; private Button mRegister; private TextView existaccount; private ProgressDialog progressDialog; private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registration); ActionBar actionBar = getSupportActionBar(); actionBar.setTitle(\"Create Account\"); actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); email = findViewById(R.id.register_email); name = findViewById(R.id.register_name); password = findViewById(R.id.register_password); mRegister = findViewById(R.id.register_button); existaccount = findViewById(R.id.homepage); mAuth = FirebaseAuth.getInstance(); progressDialog = new ProgressDialog(this); progressDialog.setMessage(\"Register\"); mRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String emaill = email.getText().toString().trim(); String uname = name.getText().toString().trim(); String pass = password.getText().toString().trim(); if (!Patterns.EMAIL_ADDRESS.matcher(emaill).matches()) { email.setError(\"Invalid Email\"); email.setFocusable(true); } else if (pass.length() < 6) { password.setError(\"Length Must be greater than 6 character\"); password.setFocusable(true); } else { registerUser(emaill, pass, uname); } } }); existaccount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(RegistrationActivity.this, LoginActivity.class)); } }); } private void registerUser(String emaill, final String pass, final String uname) { progressDialog.show(); mAuth.createUserWithEmailAndPassword(emaill, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { progressDialog.dismiss(); FirebaseUser user = mAuth.getCurrentUser(); String email = user.getEmail(); String uid = user.getUid(); HashMap<Object, String> hashMap = new HashMap<>(); hashMap.put(\"email\", email); hashMap.put(\"uid\", uid); hashMap.put(\"name\", uname); hashMap.put(\"onlineStatus\", \"online\"); hashMap.put(\"typingTo\", \"noOne\"); hashMap.put(\"image\", \"\"); FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference reference = database.getReference(\"Users\"); reference.child(uid).setValue(hashMap); Toast.makeText(RegistrationActivity.this, \"Registered User \" + user.getEmail(), Toast.LENGTH_LONG).show(); Intent mainIntent = new Intent(RegistrationActivity.this, DashboardActivity.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(mainIntent); finish(); } else { progressDialog.dismiss(); Toast.makeText(RegistrationActivity.this, \"Error\", Toast.LENGTH_LONG).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { progressDialog.dismiss(); Toast.makeText(RegistrationActivity.this, \"Error Occurred\", Toast.LENGTH_LONG).show(); } }); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return super.onSupportNavigateUp(); }}", "e": 14941, "s": 9852, "text": null }, { "code": null, "e": 14989, "s": 14941, "text": "Step 6: Working with the LoginActivity Activity" }, { "code": null, "e": 15215, "s": 14989, "text": "Navigate to the app > res > layout > activity_login.xml and add the below code to that file. Below is the code for the activity_login.xml file. Here We are creating two EditText for email and password and one Button to Login." }, { "code": null, "e": 15219, "s": 15215, "text": "XML" }, { "code": "<?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\" tools:context=\".LoginActivity\"> <ScrollView android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_alignParentStart=\"true\" android:layout_alignParentTop=\"true\"> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <TextView android:id=\"@+id/welcom\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"120dp\" android:layout_marginTop=\"50dp\" android:text=\"Welcome!\" android:textColor=\"@color/colorBlack\" android:textSize=\"30sp\" android:textStyle=\"italic|bold\" /> <TextView android:id=\"@+id/email\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/welcom\" android:layout_marginStart=\"35dp\" android:layout_marginTop=\"120dp\" android:text=\"Email\" android:textColor=\"@color/colorBlack\" /> <EditText android:id=\"@+id/login_email\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/email\" android:layout_alignParentStart=\"true\" android:layout_marginLeft=\"30dp\" android:layout_marginTop=\"5dp\" android:layout_marginRight=\"30dp\" android:background=\"@drawable/edit\" android:drawableStart=\"@drawable/ic_email\" android:hint=\"Email...\" android:inputType=\"textEmailAddress\" android:padding=\"8dp\" /> <TextView android:id=\"@+id/password\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/login_email\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"20dp\" android:text=\"Password\" android:textColor=\"@color/colorBlack\" /> <EditText android:id=\"@+id/login_password\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/password\" android:layout_alignParentStart=\"true\" android:layout_marginLeft=\"30dp\" android:layout_marginTop=\"5dp\" android:layout_marginRight=\"30dp\" android:background=\"@drawable/edit\" android:drawableStart=\"@drawable/password\" android:hint=\"Password...\" android:inputType=\"textPassword\" android:padding=\"8dp\" /> <TextView android:id=\"@+id/forgetp\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/login_password\" android:layout_marginStart=\"210dp\" android:layout_marginTop=\"15dp\" android:layout_marginEnd=\"23dp\" android:text=\"Forget Password?\" android:textAlignment=\"center\" android:textColor=\"@color/colorPrimaryDark\" android:textSize=\"17sp\" android:textStyle=\"bold\" /> <Button android:id=\"@+id/login_button\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/forgetp\" android:layout_marginLeft=\"30dp\" android:layout_marginTop=\"15dp\" android:layout_marginRight=\"30dp\" android:background=\"@drawable/buttonss\" android:padding=\"4dp\" android:text=\"Login\" android:textAllCaps=\"false\" android:textColor=\"@android:color/background_light\" android:textSize=\"24sp\" /> <TextView android:id=\"@+id/needs_new_account\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/login_button\" android:layout_centerHorizontal=\"true\" android:layout_marginStart=\"15dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"23dp\" android:text=\"Need new Account?Sign Up Here\" android:textAlignment=\"center\" android:textColor=\"@color/colorPrimary\" android:textSize=\"17sp\" android:textStyle=\"bold\" /> </RelativeLayout> </ScrollView> </LinearLayout>", "e": 20362, "s": 15219, "text": null }, { "code": null, "e": 20516, "s": 20362, "text": "Working with the LoginActivity.java file. Signing in user with the email and password written by the user. If it fails then we will be showing the error." }, { "code": null, "e": 21305, "s": 20516, "text": "mAuth.signInWithEmailAndPassword(emaill, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {\n @Override\n public void onComplete(@NonNull Task<AuthResult> task) {\n\n if (task.isSuccessful()) {\n loadingBar.dismiss();\n\n }\n else {\n loadingBar.dismiss();\n Toast.makeText(LoginActivity.this,\"Login Failed\",Toast.LENGTH_LONG).show();\n }\n }\n }).addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception e) {\n loadingBar.dismiss();\n Toast.makeText(LoginActivity.this,\"Error Occurred\",Toast.LENGTH_LONG).show();\n }\n });" }, { "code": null, "e": 21357, "s": 21305, "text": "Below is the code for the LoginActivity.java file. " }, { "code": null, "e": 21362, "s": 21357, "text": "Java" }, { "code": "package com.example.socialmediaapp; import android.app.AlertDialog;import android.app.ProgressDialog;import android.content.DialogInterface;import android.content.Intent;import android.os.Bundle;import android.text.InputType;import android.util.Patterns;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.ActionBar;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.Task;import com.google.firebase.auth.AuthResult;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase; import java.util.HashMap; public class LoginActivity extends AppCompatActivity { private EditText email, password, name; private Button mlogin; private TextView newdnewaccount, reocverpass; FirebaseUser currentUser; private ProgressDialog loadingBar; private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ActionBar actionBar = getSupportActionBar(); actionBar.setTitle(\"Create Account\"); actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); // initialising the layout items email = findViewById(R.id.login_email); password = findViewById(R.id.login_password); newdnewaccount = findViewById(R.id.needs_new_account); reocverpass = findViewById(R.id.forgetp); mAuth = FirebaseAuth.getInstance(); mlogin = findViewById(R.id.login_button); loadingBar = new ProgressDialog(this); mAuth = FirebaseAuth.getInstance(); // checking if user is null or not if (mAuth != null) { currentUser = mAuth.getCurrentUser(); } mlogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String emaill = email.getText().toString().trim(); String pass = password.getText().toString().trim(); // if format of email doesn't matches return null if (!Patterns.EMAIL_ADDRESS.matcher(emaill).matches()) { email.setError(\"Invalid Email\"); email.setFocusable(true); } else { loginUser(emaill, pass); } } }); // If new account then move to Registration Activity newdnewaccount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(LoginActivity.this, RegistrationActivity.class)); } }); // Recover Your Password using email reocverpass.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showRecoverPasswordDialog(); } }); } private void showRecoverPasswordDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(\"Recover Password\"); LinearLayout linearLayout = new LinearLayout(this); final EditText emailet = new EditText(this);//write your registered email emailet.setText(\"Email\"); emailet.setMinEms(16); emailet.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); linearLayout.addView(emailet); linearLayout.setPadding(10, 10, 10, 10); builder.setView(linearLayout); builder.setPositiveButton(\"Recover\", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String emaill = emailet.getText().toString().trim(); beginRecovery(emaill);//send a mail on the mail to recover password } }); builder.setNegativeButton(\"Cancel\", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } private void beginRecovery(String emaill) { loadingBar.setMessage(\"Sending Email....\"); loadingBar.setCanceledOnTouchOutside(false); loadingBar.show(); // send reset password email mAuth.sendPasswordResetEmail(emaill).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { loadingBar.dismiss(); if (task.isSuccessful()) { Toast.makeText(LoginActivity.this, \"Done sent\", Toast.LENGTH_LONG).show(); } else { Toast.makeText(LoginActivity.this, \"Error Occurred\", Toast.LENGTH_LONG).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { loadingBar.dismiss(); Toast.makeText(LoginActivity.this, \"Error Failed\", Toast.LENGTH_LONG).show(); } }); } private void loginUser(String emaill, String pass) { loadingBar.setMessage(\"Logging In....\"); loadingBar.show(); // sign in with email and password after authenticating mAuth.signInWithEmailAndPassword(emaill, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { loadingBar.dismiss(); FirebaseUser user = mAuth.getCurrentUser(); if (task.getResult().getAdditionalUserInfo().isNewUser()) { String email = user.getEmail(); String uid = user.getUid(); HashMap<Object, String> hashMap = new HashMap<>(); hashMap.put(\"email\", email); hashMap.put(\"uid\", uid); hashMap.put(\"name\", \"\"); hashMap.put(\"onlineStatus\", \"online\"); hashMap.put(\"typingTo\", \"noOne\"); hashMap.put(\"phone\", \"\"); hashMap.put(\"image\", \"\"); hashMap.put(\"cover\", \"\"); FirebaseDatabase database = FirebaseDatabase.getInstance(); // store the value in Database in \"Users\" Node DatabaseReference reference = database.getReference(\"Users\"); // storing the value in Firebase reference.child(uid).setValue(hashMap); } Toast.makeText(LoginActivity.this, \"Registered User \" + user.getEmail(), Toast.LENGTH_LONG).show(); Intent mainIntent = new Intent(LoginActivity.this, DashboardActivity.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(mainIntent); finish(); } else { loadingBar.dismiss(); Toast.makeText(LoginActivity.this, \"Login Failed\", Toast.LENGTH_LONG).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { loadingBar.dismiss(); Toast.makeText(LoginActivity.this, \"Error Occurred\", Toast.LENGTH_LONG).show(); } }); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return super.onSupportNavigateUp(); }}", "e": 29577, "s": 21362, "text": null }, { "code": null, "e": 29628, "s": 29577, "text": "Step 7: Working with the AndroidManifest.xml file " }, { "code": null, "e": 29742, "s": 29628, "text": "Navigate to the AndroidManifest.xml file and add the below permission for getting internet permission in the app." }, { "code": null, "e": 29804, "s": 29742, "text": "<uses-permission android:name=”android.permission.INTERNET”/>" }, { "code": null, "e": 29892, "s": 29804, "text": "Also, make the SplashScreen Acticty as the welcome screen. Refer to the following code " }, { "code": null, "e": 30148, "s": 29892, "text": "<activity android:name=\".SplashScreen\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n</activity>" }, { "code": null, "e": 30210, "s": 30148, "text": " Below is the complete code for the AndroidManifest.xml file." }, { "code": null, "e": 30214, "s": 30210, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.socialmediaapp\"> <uses-permission android:name=\"android.permission.INTERNET\" /> <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/Theme.SocialMediaApp\"> <activity android:name=\".DashboardActivity\"></activity> <activity android:name=\".LoginActivity\" /> <activity android:name=\".RegistrationActivity\" /> <activity android:name=\".SplashScreen\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>", "e": 31167, "s": 30214, "text": null }, { "code": null, "e": 31208, "s": 31167, "text": "Step 8: Working with the colors.xml file" }, { "code": null, "e": 31283, "s": 31208, "text": "Go to the app > res > values > colors.xml file and use the following color" }, { "code": null, "e": 31287, "s": 31283, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"colorPrimary\">#CC2E76BE</color> <color name=\"colorPrimaryDark\">#CC073D74</color> <color name=\"colorAccent\">#0A527E</color> <color name=\"colorBlack\">#000000</color> <color name=\"colorWhite\">#fff</color> <color name=\"colorGray\">#F5F1F1</color> <color name=\"colorgray01\">#959595</color> <color name=\"colorGray02\">#f5f0f0</color> <color name=\"colorGreen\">#17581A</color> <color name=\"colorRed\">#F4511E</color> <color name=\"btnRed\">#E61313</color> <color name=\"btnedit\">#2CA7E0</color> <color name=\"neutral\">#0a1b97</color> <color name=\"colordrawer\">#2B2C2E</color></resources>", "e": 31965, "s": 31287, "text": null }, { "code": null, "e": 31979, "s": 31965, "text": "Registration:" }, { "code": null, "e": 31986, "s": 31979, "text": "Login:" }, { "code": null, "e": 32090, "s": 31986, "text": "After successfully authenticated the admin can see the users in the firebase console like the following" }, { "code": null, "e": 32249, "s": 32090, "text": "For all the drawable file used in this article please refer to this link: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing" }, { "code": null, "e": 32312, "s": 32249, "text": "Below is the file structure after performing these operations:" }, { "code": null, "e": 32383, "s": 32312, "text": "Note: In this part, there is nothing to do with the DashboardActivity." }, { "code": null, "e": 32398, "s": 32383, "text": "adnanirshad158" }, { "code": null, "e": 32416, "s": 32398, "text": "germanshephered48" }, { "code": null, "e": 32430, "s": 32416, "text": "avtarkumar719" }, { "code": null, "e": 32440, "s": 32430, "text": "nnr223442" }, { "code": null, "e": 32453, "s": 32440, "text": "nikhatkhan11" }, { "code": null, "e": 32462, "s": 32453, "text": "Firebase" }, { "code": null, "e": 32470, "s": 32462, "text": "Android" }, { "code": null, "e": 32475, "s": 32470, "text": "Java" }, { "code": null, "e": 32480, "s": 32475, "text": "Java" }, { "code": null, "e": 32488, "s": 32480, "text": "Android" } ]
Number of Symmetric Relations on a Set
19 May, 2022 Given a number n, find out the number of Symmetric Relations on a set of first n natural numbers {1, 2, ..n}. Examples: Input : n = 2 Output : 8 Given set is {1, 2}. Below are all symmetric relation. {} {(1, 1)}, {(2, 2)}, {(1, 1), (2, 2)}, {(1, 2), (2, 1)} {(1, 1), (1, 2), (2, 1)}, {(2, 2), (1, 2), (2, 1)}, {(1, 1), (2, 2), (2, 1), (1, 2)} Input : n = 3 Output : 64 A Relation ‘R’ on Set A is said be Symmetric if xRy then yRx for every x, y ∈ A or if (x, y) ∈ R, then (y, x) ∈ R for every x, y?A Total number of symmetric relations is 2n(n+1)/2.How does this formula work?A relation R is symmetric if the value of every cell (i, j) is same as that cell (j, i). The diagonals can have any value. There are n diagonal values, total possible combination of diagonal values = 2n There are n2 – n non-diagonal values. We can only choose different value for half of them, because when we choose a value for cell (i, j), cell (j, i) gets same value. So combination of non-diagonal values = 2(n2 – n)/2Overall combination = 2n * 2(n2 – n)/2 = 2n(n+1)/2 C++ Java Python3 C# PHP Javascript // C++ program to count total symmetric relations// on a set of natural numbers.#include <bits/stdc++.h> // function find the square of nunsigned int countSymmetric(unsigned int n){ // Base case if (n == 0) return 1; // Return 2^(n(n + 1)/2) return 1 << ((n * (n + 1))/2);} // Driver codeint main(){ unsigned int n = 3; printf("%u", countSymmetric(n)); return 0;} // Java program to count total symmetric// relations on a set of natural numbers.import java.io.*;import java.util.*; class GFG { // function find the square of n static int countSymmetric(int n) { // Base case if (n == 0) return 1; // Return 2^(n(n + 1)/2) return 1 << ((n * (n + 1)) / 2); } // Driver code public static void main (String[] args) { int n = 3; System.out.println(countSymmetric(n)); }} // This code is contributed by Nikita Tiwari. # Python 3 program to count# total symmetric relations# on a set of natural numbers. # function find the square of ndef countSymmetric(n) : # Base case if (n == 0) : return 1 # Return 2^(n(n + 1)/2) return (1 << ((n * (n + 1))//2)) # Driver code n = 3print(countSymmetric(n)) # This code is contributed# by Nikita Tiwari. // C# program to count total symmetric// relations on a set of natural numbers.using System; class GFG { // function find the square of n static int countSymmetric(int n) { // Base case if (n == 0) return 1; // Return 2^(n(n + 1)/2) return 1 << ((n * (n + 1)) / 2); } // Driver code public static void Main () { int n = 3; Console.WriteLine(countSymmetric(n)); }} // This code is contributed by vt_m. <?php// PHP program to count total symmetric// relations on a set of natural numbers. // function find the square of nfunction countSymmetric($n){ // Base case if ($n == 0) return 1; // Return 2^(n(n + 1)/2) return 1 << (($n * ($n + 1))/2);} // Driver code $n = 3; echo(countSymmetric($n)); // This code is contributed by vt_m.?> <script> // JavaScript program to count total symmetric// relations on a set of natural numbers. // function find the square of n function countSymmetric(n) { // Base case if (n == 0) return 1; // Return 2^(n(n + 1)/2) return 1 << ((n * (n + 1)) / 2); } // Driver Code let n = 3; document.write(countSymmetric(n)); </script> 64 vt_m chinmoy1997pal abir22197072 Combinatorial Mathematical Mathematical Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 May, 2022" }, { "code": null, "e": 164, "s": 54, "text": "Given a number n, find out the number of Symmetric Relations on a set of first n natural numbers {1, 2, ..n}." }, { "code": null, "e": 175, "s": 164, "text": "Examples: " }, { "code": null, "e": 434, "s": 175, "text": "Input : n = 2\nOutput : 8\n \nGiven set is {1, 2}. Below are all symmetric relation.\n{}\n{(1, 1)}, \n{(2, 2)},\n{(1, 1), (2, 2)}, \n{(1, 2), (2, 1)} \n{(1, 1), (1, 2), (2, 1)},\n{(2, 2), (1, 2), (2, 1)}, \n{(1, 1), (2, 2), (2, 1), (1, 2)} \n\nInput : n = 3\nOutput : 64" }, { "code": null, "e": 566, "s": 434, "text": "A Relation ‘R’ on Set A is said be Symmetric if xRy then yRx for every x, y ∈ A or if (x, y) ∈ R, then (y, x) ∈ R for every x, y?A " }, { "code": null, "e": 767, "s": 566, "text": "Total number of symmetric relations is 2n(n+1)/2.How does this formula work?A relation R is symmetric if the value of every cell (i, j) is same as that cell (j, i). The diagonals can have any value. " }, { "code": null, "e": 1118, "s": 767, "text": "There are n diagonal values, total possible combination of diagonal values = 2n There are n2 – n non-diagonal values. We can only choose different value for half of them, because when we choose a value for cell (i, j), cell (j, i) gets same value. So combination of non-diagonal values = 2(n2 – n)/2Overall combination = 2n * 2(n2 – n)/2 = 2n(n+1)/2 " }, { "code": null, "e": 1122, "s": 1118, "text": "C++" }, { "code": null, "e": 1127, "s": 1122, "text": "Java" }, { "code": null, "e": 1135, "s": 1127, "text": "Python3" }, { "code": null, "e": 1138, "s": 1135, "text": "C#" }, { "code": null, "e": 1142, "s": 1138, "text": "PHP" }, { "code": null, "e": 1153, "s": 1142, "text": "Javascript" }, { "code": "// C++ program to count total symmetric relations// on a set of natural numbers.#include <bits/stdc++.h> // function find the square of nunsigned int countSymmetric(unsigned int n){ // Base case if (n == 0) return 1; // Return 2^(n(n + 1)/2) return 1 << ((n * (n + 1))/2);} // Driver codeint main(){ unsigned int n = 3; printf(\"%u\", countSymmetric(n)); return 0;}", "e": 1545, "s": 1153, "text": null }, { "code": "// Java program to count total symmetric// relations on a set of natural numbers.import java.io.*;import java.util.*; class GFG { // function find the square of n static int countSymmetric(int n) { // Base case if (n == 0) return 1; // Return 2^(n(n + 1)/2) return 1 << ((n * (n + 1)) / 2); } // Driver code public static void main (String[] args) { int n = 3; System.out.println(countSymmetric(n)); }} // This code is contributed by Nikita Tiwari.", "e": 2071, "s": 1545, "text": null }, { "code": "# Python 3 program to count# total symmetric relations# on a set of natural numbers. # function find the square of ndef countSymmetric(n) : # Base case if (n == 0) : return 1 # Return 2^(n(n + 1)/2) return (1 << ((n * (n + 1))//2)) # Driver code n = 3print(countSymmetric(n)) # This code is contributed# by Nikita Tiwari.", "e": 2416, "s": 2071, "text": null }, { "code": "// C# program to count total symmetric// relations on a set of natural numbers.using System; class GFG { // function find the square of n static int countSymmetric(int n) { // Base case if (n == 0) return 1; // Return 2^(n(n + 1)/2) return 1 << ((n * (n + 1)) / 2); } // Driver code public static void Main () { int n = 3; Console.WriteLine(countSymmetric(n)); }} // This code is contributed by vt_m.", "e": 2894, "s": 2416, "text": null }, { "code": "<?php// PHP program to count total symmetric// relations on a set of natural numbers. // function find the square of nfunction countSymmetric($n){ // Base case if ($n == 0) return 1; // Return 2^(n(n + 1)/2) return 1 << (($n * ($n + 1))/2);} // Driver code $n = 3; echo(countSymmetric($n)); // This code is contributed by vt_m.?>", "e": 3258, "s": 2894, "text": null }, { "code": "<script> // JavaScript program to count total symmetric// relations on a set of natural numbers. // function find the square of n function countSymmetric(n) { // Base case if (n == 0) return 1; // Return 2^(n(n + 1)/2) return 1 << ((n * (n + 1)) / 2); } // Driver Code let n = 3; document.write(countSymmetric(n)); </script>", "e": 3655, "s": 3258, "text": null }, { "code": null, "e": 3658, "s": 3655, "text": "64" }, { "code": null, "e": 3663, "s": 3658, "text": "vt_m" }, { "code": null, "e": 3678, "s": 3663, "text": "chinmoy1997pal" }, { "code": null, "e": 3691, "s": 3678, "text": "abir22197072" }, { "code": null, "e": 3705, "s": 3691, "text": "Combinatorial" }, { "code": null, "e": 3718, "s": 3705, "text": "Mathematical" }, { "code": null, "e": 3731, "s": 3718, "text": "Mathematical" }, { "code": null, "e": 3745, "s": 3731, "text": "Combinatorial" } ]
What are Wild Pointers? How can we avoid?
01 Oct, 2018 Uninitialized pointers are known as wild pointers because they point to some arbitrary memory location and may cause a program to crash or behave badly. int main(){ int *p; /* wild pointer */ /* Some unknown memory location is being corrupted. This should never be done. */ *p = 12; } Please note that if a pointer p points to a known variable then it’s not a wild pointer. In the below program, p is a wild pointer till this points to a. int main(){ int *p; /* wild pointer */ int a = 10; p = &a; /* p is not a wild pointer now*/ *p = 12; /* This is fine. Value of a is changed */ } If we want pointer to a value (or set of values) without having a variable for the value, we should explicitly allocate memory and put the value in allocated memory. int main(){ int *p = (int *)malloc(sizeof(int)); *p = 12; /* This is fine (assuming malloc doesn't return NULL) */ } guruvishnu_desireddy pointer Articles C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Oct, 2018" }, { "code": null, "e": 205, "s": 52, "text": "Uninitialized pointers are known as wild pointers because they point to some arbitrary memory location and may cause a program to crash or behave badly." }, { "code": "int main(){ int *p; /* wild pointer */ /* Some unknown memory location is being corrupted. This should never be done. */ *p = 12; }", "e": 346, "s": 205, "text": null }, { "code": null, "e": 500, "s": 346, "text": "Please note that if a pointer p points to a known variable then it’s not a wild pointer. In the below program, p is a wild pointer till this points to a." }, { "code": "int main(){ int *p; /* wild pointer */ int a = 10; p = &a; /* p is not a wild pointer now*/ *p = 12; /* This is fine. Value of a is changed */ }", "e": 651, "s": 500, "text": null }, { "code": null, "e": 817, "s": 651, "text": "If we want pointer to a value (or set of values) without having a variable for the value, we should explicitly allocate memory and put the value in allocated memory." }, { "code": "int main(){ int *p = (int *)malloc(sizeof(int)); *p = 12; /* This is fine (assuming malloc doesn't return NULL) */ }", "e": 937, "s": 817, "text": null }, { "code": null, "e": 958, "s": 937, "text": "guruvishnu_desireddy" }, { "code": null, "e": 966, "s": 958, "text": "pointer" }, { "code": null, "e": 975, "s": 966, "text": "Articles" }, { "code": null, "e": 986, "s": 975, "text": "C Language" }, { "code": null, "e": 990, "s": 986, "text": "C++" }, { "code": null, "e": 994, "s": 990, "text": "CPP" } ]
Secure coding – What is it all about?
21 Jan, 2022 So you think you can code? Well that’s great to know... The world definitely needs more geeks and nerds like you and me... But, are your programs secure? This is what this whole article is all about. As a programmer, it is not only your job but also moral responsibility to ensure that your codes don’t have any margin which can be later on exploited by any other Black Hat Hacker. This is what secure coding is all about. If you do a quick search on Google about Secure Coding, the first link that will attract your attention will be our own Wiki. Secure coding is the practice of developing computer software in a way that guards against the accidental introduction of security vulnerabilities. Defects, bugs and logic flaws are consistently the primary cause of commonly exploited software vulnerabilities. Okay! That’s enough of jargon... What does that really mean? Let me give you an example. Now, since, I am a snake charmer, I will use Python 2.7x... Python3 #test_run.pypswd ="MY PASSWORD"not_secret ="Geeks rock!" inputVal = input("Please enter number of geeks") #A VERY BAD IDEAprint ("There are", inputVal,"geeks here, chanting", not_secret) Now, go ahead and give it a try... It compiles successfully and you know what, it gives the desired output! So, here is what I got when I tried different inputs...Run – 1Please enter number of geeks 5 There are 5 geeks here, chanting Geeks rock! Run – 2 Please enter number of geeks dir() There are [‘pswd’, ‘not_secret’, ‘__builtins__’, ‘__doc__’, ‘__file__’, ‘__name__’, ‘__package__’] geeks here, chanting Geeks rock! Run – 3 Please enter number of geekspswd There are MY PASSWORD geeks here, chanting Geeks rock! If you didn’t realise it till now, let me state it... The program worked perfectly! But, not in the way we wanted it to... It printed out our secret data... Now, you can’t blame the language for this, and neither can you blame the programmer... He/she did what he was asked to do... This is where Secure Coding comes into play. Now, this example was just a small example, a very small one. There are endless number of possibilities of exploiting a program. All you need is a smart mind and an experience of exploiting the vulnerabilities. And if you are a network security guy/gal, then hiring a coder with no or very little knowledge about secure coding standards can prove to be the biggest mistake you can make. Thus, to have a safe professional future, it becomes a necessity to have complete knowledge about secure coding standards. Now, who can decide what safe way of coding is? It is not something that a single programmer can do. Thankfully, we don’t need to bother about it. Go and check out the SEI CERT Coding Standards. It has a very nice collection of recommended steps to take to ensure that your program is secure and that also sorted according to the programming languages – C, C++, Java, Perl, and Android. But, sadly, for the easiest language (in my opinion) there are no such standards given. Does that mean that a Python program is always secure? NO!! Fortunately, some Python enthusiasts set forward to make a list of similar recommendations for Python and resulted in the birth of what is known today as PEP 0008. Known as the Style Guide for Python Code, it was created in 2001. With an exhaustive list of “safe” and “unsafe” programs, it serves as a must use for any Python programmer. Now, enough of theory! Let’s get back to some coding stuff! I am now going to use a Hi-Fi term that you can further use to impress someone and that term is Cross Site Scripting (XSS). In the present scenario when every site has a comment section where they allow the visitors to share their experiences, XSS has come up to become a frequently used method by hackers (not a good term!) to steal data/ launch Distributed Denial Of Service (DDOS) attacks/ installing viruses and malwares into the system of client and many other ‘not – so – good’ acts. Most of the comment sections allow the users to write in HTML code to provide an opportunity of formatting. This means that the comment is first processed and then the result is printed on the site. So, suppose instead of a comment, I write a JavaScript code like this: window.alert(“Your comment has been received! – Geeks4Geeks”); Now, going by what I discussed just now, the code will be processed and the client will receive a pop – up mentioning, “Your comment has been received! – Geeks4Geeks”. That doesn’t sound bad... But, just imagine the possibilities. One can write a simple script which will download a malware/virus in the system of client, or show an advertisement with content that will attract him/her to click on it which will be present in an IFrame which can steal cookies (this is called Clickjacking) which further leads to what is known as Session Hijacking; options are not limited! So, what should we do? Again, the solution lies in Secure Coding! Just to give you an example, of how you can avoid XSS, and Clickjacking using Django: #Clickjacking response = render_to_response(“webpage.html”, {}, context_instance=RequestContext(request)) response[‘X-Frame-Options’] = ‘DENY’ #Frame Killing response[‘Content-Security-Policy’] = “frame-ancestors ‘none’” return response #XSS#Django by default escapes HTML, so most programs will be safe from #XSS attacks**{{ contents }}** #is safe**{{ contents|safe }}** #Overriding escape, not a good idea So, basically the summary is that if you want to be successful in the field of coding, then you should make it a habit to follow Secure Coding Standards. Why? Because only those programs are safe that are not accessible to public... As soon as they are available to everyone, there is a whole lot of people out there trying to break your code... You better take care of that! With this I take my leave!Auf Wiedersehen! !(See you again in German)About the author: Vishwesh Shrimali is an Undergraduate Mechanical Engineering student at BITS Pilani. He fulfils about all the requirements not taught in his branch- white hat hacker, network security operator, and an ex – Competitive Programmer. As a firm believer in power of Python, his majority work has been in the same language. Whenever he get some time apart from programming, attending classes, watching CSI Cyber, he go for a long walk and play guitar in silence. His motto of life is – “Enjoy your life, ‘cause it’s worth enjoying!” If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks. gabaa406 amartyaniel20 secure-coding Advanced Computer Subject GBlog Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jan, 2022" }, { "code": null, "e": 256, "s": 56, "text": "So you think you can code? Well that’s great to know... The world definitely needs more geeks and nerds like you and me... But, are your programs secure? This is what this whole article is all about." }, { "code": null, "e": 607, "s": 258, "text": "As a programmer, it is not only your job but also moral responsibility to ensure that your codes don’t have any margin which can be later on exploited by any other Black Hat Hacker. This is what secure coding is all about. If you do a quick search on Google about Secure Coding, the first link that will attract your attention will be our own Wiki." }, { "code": null, "e": 870, "s": 609, "text": "Secure coding is the practice of developing computer software in a way that guards against the accidental introduction of security vulnerabilities. Defects, bugs and logic flaws are consistently the primary cause of commonly exploited software vulnerabilities." }, { "code": null, "e": 1021, "s": 872, "text": "Okay! That’s enough of jargon... What does that really mean? Let me give you an example. Now, since, I am a snake charmer, I will use Python 2.7x..." }, { "code": null, "e": 1031, "s": 1023, "text": "Python3" }, { "code": "#test_run.pypswd =\"MY PASSWORD\"not_secret =\"Geeks rock!\" inputVal = input(\"Please enter number of geeks\") #A VERY BAD IDEAprint (\"There are\", inputVal,\"geeks here, chanting\", not_secret)", "e": 1218, "s": 1031, "text": null }, { "code": null, "e": 1421, "s": 1218, "text": "Now, go ahead and give it a try... It compiles successfully and you know what, it gives the desired output! So, here is what I got when I tried different inputs...Run – 1Please enter number of geeks 5 " }, { "code": null, "e": 1478, "s": 1421, "text": " There are 5 geeks here, chanting Geeks rock!" }, { "code": null, "e": 1532, "s": 1478, "text": "Run – 2 Please enter number of geeks dir() " }, { "code": null, "e": 1664, "s": 1532, "text": "There are [‘pswd’, ‘not_secret’, ‘__builtins__’, ‘__doc__’, ‘__file__’,\n‘__name__’, ‘__package__’] geeks here, chanting Geeks rock!" }, { "code": null, "e": 1716, "s": 1664, "text": "Run – 3 Please enter number of geekspswd " }, { "code": null, "e": 1781, "s": 1716, "text": " There are MY PASSWORD geeks here, chanting Geeks rock!" }, { "code": null, "e": 2621, "s": 1783, "text": "If you didn’t realise it till now, let me state it... The program worked perfectly! But, not in the way we wanted it to... It printed out our secret data... Now, you can’t blame the language for this, and neither can you blame the programmer... He/she did what he was asked to do... This is where Secure Coding comes into play. Now, this example was just a small example, a very small one. There are endless number of possibilities of exploiting a program. All you need is a smart mind and an experience of exploiting the vulnerabilities. And if you are a network security guy/gal, then hiring a coder with no or very little knowledge about secure coding standards can prove to be the biggest mistake you can make. Thus, to have a safe professional future, it becomes a necessity to have complete knowledge about secure coding standards." }, { "code": null, "e": 3389, "s": 2623, "text": "Now, who can decide what safe way of coding is? It is not something that a single programmer can do. Thankfully, we don’t need to bother about it. Go and check out the SEI CERT Coding Standards. It has a very nice collection of recommended steps to take to ensure that your program is secure and that also sorted according to the programming languages – C, C++, Java, Perl, and Android. But, sadly, for the easiest language (in my opinion) there are no such standards given. Does that mean that a Python program is always secure? NO!! Fortunately, some Python enthusiasts set forward to make a list of similar recommendations for Python and resulted in the birth of what is known today as PEP 0008. Known as the Style Guide for Python Code, it was created in 2001." }, { "code": null, "e": 3499, "s": 3391, "text": "With an exhaustive list of “safe” and “unsafe” programs, it serves as a must use for any Python programmer." }, { "code": null, "e": 4052, "s": 3501, "text": "Now, enough of theory! Let’s get back to some coding stuff! I am now going to use a Hi-Fi term that you can further use to impress someone and that term is Cross Site Scripting (XSS). In the present scenario when every site has a comment section where they allow the visitors to share their experiences, XSS has come up to become a frequently used method by hackers (not a good term!) to steal data/ launch Distributed Denial Of Service (DDOS) attacks/ installing viruses and malwares into the system of client and many other ‘not – so – good’ acts." }, { "code": null, "e": 4324, "s": 4054, "text": "Most of the comment sections allow the users to write in HTML code to provide an opportunity of formatting. This means that the comment is first processed and then the result is printed on the site. So, suppose instead of a comment, I write a JavaScript code like this:" }, { "code": null, "e": 4389, "s": 4326, "text": "window.alert(“Your comment has been received! – Geeks4Geeks”);" }, { "code": null, "e": 5117, "s": 4391, "text": "Now, going by what I discussed just now, the code will be processed and the client will receive a pop – up mentioning, “Your comment has been received! – Geeks4Geeks”. That doesn’t sound bad... But, just imagine the possibilities. One can write a simple script which will download a malware/virus in the system of client, or show an advertisement with content that will attract him/her to click on it which will be present in an IFrame which can steal cookies (this is called Clickjacking) which further leads to what is known as Session Hijacking; options are not limited! So, what should we do? Again, the solution lies in Secure Coding! Just to give you an example, of how you can avoid XSS, and Clickjacking using Django:" }, { "code": null, "e": 5359, "s": 5121, "text": "#Clickjacking\n\nresponse = render_to_response(“webpage.html”, {},\ncontext_instance=RequestContext(request))\nresponse[‘X-Frame-Options’] = ‘DENY’ #Frame Killing\nresponse[‘Content-Security-Policy’] = “frame-ancestors ‘none’”\nreturn response" }, { "code": null, "e": 5532, "s": 5359, "text": "#XSS#Django by default escapes HTML, so most programs will be safe from #XSS attacks**{{ contents }}** #is safe**{{ contents|safe }}** #Overriding escape, not a good idea " }, { "code": null, "e": 5908, "s": 5532, "text": "So, basically the summary is that if you want to be successful in the field of coding, then you should make it a habit to follow Secure Coding Standards. Why? Because only those programs are safe that are not accessible to public... As soon as they are available to everyone, there is a whole lot of people out there trying to break your code... You better take care of that!" }, { "code": null, "e": 5997, "s": 5908, "text": "With this I take my leave!Auf Wiedersehen! !(See you again in German)About the author: " }, { "code": null, "e": 6093, "s": 5997, "text": "Vishwesh Shrimali is an Undergraduate Mechanical Engineering student at BITS Pilani. He fulfils" }, { "code": null, "e": 6525, "s": 6093, "text": " about all the requirements not taught in his branch- white hat hacker, network security operator, and an ex – Competitive Programmer. As a firm believer in power of Python, his majority work has been in the same language. Whenever he get some time apart from programming, attending classes, watching CSI Cyber, he go for a long walk and play guitar in silence. His motto of life is – “Enjoy your life, ‘cause it’s worth enjoying!”" }, { "code": null, "e": 6629, "s": 6525, "text": "If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks. " }, { "code": null, "e": 6638, "s": 6629, "text": "gabaa406" }, { "code": null, "e": 6652, "s": 6638, "text": "amartyaniel20" }, { "code": null, "e": 6666, "s": 6652, "text": "secure-coding" }, { "code": null, "e": 6692, "s": 6666, "text": "Advanced Computer Subject" }, { "code": null, "e": 6698, "s": 6692, "text": "GBlog" }, { "code": null, "e": 6705, "s": 6698, "text": "Python" } ]
Printing Items in 0/1 Knapsack
23 Jun, 2022 Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays, val[0..n-1] and wt[0..n-1] represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the items such that sum of the weights of those items of a given subset is smaller than or equal to W. You cannot break an item, either pick the complete item or don’t pick it (0-1 property).Prerequisite : 0/1 KnapsackExamples : Input : val[] = {60, 100, 120}; wt[] = {10, 20, 30}; W = 50; Output : 220 //maximum value that can be obtained 30 20 //weights 20 and 30 are included. Input : val[] = {40, 100, 50, 60}; wt[] = {20, 10, 40, 30}; W = 60; Output : 200 30 20 10 Approach : Let val[] = {1, 4, 5, 7}, wt[] = {1, 3, 4, 5} W = 7. The 2d knapsack table will look like : Start backtracking from K[n][W].Here K[n][W] is 9.Since this value comes from the top (shown by grey arrow), the item in this row is not included. Go vertically upward in the table without including this in the knapsack. Now, this value K[n-1][W] which is 9 doesn’t come from the top which means the item in this row is included and go vertically up and then left by the weight of the included item ( shown by black arrow). Continuing this process include weights 3 and 4 with a total value 9 in the knapsack. C++ C Java Python3 C# PHP Javascript // CPP code for Dynamic Programming based// solution for 0-1 Knapsack problem#include <bits/stdc++.h>#include <iostream>using namespace std; // A utility function that returns maximum of two integersint max(int a, int b) { return (a > b) ? a : b; } // Prints the items which are put in a knapsack of capacity Wvoid printknapSack(int W, int wt[], int val[], int n){ int i, w; int K[n + 1][W + 1]; // Build table K[][] in bottom up manner for (i = 0; i <= n; i++) { for (w = 0; w <= W; w++) { if (i == 0 || w == 0) K[i][w] = 0; else if (wt[i - 1] <= w) K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]); else K[i][w] = K[i - 1][w]; } } // stores the result of Knapsack int res = K[n][W]; cout<< res << endl; w = W; for (i = n; i > 0 && res > 0; i--) { // either the result comes from the top // (K[i-1][w]) or from (val[i-1] + K[i-1] // [w-wt[i-1]]) as in Knapsack table. If // it comes from the latter one/ it means // the item is included. if (res == K[i - 1][w]) continue; else { // This item is included. cout<<" "<<wt[i - 1] ; // Since this weight is included its // value is deducted res = res - val[i - 1]; w = w - wt[i - 1]; } }} // Driver codeint main(){ int val[] = { 60, 100, 120 }; int wt[] = { 10, 20, 30 }; int W = 50; int n = sizeof(val) / sizeof(val[0]); printknapSack(W, wt, val, n); return 0;} // this code is contributed by shivanisinghss2110 // CPP code for Dynamic Programming based// solution for 0-1 Knapsack problem#include <stdio.h> // A utility function that returns maximum of two integersint max(int a, int b) { return (a > b) ? a : b; } // Prints the items which are put in a knapsack of capacity Wvoid printknapSack(int W, int wt[], int val[], int n){ int i, w; int K[n + 1][W + 1]; // Build table K[][] in bottom up manner for (i = 0; i <= n; i++) { for (w = 0; w <= W; w++) { if (i == 0 || w == 0) K[i][w] = 0; else if (wt[i - 1] <= w) K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]); else K[i][w] = K[i - 1][w]; } } // stores the result of Knapsack int res = K[n][W]; printf("%d\n", res); w = W; for (i = n; i > 0 && res > 0; i--) { // either the result comes from the top // (K[i-1][w]) or from (val[i-1] + K[i-1] // [w-wt[i-1]]) as in Knapsack table. If // it comes from the latter one/ it means // the item is included. if (res == K[i - 1][w]) continue; else { // This item is included. printf("%d ", wt[i - 1]); // Since this weight is included its // value is deducted res = res - val[i - 1]; w = w - wt[i - 1]; } }} // Driver codeint main(){ int val[] = { 60, 100, 120 }; int wt[] = { 10, 20, 30 }; int W = 50; int n = sizeof(val) / sizeof(val[0]); printknapSack(W, wt, val, n); return 0;} // Java code for Dynamic Programming based// solution for 0-1 Knapsack problem class GFG { // A utility function that returns // maximum of two integers static int max(int a, int b) { return (a > b) ? a : b; } // Prints the items which are put // in a knapsack of capacity W static void printknapSack(int W, int wt[], int val[], int n) { int i, w; int K[][] = new int[n + 1][W + 1]; // Build table K[][] in bottom up manner for (i = 0; i <= n; i++) { for (w = 0; w <= W; w++) { if (i == 0 || w == 0) K[i][w] = 0; else if (wt[i - 1] <= w) K[i][w] = Math.max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]); else K[i][w] = K[i - 1][w]; } } // stores the result of Knapsack int res = K[n][W]; System.out.println(res); w = W; for (i = n; i > 0 && res > 0; i--) { // either the result comes from the top // (K[i-1][w]) or from (val[i-1] + K[i-1] // [w-wt[i-1]]) as in Knapsack table. If // it comes from the latter one/ it means // the item is included. if (res == K[i - 1][w]) continue; else { // This item is included. System.out.print(wt[i - 1] + " "); // Since this weight is included its // value is deducted res = res - val[i - 1]; w = w - wt[i - 1]; } } } // Driver code public static void main(String arg[]) { int val[] = { 60, 100, 120 }; int wt[] = { 10, 20, 30 }; int W = 50; int n = val.length; printknapSack(W, wt, val, n); }} // This code is contributed by Anant Agarwal. # Python3 code for Dynamic Programming# based solution for 0-1 Knapsack problem # Prints the items which are put in a# knapsack of capacity Wdef printknapSack(W, wt, val, n): K = [[0 for w in range(W + 1)] for i in range(n + 1)] # Build table K[][] in bottom # up manner for i in range(n + 1): for w in range(W + 1): if i == 0 or w == 0: K[i][w] = 0 elif wt[i - 1] <= w: K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]) else: K[i][w] = K[i - 1][w] # stores the result of Knapsack res = K[n][W] print(res) w = W for i in range(n, 0, -1): if res <= 0: break # either the result comes from the # top (K[i-1][w]) or from (val[i-1] # + K[i-1] [w-wt[i-1]]) as in Knapsack # table. If it comes from the latter # one/ it means the item is included. if res == K[i - 1][w]: continue else: # This item is included. print(wt[i - 1]) # Since this weight is included # its value is deducted res = res - val[i - 1] w = w - wt[i - 1] # Driver codeval = [ 60, 100, 120 ]wt = [ 10, 20, 30 ]W = 50n = len(val) printknapSack(W, wt, val, n) # This code is contributed by Aryan Garg. // C# code for Dynamic Programming based// solution for 0-1 Knapsack problem using System ; class GFG { // A utility function that returns // maximum of two integers static int max(int a, int b) { return (a > b) ? a : b; } // Prints the items which are put // in a knapsack of capacity W static void printknapSack(int W, int []wt, int []val, int n) { int i, w; int [,]K = new int[n + 1,W + 1]; // Build table K[][] in bottom up manner for (i = 0; i <= n; i++) { for (w = 0; w <= W; w++) { if (i == 0 || w == 0) K[i,w] = 0; else if (wt[i - 1] <= w) K[i,w] = Math.Max(val[i - 1] + K[i - 1,w - wt[i - 1]], K[i - 1,w]); else K[i,w] = K[i - 1,w]; } } // stores the result of Knapsack int res = K[n,W]; Console.WriteLine(res); w = W; for (i = n; i > 0 && res > 0; i--) { // either the result comes from the top // (K[i-1][w]) or from (val[i-1] + K[i-1] // [w-wt[i-1]]) as in Knapsack table. If // it comes from the latter one/ it means // the item is included. if (res == K[i - 1,w]) continue; else { // This item is included. Console.Write(wt[i - 1] + " "); // Since this weight is included its // value is deducted res = res - val[i - 1]; w = w - wt[i - 1]; } } } // Driver code public static void Main() { int []val = { 60, 100, 120 }; int []wt = { 10, 20, 30 }; int W = 50; int n = val.Length; printknapSack(W, wt, val, n); }} // This code is contributed by Ryuga. <?php// PHP code for Dynamic Programming based// solution for 0-1 Knapsack problem // Prints the items which are kept in// a knapsack of capacity Wfunction printknapSack($W, &$wt, &$val, $n){ $K = array_fill(0, $n + 1, array_fill(0, $W + 1, NULL)); // Build table K[][] in bottom up manner for ($i = 0; $i <= $n; $i++) { for ($w = 0; $w <= $W; $w++) { if ($i == 0 || $w == 0) $K[$i][$w] = 0; else if ($wt[$i - 1] <= $w) $K[$i][$w] = max($val[$i - 1] + $K[$i - 1][$w - $wt[$i - 1]], $K[$i - 1][$w]); else $K[$i][$w] = $K[$i - 1][$w]; } } // stores the result of Knapsack $res = $K[$n][$W]; echo $res . "\n"; $w = $W; for ($i = $n; $i > 0 && $res > 0; $i--) { // either the result comes from the top // (K[i-1][w]) or from (val[i-1] + K[i-1] // [w-wt[i-1]]) as in Knapsack table. If // it comes from the latter one/ it means // the item is included. if ($res == $K[$i - 1][$w]) continue; else { // This item is included. echo $wt[$i - 1] . " "; // Since this weight is included // its value is deducted $res = $res - $val[$i - 1]; $w = $w - $wt[$i - 1]; } }} // Driver code$val = array(60, 100, 120);$wt = array(10, 20, 30);$W = 50;$n = sizeof($val);printknapSack($W, $wt, $val, $n); // This code is contributed by ita_c?> <script> // JavaScript code for Dynamic Programming based// solution for 0-1 Knapsack problem // A utility function that returns // maximum of two integers function max(a,b) { return (a > b) ? a : b; } // Prints the items which are put // in a knapsack of capacity W function printknapSack(W,wt,val,n) { let i, w; let K = new Array(n + 1); for( i=0;i<K.length;i++) { K[i]=new Array(W+1); for(let j=0;j<W+1;j++) { K[i][j]=0; } } // Build table K[][] in bottom up manner for (i = 0; i <= n; i++) { for (w = 0; w <= W; w++) { if (i == 0 || w == 0) K[i][w] = 0; else if (wt[i - 1] <= w) K[i][w] = Math.max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]); else K[i][w] = K[i - 1][w]; } } // stores the result of Knapsack let res = K[n][W]; document.write(res+"<br>"); w = W; for (i = n; i > 0 && res > 0; i--) { // either the result comes from the top // (K[i-1][w]) or from (val[i-1] + K[i-1] // [w-wt[i-1]]) as in Knapsack table. If // it comes from the latter one/ it means // the item is included. if (res == K[i - 1][w]) continue; else { // This item is included. document.write(wt[i - 1] + " "); // Since this weight is included its // value is deducted res = res - val[i - 1]; w = w - wt[i - 1]; } } } let val=[60, 100, 120 ]; let wt=[10, 20, 30 ]; let W = 50; let n = val.length; printknapSack(W, wt, val, n); // This code is contributed by avanitrachhadiya2155 </script> 220 30 20 Time complexity: O(n*W) Space complexity: O(n*W) aryan21 ankthon ukasp avanitrachhadiya2155 shivanisinghss2110 r_c knapsack Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find if there is a path between two vertices in an undirected graph Optimal Substructure Property in Dynamic Programming | DP-2 Unique paths in a Grid with Obstacles Count number of binary strings without consecutive 1's How to solve a Dynamic Programming Problem ? Maximum sum such that no two elements are adjacent Word Break Problem | DP-32 Maximum profit by buying and selling a share at most twice Top 50 Dynamic Programming Coding Problems for Interviews Palindrome Partitioning | DP-17
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2022" }, { "code": null, "e": 619, "s": 54, "text": "Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays, val[0..n-1] and wt[0..n-1] represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the items such that sum of the weights of those items of a given subset is smaller than or equal to W. You cannot break an item, either pick the complete item or don’t pick it (0-1 property).Prerequisite : 0/1 KnapsackExamples : " }, { "code": null, "e": 912, "s": 619, "text": "Input : val[] = {60, 100, 120};\n wt[] = {10, 20, 30};\n W = 50;\nOutput : 220 //maximum value that can be obtained\n 30 20 //weights 20 and 30 are included. \n\nInput : val[] = {40, 100, 50, 60};\n wt[] = {20, 10, 40, 30};\n W = 60;\nOutput : 200\n 30 20 10" }, { "code": null, "e": 1017, "s": 912, "text": "Approach : Let val[] = {1, 4, 5, 7}, wt[] = {1, 3, 4, 5} W = 7. The 2d knapsack table will look like : " }, { "code": null, "e": 1529, "s": 1017, "text": "Start backtracking from K[n][W].Here K[n][W] is 9.Since this value comes from the top (shown by grey arrow), the item in this row is not included. Go vertically upward in the table without including this in the knapsack. Now, this value K[n-1][W] which is 9 doesn’t come from the top which means the item in this row is included and go vertically up and then left by the weight of the included item ( shown by black arrow). Continuing this process include weights 3 and 4 with a total value 9 in the knapsack. " }, { "code": null, "e": 1535, "s": 1531, "text": "C++" }, { "code": null, "e": 1537, "s": 1535, "text": "C" }, { "code": null, "e": 1542, "s": 1537, "text": "Java" }, { "code": null, "e": 1550, "s": 1542, "text": "Python3" }, { "code": null, "e": 1553, "s": 1550, "text": "C#" }, { "code": null, "e": 1557, "s": 1553, "text": "PHP" }, { "code": null, "e": 1568, "s": 1557, "text": "Javascript" }, { "code": "// CPP code for Dynamic Programming based// solution for 0-1 Knapsack problem#include <bits/stdc++.h>#include <iostream>using namespace std; // A utility function that returns maximum of two integersint max(int a, int b) { return (a > b) ? a : b; } // Prints the items which are put in a knapsack of capacity Wvoid printknapSack(int W, int wt[], int val[], int n){ int i, w; int K[n + 1][W + 1]; // Build table K[][] in bottom up manner for (i = 0; i <= n; i++) { for (w = 0; w <= W; w++) { if (i == 0 || w == 0) K[i][w] = 0; else if (wt[i - 1] <= w) K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]); else K[i][w] = K[i - 1][w]; } } // stores the result of Knapsack int res = K[n][W]; cout<< res << endl; w = W; for (i = n; i > 0 && res > 0; i--) { // either the result comes from the top // (K[i-1][w]) or from (val[i-1] + K[i-1] // [w-wt[i-1]]) as in Knapsack table. If // it comes from the latter one/ it means // the item is included. if (res == K[i - 1][w]) continue; else { // This item is included. cout<<\" \"<<wt[i - 1] ; // Since this weight is included its // value is deducted res = res - val[i - 1]; w = w - wt[i - 1]; } }} // Driver codeint main(){ int val[] = { 60, 100, 120 }; int wt[] = { 10, 20, 30 }; int W = 50; int n = sizeof(val) / sizeof(val[0]); printknapSack(W, wt, val, n); return 0;} // this code is contributed by shivanisinghss2110", "e": 3281, "s": 1568, "text": null }, { "code": "// CPP code for Dynamic Programming based// solution for 0-1 Knapsack problem#include <stdio.h> // A utility function that returns maximum of two integersint max(int a, int b) { return (a > b) ? a : b; } // Prints the items which are put in a knapsack of capacity Wvoid printknapSack(int W, int wt[], int val[], int n){ int i, w; int K[n + 1][W + 1]; // Build table K[][] in bottom up manner for (i = 0; i <= n; i++) { for (w = 0; w <= W; w++) { if (i == 0 || w == 0) K[i][w] = 0; else if (wt[i - 1] <= w) K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]); else K[i][w] = K[i - 1][w]; } } // stores the result of Knapsack int res = K[n][W]; printf(\"%d\\n\", res); w = W; for (i = n; i > 0 && res > 0; i--) { // either the result comes from the top // (K[i-1][w]) or from (val[i-1] + K[i-1] // [w-wt[i-1]]) as in Knapsack table. If // it comes from the latter one/ it means // the item is included. if (res == K[i - 1][w]) continue; else { // This item is included. printf(\"%d \", wt[i - 1]); // Since this weight is included its // value is deducted res = res - val[i - 1]; w = w - wt[i - 1]; } }} // Driver codeint main(){ int val[] = { 60, 100, 120 }; int wt[] = { 10, 20, 30 }; int W = 50; int n = sizeof(val) / sizeof(val[0]); printknapSack(W, wt, val, n); return 0;}", "e": 4910, "s": 3281, "text": null }, { "code": "// Java code for Dynamic Programming based// solution for 0-1 Knapsack problem class GFG { // A utility function that returns // maximum of two integers static int max(int a, int b) { return (a > b) ? a : b; } // Prints the items which are put // in a knapsack of capacity W static void printknapSack(int W, int wt[], int val[], int n) { int i, w; int K[][] = new int[n + 1][W + 1]; // Build table K[][] in bottom up manner for (i = 0; i <= n; i++) { for (w = 0; w <= W; w++) { if (i == 0 || w == 0) K[i][w] = 0; else if (wt[i - 1] <= w) K[i][w] = Math.max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]); else K[i][w] = K[i - 1][w]; } } // stores the result of Knapsack int res = K[n][W]; System.out.println(res); w = W; for (i = n; i > 0 && res > 0; i--) { // either the result comes from the top // (K[i-1][w]) or from (val[i-1] + K[i-1] // [w-wt[i-1]]) as in Knapsack table. If // it comes from the latter one/ it means // the item is included. if (res == K[i - 1][w]) continue; else { // This item is included. System.out.print(wt[i - 1] + \" \"); // Since this weight is included its // value is deducted res = res - val[i - 1]; w = w - wt[i - 1]; } } } // Driver code public static void main(String arg[]) { int val[] = { 60, 100, 120 }; int wt[] = { 10, 20, 30 }; int W = 50; int n = val.length; printknapSack(W, wt, val, n); }} // This code is contributed by Anant Agarwal.", "e": 6843, "s": 4910, "text": null }, { "code": "# Python3 code for Dynamic Programming# based solution for 0-1 Knapsack problem # Prints the items which are put in a# knapsack of capacity Wdef printknapSack(W, wt, val, n): K = [[0 for w in range(W + 1)] for i in range(n + 1)] # Build table K[][] in bottom # up manner for i in range(n + 1): for w in range(W + 1): if i == 0 or w == 0: K[i][w] = 0 elif wt[i - 1] <= w: K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]) else: K[i][w] = K[i - 1][w] # stores the result of Knapsack res = K[n][W] print(res) w = W for i in range(n, 0, -1): if res <= 0: break # either the result comes from the # top (K[i-1][w]) or from (val[i-1] # + K[i-1] [w-wt[i-1]]) as in Knapsack # table. If it comes from the latter # one/ it means the item is included. if res == K[i - 1][w]: continue else: # This item is included. print(wt[i - 1]) # Since this weight is included # its value is deducted res = res - val[i - 1] w = w - wt[i - 1] # Driver codeval = [ 60, 100, 120 ]wt = [ 10, 20, 30 ]W = 50n = len(val) printknapSack(W, wt, val, n) # This code is contributed by Aryan Garg.", "e": 8272, "s": 6843, "text": null }, { "code": "// C# code for Dynamic Programming based// solution for 0-1 Knapsack problem using System ; class GFG { // A utility function that returns // maximum of two integers static int max(int a, int b) { return (a > b) ? a : b; } // Prints the items which are put // in a knapsack of capacity W static void printknapSack(int W, int []wt, int []val, int n) { int i, w; int [,]K = new int[n + 1,W + 1]; // Build table K[][] in bottom up manner for (i = 0; i <= n; i++) { for (w = 0; w <= W; w++) { if (i == 0 || w == 0) K[i,w] = 0; else if (wt[i - 1] <= w) K[i,w] = Math.Max(val[i - 1] + K[i - 1,w - wt[i - 1]], K[i - 1,w]); else K[i,w] = K[i - 1,w]; } } // stores the result of Knapsack int res = K[n,W]; Console.WriteLine(res); w = W; for (i = n; i > 0 && res > 0; i--) { // either the result comes from the top // (K[i-1][w]) or from (val[i-1] + K[i-1] // [w-wt[i-1]]) as in Knapsack table. If // it comes from the latter one/ it means // the item is included. if (res == K[i - 1,w]) continue; else { // This item is included. Console.Write(wt[i - 1] + \" \"); // Since this weight is included its // value is deducted res = res - val[i - 1]; w = w - wt[i - 1]; } } } // Driver code public static void Main() { int []val = { 60, 100, 120 }; int []wt = { 10, 20, 30 }; int W = 50; int n = val.Length; printknapSack(W, wt, val, n); }} // This code is contributed by Ryuga.", "e": 10181, "s": 8272, "text": null }, { "code": "<?php// PHP code for Dynamic Programming based// solution for 0-1 Knapsack problem // Prints the items which are kept in// a knapsack of capacity Wfunction printknapSack($W, &$wt, &$val, $n){ $K = array_fill(0, $n + 1, array_fill(0, $W + 1, NULL)); // Build table K[][] in bottom up manner for ($i = 0; $i <= $n; $i++) { for ($w = 0; $w <= $W; $w++) { if ($i == 0 || $w == 0) $K[$i][$w] = 0; else if ($wt[$i - 1] <= $w) $K[$i][$w] = max($val[$i - 1] + $K[$i - 1][$w - $wt[$i - 1]], $K[$i - 1][$w]); else $K[$i][$w] = $K[$i - 1][$w]; } } // stores the result of Knapsack $res = $K[$n][$W]; echo $res . \"\\n\"; $w = $W; for ($i = $n; $i > 0 && $res > 0; $i--) { // either the result comes from the top // (K[i-1][w]) or from (val[i-1] + K[i-1] // [w-wt[i-1]]) as in Knapsack table. If // it comes from the latter one/ it means // the item is included. if ($res == $K[$i - 1][$w]) continue; else { // This item is included. echo $wt[$i - 1] . \" \"; // Since this weight is included // its value is deducted $res = $res - $val[$i - 1]; $w = $w - $wt[$i - 1]; } }} // Driver code$val = array(60, 100, 120);$wt = array(10, 20, 30);$W = 50;$n = sizeof($val);printknapSack($W, $wt, $val, $n); // This code is contributed by ita_c?>", "e": 11770, "s": 10181, "text": null }, { "code": "<script> // JavaScript code for Dynamic Programming based// solution for 0-1 Knapsack problem // A utility function that returns // maximum of two integers function max(a,b) { return (a > b) ? a : b; } // Prints the items which are put // in a knapsack of capacity W function printknapSack(W,wt,val,n) { let i, w; let K = new Array(n + 1); for( i=0;i<K.length;i++) { K[i]=new Array(W+1); for(let j=0;j<W+1;j++) { K[i][j]=0; } } // Build table K[][] in bottom up manner for (i = 0; i <= n; i++) { for (w = 0; w <= W; w++) { if (i == 0 || w == 0) K[i][w] = 0; else if (wt[i - 1] <= w) K[i][w] = Math.max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]); else K[i][w] = K[i - 1][w]; } } // stores the result of Knapsack let res = K[n][W]; document.write(res+\"<br>\"); w = W; for (i = n; i > 0 && res > 0; i--) { // either the result comes from the top // (K[i-1][w]) or from (val[i-1] + K[i-1] // [w-wt[i-1]]) as in Knapsack table. If // it comes from the latter one/ it means // the item is included. if (res == K[i - 1][w]) continue; else { // This item is included. document.write(wt[i - 1] + \" \"); // Since this weight is included its // value is deducted res = res - val[i - 1]; w = w - wt[i - 1]; } } } let val=[60, 100, 120 ]; let wt=[10, 20, 30 ]; let W = 50; let n = val.length; printknapSack(W, wt, val, n); // This code is contributed by avanitrachhadiya2155 </script>", "e": 13780, "s": 11770, "text": null }, { "code": null, "e": 13790, "s": 13780, "text": "220\n30 20" }, { "code": null, "e": 13816, "s": 13792, "text": "Time complexity: O(n*W)" }, { "code": null, "e": 13841, "s": 13816, "text": "Space complexity: O(n*W)" }, { "code": null, "e": 13849, "s": 13841, "text": "aryan21" }, { "code": null, "e": 13857, "s": 13849, "text": "ankthon" }, { "code": null, "e": 13863, "s": 13857, "text": "ukasp" }, { "code": null, "e": 13884, "s": 13863, "text": "avanitrachhadiya2155" }, { "code": null, "e": 13903, "s": 13884, "text": "shivanisinghss2110" }, { "code": null, "e": 13907, "s": 13903, "text": "r_c" }, { "code": null, "e": 13916, "s": 13907, "text": "knapsack" }, { "code": null, "e": 13936, "s": 13916, "text": "Dynamic Programming" }, { "code": null, "e": 13956, "s": 13936, "text": "Dynamic Programming" }, { "code": null, "e": 14054, "s": 13956, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14122, "s": 14054, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 14182, "s": 14122, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 14220, "s": 14182, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 14275, "s": 14220, "text": "Count number of binary strings without consecutive 1's" }, { "code": null, "e": 14320, "s": 14275, "text": "How to solve a Dynamic Programming Problem ?" }, { "code": null, "e": 14371, "s": 14320, "text": "Maximum sum such that no two elements are adjacent" }, { "code": null, "e": 14398, "s": 14371, "text": "Word Break Problem | DP-32" }, { "code": null, "e": 14457, "s": 14398, "text": "Maximum profit by buying and selling a share at most twice" }, { "code": null, "e": 14515, "s": 14457, "text": "Top 50 Dynamic Programming Coding Problems for Interviews" } ]
Add a key value pair to dictionary in Python
Python dictionaries are an unordered collection of key value pairs. In this tutorial we will see how we can add new key value pairs to an already defined dictionary. Below are the two approaches which we can use. We add a new element to the dictionary by using a new key as a subscript and assigning it a value. CountryCodeDict = {"India": 91, "UK" : 44 , "USA" : 1} print(CountryCodeDict) CountryCodeDict["Spain"]= 34 print "After adding" print(CountryCodeDict) Running the above code gives us the following result − {'India': 91, 'USA': 1, 'UK': 44} After adding {'Spain': 34, 'India': 91, 'USA': 1, 'UK': 44} The update method directly takes a key-value pair and puts it into the existing dictionary. The key value pair is the argument to the update function. We can also supply multiple key values as shown below. CountryCodeDict = {"India": 91, "UK" : 44 , "USA" : 1, "Spain" : 34} print(CountryCodeDict) CountryCodeDict.update( {'Germany' : 49} ) print(CountryCodeDict) # Adding multiple key value pairs CountryCodeDict.update( [('Austria', 43),('Russia',7)] ) print(CountryCodeDict) Running the above code gives us the following result − {'Spain': 34, 'India': 91, 'USA': 1, 'UK': 44} {'Germany': 49, 'Spain': 34, 'India': 91, 'USA': 1, 'UK': 44} {'USA': 1, 'India': 91, 'Austria': 43, 'Germany': 49, 'UK': 44, 'Russia': 7, 'Spain': 34} We can also append elements to a dictionary by merging two dictionaries. Here again, we use the update() method but the argument to the method is a dictionary itself. CountryCodeDict1 = {"India": 91, "UK" : 44 , "USA" : 1, "Spain" : 34} CountryCodeDict2 = {"Germany": 49, "Russia" : 7 , "Austria" : 43} CountryCodeDict1.update(CountryCodeDict2) print(CountryCodeDict1) Running the above code gives us the following result − {'Austria': 43, 'Germany': 49, 'UK': 44, 'USA': 1, 'India': 91, 'Russia': 7, 'Spain': 34}
[ { "code": null, "e": 1275, "s": 1062, "text": "Python dictionaries are an unordered collection of key value pairs. In this tutorial we will see how we can add new key value pairs to an already defined dictionary. Below are the two approaches which we can use." }, { "code": null, "e": 1374, "s": 1275, "text": "We add a new element to the dictionary by using a new key as a subscript and assigning it a value." }, { "code": null, "e": 1525, "s": 1374, "text": "CountryCodeDict = {\"India\": 91, \"UK\" : 44 , \"USA\" : 1}\nprint(CountryCodeDict)\nCountryCodeDict[\"Spain\"]= 34\nprint \"After adding\"\nprint(CountryCodeDict)" }, { "code": null, "e": 1580, "s": 1525, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1674, "s": 1580, "text": "{'India': 91, 'USA': 1, 'UK': 44}\nAfter adding\n{'Spain': 34, 'India': 91, 'USA': 1, 'UK': 44}" }, { "code": null, "e": 1880, "s": 1674, "text": "The update method directly takes a key-value pair and puts it into the existing dictionary. The key value pair is the argument to the update function. We can also supply multiple key values as shown below." }, { "code": null, "e": 2156, "s": 1880, "text": "CountryCodeDict = {\"India\": 91, \"UK\" : 44 , \"USA\" : 1, \"Spain\" : 34}\nprint(CountryCodeDict)\n\nCountryCodeDict.update( {'Germany' : 49} )\n\nprint(CountryCodeDict)\n\n# Adding multiple key value pairs\nCountryCodeDict.update( [('Austria', 43),('Russia',7)] )\n\nprint(CountryCodeDict)" }, { "code": null, "e": 2211, "s": 2156, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2410, "s": 2211, "text": "{'Spain': 34, 'India': 91, 'USA': 1, 'UK': 44}\n{'Germany': 49, 'Spain': 34, 'India': 91, 'USA': 1, 'UK': 44}\n{'USA': 1, 'India': 91, 'Austria': 43, 'Germany': 49, 'UK': 44, 'Russia': 7, 'Spain': 34}" }, { "code": null, "e": 2577, "s": 2410, "text": "We can also append elements to a dictionary by merging two dictionaries. Here again, we use the update() method but the argument to the method is a dictionary itself." }, { "code": null, "e": 2779, "s": 2577, "text": "CountryCodeDict1 = {\"India\": 91, \"UK\" : 44 , \"USA\" : 1, \"Spain\" : 34}\nCountryCodeDict2 = {\"Germany\": 49, \"Russia\" : 7 , \"Austria\" : 43}\nCountryCodeDict1.update(CountryCodeDict2)\nprint(CountryCodeDict1)" }, { "code": null, "e": 2834, "s": 2779, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2924, "s": 2834, "text": "{'Austria': 43, 'Germany': 49, 'UK': 44, 'USA': 1, 'India': 91, 'Russia': 7, 'Spain': 34}" } ]
MongoDB - Sort Records
In this chapter, we will learn how to sort records in MongoDB. To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order. The basic syntax of sort() method is as follows − >db.COLLECTION_NAME.find().sort({KEY:1}) Consider the collection myycol has the following data. {_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"} {_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"} {_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"} Following example will display the documents sorted by title in the descending order. >db.mycol.find({},{"title":1,_id:0}).sort({"title":-1}) {"title":"Tutorials Point Overview"} {"title":"NoSQL Overview"} {"title":"MongoDB Overview"} > Please note, if you don't specify the sorting preference, then sort() method will display the documents in ascending order. 44 Lectures 3 hours Arnab Chakraborty 54 Lectures 5.5 hours Eduonix Learning Solutions 44 Lectures 4.5 hours Kaushik Roy Chowdhury 40 Lectures 2.5 hours University Code 26 Lectures 8 hours Bassir Jafarzadeh 70 Lectures 2.5 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2616, "s": 2553, "text": "In this chapter, we will learn how to sort records in MongoDB." }, { "code": null, "e": 2880, "s": 2616, "text": "To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order." }, { "code": null, "e": 2930, "s": 2880, "text": "The basic syntax of sort() method is as follows −" }, { "code": null, "e": 2971, "s": 2930, "text": ">db.COLLECTION_NAME.find().sort({KEY:1})" }, { "code": null, "e": 3026, "s": 2971, "text": "Consider the collection myycol has the following data." }, { "code": null, "e": 3248, "s": 3026, "text": "{_id : ObjectId(\"507f191e810c19729de860e1\"), title: \"MongoDB Overview\"}\n{_id : ObjectId(\"507f191e810c19729de860e2\"), title: \"NoSQL Overview\"}\n{_id : ObjectId(\"507f191e810c19729de860e3\"), title: \"Tutorials Point Overview\"}" }, { "code": null, "e": 3334, "s": 3248, "text": "Following example will display the documents sorted by title in the descending order." }, { "code": null, "e": 3485, "s": 3334, "text": ">db.mycol.find({},{\"title\":1,_id:0}).sort({\"title\":-1})\n{\"title\":\"Tutorials Point Overview\"}\n{\"title\":\"NoSQL Overview\"}\n{\"title\":\"MongoDB Overview\"}\n>" }, { "code": null, "e": 3609, "s": 3485, "text": "Please note, if you don't specify the sorting preference, then sort() method will display the documents in ascending order." }, { "code": null, "e": 3642, "s": 3609, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 3661, "s": 3642, "text": " Arnab Chakraborty" }, { "code": null, "e": 3696, "s": 3661, "text": "\n 54 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3724, "s": 3696, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3759, "s": 3724, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3782, "s": 3759, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 3817, "s": 3782, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3834, "s": 3817, "text": " University Code" }, { "code": null, "e": 3867, "s": 3834, "text": "\n 26 Lectures \n 8 hours \n" }, { "code": null, "e": 3886, "s": 3867, "text": " Bassir Jafarzadeh" }, { "code": null, "e": 3921, "s": 3886, "text": "\n 70 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3941, "s": 3921, "text": " Skillbakerystudios" }, { "code": null, "e": 3948, "s": 3941, "text": " Print" }, { "code": null, "e": 3959, "s": 3948, "text": " Add Notes" } ]
How to sort, select and query subdocument in MongoDB?
To sort, use $sort in MongoDB. Let us create a collection with documents − > db.demo236.insertOne({"details":{"Name":"Chris","Age":21}}); { "acknowledged" : true, "insertedId" : ObjectId("5e419015f4cebbeaebec514c") } > db.demo236.insertOne({"details":{"Name":"David","Age":23}}); { "acknowledged" : true, "insertedId" : ObjectId("5e41901cf4cebbeaebec514d") } > db.demo236.insertOne({"details":{"Name":"Bob","Age":24}}); { "acknowledged" : true, "insertedId" : ObjectId("5e419023f4cebbeaebec514e") } Display all documents from a collection with the help of find() method − > db.demo236.find(); This will produce the following output − { "_id" : ObjectId("5e419015f4cebbeaebec514c"), "details" : { "Name" : "Chris", "Age" : 21 } } { "_id" : ObjectId("5e41901cf4cebbeaebec514d"), "details" : { "Name" : "David", "Age" : 23 } } { "_id" : ObjectId("5e419023f4cebbeaebec514e"), "details" : { "Name" : "Bob", "Age" : 24 } } Following is the query to sort, select and query subdocument in MongoDB − > db.demo236.aggregate( ... [ ... { $unwind: "$details" }, ... { $project: { ... Name: '$details.Name', ... Age: '$details.Age' ... ... }}, ... { $sort: {Name: -1}} ...] ...); This will produce the following output − { "_id" : ObjectId("5e41901cf4cebbeaebec514d"), "Name" : "David", "Age" : 23 } { "_id" : ObjectId("5e419015f4cebbeaebec514c"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5e419023f4cebbeaebec514e"), "Name" : "Bob", "Age" : 24 }
[ { "code": null, "e": 1137, "s": 1062, "text": "To sort, use $sort in MongoDB. Let us create a collection with documents −" }, { "code": null, "e": 1579, "s": 1137, "text": "> db.demo236.insertOne({\"details\":{\"Name\":\"Chris\",\"Age\":21}});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e419015f4cebbeaebec514c\")\n}\n> db.demo236.insertOne({\"details\":{\"Name\":\"David\",\"Age\":23}});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e41901cf4cebbeaebec514d\")\n}\n> db.demo236.insertOne({\"details\":{\"Name\":\"Bob\",\"Age\":24}});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e419023f4cebbeaebec514e\")\n}" }, { "code": null, "e": 1652, "s": 1579, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1673, "s": 1652, "text": "> db.demo236.find();" }, { "code": null, "e": 1714, "s": 1673, "text": "This will produce the following output −" }, { "code": null, "e": 1997, "s": 1714, "text": "{ \"_id\" : ObjectId(\"5e419015f4cebbeaebec514c\"), \"details\" : { \"Name\" : \"Chris\", \"Age\" : 21 } }\n{ \"_id\" : ObjectId(\"5e41901cf4cebbeaebec514d\"), \"details\" : { \"Name\" : \"David\", \"Age\" : 23 } }\n{ \"_id\" : ObjectId(\"5e419023f4cebbeaebec514e\"), \"details\" : { \"Name\" : \"Bob\", \"Age\" : 24 } }" }, { "code": null, "e": 2071, "s": 1997, "text": "Following is the query to sort, select and query subdocument in MongoDB −" }, { "code": null, "e": 2283, "s": 2071, "text": "> db.demo236.aggregate(\n... [\n... { $unwind: \"$details\" },\n... { $project: {\n... Name: '$details.Name',\n... Age: '$details.Age'\n...\n... }},\n... { $sort: {Name: -1}}\n...]\n...);" }, { "code": null, "e": 2324, "s": 2283, "text": "This will produce the following output −" }, { "code": null, "e": 2559, "s": 2324, "text": "{ \"_id\" : ObjectId(\"5e41901cf4cebbeaebec514d\"), \"Name\" : \"David\", \"Age\" : 23 }\n{ \"_id\" : ObjectId(\"5e419015f4cebbeaebec514c\"), \"Name\" : \"Chris\", \"Age\" : 21 }\n{ \"_id\" : ObjectId(\"5e419023f4cebbeaebec514e\"), \"Name\" : \"Bob\", \"Age\" : 24 }" } ]
DateTimeOffset.ToOffset() Method in C#
The DateTimeOffset.ToOffset() method in C# is used to convert the value of the current DateTimeOffset object to the date and time specified by an offset value. Following is the syntax − public DateTimeOffset ToOffset (TimeSpan val); Above, the value is the offset to convert the DateTimeOffset value to. Let us now see an example to implement the DateTimeOffset.ToOffset() method − using System; public class Demo { public static void Main() { DateTimeOffset dateTimeOffset = new DateTimeOffset(2019, 9, 10, 4, 20, 30, new TimeSpan(-5, 0, 0)); Console.WriteLine("DateTimeOffset = {0}", dateTimeOffset); DateTimeOffset res = dateTimeOffset.ToOffset(new TimeSpan(-10, 1, 0)); Console.WriteLine("DateTimeOffset (updated) = {0}", res); } } This will produce the following output − DateTimeOffset = 9/10/2019 4:20:30 AM -05:00 DateTimeOffset (updated) = 9/9/2019 11:21:30 PM -09:59 Let us now see another example to implement the DateTimeOffset.ToOffset() method − using System; public class Demo { public static void Main() { DateTimeOffset dateTimeOffset = new DateTimeOffset(2019, 9, 10, 4, 20, 30, new TimeSpan(5, 0, 0)); Console.WriteLine("DateTimeOffset = {0}", dateTimeOffset); DateTimeOffset res = dateTimeOffset.ToOffset(new TimeSpan(3, 1, 0)); Console.WriteLine("DateTimeOffset (updated) = {0}", res); } } This will produce the following output − DateTimeOffset = 9/10/2019 4:20:30 AM +05:00 DateTimeOffset (updated) = 9/10/2019 2:21:30 AM +03:01
[ { "code": null, "e": 1222, "s": 1062, "text": "The DateTimeOffset.ToOffset() method in C# is used to convert the value of the current DateTimeOffset object to the date and time specified by an offset value." }, { "code": null, "e": 1248, "s": 1222, "text": "Following is the syntax −" }, { "code": null, "e": 1295, "s": 1248, "text": "public DateTimeOffset ToOffset (TimeSpan val);" }, { "code": null, "e": 1366, "s": 1295, "text": "Above, the value is the offset to convert the DateTimeOffset value to." }, { "code": null, "e": 1444, "s": 1366, "text": "Let us now see an example to implement the DateTimeOffset.ToOffset() method −" }, { "code": null, "e": 1828, "s": 1444, "text": "using System;\npublic class Demo {\n public static void Main() {\n DateTimeOffset dateTimeOffset = new DateTimeOffset(2019, 9, 10, 4, 20, 30, new TimeSpan(-5, 0, 0));\n Console.WriteLine(\"DateTimeOffset = {0}\", dateTimeOffset);\n DateTimeOffset res = dateTimeOffset.ToOffset(new TimeSpan(-10, 1, 0));\n Console.WriteLine(\"DateTimeOffset (updated) = {0}\", res);\n }\n}" }, { "code": null, "e": 1869, "s": 1828, "text": "This will produce the following output −" }, { "code": null, "e": 1969, "s": 1869, "text": "DateTimeOffset = 9/10/2019 4:20:30 AM -05:00\nDateTimeOffset (updated) = 9/9/2019 11:21:30 PM -09:59" }, { "code": null, "e": 2052, "s": 1969, "text": "Let us now see another example to implement the DateTimeOffset.ToOffset() method −" }, { "code": null, "e": 2433, "s": 2052, "text": "using System;\npublic class Demo {\n public static void Main() {\n DateTimeOffset dateTimeOffset = new DateTimeOffset(2019, 9, 10, 4, 20, 30, new TimeSpan(5, 0, 0));\n Console.WriteLine(\"DateTimeOffset = {0}\", dateTimeOffset);\n DateTimeOffset res = dateTimeOffset.ToOffset(new TimeSpan(3, 1, 0));\n Console.WriteLine(\"DateTimeOffset (updated) = {0}\", res);\n }\n}" }, { "code": null, "e": 2474, "s": 2433, "text": "This will produce the following output −" }, { "code": null, "e": 2574, "s": 2474, "text": "DateTimeOffset = 9/10/2019 4:20:30 AM +05:00\nDateTimeOffset (updated) = 9/10/2019 2:21:30 AM +03:01" } ]
Visualizing Location based data in R | by Aditya Tandel | Towards Data Science
I recently got an opportunity to work on spatial data and wanted to share my analysis on one such dataset. The data consisted of various registered business in the San Francisco Bay Area which can be found here. An updated version can be found here. Spatial data pertains to data which is associated with locations. Typically its described by a coordinate reference system, latitude and longitude. The goal of this exercise was to find pockets of neighborhoods in San Francisco with high concentration of businesses. You would need to get a key from Google’s Geolocation API to use their maps. I used the ggmap package in R to plot this data. Then I narrowed down my analysis on one particular high concentration neighborhood to see how businesses were dispersed within that area. First...Quick scan of the dataset str(biz)head(biz, 25)summary(biz) For the purpose of this exercise I was only concerned with the Neighborhoods, address, dates and most importantly the location columns which contained latitude and longitude data for each business. Names of the businesses and their codes (which are assigned by the city for registered businesses) were not considered for now. After doing basic data cleaning activities such as eliminating duplicates and nulls I extracted information only pertaining to the city of SF and eliminated records related to adjoining cities in the Bay Area. Identify data pertaining to San Francisco only There were a few ways I could go about achieving this; filter dataset based on city or by business.location or by zip codes. I chose to use the zip code logic as the other two fields had inconsistent patterns of the San Francisco city name which could easily be missed out. I have however included commands for all three methods of filtering this data. By zip sf_biz_zip <- biz %>% filter(grepl(pattern = "94016|94105|94110|94115|94119|94123|94127|94132|94139|94143|94147|94156|94161|94171|94102|94107|94108|94109|94111|94112|94114|94116|94117|94118|94120|94121|94122|94124|94125|94126|94129|94130|94131|94133|94134|94137|94140|94141|94142|94144|94145|94146|94151|94153|94154|94158|94159|94160|94162|94163|94164|94172|94177|94188", Business.Location)) By city sf_biz_city <- biz %>% filter((grepl(".*San Francisco.*|.*SAN FRANCISCO.*|.*SF.*|.*S SAN FRAN.*|.*Sf.*|.*San+francisco.*|.*S+san+fran.*", City))) By Business.Location sf_biz_loc <- biz %>% filter((grepl(".*San Francisco.*|.*SAN FRANCISCO.*|.*SF.*|.*S SAN FRAN.*|.*Sf.*|.*San+francisco.*|.*S+san+fran.*", Business.Location))) Converting date objects Next I wanted to eliminate businesses which had ceased to exist. For this I used the end dates for each location. However the date fields were stored as factors which were converted to posixct as that generally helps in further analysis when it comes to dates. sf_biz_zip$Business.Start.Date <- as.POSIXct(sf_biz_zip$Business.Start.Date, format = "%m/%d/%Y")sf_biz_zip$Business.End.Date <- as.POSIXct(sf_biz_zip$Business.End.Date, format = "%m/%d/%Y")sf_biz_zip$Location.Start.Date <- as.POSIXct(sf_biz_zip$Location.Start.Date, format = "%m/%d/%Y")sf_biz_zip$Location.End.Date <- as.POSIXct(sf_biz_zip$Location.End.Date, format = "%m/%d/%Y") Filter out inactive businesses Businesses which seized to exist after December 1, 2018 were eliminated. sf_biz_active_zip <- sf_biz_zip %>% filter(is.na(Location.End.Date))sf_biz_active_zip <- sf_biz_zip %>% filter(Location.Start.Date < "2018-12-01") Stripping out coordinates from the Business Location field The Business Location column contained addresses along with the coordinates information. So the latitude and longitude information needed to be extracted. sf_biz_active_zip <- sf_biz_active_zip %>% separate(Business.Location, c("Address", "Location"), sep = "[(]")sf_biz_active_zip <- sf_biz_active_zip %>% filter(!(is.na(Location)))sf_biz_active_zip <- separate(data = sf_biz_active_zip, col = Location, into = c("Latitude", "Longitude"), sep = ",") Other characters needed to be cleaned out too. sf_biz_active_zip$Longitude <- gsub(sf_biz_active_zip$Longitude, pattern = "[)]", replacement = "") I then converted latitude and longitude variables from discrete to continuous and stored them as numerical variables as this helps when plotting/visualizing data and to avoid errors. sf_biz_active_zip$Latitude <- as.numeric(sf_biz_active_zip$Latitude)sf_biz_active_zip$Longitude <- as.numeric(sf_biz_active_zip$Longitude) Now the fun part... Visualization the data The resultant dataset had 88,785 records which needed to be plot on a Google map. Interpreting these many records on a map would be overwhelming to say the least! Although sampling would be one way to proceed, I instead tried to find out the top 10 neighborhoods which had the largest number of businesses and plot one such neighborhood on the map. viz <- sf_biz_active_zip %>% group_by(Neighborhoods...Analysis.Boundaries) %>% tally() %>% arrange(desc(n))col.names(viz)[2] <- “Total_businesses”viz <- viz[1:10, ] I then created a histogram of these top 10 neighborhoods. fin_plot <- ggplot(viz, aes(x = Neighborhood, y = Total_Businesses)) + geom_bar(stat = "identity", fill = "#00bc6c")fin_plot <- fin_plot + geom_text(aes(label = Total_Businesses), vjust = -0.2) + theme(axis.text.x = element_text(angle = 45, size = 9, hjust = 1), plot.title = element_text(hjust = 0.5))fin_plot <- fin_plot + ggtitle("Top 10 neighborhoods by business count", size = 2) Let’s look at the Financial District/South Beach neighborhood in more detail since it has the maximum number of active businesses. Registering Google Maps key I installed the “ggmap”, “digest” and “glue” packages then registered with Google API to get the the Geolocation API key. install.packages("ggmap","digest","glue")register_google(key = "<google maps key>") Google provides terrain, satellite, hybrid among other types of maps. I chose to use the terrain map. A simple Google search can give you the city coordinates for San Francisco. sf <- c(lon = -122.3999, lat = 37.7846)map <- get_map(location = sf, zoom = 14, scale = 2) By adjusting the zoom you can get a closer look. The two images below are with different zoom sizes fin_map <- ggmap(map) + geom_point(aes(Longitude, Latitude), data = fin_dis) fin_map <- fin_map + ggtitle("Concentration of businesses in Fin. District and South Beach") + xlab("Longitude") + ylab("Latitude") + theme(plot.title = element_text(hjust = 0.5)) A better visualization A heatmap will probably make the visualization more intuitive. To make this happen we need to add one more aesthetic in addition to the x and y coordinates; z. This aesthetic is the total count of businesses in a particular lat.-lon. combination. fin_heatmap <- ggmap(map, extent = "device") + stat_summary_2d(data = u, aes(x = Longitude, y = Latitude, z = n), fun = mean, alpha = 0.6, bins = 30) + scale_fill_gradient(name = "Price", low = "green", high = "red")fin_heatmap <- fin_heatmap + ggtitle("Concentration of businesses in Fin. District and South Beach") + xlab("Longitude") + ylab("Latitude") + theme(plot.title = element_text(hjust = 0.5))") Conclusion Areas around Powell Street bart station, Union Square and Embarcadero bart station have a relatively large number of businesses while as areas around South Beach and and Lincoln Hill are sparse populated. Similarly other individual neighborhoods can be plotted to understand the distribution of businesses there. This was a fairly straightforward way of visualizing spatial data. I welcome any feedback and constructive criticism. Thank you for reading!
[ { "code": null, "e": 278, "s": 171, "text": "I recently got an opportunity to work on spatial data and wanted to share my analysis on one such dataset." }, { "code": null, "e": 421, "s": 278, "text": "The data consisted of various registered business in the San Francisco Bay Area which can be found here. An updated version can be found here." }, { "code": null, "e": 569, "s": 421, "text": "Spatial data pertains to data which is associated with locations. Typically its described by a coordinate reference system, latitude and longitude." }, { "code": null, "e": 952, "s": 569, "text": "The goal of this exercise was to find pockets of neighborhoods in San Francisco with high concentration of businesses. You would need to get a key from Google’s Geolocation API to use their maps. I used the ggmap package in R to plot this data. Then I narrowed down my analysis on one particular high concentration neighborhood to see how businesses were dispersed within that area." }, { "code": null, "e": 986, "s": 952, "text": "First...Quick scan of the dataset" }, { "code": null, "e": 1020, "s": 986, "text": "str(biz)head(biz, 25)summary(biz)" }, { "code": null, "e": 1346, "s": 1020, "text": "For the purpose of this exercise I was only concerned with the Neighborhoods, address, dates and most importantly the location columns which contained latitude and longitude data for each business. Names of the businesses and their codes (which are assigned by the city for registered businesses) were not considered for now." }, { "code": null, "e": 1556, "s": 1346, "text": "After doing basic data cleaning activities such as eliminating duplicates and nulls I extracted information only pertaining to the city of SF and eliminated records related to adjoining cities in the Bay Area." }, { "code": null, "e": 1603, "s": 1556, "text": "Identify data pertaining to San Francisco only" }, { "code": null, "e": 1956, "s": 1603, "text": "There were a few ways I could go about achieving this; filter dataset based on city or by business.location or by zip codes. I chose to use the zip code logic as the other two fields had inconsistent patterns of the San Francisco city name which could easily be missed out. I have however included commands for all three methods of filtering this data." }, { "code": null, "e": 1963, "s": 1956, "text": "By zip" }, { "code": null, "e": 2355, "s": 1963, "text": "sf_biz_zip <- biz %>% filter(grepl(pattern = \"94016|94105|94110|94115|94119|94123|94127|94132|94139|94143|94147|94156|94161|94171|94102|94107|94108|94109|94111|94112|94114|94116|94117|94118|94120|94121|94122|94124|94125|94126|94129|94130|94131|94133|94134|94137|94140|94141|94142|94144|94145|94146|94151|94153|94154|94158|94159|94160|94162|94163|94164|94172|94177|94188\", Business.Location))" }, { "code": null, "e": 2363, "s": 2355, "text": "By city" }, { "code": null, "e": 2512, "s": 2363, "text": "sf_biz_city <- biz %>% filter((grepl(\".*San Francisco.*|.*SAN FRANCISCO.*|.*SF.*|.*S SAN FRAN.*|.*Sf.*|.*San+francisco.*|.*S+san+fran.*\", City)))" }, { "code": null, "e": 2533, "s": 2512, "text": "By Business.Location" }, { "code": null, "e": 2691, "s": 2533, "text": "sf_biz_loc <- biz %>% filter((grepl(\".*San Francisco.*|.*SAN FRANCISCO.*|.*SF.*|.*S SAN FRAN.*|.*Sf.*|.*San+francisco.*|.*S+san+fran.*\", Business.Location)))" }, { "code": null, "e": 2715, "s": 2691, "text": "Converting date objects" }, { "code": null, "e": 2976, "s": 2715, "text": "Next I wanted to eliminate businesses which had ceased to exist. For this I used the end dates for each location. However the date fields were stored as factors which were converted to posixct as that generally helps in further analysis when it comes to dates." }, { "code": null, "e": 3357, "s": 2976, "text": "sf_biz_zip$Business.Start.Date <- as.POSIXct(sf_biz_zip$Business.Start.Date, format = \"%m/%d/%Y\")sf_biz_zip$Business.End.Date <- as.POSIXct(sf_biz_zip$Business.End.Date, format = \"%m/%d/%Y\")sf_biz_zip$Location.Start.Date <- as.POSIXct(sf_biz_zip$Location.Start.Date, format = \"%m/%d/%Y\")sf_biz_zip$Location.End.Date <- as.POSIXct(sf_biz_zip$Location.End.Date, format = \"%m/%d/%Y\")" }, { "code": null, "e": 3388, "s": 3357, "text": "Filter out inactive businesses" }, { "code": null, "e": 3461, "s": 3388, "text": "Businesses which seized to exist after December 1, 2018 were eliminated." }, { "code": null, "e": 3608, "s": 3461, "text": "sf_biz_active_zip <- sf_biz_zip %>% filter(is.na(Location.End.Date))sf_biz_active_zip <- sf_biz_zip %>% filter(Location.Start.Date < \"2018-12-01\")" }, { "code": null, "e": 3667, "s": 3608, "text": "Stripping out coordinates from the Business Location field" }, { "code": null, "e": 3822, "s": 3667, "text": "The Business Location column contained addresses along with the coordinates information. So the latitude and longitude information needed to be extracted." }, { "code": null, "e": 4118, "s": 3822, "text": "sf_biz_active_zip <- sf_biz_active_zip %>% separate(Business.Location, c(\"Address\", \"Location\"), sep = \"[(]\")sf_biz_active_zip <- sf_biz_active_zip %>% filter(!(is.na(Location)))sf_biz_active_zip <- separate(data = sf_biz_active_zip, col = Location, into = c(\"Latitude\", \"Longitude\"), sep = \",\")" }, { "code": null, "e": 4165, "s": 4118, "text": "Other characters needed to be cleaned out too." }, { "code": null, "e": 4265, "s": 4165, "text": "sf_biz_active_zip$Longitude <- gsub(sf_biz_active_zip$Longitude, pattern = \"[)]\", replacement = \"\")" }, { "code": null, "e": 4448, "s": 4265, "text": "I then converted latitude and longitude variables from discrete to continuous and stored them as numerical variables as this helps when plotting/visualizing data and to avoid errors." }, { "code": null, "e": 4587, "s": 4448, "text": "sf_biz_active_zip$Latitude <- as.numeric(sf_biz_active_zip$Latitude)sf_biz_active_zip$Longitude <- as.numeric(sf_biz_active_zip$Longitude)" }, { "code": null, "e": 4607, "s": 4587, "text": "Now the fun part..." }, { "code": null, "e": 4630, "s": 4607, "text": "Visualization the data" }, { "code": null, "e": 4979, "s": 4630, "text": "The resultant dataset had 88,785 records which needed to be plot on a Google map. Interpreting these many records on a map would be overwhelming to say the least! Although sampling would be one way to proceed, I instead tried to find out the top 10 neighborhoods which had the largest number of businesses and plot one such neighborhood on the map." }, { "code": null, "e": 5144, "s": 4979, "text": "viz <- sf_biz_active_zip %>% group_by(Neighborhoods...Analysis.Boundaries) %>% tally() %>% arrange(desc(n))col.names(viz)[2] <- “Total_businesses”viz <- viz[1:10, ]" }, { "code": null, "e": 5202, "s": 5144, "text": "I then created a histogram of these top 10 neighborhoods." }, { "code": null, "e": 5587, "s": 5202, "text": "fin_plot <- ggplot(viz, aes(x = Neighborhood, y = Total_Businesses)) + geom_bar(stat = \"identity\", fill = \"#00bc6c\")fin_plot <- fin_plot + geom_text(aes(label = Total_Businesses), vjust = -0.2) + theme(axis.text.x = element_text(angle = 45, size = 9, hjust = 1), plot.title = element_text(hjust = 0.5))fin_plot <- fin_plot + ggtitle(\"Top 10 neighborhoods by business count\", size = 2)" }, { "code": null, "e": 5718, "s": 5587, "text": "Let’s look at the Financial District/South Beach neighborhood in more detail since it has the maximum number of active businesses." }, { "code": null, "e": 5746, "s": 5718, "text": "Registering Google Maps key" }, { "code": null, "e": 5868, "s": 5746, "text": "I installed the “ggmap”, “digest” and “glue” packages then registered with Google API to get the the Geolocation API key." }, { "code": null, "e": 5952, "s": 5868, "text": "install.packages(\"ggmap\",\"digest\",\"glue\")register_google(key = \"<google maps key>\")" }, { "code": null, "e": 6130, "s": 5952, "text": "Google provides terrain, satellite, hybrid among other types of maps. I chose to use the terrain map. A simple Google search can give you the city coordinates for San Francisco." }, { "code": null, "e": 6221, "s": 6130, "text": "sf <- c(lon = -122.3999, lat = 37.7846)map <- get_map(location = sf, zoom = 14, scale = 2)" }, { "code": null, "e": 6321, "s": 6221, "text": "By adjusting the zoom you can get a closer look. The two images below are with different zoom sizes" }, { "code": null, "e": 6578, "s": 6321, "text": "fin_map <- ggmap(map) + geom_point(aes(Longitude, Latitude), data = fin_dis) fin_map <- fin_map + ggtitle(\"Concentration of businesses in Fin. District and South Beach\") + xlab(\"Longitude\") + ylab(\"Latitude\") + theme(plot.title = element_text(hjust = 0.5))" }, { "code": null, "e": 6601, "s": 6578, "text": "A better visualization" }, { "code": null, "e": 6848, "s": 6601, "text": "A heatmap will probably make the visualization more intuitive. To make this happen we need to add one more aesthetic in addition to the x and y coordinates; z. This aesthetic is the total count of businesses in a particular lat.-lon. combination." }, { "code": null, "e": 7254, "s": 6848, "text": "fin_heatmap <- ggmap(map, extent = \"device\") + stat_summary_2d(data = u, aes(x = Longitude, y = Latitude, z = n), fun = mean, alpha = 0.6, bins = 30) + scale_fill_gradient(name = \"Price\", low = \"green\", high = \"red\")fin_heatmap <- fin_heatmap + ggtitle(\"Concentration of businesses in Fin. District and South Beach\") + xlab(\"Longitude\") + ylab(\"Latitude\") + theme(plot.title = element_text(hjust = 0.5))\")" }, { "code": null, "e": 7265, "s": 7254, "text": "Conclusion" }, { "code": null, "e": 7470, "s": 7265, "text": "Areas around Powell Street bart station, Union Square and Embarcadero bart station have a relatively large number of businesses while as areas around South Beach and and Lincoln Hill are sparse populated." }, { "code": null, "e": 7578, "s": 7470, "text": "Similarly other individual neighborhoods can be plotted to understand the distribution of businesses there." }, { "code": null, "e": 7696, "s": 7578, "text": "This was a fairly straightforward way of visualizing spatial data. I welcome any feedback and constructive criticism." } ]
How to set encoding in PHP FPDI library?
Below is the same code to set encoding for FPDI library− Add new fonts that have the correct alphabets. $pdf->AddFont('DejaVu','','DejaVuSansCondensed.php'); $pdf->SetFont('DejaVu', '', 10, '', false); The following are three possible encodings that are possible. cp1250 (Central Europe) cp1251 (Cyrillic) cp1252 (Western Europe) cp1253 (Greek) cp1254 (Turkish) cp1255 (Hebrew) cp1257 (Baltic) cp1258 (Vietnamese) cp874 (Thai) or ISO-8859-1 (Western Europe) ISO-8859-2 (Central Europe) ISO-8859-4 (Baltic) ISO-8859-5 (Cyrillic) ISO-8859-7 (Greek) ISO-8859-9 (Turkish) ISO-8859-11 (Thai) ISO-8859-15 (Western Europe) ISO-8859-16 (Central Europe) Or KOI8-R (Russian) KOI8-U (Ukrainian) Let us see an example to convert the UTF-8 to cp1250. $str = iconv('UTF-8', 'cp1250', 'zazółcić gęślą jaźń'); Note− If the string sent by the user to the PDF is in UTF-8 encoding, it needs to be converted to cp1250.
[ { "code": null, "e": 1119, "s": 1062, "text": "Below is the same code to set encoding for FPDI library−" }, { "code": null, "e": 1166, "s": 1119, "text": "Add new fonts that have the correct alphabets." }, { "code": null, "e": 1264, "s": 1166, "text": "$pdf->AddFont('DejaVu','','DejaVuSansCondensed.php');\n$pdf->SetFont('DejaVu', '', 10, '', false);" }, { "code": null, "e": 1326, "s": 1264, "text": "The following are three possible encodings that are possible." }, { "code": null, "e": 1746, "s": 1326, "text": "cp1250 (Central Europe)\ncp1251 (Cyrillic)\ncp1252 (Western Europe)\ncp1253 (Greek)\ncp1254 (Turkish)\ncp1255 (Hebrew)\ncp1257 (Baltic)\ncp1258 (Vietnamese)\ncp874 (Thai)\nor\nISO-8859-1 (Western Europe)\nISO-8859-2 (Central Europe)\nISO-8859-4 (Baltic)\nISO-8859-5 (Cyrillic)\nISO-8859-7 (Greek)\nISO-8859-9 (Turkish)\nISO-8859-11 (Thai)\nISO-8859-15 (Western Europe)\nISO-8859-16 (Central Europe)\nOr\nKOI8-R (Russian)\nKOI8-U (Ukrainian)" }, { "code": null, "e": 1800, "s": 1746, "text": "Let us see an example to convert the UTF-8 to cp1250." }, { "code": null, "e": 1863, "s": 1800, "text": "$str = iconv('UTF-8', 'cp1250', 'zazółcić gęślą jaźń');" }, { "code": null, "e": 1969, "s": 1863, "text": "Note− If the string sent by the user to the PDF is in UTF-8 encoding, it needs to be converted to cp1250." } ]
C# | Math.Tan() Method - GeeksforGeeks
31 Jan, 2019 Math.Tan() is an inbuilt Math class method which returns the tangent of a given double value argument(specified angle). Syntax: public static double Tan(double num) Parameter: num: It is the angle(measured in radian) whose tangent is to be returned and the type of this parameter is System.Double. Return Value: Returns the tangent of num of type System.Double. If num is equal to NegativeInfinity, PositiveInfinity, or NaN, then this method returns NaN. Below are the programs to illustrate the Math.Tan() method. Program 1: To show the working of Math.Tan() method. // C# program to demonstrate working// Math.Tan() methodusing System; class Geeks { // Main Method public static void Main(String []args) { double a = 12; // converting value to radians double b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Tan(b)); a = 63; // converting value to radians b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Tan(b)); a = 187; // converting value to radians b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Tan(b)); a = 45; // converting value to radians b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Tan(b)); }} 0.212556561670022 1.96261050550515 0.122784560902905 1 Program 2: To show the working of Math.Tan() method when the argument is NaN or infinity. // C# program to demonstrate working// Math.Tan() method in infinity caseusing System; class Geeks { // Main Method public static void Main(String []args) { double positiveInfinity = Double.PositiveInfinity; double negativeInfinity = Double.NegativeInfinity; double nan = Double.NaN; double result; // Here argument is negative infinity, // output will be NaN result = Math.Tan(negativeInfinity); Console.WriteLine(result); // Here argument is positive infinity, // output will also be NaN result = Math.Tan(positiveInfinity); Console.WriteLine(result); // Here argument is NaN, output will be NaN result = Math.Tan(nan); Console.WriteLine(result); }} NaN NaN NaN CSharp-Math CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extension Method in C# Top 50 C# Interview Questions & Answers Partial Classes in C# HashSet in C# with Examples C# | Inheritance C# | How to insert an element in an Array? C# | List Class Lambda Expressions in C# C# | Generics - Introduction What is Regular Expression in C#?
[ { "code": null, "e": 24222, "s": 24194, "text": "\n31 Jan, 2019" }, { "code": null, "e": 24342, "s": 24222, "text": "Math.Tan() is an inbuilt Math class method which returns the tangent of a given double value argument(specified angle)." }, { "code": null, "e": 24350, "s": 24342, "text": "Syntax:" }, { "code": null, "e": 24387, "s": 24350, "text": "public static double Tan(double num)" }, { "code": null, "e": 24398, "s": 24387, "text": "Parameter:" }, { "code": null, "e": 24520, "s": 24398, "text": "num: It is the angle(measured in radian) whose tangent is to be returned and the type of this parameter is System.Double." }, { "code": null, "e": 24677, "s": 24520, "text": "Return Value: Returns the tangent of num of type System.Double. If num is equal to NegativeInfinity, PositiveInfinity, or NaN, then this method returns NaN." }, { "code": null, "e": 24737, "s": 24677, "text": "Below are the programs to illustrate the Math.Tan() method." }, { "code": null, "e": 24790, "s": 24737, "text": "Program 1: To show the working of Math.Tan() method." }, { "code": "// C# program to demonstrate working// Math.Tan() methodusing System; class Geeks { // Main Method public static void Main(String []args) { double a = 12; // converting value to radians double b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Tan(b)); a = 63; // converting value to radians b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Tan(b)); a = 187; // converting value to radians b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Tan(b)); a = 45; // converting value to radians b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Tan(b)); }}", "e": 25704, "s": 24790, "text": null }, { "code": null, "e": 25760, "s": 25704, "text": "0.212556561670022\n1.96261050550515\n0.122784560902905\n1\n" }, { "code": null, "e": 25851, "s": 25760, "text": " Program 2: To show the working of Math.Tan() method when the argument is NaN or infinity." }, { "code": "// C# program to demonstrate working// Math.Tan() method in infinity caseusing System; class Geeks { // Main Method public static void Main(String []args) { double positiveInfinity = Double.PositiveInfinity; double negativeInfinity = Double.NegativeInfinity; double nan = Double.NaN; double result; // Here argument is negative infinity, // output will be NaN result = Math.Tan(negativeInfinity); Console.WriteLine(result); // Here argument is positive infinity, // output will also be NaN result = Math.Tan(positiveInfinity); Console.WriteLine(result); // Here argument is NaN, output will be NaN result = Math.Tan(nan); Console.WriteLine(result); }}", "e": 26688, "s": 25851, "text": null }, { "code": null, "e": 26701, "s": 26688, "text": "NaN\nNaN\nNaN\n" }, { "code": null, "e": 26713, "s": 26701, "text": "CSharp-Math" }, { "code": null, "e": 26727, "s": 26713, "text": "CSharp-method" }, { "code": null, "e": 26730, "s": 26727, "text": "C#" }, { "code": null, "e": 26828, "s": 26730, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26837, "s": 26828, "text": "Comments" }, { "code": null, "e": 26850, "s": 26837, "text": "Old Comments" }, { "code": null, "e": 26873, "s": 26850, "text": "Extension Method in C#" }, { "code": null, "e": 26913, "s": 26873, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26935, "s": 26913, "text": "Partial Classes in C#" }, { "code": null, "e": 26963, "s": 26935, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26980, "s": 26963, "text": "C# | Inheritance" }, { "code": null, "e": 27023, "s": 26980, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27039, "s": 27023, "text": "C# | List Class" }, { "code": null, "e": 27064, "s": 27039, "text": "Lambda Expressions in C#" }, { "code": null, "e": 27093, "s": 27064, "text": "C# | Generics - Introduction" } ]
Kalman Filter in a Nutshell. Taking a tour through Kalman filter... | by Shuo Wang | Towards Data Science
When I first started learning to use Kalman filter, it seemed very complicated to me, mainly because there were so many inputs to it and you never really knew if you’ve set them correctly. By going through this example, I hope my readers will understand that the motivations and logic behind it is really very pragmatic in nature and not so complicated after all. So let’s get started with our example. I am dropping a tennis ball from a helicopter (or maybe my airship), I would like to predict its position in the air until it hits the ground. You would think this is a very simple problem, right? After all, we’ve got our equations of motion: Where g is acceleration due to gravity (9.81 meters per second squared). Well, unfortunately the real world is not that simple. If you are dropping a lead ball I suppose the equations of motion are all you need, but for something light like a tennis ball, it’s trajectory might be affected by all sorts of things. For example, there might be a really strong wind blowing. Or a really hungry alligator might be near by... The real world is complicated. So, if your prediction solely comes from the equations, it might be really off by the time the ball reaches the ground. Let’s take a closer look. Let’s simulate what happens. Suppose we drop a ball 20,000 meters above ground, it will mostly follow the the equations of motion, with random forces such as wind and alligators affecting it’s trajectory: Where F is the equations of motion we just discussed. G and N are the random forces affecting the ball in real life (wind and alligators). N is basically a random variable of normal distribution, with mean 0 and standard deviation sigma(a). Our initial conditions, therefore, are as follows: # initial valuesx0 = np.matrix([[20000], [0], [-9.81]]) # gravity And suppose that our random forces effectively have a standard deviation of say 1 meters per second squared. sa = 1 # sigma a The trajectory of the tennis ball will look something like below: Simulated with codes below: def xk(F, xk1, G, sa): _xk = F.dot(xk1) + \ G * np.random.normal(loc=0, scale=sa) return _xk How accurate is our prediction with equations of motion? Now suppose we try to predict the trajectory of the tennis ball with only the equations of motion, how accurate will it be? As you can see, the difference can accumulate and become quite significant, in this case, they are off by more than 1000 meters. How do we improve this prediction with Kalman filter? Kalman filter takes advantage of the fact that you don’t need to wait till the tennis hits the ground to know its position. If you have a camera with you, for example, you can take a picture of the tennis ball every 10 seconds and estimate its position from it so that you can update your prediction from the observation. (So don’t ever forget to bring your phone!) Suppose at time t, we take a picture of tennis ball, what will it look like? It’s not going to give you a perfect observation (nothing can be perfect). But you can get a good estimate from it. Below is the mathematical representation of the observation: In this case, you have the actual state of the ball for which you don’t know the exact values, but you can observe it with an observation model, H. H represents our camera, since from the picture taken by a camera you can only find position y at time t, it’s a horizontal unit vector. If, say, we have a radar that can actually observe the velocity as well, we can use [1, 1, 0] as observation model. The third part represents the inaccuracies associated with the observation, and it’s a normal random variable with mean 0 and standard deviation sigma z. Apply Kalman filter to improve the predictions with observations. Kalman filter provides us with a recipe for using the observation to improve the prediction. You start with your predicted state(position, velocity, acceleration) of the tennis ball and their predicted covariances (accuracy in prediction), the predicted covariance is updated during each step along with state proportional to how much random force is on the tennis ball. Calculate the difference between the predicted position and the observation. Calculate the gain warranted from the difference based on the covariance of the tennis ball’s state and the accuracy of the observation. — here the idea is that if the observation is perfect (R=0), then the gain should be 1, so that your updated estimate is basically the observation. — if the variance of the position is high (the prediction is not very accurate), even if the observation is not that accurate, it’s a good idea to give a bit more weight to it since compared to the accuracy of the prediction it’s not so bad. Apply the gain to the predicted position and predicted covariance to update them. How does Kalman filter perform? As you can see, the purpose of Kalman filter is to improve your predictions with periodic observations. If you have observations, great, let’s use them, if not, just continue the prediction process. Below is a comparison of performance using Kalman filters to improve prediction with observations every 50, 10, 5 seconds: As you can see, more frequent observations definitely improve predicted values. What’s next? By going through this simple application of Kalman filter, I hope my readers have gained an intuitive understanding of the Kalman filter estimation improvement process. As we can see from the example, how accurate the prediction is ultimately depends on the model used to generate the prediction. Kalman filter can help improve the prediction with appropriately chosen error models for the prediction(sigma a) and the observation (sigma z). There are many improvements that can be made to the Kalman filter, we’ll talk about them in the future. Please see my GitHub gist for complete code: Gist for Kalman Filter
[ { "code": null, "e": 535, "s": 171, "text": "When I first started learning to use Kalman filter, it seemed very complicated to me, mainly because there were so many inputs to it and you never really knew if you’ve set them correctly. By going through this example, I hope my readers will understand that the motivations and logic behind it is really very pragmatic in nature and not so complicated after all." }, { "code": null, "e": 574, "s": 535, "text": "So let’s get started with our example." }, { "code": null, "e": 717, "s": 574, "text": "I am dropping a tennis ball from a helicopter (or maybe my airship), I would like to predict its position in the air until it hits the ground." }, { "code": null, "e": 817, "s": 717, "text": "You would think this is a very simple problem, right? After all, we’ve got our equations of motion:" }, { "code": null, "e": 890, "s": 817, "text": "Where g is acceleration due to gravity (9.81 meters per second squared)." }, { "code": null, "e": 1131, "s": 890, "text": "Well, unfortunately the real world is not that simple. If you are dropping a lead ball I suppose the equations of motion are all you need, but for something light like a tennis ball, it’s trajectory might be affected by all sorts of things." }, { "code": null, "e": 1189, "s": 1131, "text": "For example, there might be a really strong wind blowing." }, { "code": null, "e": 1238, "s": 1189, "text": "Or a really hungry alligator might be near by..." }, { "code": null, "e": 1269, "s": 1238, "text": "The real world is complicated." }, { "code": null, "e": 1389, "s": 1269, "text": "So, if your prediction solely comes from the equations, it might be really off by the time the ball reaches the ground." }, { "code": null, "e": 1415, "s": 1389, "text": "Let’s take a closer look." }, { "code": null, "e": 1444, "s": 1415, "text": "Let’s simulate what happens." }, { "code": null, "e": 1620, "s": 1444, "text": "Suppose we drop a ball 20,000 meters above ground, it will mostly follow the the equations of motion, with random forces such as wind and alligators affecting it’s trajectory:" }, { "code": null, "e": 1861, "s": 1620, "text": "Where F is the equations of motion we just discussed. G and N are the random forces affecting the ball in real life (wind and alligators). N is basically a random variable of normal distribution, with mean 0 and standard deviation sigma(a)." }, { "code": null, "e": 1912, "s": 1861, "text": "Our initial conditions, therefore, are as follows:" }, { "code": null, "e": 2008, "s": 1912, "text": "# initial valuesx0 = np.matrix([[20000], [0], [-9.81]]) # gravity" }, { "code": null, "e": 2117, "s": 2008, "text": "And suppose that our random forces effectively have a standard deviation of say 1 meters per second squared." }, { "code": null, "e": 2134, "s": 2117, "text": "sa = 1 # sigma a" }, { "code": null, "e": 2200, "s": 2134, "text": "The trajectory of the tennis ball will look something like below:" }, { "code": null, "e": 2228, "s": 2200, "text": "Simulated with codes below:" }, { "code": null, "e": 2336, "s": 2228, "text": "def xk(F, xk1, G, sa): _xk = F.dot(xk1) + \\ G * np.random.normal(loc=0, scale=sa) return _xk" }, { "code": null, "e": 2393, "s": 2336, "text": "How accurate is our prediction with equations of motion?" }, { "code": null, "e": 2517, "s": 2393, "text": "Now suppose we try to predict the trajectory of the tennis ball with only the equations of motion, how accurate will it be?" }, { "code": null, "e": 2646, "s": 2517, "text": "As you can see, the difference can accumulate and become quite significant, in this case, they are off by more than 1000 meters." }, { "code": null, "e": 2700, "s": 2646, "text": "How do we improve this prediction with Kalman filter?" }, { "code": null, "e": 3066, "s": 2700, "text": "Kalman filter takes advantage of the fact that you don’t need to wait till the tennis hits the ground to know its position. If you have a camera with you, for example, you can take a picture of the tennis ball every 10 seconds and estimate its position from it so that you can update your prediction from the observation. (So don’t ever forget to bring your phone!)" }, { "code": null, "e": 3143, "s": 3066, "text": "Suppose at time t, we take a picture of tennis ball, what will it look like?" }, { "code": null, "e": 3320, "s": 3143, "text": "It’s not going to give you a perfect observation (nothing can be perfect). But you can get a good estimate from it. Below is the mathematical representation of the observation:" }, { "code": null, "e": 3468, "s": 3320, "text": "In this case, you have the actual state of the ball for which you don’t know the exact values, but you can observe it with an observation model, H." }, { "code": null, "e": 3721, "s": 3468, "text": "H represents our camera, since from the picture taken by a camera you can only find position y at time t, it’s a horizontal unit vector. If, say, we have a radar that can actually observe the velocity as well, we can use [1, 1, 0] as observation model." }, { "code": null, "e": 3875, "s": 3721, "text": "The third part represents the inaccuracies associated with the observation, and it’s a normal random variable with mean 0 and standard deviation sigma z." }, { "code": null, "e": 3941, "s": 3875, "text": "Apply Kalman filter to improve the predictions with observations." }, { "code": null, "e": 4034, "s": 3941, "text": "Kalman filter provides us with a recipe for using the observation to improve the prediction." }, { "code": null, "e": 4312, "s": 4034, "text": "You start with your predicted state(position, velocity, acceleration) of the tennis ball and their predicted covariances (accuracy in prediction), the predicted covariance is updated during each step along with state proportional to how much random force is on the tennis ball." }, { "code": null, "e": 4389, "s": 4312, "text": "Calculate the difference between the predicted position and the observation." }, { "code": null, "e": 4526, "s": 4389, "text": "Calculate the gain warranted from the difference based on the covariance of the tennis ball’s state and the accuracy of the observation." }, { "code": null, "e": 4674, "s": 4526, "text": "— here the idea is that if the observation is perfect (R=0), then the gain should be 1, so that your updated estimate is basically the observation." }, { "code": null, "e": 4916, "s": 4674, "text": "— if the variance of the position is high (the prediction is not very accurate), even if the observation is not that accurate, it’s a good idea to give a bit more weight to it since compared to the accuracy of the prediction it’s not so bad." }, { "code": null, "e": 4998, "s": 4916, "text": "Apply the gain to the predicted position and predicted covariance to update them." }, { "code": null, "e": 5030, "s": 4998, "text": "How does Kalman filter perform?" }, { "code": null, "e": 5229, "s": 5030, "text": "As you can see, the purpose of Kalman filter is to improve your predictions with periodic observations. If you have observations, great, let’s use them, if not, just continue the prediction process." }, { "code": null, "e": 5352, "s": 5229, "text": "Below is a comparison of performance using Kalman filters to improve prediction with observations every 50, 10, 5 seconds:" }, { "code": null, "e": 5432, "s": 5352, "text": "As you can see, more frequent observations definitely improve predicted values." }, { "code": null, "e": 5445, "s": 5432, "text": "What’s next?" }, { "code": null, "e": 5990, "s": 5445, "text": "By going through this simple application of Kalman filter, I hope my readers have gained an intuitive understanding of the Kalman filter estimation improvement process. As we can see from the example, how accurate the prediction is ultimately depends on the model used to generate the prediction. Kalman filter can help improve the prediction with appropriately chosen error models for the prediction(sigma a) and the observation (sigma z). There are many improvements that can be made to the Kalman filter, we’ll talk about them in the future." } ]
Importance of Loss Function in Machine Learning | by Aditya Rakhecha | Towards Data Science
Originally published at OpenGenus IQ. Assume you are given a task to fill a bag with 10 Kg of sand. You fill it up till the measuring machine gives you a perfect reading of 10 Kg or you take out the sand if the reading exceeds 10kg. Just like that weighing machine, if your predictions are off, your loss function will output a higher number. If they’re pretty good, it’ll output a lower number. As you experiment with your algorithm to try and improve your model, your loss function will tell you if you’re getting(or reaching) anywhere. “The function we want to minimize or maximize is called the objective function or criterion. When we are minimizing it, we may also call it the cost function, loss function, or error function” — Source At its core, a loss function is a measure of how good your prediction model does in terms of being able to predict the expected outcome(or value). We convert the learning problem into an optimization problem, define a loss function and then optimize the algorithm to minimize the loss function. Most commonly used loss functions are: Mean Squared error Mean Absolute Error Log-Likelihood Loss Hinge Loss Huber Loss Mean Squared Error Mean Squared Error Mean Squared Error (MSE) is the workspace of basic loss functions, as it is easy to understand and implement and generally works pretty well. To calculate MSE, you take the difference between your model’s predictions and the ground truth, square it out and then average it out across the whole dataset. The result is always positive regardless of the sign of the predicted and ground truth values and a perfect value is 0.0. # function to calculate MSEdef MSE(y_predicted, y_actual): squared_error = (y_predicted - y_actual) ** 2 sum_squared_error = np.sum(squared_error) mse = sum_squared_error / y_actual.size return mse 2. Mean Absolute Error Mean Absolute Error (MAE) is only slightly different in definition from the MSE, but interestingly provides almost exactly opposite properties. To calculate the MAE, you take the difference between your model’s predictions and the ground truth, apply the absolute value to that difference, and then average it out across the whole dataset. # function to calculate MAEdef MAE(y_predicted, y_actual): abs_error = np.abs(y_predicted - y_actual) sum_abs_error = np.sum(abs_error) mae = sum_abs_error / y_actual.size return mae 3. Log-Likelihood Loss This loss function is also relatively simple and commonly used in classification problems. In this, the error between two probability distributions is measured using cross-entropy. -(y_actual * log(y_predicted) + (1 - y_actual) * log(1 - y_predicted)) Here, you can see that when the actual class is 1, the second half of the function disappears, and when the actual class is 0, the first half drops. That way, we just end up multiplying the log of the actual predicted probability for the ground truth class. Cross-entropy for a binary or two-class prediction problem is actually calculated as the average cross-entropy across all examples. from math import log # function to calculate binary cross entropydef binary_cross_entropy(actual, predicted): sum_score = 0.0 for i in range(len(actual)): sum_score += actual[i] * log(1e-15 + predicted[i]) mean_sum_score = 1.0 / len(actual) * sum_score return -mean_sum_score This function is one of the most popular measures for Kaggle competitions. It’s just a straightforward modification of the likelihood function with logarithms. 4. Hinge Loss The Hinge loss function is popular with Support Vector Machines(SVMs). These are used for training the classifiers. Let ‘t’ be the target output such that t = -1 or 1, and the classifier score be ‘y’, then the hinge loss for the prediction is given as: L(y) = max(0, 1-t.y) 5. Huber Loss We know that MSE is great for learning outliers while the MAE is great for ignoring them. But what about something in the middle? Consider an example where we have a dataset of 100 values we would like our model to be trained to predict. Out of all that data, 25% of the expected values are 5 while the other 75% is 10. An MSE loss wouldn’t quite do the trick since we don’t have “outliers”; 25% is by no means a small fraction. On the other hand, we don’t necessarily want to weight that 25% too low with an MAE. Those values of 5 aren’t close to the median (10 — since 75% of the points have a value of 10), but they’re also not outliers. The Huber Loss Function. The Huber Loss offers the best of both worlds by balancing the MSE and MAE together. We can define it using the following piecewise function: What this equation actually means is that for loss values less than delta, use the MSE; for loss values greater than delta, use the MAE. This effectively combines the best of both worlds from the two loss functions. # function to calculate Huber lossdef huber_loss(y_predicted, y_actual, delta=1.0): huber_mse = 0.5*(y_actual-y_predicted)**2 huber_mae = delta * (np.abs(y_actual - y_predicted) - 0.5 * delta) return np.where(np.abs(y_actual - y_predicted) <= delta, huber_mse, huber_mae) Loss functions provide more than just a static representation of how your model is performing–they’re how your algorithms fit data in the first place. Most machine learning algorithms use some sort of loss function in the process of optimization or finding the best parameters (weights) for your data. Importantly, the choice of the loss function is directly related to the activation function used in the output layer of your neural network. These two design elements are connected. Think of the configuration of the output layer as a choice about the framing of your prediction problem, and the choice of the loss function as the way to calculate the error for a given framing of your problem. Further reading Deep Learning Book by Ian Goodfellow, Yoshua Bengio and Aaron Courville.
[ { "code": null, "e": 210, "s": 172, "text": "Originally published at OpenGenus IQ." }, { "code": null, "e": 405, "s": 210, "text": "Assume you are given a task to fill a bag with 10 Kg of sand. You fill it up till the measuring machine gives you a perfect reading of 10 Kg or you take out the sand if the reading exceeds 10kg." }, { "code": null, "e": 711, "s": 405, "text": "Just like that weighing machine, if your predictions are off, your loss function will output a higher number. If they’re pretty good, it’ll output a lower number. As you experiment with your algorithm to try and improve your model, your loss function will tell you if you’re getting(or reaching) anywhere." }, { "code": null, "e": 913, "s": 711, "text": "“The function we want to minimize or maximize is called the objective function or criterion. When we are minimizing it, we may also call it the cost function, loss function, or error function” — Source" }, { "code": null, "e": 1208, "s": 913, "text": "At its core, a loss function is a measure of how good your prediction model does in terms of being able to predict the expected outcome(or value). We convert the learning problem into an optimization problem, define a loss function and then optimize the algorithm to minimize the loss function." }, { "code": null, "e": 1247, "s": 1208, "text": "Most commonly used loss functions are:" }, { "code": null, "e": 1266, "s": 1247, "text": "Mean Squared error" }, { "code": null, "e": 1286, "s": 1266, "text": "Mean Absolute Error" }, { "code": null, "e": 1306, "s": 1286, "text": "Log-Likelihood Loss" }, { "code": null, "e": 1317, "s": 1306, "text": "Hinge Loss" }, { "code": null, "e": 1328, "s": 1317, "text": "Huber Loss" }, { "code": null, "e": 1347, "s": 1328, "text": "Mean Squared Error" }, { "code": null, "e": 1366, "s": 1347, "text": "Mean Squared Error" }, { "code": null, "e": 1791, "s": 1366, "text": "Mean Squared Error (MSE) is the workspace of basic loss functions, as it is easy to understand and implement and generally works pretty well. To calculate MSE, you take the difference between your model’s predictions and the ground truth, square it out and then average it out across the whole dataset. The result is always positive regardless of the sign of the predicted and ground truth values and a perfect value is 0.0." }, { "code": null, "e": 2001, "s": 1791, "text": "# function to calculate MSEdef MSE(y_predicted, y_actual): squared_error = (y_predicted - y_actual) ** 2 sum_squared_error = np.sum(squared_error) mse = sum_squared_error / y_actual.size return mse" }, { "code": null, "e": 2024, "s": 2001, "text": "2. Mean Absolute Error" }, { "code": null, "e": 2364, "s": 2024, "text": "Mean Absolute Error (MAE) is only slightly different in definition from the MSE, but interestingly provides almost exactly opposite properties. To calculate the MAE, you take the difference between your model’s predictions and the ground truth, apply the absolute value to that difference, and then average it out across the whole dataset." }, { "code": null, "e": 2567, "s": 2364, "text": "# function to calculate MAEdef MAE(y_predicted, y_actual): abs_error = np.abs(y_predicted - y_actual) sum_abs_error = np.sum(abs_error) mae = sum_abs_error / y_actual.size return mae" }, { "code": null, "e": 2590, "s": 2567, "text": "3. Log-Likelihood Loss" }, { "code": null, "e": 2771, "s": 2590, "text": "This loss function is also relatively simple and commonly used in classification problems. In this, the error between two probability distributions is measured using cross-entropy." }, { "code": null, "e": 2842, "s": 2771, "text": "-(y_actual * log(y_predicted) + (1 - y_actual) * log(1 - y_predicted))" }, { "code": null, "e": 3100, "s": 2842, "text": "Here, you can see that when the actual class is 1, the second half of the function disappears, and when the actual class is 0, the first half drops. That way, we just end up multiplying the log of the actual predicted probability for the ground truth class." }, { "code": null, "e": 3232, "s": 3100, "text": "Cross-entropy for a binary or two-class prediction problem is actually calculated as the average cross-entropy across all examples." }, { "code": null, "e": 3509, "s": 3232, "text": "from math import log # function to calculate binary cross entropydef binary_cross_entropy(actual, predicted):\tsum_score = 0.0\tfor i in range(len(actual)):\t\tsum_score += actual[i] * log(1e-15 + predicted[i])\tmean_sum_score = 1.0 / len(actual) * sum_score\treturn -mean_sum_score" }, { "code": null, "e": 3669, "s": 3509, "text": "This function is one of the most popular measures for Kaggle competitions. It’s just a straightforward modification of the likelihood function with logarithms." }, { "code": null, "e": 3683, "s": 3669, "text": "4. Hinge Loss" }, { "code": null, "e": 3957, "s": 3683, "text": "The Hinge loss function is popular with Support Vector Machines(SVMs). These are used for training the classifiers. Let ‘t’ be the target output such that t = -1 or 1, and the classifier score be ‘y’, then the hinge loss for the prediction is given as: L(y) = max(0, 1-t.y)" }, { "code": null, "e": 3971, "s": 3957, "text": "5. Huber Loss" }, { "code": null, "e": 4291, "s": 3971, "text": "We know that MSE is great for learning outliers while the MAE is great for ignoring them. But what about something in the middle? Consider an example where we have a dataset of 100 values we would like our model to be trained to predict. Out of all that data, 25% of the expected values are 5 while the other 75% is 10." }, { "code": null, "e": 4612, "s": 4291, "text": "An MSE loss wouldn’t quite do the trick since we don’t have “outliers”; 25% is by no means a small fraction. On the other hand, we don’t necessarily want to weight that 25% too low with an MAE. Those values of 5 aren’t close to the median (10 — since 75% of the points have a value of 10), but they’re also not outliers." }, { "code": null, "e": 4637, "s": 4612, "text": "The Huber Loss Function." }, { "code": null, "e": 4779, "s": 4637, "text": "The Huber Loss offers the best of both worlds by balancing the MSE and MAE together. We can define it using the following piecewise function:" }, { "code": null, "e": 4995, "s": 4779, "text": "What this equation actually means is that for loss values less than delta, use the MSE; for loss values greater than delta, use the MAE. This effectively combines the best of both worlds from the two loss functions." }, { "code": null, "e": 5310, "s": 4995, "text": "# function to calculate Huber lossdef huber_loss(y_predicted, y_actual, delta=1.0): huber_mse = 0.5*(y_actual-y_predicted)**2 huber_mae = delta * (np.abs(y_actual - y_predicted) - 0.5 * delta) return np.where(np.abs(y_actual - y_predicted) <= delta, huber_mse, huber_mae)" }, { "code": null, "e": 5612, "s": 5310, "text": "Loss functions provide more than just a static representation of how your model is performing–they’re how your algorithms fit data in the first place. Most machine learning algorithms use some sort of loss function in the process of optimization or finding the best parameters (weights) for your data." }, { "code": null, "e": 5794, "s": 5612, "text": "Importantly, the choice of the loss function is directly related to the activation function used in the output layer of your neural network. These two design elements are connected." }, { "code": null, "e": 6006, "s": 5794, "text": "Think of the configuration of the output layer as a choice about the framing of your prediction problem, and the choice of the loss function as the way to calculate the error for a given framing of your problem." } ]
Explain the performance of Addition and Subtraction with signed magnitude data in computer architecture?
A signed-magnitude method is used by computers to implement floating-point operations. Signed-2’s complement method is used by most computers for arithmetic operations executed on integers. In this approach, the leftmost bit in the number is used for signifying the sign; 0 indicates a positive integer, and 1 indicates a negative integer. The remaining bits in the number supported the magnitude of the number. Example: -2410 is defined as − 10011000 In this example, the leftmost bit 1 defines negative, and the magnitude is 24. The magnitude for both positive and negative values is the same, but they change only with their signs. The range of values for the sign and magnitude representation is from -127 to 127. There are eight conditions to consider while adding or subtracting signed numbers. These conditions are based on the operations implemented and the sign of the numbers. The table displays the algorithm for addition and subtraction. The first column in the table displays these conditions. The other columns of the table define the actual operations to be implemented with the magnitude of numbers. The last column of the table is needed to avoid a negative zero. This defines that when two same numbers are subtracted, the output must not be - 0. It should consistently be +0. In the table, the magnitude of the two numbers is defined by P and Q. Addition and Subtraction of Signed Magnitude Numbers As display in the table, the addition algorithm states that − When the signs of P and Q are equal, add the two magnitudes and connect the sign of P to the output. When the signs of P and Q are equal, add the two magnitudes and connect the sign of P to the output. When the signs of P and Q are different, compare the magnitudes and subtract the smaller number from the greater number. When the signs of P and Q are different, compare the magnitudes and subtract the smaller number from the greater number. The signs of the output have to be equal as P in case P > Q or the complement of the sign of P in case P < Q. The signs of the output have to be equal as P in case P > Q or the complement of the sign of P in case P < Q. When the two magnitudes are equal, subtract Q from P and modify the sign of the output to positive. When the two magnitudes are equal, subtract Q from P and modify the sign of the output to positive. The subtraction algorithm states that − When the signs of P and Q are different, add the two magnitudes and connect the signs of P to the output. When the signs of P and Q are different, add the two magnitudes and connect the signs of P to the output. When the signs of P and Q are the same, compare the magnitudes and subtract the smaller number from the greater number. When the signs of P and Q are the same, compare the magnitudes and subtract the smaller number from the greater number. The signs of the output have to be equal as P in case P > Q or the complement of the sign of P in case P < Q. The signs of the output have to be equal as P in case P > Q or the complement of the sign of P in case P < Q. When the two magnitudes are equal, subtract Q from P and modify the sign of the output to positive. When the two magnitudes are equal, subtract Q from P and modify the sign of the output to positive.
[ { "code": null, "e": 1474, "s": 1062, "text": "A signed-magnitude method is used by computers to implement floating-point operations. Signed-2’s complement method is used by most computers for arithmetic operations executed on integers. In this approach, the leftmost bit in the number is used for signifying the sign; 0 indicates a positive integer, and 1 indicates a negative integer. The remaining bits in the number supported the magnitude of the number." }, { "code": null, "e": 1505, "s": 1474, "text": "Example: -2410 is defined as −" }, { "code": null, "e": 1514, "s": 1505, "text": "10011000" }, { "code": null, "e": 1593, "s": 1514, "text": "In this example, the leftmost bit 1 defines negative, and the magnitude is 24." }, { "code": null, "e": 1697, "s": 1593, "text": "The magnitude for both positive and negative values is the same, but they change only with their signs." }, { "code": null, "e": 1780, "s": 1697, "text": "The range of values for the sign and magnitude representation is from -127 to 127." }, { "code": null, "e": 1949, "s": 1780, "text": "There are eight conditions to consider while adding or subtracting signed numbers. These conditions are based on the operations implemented and the sign of the numbers." }, { "code": null, "e": 2357, "s": 1949, "text": "The table displays the algorithm for addition and subtraction. The first column in the table displays these conditions. The other columns of the table define the actual operations to be implemented with the magnitude of numbers. The last column of the table is needed to avoid a negative zero. This defines that when two same numbers are subtracted, the output must not be - 0. It should consistently be +0." }, { "code": null, "e": 2427, "s": 2357, "text": "In the table, the magnitude of the two numbers is defined by P and Q." }, { "code": null, "e": 2480, "s": 2427, "text": "Addition and Subtraction of Signed Magnitude Numbers" }, { "code": null, "e": 2542, "s": 2480, "text": "As display in the table, the addition algorithm states that −" }, { "code": null, "e": 2643, "s": 2542, "text": "When the signs of P and Q are equal, add the two magnitudes and connect the sign of P to the output." }, { "code": null, "e": 2744, "s": 2643, "text": "When the signs of P and Q are equal, add the two magnitudes and connect the sign of P to the output." }, { "code": null, "e": 2865, "s": 2744, "text": "When the signs of P and Q are different, compare the magnitudes and subtract the smaller number from the greater number." }, { "code": null, "e": 2986, "s": 2865, "text": "When the signs of P and Q are different, compare the magnitudes and subtract the smaller number from the greater number." }, { "code": null, "e": 3096, "s": 2986, "text": "The signs of the output have to be equal as P in case P > Q or the complement of the sign of P in case P < Q." }, { "code": null, "e": 3206, "s": 3096, "text": "The signs of the output have to be equal as P in case P > Q or the complement of the sign of P in case P < Q." }, { "code": null, "e": 3306, "s": 3206, "text": "When the two magnitudes are equal, subtract Q from P and modify the sign of the output to positive." }, { "code": null, "e": 3406, "s": 3306, "text": "When the two magnitudes are equal, subtract Q from P and modify the sign of the output to positive." }, { "code": null, "e": 3446, "s": 3406, "text": "The subtraction algorithm states that −" }, { "code": null, "e": 3552, "s": 3446, "text": "When the signs of P and Q are different, add the two magnitudes and connect the signs of P to the output." }, { "code": null, "e": 3658, "s": 3552, "text": "When the signs of P and Q are different, add the two magnitudes and connect the signs of P to the output." }, { "code": null, "e": 3778, "s": 3658, "text": "When the signs of P and Q are the same, compare the magnitudes and subtract the smaller number from the greater number." }, { "code": null, "e": 3898, "s": 3778, "text": "When the signs of P and Q are the same, compare the magnitudes and subtract the smaller number from the greater number." }, { "code": null, "e": 4008, "s": 3898, "text": "The signs of the output have to be equal as P in case P > Q or the complement of the sign of P in case P < Q." }, { "code": null, "e": 4118, "s": 4008, "text": "The signs of the output have to be equal as P in case P > Q or the complement of the sign of P in case P < Q." }, { "code": null, "e": 4218, "s": 4118, "text": "When the two magnitudes are equal, subtract Q from P and modify the sign of the output to positive." }, { "code": null, "e": 4318, "s": 4218, "text": "When the two magnitudes are equal, subtract Q from P and modify the sign of the output to positive." } ]
Python Number min() Method
Python number method min() returns the smallest of its arguments: the value closest to negative infinity. Following is the syntax for min() method − min( x, y, z, .... ) x − This is a numeric expression. x − This is a numeric expression. y − This is also a numeric expression. y − This is also a numeric expression. z − This is also a numeric expression. z − This is also a numeric expression. This method returns smallest of its arguments. The following example shows the usage of min() method. #!/usr/bin/python print "min(80, 100, 1000) : ", min(80, 100, 1000) print "min(-20, 100, 400) : ", min(-20, 100, 400) print "min(-80, -20, -10) : ", min(-80, -20, -10) print "min(0, 100, -400) : ", min(0, 100, -400) When we run above program, it produces following result − min(80, 100, 1000) : 80 min(-20, 100, 400) : -20 min(-80, -20, -10) : -80 min(0, 100, -400) : -400 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": 2351, "s": 2244, "text": "Python number method min() returns the smallest of its arguments: the value closest to negative infinity." }, { "code": null, "e": 2394, "s": 2351, "text": "Following is the syntax for min() method −" }, { "code": null, "e": 2416, "s": 2394, "text": "min( x, y, z, .... )\n" }, { "code": null, "e": 2450, "s": 2416, "text": "x − This is a numeric expression." }, { "code": null, "e": 2484, "s": 2450, "text": "x − This is a numeric expression." }, { "code": null, "e": 2523, "s": 2484, "text": "y − This is also a numeric expression." }, { "code": null, "e": 2562, "s": 2523, "text": "y − This is also a numeric expression." }, { "code": null, "e": 2601, "s": 2562, "text": "z − This is also a numeric expression." }, { "code": null, "e": 2640, "s": 2601, "text": "z − This is also a numeric expression." }, { "code": null, "e": 2687, "s": 2640, "text": "This method returns smallest of its arguments." }, { "code": null, "e": 2742, "s": 2687, "text": "The following example shows the usage of min() method." }, { "code": null, "e": 2959, "s": 2742, "text": "#!/usr/bin/python\n\nprint \"min(80, 100, 1000) : \", min(80, 100, 1000)\nprint \"min(-20, 100, 400) : \", min(-20, 100, 400)\nprint \"min(-80, -20, -10) : \", min(-80, -20, -10)\nprint \"min(0, 100, -400) : \", min(0, 100, -400)" }, { "code": null, "e": 3017, "s": 2959, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 3121, "s": 3017, "text": "min(80, 100, 1000) : 80\nmin(-20, 100, 400) : -20\nmin(-80, -20, -10) : -80\nmin(0, 100, -400) : -400\n" }, { "code": null, "e": 3158, "s": 3121, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3174, "s": 3158, "text": " Malhar Lathkar" }, { "code": null, "e": 3207, "s": 3174, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3226, "s": 3207, "text": " Arnab Chakraborty" }, { "code": null, "e": 3261, "s": 3226, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3283, "s": 3261, "text": " In28Minutes Official" }, { "code": null, "e": 3317, "s": 3283, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3345, "s": 3317, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3380, "s": 3345, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3394, "s": 3380, "text": " Lets Kode It" }, { "code": null, "e": 3427, "s": 3394, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3444, "s": 3427, "text": " Abhilash Nelson" }, { "code": null, "e": 3451, "s": 3444, "text": " Print" }, { "code": null, "e": 3462, "s": 3451, "text": " Add Notes" } ]
How we can update a Python tuple element value?
Python tuple is an immutable object. Hence any operation that tries to update it is not allowed. However, following workaround can be used. First, convert tuple to list by built-in function list(). You can always update an item to list object assigning new value to element at certain index. Then use another built-in function tuple() to convert this list object back to tuple. >>> T1=(10,50,20,9,40,25,60,30,1,56) >>> L1=list(T1) >>> L1[5]=100 >>> T1=tuple(L1) >>> T1 (10, 50, 20, 9, 40, 100, 60, 30, 1, 56) Element at index 4 in original tuple has been changed from 25 to 100.
[ { "code": null, "e": 1327, "s": 1187, "text": "Python tuple is an immutable object. Hence any operation that tries to update it is not allowed. However, following workaround can be used." }, { "code": null, "e": 1565, "s": 1327, "text": "First, convert tuple to list by built-in function list(). You can always update an item to list object assigning new value to element at certain index. Then use another built-in function tuple() to convert this list object back to tuple." }, { "code": null, "e": 1696, "s": 1565, "text": ">>> T1=(10,50,20,9,40,25,60,30,1,56)\n>>> L1=list(T1)\n>>> L1[5]=100\n>>> T1=tuple(L1)\n>>> T1\n(10, 50, 20, 9, 40, 100, 60, 30, 1, 56)" }, { "code": null, "e": 1766, "s": 1696, "text": "Element at index 4 in original tuple has been changed from 25 to 100." } ]
Signals in C language
08 Feb, 2018 Prerequisite : Fork system call, Wait system callA signal is a software generated interrupt that is sent to a process by the OS because of when user press ctrl-c or another process tell something to this process.There are fix set of signals that can be sent to a process. signal are identified by integers.Signal number have symbolic names. For example SIGCHLD is number of the signal sent to the parent process when child terminates.Examples: #define SIGHUP 1 /* Hangup the process */ #define SIGINT 2 /* Interrupt the process */ #define SIGQUIT 3 /* Quit the process */ #define SIGILL 4 /* Illegal instruction. */ #define SIGTRAP 5 /* Trace trap. */ #define SIGABRT 6 /* Abort. */ OS Structures for Signals For each process, the operating system maintains 2 integers with the bits corresponding to a signal numbers. The two integers keep track of: pending signals and blocked signals With 32 bit integers, up to 32 different signals can be represented. Example :In the example below, the SIGINT ( = 2) signal is blocked and no signals are pending. A signal is sent to a process setting the corresponding bit in the pending signals integer for the process. Each time the OS selects a process to be run on a processor, the pending and blocked integers are checked. If no signals are pending, the process is restarted normally and continues executing at its next instruction. If 1 or more signals are pending, but each one is blocked, the process is also restarted normally but with the signals still marked as pending. If 1 or more signals are pending and NOT blocked, the OS executes the routines in the process’s code to handle the signals. Default Signal Handlers There are several default signal handler routines. Each signal is associated with one of these default handler routine. The different default handler routines typically have one of the following actions: Ign: Ignore the signal; i.e., do nothing, just return Term: terminate the process Cont: unblock a stopped process Stop: block the process // CPP program to illustrate// default Signal Handler#include<stdio.h>#include<signal.h> int main(){ signal(SIGINT, handle_sigint); while (1) { printf(“hello world\n”); sleep(1); } return 0;} Output: Print hello world infinite times. If user presses ctrl-c to terminate the process because of SIGINT signal sent and its default handler to terminate the process. hello world hello world hello world terminated User Defined Signal Handlers A process can replace the default signal handler for almost all signals (but not SIGKILL) by its user’s own handler function.A signal handler function can have any name, but must have return type void and have one int parameter.Example: you might choose the name sigchld_handler for a signal handler for the SIGCHLD signal (termination of a child process). Then the declaration would be: void sigchld_handler(int sig); When a signal handler executes, the parameter passed to it is the number of the signal. A programmer can use the same signal handler function to handle several signals. In this case the handler would need to check the parameter to see which signal was sent. On the other hand, if a signal handler function only handles one signal, it isn’t necessary to bother examining the parameter since it will always be that signal number. // CPP program to illustrate// User-defined Signal Handler#include<stdio.h>#include<signal.h> // Handler for SIGINT, caused by// Ctrl-C at keyboardvoid handle_sigint(int sig){ printf("Caught signal %d\n", sig);} int main(){ signal(SIGINT, handle_sigint); while (1) ; return 0;} Output: ^CCaught signal 2 // when user presses ctrl-c ^CCaught signal 2 Sending signals via kill() We can send a signal using kill() to the process. int kill(pid_t pid, int signal); pid: id of destination process signal: the type of signal to send Return value: 0 if signal was sent successfully Example: pid_t iPid = getpid(); /* Process gets its id.*/ kill(iPid, SIGINT); /* Process sends itself a SIGINT signal (commits suicide?)(because of SIGINT signal default handler is terminate the process) */ Questions 1. What is the Output of the following program? #include<stdio.h>#include<wait.h>#include<signal.h>int main(){ int stat; pid_t pid; if ((pid = fork()) == 0) while(1) ; else { kill(pid, SIGINT); wait(&stat); if (WIFSIGNALED(stat)) psignal(WTERMSIG(stat), "Child term due to"); }} Output: Child term due to: Interrupt 2. What is the Output of the following program? #include<stdio.h>#include<signal.h>#include<wait.h>int val = 10;void handler(int sig){ val += 5;}int main(){ pid_t pid; signal(SIGCHLD, handler); if ((pid = fork()) == 0) { val -= 3; exit(0); } waitpid(pid, NULL, 0); printf("val = %d\n", val); exit(0);} Output: val = 15 3. Consider the following code. What is the output? #include<stdio.h>#include<wait.h>#include<signal.h>pid_t pid;int counter = 0;void handler1(int sig){ counter++; printf("counter = %d\n", counter); /* Flushes the printed string to stdout */ fflush(stdout); kill(pid, SIGUSR1);}void handler2(int sig){ counter += 3; printf("counter = %d\n", counter); exit(0);} int main(){ pid_t p; int status; signal(SIGUSR1, handler1); if ((pid = fork()) == 0) { signal(SIGUSR1, handler2); kill(getppid(), SIGUSR1); while(1) ; } if ((p = wait(&status)) > 0) { counter += 4; printf("counter = %d\n", counter); }} Output counter = 1 //(parent’s handler) counter = 3 //(child’s handler) counter = 5 //(parent’s main) This article is contributed by Kadam Patel. 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. C-Library system-programming C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Different Methods to Reverse a String in C++ std::string class in C++ Unordered Sets in C++ Standard Template Library Enumeration (or enum) in C What is the purpose of a function prototype? C Language Introduction Memory Layout of C Programs Operators in C / C++
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Feb, 2018" }, { "code": null, "e": 498, "s": 54, "text": "Prerequisite : Fork system call, Wait system callA signal is a software generated interrupt that is sent to a process by the OS because of when user press ctrl-c or another process tell something to this process.There are fix set of signals that can be sent to a process. signal are identified by integers.Signal number have symbolic names. For example SIGCHLD is number of the signal sent to the parent process when child terminates.Examples:" }, { "code": null, "e": 758, "s": 498, "text": "#define SIGHUP 1 /* Hangup the process */ \n#define SIGINT 2 /* Interrupt the process */ \n#define SIGQUIT 3 /* Quit the process */ \n#define SIGILL 4 /* Illegal instruction. */ \n#define SIGTRAP 5 /* Trace trap. */ \n#define SIGABRT 6 /* Abort. */\n" }, { "code": null, "e": 784, "s": 758, "text": "OS Structures for Signals" }, { "code": null, "e": 893, "s": 784, "text": "For each process, the operating system maintains 2 integers with the bits corresponding to a signal numbers." }, { "code": null, "e": 961, "s": 893, "text": "The two integers keep track of: pending signals and blocked signals" }, { "code": null, "e": 1030, "s": 961, "text": "With 32 bit integers, up to 32 different signals can be represented." }, { "code": null, "e": 1125, "s": 1030, "text": "Example :In the example below, the SIGINT ( = 2) signal is blocked and no signals are pending." }, { "code": null, "e": 1450, "s": 1125, "text": "A signal is sent to a process setting the corresponding bit in the pending signals integer for the process. Each time the OS selects a process to be run on a processor, the pending and blocked integers are checked. If no signals are pending, the process is restarted normally and continues executing at its next instruction." }, { "code": null, "e": 1718, "s": 1450, "text": "If 1 or more signals are pending, but each one is blocked, the process is also restarted normally but with the signals still marked as pending. If 1 or more signals are pending and NOT blocked, the OS executes the routines in the process’s code to handle the signals." }, { "code": null, "e": 1742, "s": 1718, "text": "Default Signal Handlers" }, { "code": null, "e": 1946, "s": 1742, "text": "There are several default signal handler routines. Each signal is associated with one of these default handler routine. The different default handler routines typically have one of the following actions:" }, { "code": null, "e": 2000, "s": 1946, "text": "Ign: Ignore the signal; i.e., do nothing, just return" }, { "code": null, "e": 2028, "s": 2000, "text": "Term: terminate the process" }, { "code": null, "e": 2060, "s": 2028, "text": "Cont: unblock a stopped process" }, { "code": null, "e": 2084, "s": 2060, "text": "Stop: block the process" }, { "code": "// CPP program to illustrate// default Signal Handler#include<stdio.h>#include<signal.h> int main(){ signal(SIGINT, handle_sigint); while (1) { printf(“hello world\\n”); sleep(1); } return 0;}", "e": 2306, "s": 2084, "text": null }, { "code": null, "e": 2476, "s": 2306, "text": "Output: Print hello world infinite times. If user presses ctrl-c to terminate the process because of SIGINT signal sent and its default handler to terminate the process." }, { "code": null, "e": 2555, "s": 2476, "text": "hello world \nhello world \nhello world \nterminated \n" }, { "code": null, "e": 2584, "s": 2555, "text": "User Defined Signal Handlers" }, { "code": null, "e": 2972, "s": 2584, "text": "A process can replace the default signal handler for almost all signals (but not SIGKILL) by its user’s own handler function.A signal handler function can have any name, but must have return type void and have one int parameter.Example: you might choose the name sigchld_handler for a signal handler for the SIGCHLD signal (termination of a child process). Then the declaration would be:" }, { "code": null, "e": 3003, "s": 2972, "text": "void sigchld_handler(int sig);" }, { "code": null, "e": 3431, "s": 3003, "text": "When a signal handler executes, the parameter passed to it is the number of the signal. A programmer can use the same signal handler function to handle several signals. In this case the handler would need to check the parameter to see which signal was sent. On the other hand, if a signal handler function only handles one signal, it isn’t necessary to bother examining the parameter since it will always be that signal number." }, { "code": "// CPP program to illustrate// User-defined Signal Handler#include<stdio.h>#include<signal.h> // Handler for SIGINT, caused by// Ctrl-C at keyboardvoid handle_sigint(int sig){ printf(\"Caught signal %d\\n\", sig);} int main(){ signal(SIGINT, handle_sigint); while (1) ; return 0;}", "e": 3723, "s": 3431, "text": null }, { "code": null, "e": 3731, "s": 3723, "text": "Output:" }, { "code": null, "e": 3798, "s": 3731, "text": "^CCaught signal 2 // when user presses ctrl-c\n^CCaught signal 2 \n" }, { "code": null, "e": 3825, "s": 3798, "text": "Sending signals via kill()" }, { "code": null, "e": 3875, "s": 3825, "text": "We can send a signal using kill() to the process." }, { "code": null, "e": 4022, "s": 3875, "text": "int kill(pid_t pid, int signal);\npid: id of destination process\nsignal: the type of signal to send\nReturn value: 0 if signal was sent successfully" }, { "code": null, "e": 4031, "s": 4022, "text": "Example:" }, { "code": null, "e": 4244, "s": 4031, "text": "pid_t iPid = getpid(); /* Process gets its id.*/\nkill(iPid, SIGINT); /* Process sends itself a SIGINT signal \n(commits suicide?)(because of SIGINT \nsignal default handler is terminate the process) */\n " }, { "code": null, "e": 4254, "s": 4244, "text": "Questions" }, { "code": null, "e": 4302, "s": 4254, "text": "1. What is the Output of the following program?" }, { "code": "#include<stdio.h>#include<wait.h>#include<signal.h>int main(){ int stat; pid_t pid; if ((pid = fork()) == 0) while(1) ; else { kill(pid, SIGINT); wait(&stat); if (WIFSIGNALED(stat)) psignal(WTERMSIG(stat), \"Child term due to\"); }}", "e": 4590, "s": 4302, "text": null }, { "code": null, "e": 4598, "s": 4590, "text": "Output:" }, { "code": null, "e": 4629, "s": 4598, "text": " Child term due to: Interrupt\n" }, { "code": null, "e": 4677, "s": 4629, "text": "2. What is the Output of the following program?" }, { "code": "#include<stdio.h>#include<signal.h>#include<wait.h>int val = 10;void handler(int sig){ val += 5;}int main(){ pid_t pid; signal(SIGCHLD, handler); if ((pid = fork()) == 0) { val -= 3; exit(0); } waitpid(pid, NULL, 0); printf(\"val = %d\\n\", val); exit(0);}", "e": 4972, "s": 4677, "text": null }, { "code": null, "e": 4980, "s": 4972, "text": "Output:" }, { "code": null, "e": 4991, "s": 4980, "text": "val = 15 \n" }, { "code": null, "e": 5043, "s": 4991, "text": "3. Consider the following code. What is the output?" }, { "code": "#include<stdio.h>#include<wait.h>#include<signal.h>pid_t pid;int counter = 0;void handler1(int sig){ counter++; printf(\"counter = %d\\n\", counter); /* Flushes the printed string to stdout */ fflush(stdout); kill(pid, SIGUSR1);}void handler2(int sig){ counter += 3; printf(\"counter = %d\\n\", counter); exit(0);} int main(){ pid_t p; int status; signal(SIGUSR1, handler1); if ((pid = fork()) == 0) { signal(SIGUSR1, handler2); kill(getppid(), SIGUSR1); while(1) ; } if ((p = wait(&status)) > 0) { counter += 4; printf(\"counter = %d\\n\", counter); }}", "e": 5675, "s": 5043, "text": null }, { "code": null, "e": 5682, "s": 5675, "text": "Output" }, { "code": null, "e": 5805, "s": 5682, "text": "counter = 1 //(parent’s handler) \ncounter = 3 //(child’s handler) \ncounter = 5 //(parent’s main) \n" }, { "code": null, "e": 6104, "s": 5805, "text": "This article is contributed by Kadam Patel. 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": 6229, "s": 6104, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 6239, "s": 6229, "text": "C-Library" }, { "code": null, "e": 6258, "s": 6239, "text": "system-programming" }, { "code": null, "e": 6269, "s": 6258, "text": "C Language" }, { "code": null, "e": 6367, "s": 6269, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6384, "s": 6367, "text": "Substring in C++" }, { "code": null, "e": 6406, "s": 6384, "text": "Function Pointer in C" }, { "code": null, "e": 6451, "s": 6406, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 6476, "s": 6451, "text": "std::string class in C++" }, { "code": null, "e": 6524, "s": 6476, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 6551, "s": 6524, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 6596, "s": 6551, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 6620, "s": 6596, "text": "C Language Introduction" }, { "code": null, "e": 6648, "s": 6620, "text": "Memory Layout of C Programs" } ]
Shallow Copy and Deep Copy in C++
16 Jun, 2022 In general, creating a copy of an object means to create an exact replica of the object having the same literal value, data type, and resources. Copy Constructor Default assignment operator // Copy ConstructorGeeks Obj1(Obj);orGeeks Obj1 = Obj; // Default assignment operatorGeeks Obj2;Obj2 = Obj1; Depending upon the resources like dynamic memory held by the object, either we need to perform Shallow Copy or Deep Copy in order to create a replica of the object. In general, if the variables of an object have been dynamically allocated, then it is required to do a Deep Copy in order to create a copy of the object. In shallow copy, an object is created by simply copying the data of all variables of the original object. This works well if none of the variables of the object are defined in the heap section of memory. If some variables are dynamically allocated memory from heap section, then the copied object variable will also reference the same memory location.This will create ambiguity and run-time errors, dangling pointer. Since both objects will reference to the same memory location, then change made by one will reflect those change in another object as well. Since we wanted to create a replica of the object, this purpose will not be filled by Shallow copy. Note: C++ compiler implicitly creates a copy constructor and overloads assignment operator in order to perform shallow copy at compile time. Shallow Copy of object if some variables are defined in heap memory, then: Below is the implementation of the above approach: C++ // C++ program for the above approach#include <iostream>using namespace std; // Box Classclass box {private: int length; int breadth; int height; public: // Function that sets the dimensions void set_dimensions(int length1, int breadth1, int height1) { length = length1; breadth = breadth1; height = height1; } // Function to display the dimensions // of the Box object void show_data() { cout << " Length = " << length << "\n Breadth = " << breadth << "\n Height = " << height << endl; }}; // Driver Codeint main(){ // Object of class Box box B1, B3; // Set dimensions of Box B1 B1.set_dimensions(14, 12, 16); B1.show_data(); // When copying the data of object // at the time of initialization // then copy is made through // COPY CONSTRUCTOR box B2 = B1; B2.show_data(); // When copying the data of object // after initialization then the // copy is done through DEFAULT // ASSIGNMENT OPERATOR B3 = B1; B3.show_data(); return 0;} Length = 14 Breadth = 12 Height = 16 Length = 14 Breadth = 12 Height = 16 Length = 14 Breadth = 12 Height = 16 In Deep copy, an object is created by copying data of all variables, and it also allocates similar memory resources with the same value to the object. In order to perform Deep copy, we need to explicitly define the copy constructor and assign dynamic memory as well, if required. Also, it is required to dynamically allocate memory to the variables in the other constructors, as well. Below is the implementation of the above approach: C++ // C++ program to implement the// deep copy#include <iostream>using namespace std; // Box Classclass box {private: int length; int* breadth; int height; public: // Constructor box() { breadth = new int; } // Function to set the dimensions // of the Box void set_dimension(int len, int brea, int heig) { length = len; *breadth = brea; height = heig; } // Function to show the dimensions // of the Box void show_data() { cout << " Length = " << length << "\n Breadth = " << *breadth << "\n Height = " << height << endl; } // Parameterized Constructors for // for implementing deep copy box(box& sample) { length = sample.length; breadth = new int; *breadth = *(sample.breadth); height = sample.height; } // Destructors ~box() { delete breadth; }}; // Driver Codeint main(){ // Object of class first box first; // Set the dimensions first.set_dimension(12, 14, 16); // Display the dimensions first.show_data(); // When the data will be copied then // all the resources will also get // allocated to the new object box second = first; // Display the dimensions second.show_data(); return 0;} Length = 12 Breadth = 14 Height = 16 Length = 12 Breadth = 14 Height = 16 Let us see the differences in a tabular form -: mayank007rawa jayanth_mkv Constructors cpp-constructor C++ C++ Programs Difference Between Programming Language CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Priority Queue in C++ Standard Template Library (STL) Substring in C++ Header files in C/C++ and its uses Sorting a Map by value in C++ STL Program to print ASCII Value of a character How to return multiple values from a function in C or C++? C++ program for hashing with chaining
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jun, 2022" }, { "code": null, "e": 197, "s": 52, "text": "In general, creating a copy of an object means to create an exact replica of the object having the same literal value, data type, and resources." }, { "code": null, "e": 214, "s": 197, "text": "Copy Constructor" }, { "code": null, "e": 242, "s": 214, "text": "Default assignment operator" }, { "code": null, "e": 297, "s": 242, "text": "// Copy ConstructorGeeks Obj1(Obj);orGeeks Obj1 = Obj;" }, { "code": null, "e": 351, "s": 297, "text": "// Default assignment operatorGeeks Obj2;Obj2 = Obj1;" }, { "code": null, "e": 670, "s": 351, "text": "Depending upon the resources like dynamic memory held by the object, either we need to perform Shallow Copy or Deep Copy in order to create a replica of the object. In general, if the variables of an object have been dynamically allocated, then it is required to do a Deep Copy in order to create a copy of the object." }, { "code": null, "e": 1469, "s": 670, "text": "In shallow copy, an object is created by simply copying the data of all variables of the original object. This works well if none of the variables of the object are defined in the heap section of memory. If some variables are dynamically allocated memory from heap section, then the copied object variable will also reference the same memory location.This will create ambiguity and run-time errors, dangling pointer. Since both objects will reference to the same memory location, then change made by one will reflect those change in another object as well. Since we wanted to create a replica of the object, this purpose will not be filled by Shallow copy. Note: C++ compiler implicitly creates a copy constructor and overloads assignment operator in order to perform shallow copy at compile time. " }, { "code": null, "e": 1544, "s": 1469, "text": "Shallow Copy of object if some variables are defined in heap memory, then:" }, { "code": null, "e": 1595, "s": 1544, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1599, "s": 1595, "text": "C++" }, { "code": "// C++ program for the above approach#include <iostream>using namespace std; // Box Classclass box {private: int length; int breadth; int height; public: // Function that sets the dimensions void set_dimensions(int length1, int breadth1, int height1) { length = length1; breadth = breadth1; height = height1; } // Function to display the dimensions // of the Box object void show_data() { cout << \" Length = \" << length << \"\\n Breadth = \" << breadth << \"\\n Height = \" << height << endl; }}; // Driver Codeint main(){ // Object of class Box box B1, B3; // Set dimensions of Box B1 B1.set_dimensions(14, 12, 16); B1.show_data(); // When copying the data of object // at the time of initialization // then copy is made through // COPY CONSTRUCTOR box B2 = B1; B2.show_data(); // When copying the data of object // after initialization then the // copy is done through DEFAULT // ASSIGNMENT OPERATOR B3 = B1; B3.show_data(); return 0;}", "e": 2713, "s": 1599, "text": null }, { "code": null, "e": 2832, "s": 2713, "text": "Length = 14\n Breadth = 12\n Height = 16\n Length = 14\n Breadth = 12\n Height = 16\n Length = 14\n Breadth = 12\n Height = 16" }, { "code": null, "e": 3217, "s": 2832, "text": "In Deep copy, an object is created by copying data of all variables, and it also allocates similar memory resources with the same value to the object. In order to perform Deep copy, we need to explicitly define the copy constructor and assign dynamic memory as well, if required. Also, it is required to dynamically allocate memory to the variables in the other constructors, as well." }, { "code": null, "e": 3268, "s": 3217, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 3272, "s": 3268, "text": "C++" }, { "code": "// C++ program to implement the// deep copy#include <iostream>using namespace std; // Box Classclass box {private: int length; int* breadth; int height; public: // Constructor box() { breadth = new int; } // Function to set the dimensions // of the Box void set_dimension(int len, int brea, int heig) { length = len; *breadth = brea; height = heig; } // Function to show the dimensions // of the Box void show_data() { cout << \" Length = \" << length << \"\\n Breadth = \" << *breadth << \"\\n Height = \" << height << endl; } // Parameterized Constructors for // for implementing deep copy box(box& sample) { length = sample.length; breadth = new int; *breadth = *(sample.breadth); height = sample.height; } // Destructors ~box() { delete breadth; }}; // Driver Codeint main(){ // Object of class first box first; // Set the dimensions first.set_dimension(12, 14, 16); // Display the dimensions first.show_data(); // When the data will be copied then // all the resources will also get // allocated to the new object box second = first; // Display the dimensions second.show_data(); return 0;}", "e": 4614, "s": 3272, "text": null }, { "code": null, "e": 4693, "s": 4614, "text": "Length = 12\n Breadth = 14\n Height = 16\n Length = 12\n Breadth = 14\n Height = 16" }, { "code": null, "e": 4741, "s": 4693, "text": "Let us see the differences in a tabular form -:" }, { "code": null, "e": 4755, "s": 4741, "text": "mayank007rawa" }, { "code": null, "e": 4767, "s": 4755, "text": "jayanth_mkv" }, { "code": null, "e": 4780, "s": 4767, "text": "Constructors" }, { "code": null, "e": 4796, "s": 4780, "text": "cpp-constructor" }, { "code": null, "e": 4800, "s": 4796, "text": "C++" }, { "code": null, "e": 4813, "s": 4800, "text": "C++ Programs" }, { "code": null, "e": 4832, "s": 4813, "text": "Difference Between" }, { "code": null, "e": 4853, "s": 4832, "text": "Programming Language" }, { "code": null, "e": 4857, "s": 4853, "text": "CPP" }, { "code": null, "e": 4955, "s": 4857, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4998, "s": 4955, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 5032, "s": 4998, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 5057, "s": 5032, "text": "unordered_map in C++ STL" }, { "code": null, "e": 5111, "s": 5057, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 5128, "s": 5111, "text": "Substring in C++" }, { "code": null, "e": 5163, "s": 5128, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 5197, "s": 5163, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 5241, "s": 5197, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 5300, "s": 5241, "text": "How to return multiple values from a function in C or C++?" } ]
Find the number of paths of length K in a directed graph
19 Jul, 2021 Given a directed, unweighted graph with N vertices and an integer K. The task is to find the number of paths of length K for each pair of vertices (u, v). Paths don’t have to be simple i.e. vertices and edges can be visited any number of times in a single path. The graph is represented as adjacency matrix where the value G[i][j] = 1 indicates that there is an edge from vertex i to vertex j and G[i][j] = 0 indicates no edge from i to j.Examples: Input: K = 2, Output: 1 2 2 0 1 0 0 0 1 Number of paths from 0 to 0 of length k is 1({0->0->0}) Number of paths from 0 to 1 of length k are 2({0->0->1}, {0->2->1}) Number of paths from 0 to 2 of length k are 2({0->0->2}, {0->1->2}) Number of paths from 1 to 1 of length k is 1({1->2->1}) Number of paths from 2 to 2 of length k is 1({2->1->2})Input: K = 3, Output: 1 0 0 0 1 0 0 0 1 Number of paths from 0 to 0 of length k is 1({0->1->2->0}) Number of paths from 1 to 1 of length k is 1({1->2->0->1}) Number of paths from 2 to 2 of length k is 1({2->1->0->2}) Prerequisite: Matrix exponentiation, Matrix multiplicationApproach: It is obvious that given adjacency matrix is the answer to the problem for the case k = 1. It contains the number of paths of length 1 between each pair of vertices. Let’s assume that the answer for some k is Matk and the answer for k + 1 is Matk + 1. Matk + 1[i][j] = ∑p = 1NMatk[i][p]*G[p][j]It is easy to see that the formula computes nothing other than the product of the matrices Matk and G i.e. Matk + 1 = Matk * GThus, the solution of the problem can be represented as Matk = G * G * ... * G(k times) = GkBelow is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define N 3 // Function to multiply two matricesvoid multiply(int a[][N], int b[][N], int res[][N]){ int mul[N][N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { mul[i][j] = 0; for (int k = 0; k < N; k++) mul[i][j] += a[i][k] * b[k][j]; } } // Storing the multiplication result in res[][] for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) res[i][j] = mul[i][j];} // Function to compute G raised to the power nvoid power(int G[N][N], int res[N][N], int n){ // Base condition if (n == 1) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) res[i][j] = G[i][j]; return; } // Recursion call for first half power(G, res, n / 2); // Multiply two halves multiply(res, res, res); // If n is odd if (n % 2 != 0) multiply(res, G, res);} // Driver codeint main(){ int G[N][N] = { { 1, 1, 1 }, { 0, 0, 1 }, { 0, 1, 0 } }; int k = 2, res[N][N]; power(G, res, k); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << res[i][j] << " "; cout << "\n"; } return 0;}// This Code is improved by cidacoder // Java implementation of the approachclass GFG{ static int N = 3; // Function to multiply two matricesstatic void multiply(int a[][], int b[][], int res[][]){ int [][]mul = new int[N][N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { mul[i][j] = 0; for (int k = 0; k < N; k++) mul[i][j] += a[i][k] * b[k][j]; } } // Storing the multiplication result in res[][] for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) res[i][j] = mul[i][j];} // Function to compute G raised to the power nstatic void power(int G[][], int res[][], int n){ // Base condition if (n == 1) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) res[i][j] = G[i][j]; return; } // Recursion call for first half power(G, res, n / 2); multiply(res, res, res); // If n is odd if (n % 2 != 0) multiply(res, G, res);} // Driver codepublic static void main(String[] args){ int G[][] = { { 1, 1, 1 }, { 0, 0, 1 }, { 0, 1, 0 } }; int k = 2; int [][]res = new int[N][N]; power(G, res, k); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(res[i][j] + " "); System.out.println(""); }}} // This code is contributed by 29AjayKumar// This Code is improved by cidacoder # Python3 implementation of the approach import numpy as np N = 3 # Function to multiply two matricesdef multiply(a, b, res) : mul = np.zeros((N,N)); for i in range(N) : for j in range(N) : mul[i][j] = 0; for k in range(N) : mul[i][j] += a[i][k] * b[k][j]; # Storing the multiplication result in res[][] for i in range(N) : for j in range(N) : res[i][j] = mul[i][j]; # Function to compute G raised to the power ndef power(G, res, n) : # Base condition if (n == 1) : for i in range(N) : for j in range(N) : res[i][j] = G[i][j]; return; # Recursion call for first half power(G, res, n // 2); # Multiply two halves multiply(res, res, res); # If n is odd if (n % 2 != 0) : multiply(res, G, res); # Driver codeif __name__ == "__main__" : G = [ [ 1, 1, 1 ], [ 0, 0, 1 ], [ 0, 1, 0 ] ]; k = 2; res = np.zeros((N,N)); power(G, res, k); for i in range(N) : for j in range(N) : print(res[i][j],end = " "); print() # This code is contributed by AnkitRai01# This Code is improved by cidacoder // C# implementation of the approachusing System; class GFG{ static int N = 3; // Function to multiply two matricesstatic void multiply(int [,]a, int [,]b, int [,]res){ int [,]mul = new int[N,N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { mul[i,j] = 0; for (int k = 0; k < N; k++) mul[i,j] += a[i,k] * b[k,j]; } } // Storing the multiplication result in res[][] for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) res[i,j] = mul[i,j];} // Function to compute G raised to the power nstatic void power(int [,]G, int [,]res, int n){ // Base condition if (n == 1) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) res[i,j] = G[i,j]; return; } // Recursion call for first half power(G, res, n / 2); // Multiply two halves multiply(res, res, res); // If n is odd if (n % 2 != 0) multiply(res, G, res);} // Driver codepublic static void Main(){ int [,]G = { { 1, 1, 1 }, { 0, 0, 1 }, { 0, 1, 0 } }; int k = 2; int [,]res = new int[N,N]; power(G, res, k); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(res[i,j] + " "); Console.WriteLine(""); }}} // This code is contributed by anuj_67..// This code is improved by cidacoder <script> // Javascript implementation of the approach let N = 3; // Function to multiply two matrices function multiply(a, b, res) { let mul = new Array(N); for (let i = 0; i < N; i++) { mul[i] = new Array(N); for (let j = 0; j < N; j++) { mul[i][j] = 0; for (let k = 0; k < N; k++) mul[i][j] += a[i][k] * b[k][j]; } } // Storing the multiplication result in res[][] for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) res[i][j] = mul[i][j]; } // Function to compute G raised to the power n function power(G, res, n) { // Base condition if (n == 1) { for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) res[i][j] = G[i][j]; return; } // Recursion call for first half power(G, res, parseInt(n / 2, 10)); // Multiply two halves multiply(res, res, res); // If n is odd if (n % 2 != 0) multiply(res, G, res); } let G = [ [ 1, 1, 1 ], [ 0, 0, 1 ], [ 0, 1, 0 ] ]; let k = 2; let res = new Array(N); for (let i = 0; i < N; i++) { res[i] = new Array(N); for (let j = 0; j < N; j++) { res[i][j] = 0; } } power(G, res, k); for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) document.write(res[i][j] + " "); document.write("</br>"); } </script> 1 2 2 0 1 0 0 0 1 Time Complexity – Since we have to multiply the adjacency matrix log(k) times (using matrix exponentiation), the time complexity of the algorithm is O((|V|^3)*log(k)), where V is the number of vertices, and k is the length of the path. 29AjayKumar vt_m ankthon gyanhajong divyesh072019 cidacoder Graph Matrix Matrix Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find if there is a path between two vertices in a directed graph Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Find if there is a path between two vertices in an undirected graph Minimum steps to reach target by a Knight | Set 1 Matrix Chain Multiplication | DP-8 Print a given matrix in spiral form Program to find largest element in an array Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Jul, 2021" }, { "code": null, "e": 503, "s": 52, "text": "Given a directed, unweighted graph with N vertices and an integer K. The task is to find the number of paths of length K for each pair of vertices (u, v). Paths don’t have to be simple i.e. vertices and edges can be visited any number of times in a single path. The graph is represented as adjacency matrix where the value G[i][j] = 1 indicates that there is an edge from vertex i to vertex j and G[i][j] = 0 indicates no edge from i to j.Examples: " }, { "code": null, "e": 519, "s": 503, "text": "Input: K = 2, " }, { "code": null, "e": 864, "s": 519, "text": "Output: 1 2 2 0 1 0 0 0 1 Number of paths from 0 to 0 of length k is 1({0->0->0}) Number of paths from 0 to 1 of length k are 2({0->0->1}, {0->2->1}) Number of paths from 0 to 2 of length k are 2({0->0->2}, {0->1->2}) Number of paths from 1 to 1 of length k is 1({1->2->1}) Number of paths from 2 to 2 of length k is 1({2->1->2})Input: K = 3, " }, { "code": null, "e": 1069, "s": 864, "text": "Output: 1 0 0 0 1 0 0 0 1 Number of paths from 0 to 0 of length k is 1({0->1->2->0}) Number of paths from 1 to 1 of length k is 1({1->2->0->1}) Number of paths from 2 to 2 of length k is 1({2->1->0->2}) " }, { "code": null, "e": 1704, "s": 1071, "text": "Prerequisite: Matrix exponentiation, Matrix multiplicationApproach: It is obvious that given adjacency matrix is the answer to the problem for the case k = 1. It contains the number of paths of length 1 between each pair of vertices. Let’s assume that the answer for some k is Matk and the answer for k + 1 is Matk + 1. Matk + 1[i][j] = ∑p = 1NMatk[i][p]*G[p][j]It is easy to see that the formula computes nothing other than the product of the matrices Matk and G i.e. Matk + 1 = Matk * GThus, the solution of the problem can be represented as Matk = G * G * ... * G(k times) = GkBelow is the implementation of the above approach: " }, { "code": null, "e": 1708, "s": 1704, "text": "C++" }, { "code": null, "e": 1713, "s": 1708, "text": "Java" }, { "code": null, "e": 1721, "s": 1713, "text": "Python3" }, { "code": null, "e": 1724, "s": 1721, "text": "C#" }, { "code": null, "e": 1735, "s": 1724, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define N 3 // Function to multiply two matricesvoid multiply(int a[][N], int b[][N], int res[][N]){ int mul[N][N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { mul[i][j] = 0; for (int k = 0; k < N; k++) mul[i][j] += a[i][k] * b[k][j]; } } // Storing the multiplication result in res[][] for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) res[i][j] = mul[i][j];} // Function to compute G raised to the power nvoid power(int G[N][N], int res[N][N], int n){ // Base condition if (n == 1) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) res[i][j] = G[i][j]; return; } // Recursion call for first half power(G, res, n / 2); // Multiply two halves multiply(res, res, res); // If n is odd if (n % 2 != 0) multiply(res, G, res);} // Driver codeint main(){ int G[N][N] = { { 1, 1, 1 }, { 0, 0, 1 }, { 0, 1, 0 } }; int k = 2, res[N][N]; power(G, res, k); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << res[i][j] << \" \"; cout << \"\\n\"; } return 0;}// This Code is improved by cidacoder", "e": 3089, "s": 1735, "text": null }, { "code": "// Java implementation of the approachclass GFG{ static int N = 3; // Function to multiply two matricesstatic void multiply(int a[][], int b[][], int res[][]){ int [][]mul = new int[N][N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { mul[i][j] = 0; for (int k = 0; k < N; k++) mul[i][j] += a[i][k] * b[k][j]; } } // Storing the multiplication result in res[][] for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) res[i][j] = mul[i][j];} // Function to compute G raised to the power nstatic void power(int G[][], int res[][], int n){ // Base condition if (n == 1) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) res[i][j] = G[i][j]; return; } // Recursion call for first half power(G, res, n / 2); multiply(res, res, res); // If n is odd if (n % 2 != 0) multiply(res, G, res);} // Driver codepublic static void main(String[] args){ int G[][] = { { 1, 1, 1 }, { 0, 0, 1 }, { 0, 1, 0 } }; int k = 2; int [][]res = new int[N][N]; power(G, res, k); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(res[i][j] + \" \"); System.out.println(\"\"); }}} // This code is contributed by 29AjayKumar// This Code is improved by cidacoder", "e": 4524, "s": 3089, "text": null }, { "code": "# Python3 implementation of the approach import numpy as np N = 3 # Function to multiply two matricesdef multiply(a, b, res) : mul = np.zeros((N,N)); for i in range(N) : for j in range(N) : mul[i][j] = 0; for k in range(N) : mul[i][j] += a[i][k] * b[k][j]; # Storing the multiplication result in res[][] for i in range(N) : for j in range(N) : res[i][j] = mul[i][j]; # Function to compute G raised to the power ndef power(G, res, n) : # Base condition if (n == 1) : for i in range(N) : for j in range(N) : res[i][j] = G[i][j]; return; # Recursion call for first half power(G, res, n // 2); # Multiply two halves multiply(res, res, res); # If n is odd if (n % 2 != 0) : multiply(res, G, res); # Driver codeif __name__ == \"__main__\" : G = [ [ 1, 1, 1 ], [ 0, 0, 1 ], [ 0, 1, 0 ] ]; k = 2; res = np.zeros((N,N)); power(G, res, k); for i in range(N) : for j in range(N) : print(res[i][j],end = \" \"); print() # This code is contributed by AnkitRai01# This Code is improved by cidacoder", "e": 5755, "s": 4524, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ static int N = 3; // Function to multiply two matricesstatic void multiply(int [,]a, int [,]b, int [,]res){ int [,]mul = new int[N,N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { mul[i,j] = 0; for (int k = 0; k < N; k++) mul[i,j] += a[i,k] * b[k,j]; } } // Storing the multiplication result in res[][] for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) res[i,j] = mul[i,j];} // Function to compute G raised to the power nstatic void power(int [,]G, int [,]res, int n){ // Base condition if (n == 1) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) res[i,j] = G[i,j]; return; } // Recursion call for first half power(G, res, n / 2); // Multiply two halves multiply(res, res, res); // If n is odd if (n % 2 != 0) multiply(res, G, res);} // Driver codepublic static void Main(){ int [,]G = { { 1, 1, 1 }, { 0, 0, 1 }, { 0, 1, 0 } }; int k = 2; int [,]res = new int[N,N]; power(G, res, k); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(res[i,j] + \" \"); Console.WriteLine(\"\"); }}} // This code is contributed by anuj_67..// This code is improved by cidacoder", "e": 7190, "s": 5755, "text": null }, { "code": "<script> // Javascript implementation of the approach let N = 3; // Function to multiply two matrices function multiply(a, b, res) { let mul = new Array(N); for (let i = 0; i < N; i++) { mul[i] = new Array(N); for (let j = 0; j < N; j++) { mul[i][j] = 0; for (let k = 0; k < N; k++) mul[i][j] += a[i][k] * b[k][j]; } } // Storing the multiplication result in res[][] for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) res[i][j] = mul[i][j]; } // Function to compute G raised to the power n function power(G, res, n) { // Base condition if (n == 1) { for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) res[i][j] = G[i][j]; return; } // Recursion call for first half power(G, res, parseInt(n / 2, 10)); // Multiply two halves multiply(res, res, res); // If n is odd if (n % 2 != 0) multiply(res, G, res); } let G = [ [ 1, 1, 1 ], [ 0, 0, 1 ], [ 0, 1, 0 ] ]; let k = 2; let res = new Array(N); for (let i = 0; i < N; i++) { res[i] = new Array(N); for (let j = 0; j < N; j++) { res[i][j] = 0; } } power(G, res, k); for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) document.write(res[i][j] + \" \"); document.write(\"</br>\"); } </script>", "e": 8806, "s": 7190, "text": null }, { "code": null, "e": 8826, "s": 8806, "text": "1 2 2 \n0 1 0 \n0 0 1" }, { "code": null, "e": 9065, "s": 8828, "text": "Time Complexity – Since we have to multiply the adjacency matrix log(k) times (using matrix exponentiation), the time complexity of the algorithm is O((|V|^3)*log(k)), where V is the number of vertices, and k is the length of the path. " }, { "code": null, "e": 9077, "s": 9065, "text": "29AjayKumar" }, { "code": null, "e": 9082, "s": 9077, "text": "vt_m" }, { "code": null, "e": 9090, "s": 9082, "text": "ankthon" }, { "code": null, "e": 9101, "s": 9090, "text": "gyanhajong" }, { "code": null, "e": 9115, "s": 9101, "text": "divyesh072019" }, { "code": null, "e": 9125, "s": 9115, "text": "cidacoder" }, { "code": null, "e": 9131, "s": 9125, "text": "Graph" }, { "code": null, "e": 9138, "s": 9131, "text": "Matrix" }, { "code": null, "e": 9145, "s": 9138, "text": "Matrix" }, { "code": null, "e": 9151, "s": 9145, "text": "Graph" }, { "code": null, "e": 9249, "s": 9151, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9314, "s": 9249, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 9346, "s": 9314, "text": "Introduction to Data Structures" }, { "code": null, "e": 9410, "s": 9346, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 9478, "s": 9410, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 9528, "s": 9478, "text": "Minimum steps to reach target by a Knight | Set 1" }, { "code": null, "e": 9563, "s": 9528, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 9599, "s": 9563, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 9643, "s": 9599, "text": "Program to find largest element in an array" }, { "code": null, "e": 9674, "s": 9643, "text": "Rat in a Maze | Backtracking-2" } ]
Method and Block Synchronization in Java
16 Oct, 2019 Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. Some synchronization constructs are needed to prevent these errors. Following example shows a situation where we need synchronization. Need of Synchronization Consider the following Example: // Java program to illustrate need// of Synchronizationimport java.io.*; class Multithread{ private int i = 0; public void increment() { i++; } public int getValue() { return i; }} class GfG{ public static void main (String[] args) { Multithread t = new Multithread(); t.increment(); System.out.println(t.getValue()); }} Output: 1 In above example three operations are performed: Fetch the value of variable i.Increment the fetched value.And store the increased value of i to its location. Fetch the value of variable i. Increment the fetched value. And store the increased value of i to its location. Here, 1st thread fetches the value of i. (Currently value i is 0) and increases it by one, so value of variable i becomes 1. Now 2nd thread accesses the value of i that would be 0 as 1st thread did not store it back to its location.And 2nd thread also increment it and store it back to its location. And 1st also store it. Finally value of variable i is 1. But it should be 2 by the effect of both threads. That’s why we need to synchronize the access to shared variable i. Java is multi-threaded language where multiple threads runs parallel to complete their execution. We need to synchronize the shared resources to ensure that at a time only one thread is able to access the shared resource.If an Object is shared by multiple threads then there is need of synchronization in order to avoid the Object’s state to be getting corrupted. Synchronization is needed when Object is mutable. If shared Object is immutable or all the threads which share the same Object are only reading the Object’s state not modifying then you don’t need to synchronize it. Java programming language provide two synchronization idioms: Methods synchronization Statement(s) synchronization (Block synchronization) Method Synchronization Synchronized methods enables a simple strategy for preventing the thread interference and memory consistency errors. If a Object is visible to more than one threads, all reads or writes to that Object’s fields are done through the synchronized method. It is not possible for two invocations for synchronized methods to interleave. If one thread is executing the synchronized method, all others thread that invoke synchronized method on the same Object will have to wait until first thread is done with the Object. Example: This shows if more than one threads accessing getLine() method without synchronization. // Example illustrates multiple threads are executing// on the same Object at same time without synchronization.import java.io.*; class Line{ // if multiple threads(trains) will try to // access this unsynchronized method, // they all will get it. So there is chance // that Object's state will be corrupted. public void getLine() { for (int i = 0; i < 3; i++) { System.out.println(i); try { Thread.sleep(400); } catch (Exception e) { System.out.println(e); } } }} class Train extends Thread{ // reference to Line's Object. Line line; Train(Line line) { this.line = line; } @Override public void run() { line.getLine(); }} class GFG{ public static void main(String[] args) { // Object of Line class that is shared // among the threads. Line obj = new Line(); // creating the threads that are // sharing the same Object. Train train1 = new Train(obj); Train train2 = new Train(obj); // threads start their execution. train1.start(); train2.start(); }} Output 0 0 1 1 2 2 There can be two trains (more than two) which need to use same at same time so there is chance of collision. Therefore to avoid collision we need to synchronize the line in which multiple want to run. Example: Synchronized access to getLine() method on the same Object // Example that shows multiple threads// can execute the same method but in// synchronized way.class Line{ // if multiple threads(trains) trying to access // this synchronized method on the same Object // but only one thread will be able // to execute it at a time. synchronized public void getLine() { for (int i = 0; i < 3; i++) { System.out.println(i); try { Thread.sleep(400); } catch (Exception e) { System.out.println(e); } } }} class Train extends Thread{ // Reference variable of type Line. Line line; Train(Line line) { this.line = line; } @Override public void run() { line.getLine(); }} class GFG{ public static void main(String[] args) { Line obj = new Line(); // we are creating two threads which share // same Object. Train train1 = new Train(obj); Train train2 = new Train(obj); // both threads start executing . train1.start(); train2.start(); }} Output: 0 1 2 0 1 2 Block Synchronization If we only need to execute some subsequent lines of code not all lines (instructions) of code within a method, then we should synchronize only block of the code within which required instructions are exists.For example, lets suppose there is a method that contains 100 lines of code but there are only 10 lines (one after one) of code which contain critical section of code i.e. these lines can modify (change) the Object’s state. So we only need to synchronize these 10 lines of code method to avoid any modification in state of the Object and to ensure that other threads can execute rest of the lines within the same method without any interruption. import java.io.*;import java.util.*; public class Geek{ String name = ""; public int count = 0; public void geekName(String geek, List<String> list) { // Only one thread is permitted // to change geek's name at a time. synchronized(this) { name = geek; count++; // how many threads change geek's name. } // All other threads are permitted // to add geek name into list. list.add(geek); }} class GFG{ public static void main (String[] args) { Geek gk = new Geek(); List<String> list = new ArrayList<String>(); gk.geekName("mohit", list); System.out.println(gk.name); }} Output : mohit Important points: When a thread enters into synchronized method or block, it acquires lock and once it completes its task and exits from the synchronized method, it releases the lock. When thread enters into synchronized instance method or block, it acquires Object level lock and when it enters into synchronized static method or block it acquires class level lock. Java synchronization will throw null pointer exception if Object used in synchronized block is null. For example, If in synchronized(instance) , instance is null then it will throw null pointer exception. In Java, wait(), notify() and notifyAll() are the important methods that are used in synchronization. You can not apply java synchronized keyword with the variables. Don’t synchronize on the non-final field on synchronized block because the reference to the non-final field may change anytime and then different threads might synchronize on different objects i.e. no synchronization at all. Advantages Multithreading: Since java is multithreaded language, synchronization is a good way to achieve mutual exclusion on shared resource(s). Instance and Static Methods: Both synchronized instance methods and synchronized static methods can be executed concurrently because they are used to lock different Objects. Limitations Concurrency Limitations: Java synchronization does not allow concurrent reads. Decreases Efficiency: Java synchronized method run very slowly and can degrade the performance, so you should synchronize the method when it is absolutely necessary otherwise not and to synchronize block only for critical section of the code. This article is contributed by Nitsdheerendra. 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. vsushko Akanksha_Rai Java-Multithreading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Oct, 2019" }, { "code": null, "e": 430, "s": 52, "text": "Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. Some synchronization constructs are needed to prevent these errors. Following example shows a situation where we need synchronization." }, { "code": null, "e": 454, "s": 430, "text": "Need of Synchronization" }, { "code": null, "e": 486, "s": 454, "text": "Consider the following Example:" }, { "code": "// Java program to illustrate need// of Synchronizationimport java.io.*; class Multithread{ private int i = 0; public void increment() { i++; } public int getValue() { return i; }} class GfG{ public static void main (String[] args) { Multithread t = new Multithread(); t.increment(); System.out.println(t.getValue()); }}", "e": 876, "s": 486, "text": null }, { "code": null, "e": 884, "s": 876, "text": "Output:" }, { "code": null, "e": 886, "s": 884, "text": "1" }, { "code": null, "e": 935, "s": 886, "text": "In above example three operations are performed:" }, { "code": null, "e": 1045, "s": 935, "text": "Fetch the value of variable i.Increment the fetched value.And store the increased value of i to its location." }, { "code": null, "e": 1076, "s": 1045, "text": "Fetch the value of variable i." }, { "code": null, "e": 1105, "s": 1076, "text": "Increment the fetched value." }, { "code": null, "e": 1157, "s": 1105, "text": "And store the increased value of i to its location." }, { "code": null, "e": 1163, "s": 1157, "text": "Here," }, { "code": null, "e": 1282, "s": 1163, "text": "1st thread fetches the value of i. (Currently value i is 0) and increases it by one, so value of variable i becomes 1." }, { "code": null, "e": 1480, "s": 1282, "text": "Now 2nd thread accesses the value of i that would be 0 as 1st thread did not store it back to its location.And 2nd thread also increment it and store it back to its location. And 1st also store it." }, { "code": null, "e": 1631, "s": 1480, "text": "Finally value of variable i is 1. But it should be 2 by the effect of both threads. That’s why we need to synchronize the access to shared variable i." }, { "code": null, "e": 2211, "s": 1631, "text": "Java is multi-threaded language where multiple threads runs parallel to complete their execution. We need to synchronize the shared resources to ensure that at a time only one thread is able to access the shared resource.If an Object is shared by multiple threads then there is need of synchronization in order to avoid the Object’s state to be getting corrupted. Synchronization is needed when Object is mutable. If shared Object is immutable or all the threads which share the same Object are only reading the Object’s state not modifying then you don’t need to synchronize it." }, { "code": null, "e": 2273, "s": 2211, "text": "Java programming language provide two synchronization idioms:" }, { "code": null, "e": 2297, "s": 2273, "text": "Methods synchronization" }, { "code": null, "e": 2350, "s": 2297, "text": "Statement(s) synchronization (Block synchronization)" }, { "code": null, "e": 2373, "s": 2350, "text": "Method Synchronization" }, { "code": null, "e": 2625, "s": 2373, "text": "Synchronized methods enables a simple strategy for preventing the thread interference and memory consistency errors. If a Object is visible to more than one threads, all reads or writes to that Object’s fields are done through the synchronized method." }, { "code": null, "e": 2887, "s": 2625, "text": "It is not possible for two invocations for synchronized methods to interleave. If one thread is executing the synchronized method, all others thread that invoke synchronized method on the same Object will have to wait until first thread is done with the Object." }, { "code": null, "e": 2984, "s": 2887, "text": "Example: This shows if more than one threads accessing getLine() method without synchronization." }, { "code": "// Example illustrates multiple threads are executing// on the same Object at same time without synchronization.import java.io.*; class Line{ // if multiple threads(trains) will try to // access this unsynchronized method, // they all will get it. So there is chance // that Object's state will be corrupted. public void getLine() { for (int i = 0; i < 3; i++) { System.out.println(i); try { Thread.sleep(400); } catch (Exception e) { System.out.println(e); } } }} class Train extends Thread{ // reference to Line's Object. Line line; Train(Line line) { this.line = line; } @Override public void run() { line.getLine(); }} class GFG{ public static void main(String[] args) { // Object of Line class that is shared // among the threads. Line obj = new Line(); // creating the threads that are // sharing the same Object. Train train1 = new Train(obj); Train train2 = new Train(obj); // threads start their execution. train1.start(); train2.start(); }}", "e": 4216, "s": 2984, "text": null }, { "code": null, "e": 4223, "s": 4216, "text": "Output" }, { "code": null, "e": 4236, "s": 4223, "text": "0\n0\n1\n1\n2\n2\n" }, { "code": null, "e": 4437, "s": 4236, "text": "There can be two trains (more than two) which need to use same at same time so there is chance of collision. Therefore to avoid collision we need to synchronize the line in which multiple want to run." }, { "code": null, "e": 4505, "s": 4437, "text": "Example: Synchronized access to getLine() method on the same Object" }, { "code": "// Example that shows multiple threads// can execute the same method but in// synchronized way.class Line{ // if multiple threads(trains) trying to access // this synchronized method on the same Object // but only one thread will be able // to execute it at a time. synchronized public void getLine() { for (int i = 0; i < 3; i++) { System.out.println(i); try { Thread.sleep(400); } catch (Exception e) { System.out.println(e); } } }} class Train extends Thread{ // Reference variable of type Line. Line line; Train(Line line) { this.line = line; } @Override public void run() { line.getLine(); }} class GFG{ public static void main(String[] args) { Line obj = new Line(); // we are creating two threads which share // same Object. Train train1 = new Train(obj); Train train2 = new Train(obj); // both threads start executing . train1.start(); train2.start(); }}", "e": 5635, "s": 4505, "text": null }, { "code": null, "e": 5643, "s": 5635, "text": "Output:" }, { "code": null, "e": 5656, "s": 5643, "text": "0\n1\n2\n0\n1\n2\n" }, { "code": null, "e": 5678, "s": 5656, "text": "Block Synchronization" }, { "code": null, "e": 6331, "s": 5678, "text": "If we only need to execute some subsequent lines of code not all lines (instructions) of code within a method, then we should synchronize only block of the code within which required instructions are exists.For example, lets suppose there is a method that contains 100 lines of code but there are only 10 lines (one after one) of code which contain critical section of code i.e. these lines can modify (change) the Object’s state. So we only need to synchronize these 10 lines of code method to avoid any modification in state of the Object and to ensure that other threads can execute rest of the lines within the same method without any interruption." }, { "code": "import java.io.*;import java.util.*; public class Geek{ String name = \"\"; public int count = 0; public void geekName(String geek, List<String> list) { // Only one thread is permitted // to change geek's name at a time. synchronized(this) { name = geek; count++; // how many threads change geek's name. } // All other threads are permitted // to add geek name into list. list.add(geek); }} class GFG{ public static void main (String[] args) { Geek gk = new Geek(); List<String> list = new ArrayList<String>(); gk.geekName(\"mohit\", list); System.out.println(gk.name); }}", "e": 7039, "s": 6331, "text": null }, { "code": null, "e": 7048, "s": 7039, "text": "Output :" }, { "code": null, "e": 7055, "s": 7048, "text": "mohit\n" }, { "code": null, "e": 7073, "s": 7055, "text": "Important points:" }, { "code": null, "e": 7239, "s": 7073, "text": "When a thread enters into synchronized method or block, it acquires lock and once it completes its task and exits from the synchronized method, it releases the lock." }, { "code": null, "e": 7422, "s": 7239, "text": "When thread enters into synchronized instance method or block, it acquires Object level lock and when it enters into synchronized static method or block it acquires class level lock." }, { "code": null, "e": 7627, "s": 7422, "text": "Java synchronization will throw null pointer exception if Object used in synchronized block is null. For example, If in synchronized(instance) , instance is null then it will throw null pointer exception." }, { "code": null, "e": 7729, "s": 7627, "text": "In Java, wait(), notify() and notifyAll() are the important methods that are used in synchronization." }, { "code": null, "e": 7793, "s": 7729, "text": "You can not apply java synchronized keyword with the variables." }, { "code": null, "e": 8018, "s": 7793, "text": "Don’t synchronize on the non-final field on synchronized block because the reference to the non-final field may change anytime and then different threads might synchronize on different objects i.e. no synchronization at all." }, { "code": null, "e": 8029, "s": 8018, "text": "Advantages" }, { "code": null, "e": 8164, "s": 8029, "text": "Multithreading: Since java is multithreaded language, synchronization is a good way to achieve mutual exclusion on shared resource(s)." }, { "code": null, "e": 8338, "s": 8164, "text": "Instance and Static Methods: Both synchronized instance methods and synchronized static methods can be executed concurrently because they are used to lock different Objects." }, { "code": null, "e": 8350, "s": 8338, "text": "Limitations" }, { "code": null, "e": 8429, "s": 8350, "text": "Concurrency Limitations: Java synchronization does not allow concurrent reads." }, { "code": null, "e": 8672, "s": 8429, "text": "Decreases Efficiency: Java synchronized method run very slowly and can degrade the performance, so you should synchronize the method when it is absolutely necessary otherwise not and to synchronize block only for critical section of the code." }, { "code": null, "e": 8974, "s": 8672, "text": "This article is contributed by Nitsdheerendra. 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": 9099, "s": 8974, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 9107, "s": 9099, "text": "vsushko" }, { "code": null, "e": 9120, "s": 9107, "text": "Akanksha_Rai" }, { "code": null, "e": 9140, "s": 9120, "text": "Java-Multithreading" }, { "code": null, "e": 9145, "s": 9140, "text": "Java" }, { "code": null, "e": 9150, "s": 9145, "text": "Java" } ]
Java Program to Swap two Variables
08 Jun, 2021 Given two numbers x and y, we need to swap their valuesExamples: Input : x = 10, y = 20; Output : x = 20, y = 10 Input : x = 200, y = 100 Output : x = 100, y = 200 Below are the simple steps we follow: 1) Assign x to a temp variable : temp = x 2) Assign y to x : x = y 3) Assign temp to y : y = tempLet us understand with an example. 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 = 100, y = 200After line 1: temp = x temp = 100After line 2: x = y x = 200After line 3 : y = temp y = 100 Java // Java program to swap two variablespublic class GfG { public static void main(String[] args) { int x = 100, y = 200; System.out.println("Before Swap"); System.out.println("x = " + x); System.out.println("y = " + y); int temp = x; x = y; y = temp; System.out.println("After swap"); System.out.println("x = " + x); System.out.println("y = " + y); }} Before Swap x = 100 y = 200 After swap x = 200 y = 100 How to swap two numbers without using a temporary variable? How to swap or exchange objects in Java? Swap two variables in one line in C/C++, Python, PHP and Java simranarora5sos Swap-Program Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Jun, 2021" }, { "code": null, "e": 120, "s": 53, "text": "Given two numbers x and y, we need to swap their valuesExamples: " }, { "code": null, "e": 220, "s": 120, "text": "Input : x = 10, y = 20;\nOutput : x = 20, y = 10\n\nInput : x = 200, y = 100\nOutput : x = 100, y = 200" }, { "code": null, "e": 395, "s": 224, "text": "Below are the simple steps we follow: 1) Assign x to a temp variable : temp = x 2) Assign y to x : x = y 3) Assign temp to y : y = tempLet us understand with an example. " }, { "code": null, "e": 404, "s": 395, "text": "Chapters" }, { "code": null, "e": 431, "s": 404, "text": "descriptions off, selected" }, { "code": null, "e": 481, "s": 431, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 504, "s": 481, "text": "captions off, selected" }, { "code": null, "e": 512, "s": 504, "text": "English" }, { "code": null, "e": 536, "s": 512, "text": "This is a modal window." }, { "code": null, "e": 605, "s": 536, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 627, "s": 605, "text": "End of dialog window." }, { "code": null, "e": 735, "s": 627, "text": "x = 100, y = 200After line 1: temp = x temp = 100After line 2: x = y x = 200After line 3 : y = temp y = 100" }, { "code": null, "e": 742, "s": 737, "text": "Java" }, { "code": "// Java program to swap two variablespublic class GfG { public static void main(String[] args) { int x = 100, y = 200; System.out.println(\"Before Swap\"); System.out.println(\"x = \" + x); System.out.println(\"y = \" + y); int temp = x; x = y; y = temp; System.out.println(\"After swap\"); System.out.println(\"x = \" + x); System.out.println(\"y = \" + y); }}", "e": 1176, "s": 742, "text": null }, { "code": null, "e": 1231, "s": 1176, "text": "Before Swap\nx = 100\ny = 200\nAfter swap\nx = 200\ny = 100" }, { "code": null, "e": 1293, "s": 1233, "text": "How to swap two numbers without using a temporary variable?" }, { "code": null, "e": 1334, "s": 1293, "text": "How to swap or exchange objects in Java?" }, { "code": null, "e": 1396, "s": 1334, "text": "Swap two variables in one line in C/C++, Python, PHP and Java" }, { "code": null, "e": 1412, "s": 1396, "text": "simranarora5sos" }, { "code": null, "e": 1425, "s": 1412, "text": "Swap-Program" }, { "code": null, "e": 1439, "s": 1425, "text": "Java Programs" } ]
Python – Status object in Tweepy
03 Jul, 2020 Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication. The Status object in Tweepy module contains the information about a status/tweet. Here are the list of attributes in the Status object : created_at : The time the status was posted. id : The ID of the status. id_str : The ID of the status as a string. text : The text of the status. entities : The parsed entities of the status such as hashtags, URLs etc. source : The source of the status. source_url : The URL of the source of the status. in_reply_to_status_id : The ID of the status being replied to. in_reply_to_status_id_str : The ID of the status being replied to in as a string. in_reply_to_user_id : The ID of the user being replied to. in_reply_to_user_id_str : The ID of the user being replied to as a string. in_reply_to_screen_name : The screen name of the user being replied to user : The User object of the poster of the status. geo : The geo object of the status. coordinates : The coordinates of the status. place : The place of the status. contributors : The contributors of the status. is_quote_status : Indicates whether the status is a quoted status or not. retweet_count : The number of retweets of the status. favorite_count : The number of likes of the status. favorited : Indicates whether the status has been favourited by the authenticated user or not. retweeted : Indicates whether the status has been retweeted by the authenticated user or not. possibly_sensitive : Indicates whether the status is sensitive or not. lang : The language of the status. Example : Consider the following status :Use get_status() method to fetch the status. # import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the statusid = 1268080321590935553 # fetching the statusstatus = api.get_status(id) # printing the informationprint("The status was created at : " + str(status.created_at))print("The id is : " + str(status.id))print("The id_str is : " + status.id_str)print("The text is : " + status.text)print("The entitities are : " + str(status.entities))print("The source is : " + status.source)print("The source_url is : " + status.source_url) print("The in_reply_to_status_id is : " + str(status.in_reply_to_status_id))print("The in_reply_to_status_id_str is : " + str(status.in_reply_to_status_id_str))print("The in_reply_to_user_id is : " + str(status.in_reply_to_user_id))print("The in_reply_to_user_id_str is : " + str(status.in_reply_to_user_id_str))print("The in_reply_to_screen_name is : " + str(status.in_reply_to_screen_name)) print("The poster's screen name is : " + status.user.screen_name)print("The geo is : " + str(status.geo))print("The coordinates are : " + str(status.coordinates))print("The place is : " + str(status.place))print("The contributors are : " + str(status.contributors))print("The is_quote_status is : " + str(status.is_quote_status))print("The retweet_count is : " + str(status.retweet_count))print("The favorite_count is : " + str(status.favorite_count)) print("Has the authenticated user favourited the status? : " + str(status.favorited))print("Has the authenticated user retweeted the status? " + str(status.retweeted))print("Is the status possibly_sensitive? : " + str(status.possibly_sensitive))print("The lang is : " + status.lang) Output : The status was created at : 2020-06-03 07:21:23The id is : 1268080321590935553The id_str is : 1268080321590935553The text is : Time really hits differently when you are??holding a plank for a minute,??washing your hands for 20 seconds, and... https://t.co/BBg2RIamGyThe entitities are : {‘hashtags’: [], ‘symbols’: [], ‘user_mentions’: [], ‘urls’: [{‘url’: ‘https://t.co/BBg2RIamGy’, ‘expanded_url’: ‘https://twitter.com/i/web/status/1268080321590935553’, ‘display_url’: ‘twitter.com/i/web/status/1...’, ‘indices’: [116, 139]}]}The source is : Twitter Web AppThe source_url is : https://mobile.twitter.comThe in_reply_to_status_id is : NoneThe in_reply_to_status_id_str is : NoneThe in_reply_to_user_id is : NoneThe in_reply_to_user_id_str is : NoneThe in_reply_to_screen_name is : NoneThe poster’s screen name is : geeksforgeeksThe geo is : NoneThe coordinates are : NoneThe place is : NoneThe contributors are : NoneThe is_quote_status is : FalseThe retweet_count is : 2The favorite_count is : 31Has the authenticated user favourited the status? : TrueHas the authenticated user retweeted the status? FalseIs the status possibly_sensitive? : FalseThe lang is : en Python-Tweepy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jul, 2020" }, { "code": null, "e": 428, "s": 28, "text": "Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication." }, { "code": null, "e": 510, "s": 428, "text": "The Status object in Tweepy module contains the information about a status/tweet." }, { "code": null, "e": 565, "s": 510, "text": "Here are the list of attributes in the Status object :" }, { "code": null, "e": 610, "s": 565, "text": "created_at : The time the status was posted." }, { "code": null, "e": 637, "s": 610, "text": "id : The ID of the status." }, { "code": null, "e": 680, "s": 637, "text": "id_str : The ID of the status as a string." }, { "code": null, "e": 711, "s": 680, "text": "text : The text of the status." }, { "code": null, "e": 784, "s": 711, "text": "entities : The parsed entities of the status such as hashtags, URLs etc." }, { "code": null, "e": 819, "s": 784, "text": "source : The source of the status." }, { "code": null, "e": 869, "s": 819, "text": "source_url : The URL of the source of the status." }, { "code": null, "e": 932, "s": 869, "text": "in_reply_to_status_id : The ID of the status being replied to." }, { "code": null, "e": 1014, "s": 932, "text": "in_reply_to_status_id_str : The ID of the status being replied to in as a string." }, { "code": null, "e": 1073, "s": 1014, "text": "in_reply_to_user_id : The ID of the user being replied to." }, { "code": null, "e": 1148, "s": 1073, "text": "in_reply_to_user_id_str : The ID of the user being replied to as a string." }, { "code": null, "e": 1219, "s": 1148, "text": "in_reply_to_screen_name : The screen name of the user being replied to" }, { "code": null, "e": 1271, "s": 1219, "text": "user : The User object of the poster of the status." }, { "code": null, "e": 1307, "s": 1271, "text": "geo : The geo object of the status." }, { "code": null, "e": 1352, "s": 1307, "text": "coordinates : The coordinates of the status." }, { "code": null, "e": 1385, "s": 1352, "text": "place : The place of the status." }, { "code": null, "e": 1432, "s": 1385, "text": "contributors : The contributors of the status." }, { "code": null, "e": 1506, "s": 1432, "text": "is_quote_status : Indicates whether the status is a quoted status or not." }, { "code": null, "e": 1560, "s": 1506, "text": "retweet_count : The number of retweets of the status." }, { "code": null, "e": 1612, "s": 1560, "text": "favorite_count : The number of likes of the status." }, { "code": null, "e": 1707, "s": 1612, "text": "favorited : Indicates whether the status has been favourited by the authenticated user or not." }, { "code": null, "e": 1801, "s": 1707, "text": "retweeted : Indicates whether the status has been retweeted by the authenticated user or not." }, { "code": null, "e": 1872, "s": 1801, "text": "possibly_sensitive : Indicates whether the status is sensitive or not." }, { "code": null, "e": 1907, "s": 1872, "text": "lang : The language of the status." }, { "code": null, "e": 1993, "s": 1907, "text": "Example : Consider the following status :Use get_status() method to fetch the status." }, { "code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the statusid = 1268080321590935553 # fetching the statusstatus = api.get_status(id) # printing the informationprint(\"The status was created at : \" + str(status.created_at))print(\"The id is : \" + str(status.id))print(\"The id_str is : \" + status.id_str)print(\"The text is : \" + status.text)print(\"The entitities are : \" + str(status.entities))print(\"The source is : \" + status.source)print(\"The source_url is : \" + status.source_url) print(\"The in_reply_to_status_id is : \" + str(status.in_reply_to_status_id))print(\"The in_reply_to_status_id_str is : \" + str(status.in_reply_to_status_id_str))print(\"The in_reply_to_user_id is : \" + str(status.in_reply_to_user_id))print(\"The in_reply_to_user_id_str is : \" + str(status.in_reply_to_user_id_str))print(\"The in_reply_to_screen_name is : \" + str(status.in_reply_to_screen_name)) print(\"The poster's screen name is : \" + status.user.screen_name)print(\"The geo is : \" + str(status.geo))print(\"The coordinates are : \" + str(status.coordinates))print(\"The place is : \" + str(status.place))print(\"The contributors are : \" + str(status.contributors))print(\"The is_quote_status is : \" + str(status.is_quote_status))print(\"The retweet_count is : \" + str(status.retweet_count))print(\"The favorite_count is : \" + str(status.favorite_count)) print(\"Has the authenticated user favourited the status? : \" + str(status.favorited))print(\"Has the authenticated user retweeted the status? \" + str(status.retweeted))print(\"Is the status possibly_sensitive? : \" + str(status.possibly_sensitive))print(\"The lang is : \" + status.lang)", "e": 3981, "s": 1993, "text": null }, { "code": null, "e": 3990, "s": 3981, "text": "Output :" }, { "code": null, "e": 5156, "s": 3990, "text": "The status was created at : 2020-06-03 07:21:23The id is : 1268080321590935553The id_str is : 1268080321590935553The text is : Time really hits differently when you are??holding a plank for a minute,??washing your hands for 20 seconds, and... https://t.co/BBg2RIamGyThe entitities are : {‘hashtags’: [], ‘symbols’: [], ‘user_mentions’: [], ‘urls’: [{‘url’: ‘https://t.co/BBg2RIamGy’, ‘expanded_url’: ‘https://twitter.com/i/web/status/1268080321590935553’, ‘display_url’: ‘twitter.com/i/web/status/1...’, ‘indices’: [116, 139]}]}The source is : Twitter Web AppThe source_url is : https://mobile.twitter.comThe in_reply_to_status_id is : NoneThe in_reply_to_status_id_str is : NoneThe in_reply_to_user_id is : NoneThe in_reply_to_user_id_str is : NoneThe in_reply_to_screen_name is : NoneThe poster’s screen name is : geeksforgeeksThe geo is : NoneThe coordinates are : NoneThe place is : NoneThe contributors are : NoneThe is_quote_status is : FalseThe retweet_count is : 2The favorite_count is : 31Has the authenticated user favourited the status? : TrueHas the authenticated user retweeted the status? FalseIs the status possibly_sensitive? : FalseThe lang is : en" }, { "code": null, "e": 5170, "s": 5156, "text": "Python-Tweepy" }, { "code": null, "e": 5177, "s": 5170, "text": "Python" } ]
Transpose a matrix in Single line in Python
24 Dec, 2021 Transpose of a matrix is a task we all can perform very easily in python (Using a nested loop). But there are some interesting ways to do the same in a single line.In Python, we can implement a matrix as nested list (list inside a list). Each element is treated as a row of the matrix. For example m = [[1, 2], [4, 5], [3, 6]] represents a matrix of 3 rows and 2 columns.First element of the list – m[0] and element in first row, first column – m[0][0]. Using Nested List Comprehension: Nested list comprehension are used to iterate through each element in the matrix. In the given example, we iterate through each element of matrix (m) in column major manner and assign the result to rez matrix which is the transpose of m.m = [[1,2],[3,4],[5,6]]for row in m : print(row)rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]print("\n")for row in rez: print(row)Output:[1, 2] [3, 4] [5, 6] [1, 3, 5] [2, 4, 6] Using Nested List Comprehension: Nested list comprehension are used to iterate through each element in the matrix. In the given example, we iterate through each element of matrix (m) in column major manner and assign the result to rez matrix which is the transpose of m.m = [[1,2],[3,4],[5,6]]for row in m : print(row)rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]print("\n")for row in rez: print(row)Output:[1, 2] [3, 4] [5, 6] [1, 3, 5] [2, 4, 6] m = [[1,2],[3,4],[5,6]]for row in m : print(row)rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]print("\n")for row in rez: print(row) Output: [1, 2] [3, 4] [5, 6] [1, 3, 5] [2, 4, 6] Using zip: Zip returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. In this example we unzip our array using * and then zip it to get the transpose.matrix=[(1,2,3),(4,5,6),(7,8,9),(10,11,12)]for row in matrix: print(row)print("\n")t_matrix = zip(*matrix)for row in t_matrix: print(row)Output:(1, 2, 3) (4, 5, 6) (7, 8, 9) (10, 11, 12) (1, 4, 7, 10) (2, 5, 8, 11) (3, 6, 9, 12) Note :- If you want your result in the form [[1,4,7,10][2,5,8,11][3,6,9,12]] , you can use t_matrix=map(list, zip(*matrix)). Using zip: Zip returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. In this example we unzip our array using * and then zip it to get the transpose.matrix=[(1,2,3),(4,5,6),(7,8,9),(10,11,12)]for row in matrix: print(row)print("\n")t_matrix = zip(*matrix)for row in t_matrix: print(row)Output:(1, 2, 3) (4, 5, 6) (7, 8, 9) (10, 11, 12) (1, 4, 7, 10) (2, 5, 8, 11) (3, 6, 9, 12) Note :- If you want your result in the form [[1,4,7,10][2,5,8,11][3,6,9,12]] , you can use t_matrix=map(list, zip(*matrix)). matrix=[(1,2,3),(4,5,6),(7,8,9),(10,11,12)]for row in matrix: print(row)print("\n")t_matrix = zip(*matrix)for row in t_matrix: print(row) Output: (1, 2, 3) (4, 5, 6) (7, 8, 9) (10, 11, 12) (1, 4, 7, 10) (2, 5, 8, 11) (3, 6, 9, 12) Note :- If you want your result in the form [[1,4,7,10][2,5,8,11][3,6,9,12]] , you can use t_matrix=map(list, zip(*matrix)). Using numpy: NumPy is a general-purpose array-processing package designed to efficiently manipulate large multi-dimensional arrays. The transpose method returns a transposed view of the passed multi-dimensional matrix.# You need to install numpy in order to import it# Numpy transpose returns similar result when # applied on 1D matriximport numpy matrix=[[1,2,3],[4,5,6]]print(matrix)print("\n")print(numpy.transpose(matrix))Or, simply using “.T” after the variable# You need to install numpy in order to import itimport numpy as npmatrix = np.array([[1,2,3],[4,5,6]])print(matrix)print("\n")print(matrix.T)Output:[[1 2 3] [4 5 6]] [[1 4] [2 5] [3 6]] Note :- “.T” only works on numpy arrays Using numpy: NumPy is a general-purpose array-processing package designed to efficiently manipulate large multi-dimensional arrays. The transpose method returns a transposed view of the passed multi-dimensional matrix.# You need to install numpy in order to import it# Numpy transpose returns similar result when # applied on 1D matriximport numpy matrix=[[1,2,3],[4,5,6]]print(matrix)print("\n")print(numpy.transpose(matrix))Or, simply using “.T” after the variable# You need to install numpy in order to import itimport numpy as npmatrix = np.array([[1,2,3],[4,5,6]])print(matrix)print("\n")print(matrix.T)Output:[[1 2 3] [4 5 6]] [[1 4] [2 5] [3 6]] Note :- “.T” only works on numpy arrays # You need to install numpy in order to import it# Numpy transpose returns similar result when # applied on 1D matriximport numpy matrix=[[1,2,3],[4,5,6]]print(matrix)print("\n")print(numpy.transpose(matrix)) Or, simply using “.T” after the variable # You need to install numpy in order to import itimport numpy as npmatrix = np.array([[1,2,3],[4,5,6]])print(matrix)print("\n")print(matrix.T) Output: [[1 2 3] [4 5 6]] [[1 4] [2 5] [3 6]] Note :- “.T” only works on numpy arrays This article is contributed by Mayank Rawat & simply modified by Md. Tahmid Hasan. 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. pwakchaure tahmidhasan3003 punamsingh628700 Python matrix-program Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Dec, 2021" }, { "code": null, "e": 506, "s": 52, "text": "Transpose of a matrix is a task we all can perform very easily in python (Using a nested loop). But there are some interesting ways to do the same in a single line.In Python, we can implement a matrix as nested list (list inside a list). Each element is treated as a row of the matrix. For example m = [[1, 2], [4, 5], [3, 6]] represents a matrix of 3 rows and 2 columns.First element of the list – m[0] and element in first row, first column – m[0][0]." }, { "code": null, "e": 984, "s": 506, "text": "Using Nested List Comprehension: Nested list comprehension are used to iterate through each element in the matrix. In the given example, we iterate through each element of matrix (m) in column major manner and assign the result to rez matrix which is the transpose of m.m = [[1,2],[3,4],[5,6]]for row in m : print(row)rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]print(\"\\n\")for row in rez: print(row)Output:[1, 2]\n[3, 4]\n[5, 6]\n\n\n[1, 3, 5]\n[2, 4, 6]\n" }, { "code": null, "e": 1462, "s": 984, "text": "Using Nested List Comprehension: Nested list comprehension are used to iterate through each element in the matrix. In the given example, we iterate through each element of matrix (m) in column major manner and assign the result to rez matrix which is the transpose of m.m = [[1,2],[3,4],[5,6]]for row in m : print(row)rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]print(\"\\n\")for row in rez: print(row)Output:[1, 2]\n[3, 4]\n[5, 6]\n\n\n[1, 3, 5]\n[2, 4, 6]\n" }, { "code": "m = [[1,2],[3,4],[5,6]]for row in m : print(row)rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]print(\"\\n\")for row in rez: print(row)", "e": 1620, "s": 1462, "text": null }, { "code": null, "e": 1628, "s": 1620, "text": "Output:" }, { "code": null, "e": 1672, "s": 1628, "text": "[1, 2]\n[3, 4]\n[5, 6]\n\n\n[1, 3, 5]\n[2, 4, 6]\n" }, { "code": null, "e": 2256, "s": 1672, "text": "Using zip: Zip returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. In this example we unzip our array using * and then zip it to get the transpose.matrix=[(1,2,3),(4,5,6),(7,8,9),(10,11,12)]for row in matrix: print(row)print(\"\\n\")t_matrix = zip(*matrix)for row in t_matrix: print(row)Output:(1, 2, 3)\n(4, 5, 6)\n(7, 8, 9)\n(10, 11, 12)\n\n(1, 4, 7, 10)\n(2, 5, 8, 11)\n(3, 6, 9, 12)\nNote :- If you want your result in the form [[1,4,7,10][2,5,8,11][3,6,9,12]] , you can use t_matrix=map(list, zip(*matrix))." }, { "code": null, "e": 2840, "s": 2256, "text": "Using zip: Zip returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. In this example we unzip our array using * and then zip it to get the transpose.matrix=[(1,2,3),(4,5,6),(7,8,9),(10,11,12)]for row in matrix: print(row)print(\"\\n\")t_matrix = zip(*matrix)for row in t_matrix: print(row)Output:(1, 2, 3)\n(4, 5, 6)\n(7, 8, 9)\n(10, 11, 12)\n\n(1, 4, 7, 10)\n(2, 5, 8, 11)\n(3, 6, 9, 12)\nNote :- If you want your result in the form [[1,4,7,10][2,5,8,11][3,6,9,12]] , you can use t_matrix=map(list, zip(*matrix))." }, { "code": "matrix=[(1,2,3),(4,5,6),(7,8,9),(10,11,12)]for row in matrix: print(row)print(\"\\n\")t_matrix = zip(*matrix)for row in t_matrix: print(row)", "e": 2984, "s": 2840, "text": null }, { "code": null, "e": 2992, "s": 2984, "text": "Output:" }, { "code": null, "e": 3079, "s": 2992, "text": "(1, 2, 3)\n(4, 5, 6)\n(7, 8, 9)\n(10, 11, 12)\n\n(1, 4, 7, 10)\n(2, 5, 8, 11)\n(3, 6, 9, 12)\n" }, { "code": null, "e": 3204, "s": 3079, "text": "Note :- If you want your result in the form [[1,4,7,10][2,5,8,11][3,6,9,12]] , you can use t_matrix=map(list, zip(*matrix))." }, { "code": null, "e": 3901, "s": 3204, "text": "Using numpy: NumPy is a general-purpose array-processing package designed to efficiently manipulate large multi-dimensional arrays. The transpose method returns a transposed view of the passed multi-dimensional matrix.# You need to install numpy in order to import it# Numpy transpose returns similar result when # applied on 1D matriximport numpy matrix=[[1,2,3],[4,5,6]]print(matrix)print(\"\\n\")print(numpy.transpose(matrix))Or, simply using “.T” after the variable# You need to install numpy in order to import itimport numpy as npmatrix = np.array([[1,2,3],[4,5,6]])print(matrix)print(\"\\n\")print(matrix.T)Output:[[1 2 3]\n [4 5 6]]\n\n[[1 4]\n [2 5]\n [3 6]]\nNote :- “.T” only works on numpy arrays" }, { "code": null, "e": 4598, "s": 3901, "text": "Using numpy: NumPy is a general-purpose array-processing package designed to efficiently manipulate large multi-dimensional arrays. The transpose method returns a transposed view of the passed multi-dimensional matrix.# You need to install numpy in order to import it# Numpy transpose returns similar result when # applied on 1D matriximport numpy matrix=[[1,2,3],[4,5,6]]print(matrix)print(\"\\n\")print(numpy.transpose(matrix))Or, simply using “.T” after the variable# You need to install numpy in order to import itimport numpy as npmatrix = np.array([[1,2,3],[4,5,6]])print(matrix)print(\"\\n\")print(matrix.T)Output:[[1 2 3]\n [4 5 6]]\n\n[[1 4]\n [2 5]\n [3 6]]\nNote :- “.T” only works on numpy arrays" }, { "code": "# You need to install numpy in order to import it# Numpy transpose returns similar result when # applied on 1D matriximport numpy matrix=[[1,2,3],[4,5,6]]print(matrix)print(\"\\n\")print(numpy.transpose(matrix))", "e": 4807, "s": 4598, "text": null }, { "code": null, "e": 4848, "s": 4807, "text": "Or, simply using “.T” after the variable" }, { "code": "# You need to install numpy in order to import itimport numpy as npmatrix = np.array([[1,2,3],[4,5,6]])print(matrix)print(\"\\n\")print(matrix.T)", "e": 4991, "s": 4848, "text": null }, { "code": null, "e": 4999, "s": 4991, "text": "Output:" }, { "code": null, "e": 5042, "s": 4999, "text": "[[1 2 3]\n [4 5 6]]\n\n[[1 4]\n [2 5]\n [3 6]]\n" }, { "code": null, "e": 5082, "s": 5042, "text": "Note :- “.T” only works on numpy arrays" }, { "code": null, "e": 5416, "s": 5082, "text": "This article is contributed by Mayank Rawat & simply modified by Md. Tahmid Hasan. 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." }, { "code": null, "e": 5541, "s": 5416, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5552, "s": 5541, "text": "pwakchaure" }, { "code": null, "e": 5568, "s": 5552, "text": "tahmidhasan3003" }, { "code": null, "e": 5585, "s": 5568, "text": "punamsingh628700" }, { "code": null, "e": 5607, "s": 5585, "text": "Python matrix-program" }, { "code": null, "e": 5614, "s": 5607, "text": "Python" } ]
Reversal algorithm for right rotation of an array
09 Jun, 2022 Given an array, right rotate it by k elements. After K=3 rotation Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} k = 3 Output: 8 9 10 1 2 3 4 5 6 7 Input: arr[] = {121, 232, 33, 43 ,5} k = 2 Output: 43 5 121 232 33 Note : In the below solution, k is assumed to be smaller than or equal to n. We can easily modify the solutions to handle larger k values by doing k = k % nAlgorithm: rotate(arr[], d, n) reverse(arr[], 0, n-1) ; reverse(arr[], 0, d-1); reverse(arr[], d, n-1); Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ program for right rotation of// an array (Reversal Algorithm)#include <bits/stdc++.h> /*Function to reverse arr[]from index start to end*/void reverseArray(int arr[], int start, int end){ while (start < end) { std::swap(arr[start], arr[end]); start++; end--; }} /* Function to right rotate arr[]of size n by d */void rightRotate(int arr[], int d, int n){ // if in case d>n,this will give segmentation fault. d=d%n; reverseArray(arr, 0, n-1); reverseArray(arr, 0, d-1); reverseArray(arr, d, n-1);} /* function to print an array */void printArray(int arr[], int size){ for (int i = 0; i < size; i++) std::cout << arr[i] << " ";} // driver codeint main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int n = sizeof(arr)/sizeof(arr[0]); int k = 3; rightRotate(arr, k, n); printArray(arr, n); return 0;} // Java program for right rotation of// an array (Reversal Algorithm)import java.io.*; class GFG{ // Function to reverse arr[] // from index start to end static void reverseArray(int arr[], int start, int end) { while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } // Function to right rotate // arr[] of size n by d static void rightRotate(int arr[], int d, int n) { reverseArray(arr, 0, n - 1); reverseArray(arr, 0, d - 1); reverseArray(arr, d, n - 1); } // Function to print an array static void printArray(int arr[], int size) { for (int i = 0; i < size; i++) System.out.print(arr[i] + " "); } public static void main (String[] args) { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int n = arr.length; int k = 3; rightRotate(arr, k, n); printArray(arr, n); }}// This code is contributed by Gitanjali. # Python3 program for right rotation of# an array (Reversal Algorithm) # Function to reverse arr# from index start to enddef reverseArray( arr, start, end): while (start < end): arr[start], arr[end] = arr[end], arr[start] start = start + 1 end = end - 1 # Function to right rotate arr# of size n by ddef rightRotate( arr, d, n): reverseArray(arr, 0, n - 1); reverseArray(arr, 0, d - 1); reverseArray(arr, d, n - 1); # function to print an arraydef printArray( arr, size): for i in range(0, size): print (arr[i], end = ' ') # Driver codearr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]n = len(arr)k = 3 # Function callrightRotate(arr, k, n)printArray(arr, n) # This article is contributed# by saloni1297 // C# program for right rotation of// an array (Reversal Algorithm)using System; class GFG { // Function to reverse arr[] // from index start to end static void reverseArray(int []arr, int start, int end) { while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } // Function to right rotate // arr[] of size n by d static void rightRotate(int []arr, int d, int n) { reverseArray(arr, 0, n - 1); reverseArray(arr, 0, d - 1); reverseArray(arr, d, n - 1); } // Function to print an array static void printArray(int []arr, int size) { for (int i = 0; i < size; i++) Console.Write(arr[i] + " "); } // Driver code public static void Main () { int []arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int n = arr.Length; int k = 3; rightRotate(arr, k, n); printArray(arr, n); }} // This code is contributed by vt_m. <?php// PHP program for right rotation of// an array (Reversal Algorithm) /*Function to reverse arr[]from index start to end*/function reverseArray(&$arr, $start, $end){ while ($start < $end) { $temp = $arr[$start]; $arr[$start] = $arr[$end]; $arr[$end] = $temp; $start++; $end--; }} /* Function to right rotate arr[]of size n by d */function rightRotate(&$arr, $d, $n){ reverseArray($arr, 0, $n - 1); reverseArray($arr, 0, $d - 1); reverseArray($arr, $d, $n - 1);} /* function to print an array */function printArray(&$arr, $size){ for ($i = 0; $i < $size; $i++) echo $arr[$i] . " ";} // Driver code$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); $n = sizeof($arr);$k = 3; rightRotate($arr, $k, $n);printArray($arr, $n); // This code is contributed by ita_c?> <script>// JavaScript program for right rotation of// an array (Reversal Algorithm) /*Function to reverse arr[]from index start to end*/function reverseArray(arr, start, end){ while (start < end){ let temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } return arr;} /* Function to right rotate arr[]of size n by d */function rightRotate(arr, d, n){ arr = reverseArray(arr, 0, n-1); arr = reverseArray(arr, 0, d-1); arr = reverseArray(arr, d, n-1); return arr;} /* function to print an array */function printArray( arr, size){ for (let i = 0; i < size; i++) document.write( arr[i] + " ");} // driver codelet arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let n = arr.length;let k = 3; arr = rightRotate(arr, k, n);printArray(arr, n); </script> Output: 8 9 10 1 2 3 4 5 6 7 Time Complexity: O(n) Space Complexity: O(1) This article is contributed by Aditya Ranjan. 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. ukasp rohitsingh07052 rohanthakurarmy abhishekashware12517 lfgowq0nisa5m3d7n2fn2ivime50337q4e5eivbs rkbhola5 simmytarika5 rotation Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in Java Maximum and minimum of an array using minimum number of comparisons Python | Using 2D arrays/lists the right way Find the smallest positive integer value that cannot be represented as sum of any subset of a given array Find a triplet that sum to a given value Product of Array except itself Introduction to Arrays Linked List vs Array Median of two sorted arrays of same size Stack Data Structure (Introduction and Program)
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Jun, 2022" }, { "code": null, "e": 101, "s": 52, "text": "Given an array, right rotate it by k elements. " }, { "code": null, "e": 122, "s": 101, "text": "After K=3 rotation " }, { "code": null, "e": 134, "s": 122, "text": "Examples: " }, { "code": null, "e": 322, "s": 134, "text": "Input: arr[] = {1, 2, 3, 4, 5, \n 6, 7, 8, 9, 10}\n k = 3\nOutput: 8 9 10 1 2 3 4 5 6 7\n\nInput: arr[] = {121, 232, 33, 43 ,5}\n k = 2\nOutput: 43 5 121 232 33" }, { "code": null, "e": 493, "s": 324, "text": "Note : In the below solution, k is assumed to be smaller than or equal to n. We can easily modify the solutions to handle larger k values by doing k = k % nAlgorithm: " }, { "code": null, "e": 592, "s": 493, "text": "rotate(arr[], d, n)\n reverse(arr[], 0, n-1) ;\n reverse(arr[], 0, d-1);\n reverse(arr[], d, n-1);" }, { "code": null, "e": 641, "s": 592, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 645, "s": 641, "text": "C++" }, { "code": null, "e": 650, "s": 645, "text": "Java" }, { "code": null, "e": 658, "s": 650, "text": "Python3" }, { "code": null, "e": 661, "s": 658, "text": "C#" }, { "code": null, "e": 665, "s": 661, "text": "PHP" }, { "code": null, "e": 676, "s": 665, "text": "Javascript" }, { "code": "// C++ program for right rotation of// an array (Reversal Algorithm)#include <bits/stdc++.h> /*Function to reverse arr[]from index start to end*/void reverseArray(int arr[], int start, int end){ while (start < end) { std::swap(arr[start], arr[end]); start++; end--; }} /* Function to right rotate arr[]of size n by d */void rightRotate(int arr[], int d, int n){ // if in case d>n,this will give segmentation fault. d=d%n; reverseArray(arr, 0, n-1); reverseArray(arr, 0, d-1); reverseArray(arr, d, n-1);} /* function to print an array */void printArray(int arr[], int size){ for (int i = 0; i < size; i++) std::cout << arr[i] << \" \";} // driver codeint main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int n = sizeof(arr)/sizeof(arr[0]); int k = 3; rightRotate(arr, k, n); printArray(arr, n); return 0;}", "e": 1609, "s": 676, "text": null }, { "code": "// Java program for right rotation of// an array (Reversal Algorithm)import java.io.*; class GFG{ // Function to reverse arr[] // from index start to end static void reverseArray(int arr[], int start, int end) { while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } // Function to right rotate // arr[] of size n by d static void rightRotate(int arr[], int d, int n) { reverseArray(arr, 0, n - 1); reverseArray(arr, 0, d - 1); reverseArray(arr, d, n - 1); } // Function to print an array static void printArray(int arr[], int size) { for (int i = 0; i < size; i++) System.out.print(arr[i] + \" \"); } public static void main (String[] args) { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int n = arr.length; int k = 3; rightRotate(arr, k, n); printArray(arr, n); }}// This code is contributed by Gitanjali.", "e": 2710, "s": 1609, "text": null }, { "code": "# Python3 program for right rotation of# an array (Reversal Algorithm) # Function to reverse arr# from index start to enddef reverseArray( arr, start, end): while (start < end): arr[start], arr[end] = arr[end], arr[start] start = start + 1 end = end - 1 # Function to right rotate arr# of size n by ddef rightRotate( arr, d, n): reverseArray(arr, 0, n - 1); reverseArray(arr, 0, d - 1); reverseArray(arr, d, n - 1); # function to print an arraydef printArray( arr, size): for i in range(0, size): print (arr[i], end = ' ') # Driver codearr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]n = len(arr)k = 3 # Function callrightRotate(arr, k, n)printArray(arr, n) # This article is contributed# by saloni1297", "e": 3477, "s": 2710, "text": null }, { "code": "// C# program for right rotation of// an array (Reversal Algorithm)using System; class GFG { // Function to reverse arr[] // from index start to end static void reverseArray(int []arr, int start, int end) { while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } // Function to right rotate // arr[] of size n by d static void rightRotate(int []arr, int d, int n) { reverseArray(arr, 0, n - 1); reverseArray(arr, 0, d - 1); reverseArray(arr, d, n - 1); } // Function to print an array static void printArray(int []arr, int size) { for (int i = 0; i < size; i++) Console.Write(arr[i] + \" \"); } // Driver code public static void Main () { int []arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int n = arr.Length; int k = 3; rightRotate(arr, k, n); printArray(arr, n); }} // This code is contributed by vt_m.", "e": 4612, "s": 3477, "text": null }, { "code": "<?php// PHP program for right rotation of// an array (Reversal Algorithm) /*Function to reverse arr[]from index start to end*/function reverseArray(&$arr, $start, $end){ while ($start < $end) { $temp = $arr[$start]; $arr[$start] = $arr[$end]; $arr[$end] = $temp; $start++; $end--; }} /* Function to right rotate arr[]of size n by d */function rightRotate(&$arr, $d, $n){ reverseArray($arr, 0, $n - 1); reverseArray($arr, 0, $d - 1); reverseArray($arr, $d, $n - 1);} /* function to print an array */function printArray(&$arr, $size){ for ($i = 0; $i < $size; $i++) echo $arr[$i] . \" \";} // Driver code$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); $n = sizeof($arr);$k = 3; rightRotate($arr, $k, $n);printArray($arr, $n); // This code is contributed by ita_c?>", "e": 5445, "s": 4612, "text": null }, { "code": "<script>// JavaScript program for right rotation of// an array (Reversal Algorithm) /*Function to reverse arr[]from index start to end*/function reverseArray(arr, start, end){ while (start < end){ let temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } return arr;} /* Function to right rotate arr[]of size n by d */function rightRotate(arr, d, n){ arr = reverseArray(arr, 0, n-1); arr = reverseArray(arr, 0, d-1); arr = reverseArray(arr, d, n-1); return arr;} /* function to print an array */function printArray( arr, size){ for (let i = 0; i < size; i++) document.write( arr[i] + \" \");} // driver codelet arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let n = arr.length;let k = 3; arr = rightRotate(arr, k, n);printArray(arr, n); </script>", "e": 6294, "s": 5445, "text": null }, { "code": null, "e": 6304, "s": 6294, "text": "Output: " }, { "code": null, "e": 6326, "s": 6304, "text": "8 9 10 1 2 3 4 5 6 7 " }, { "code": null, "e": 6348, "s": 6326, "text": "Time Complexity: O(n)" }, { "code": null, "e": 6371, "s": 6348, "text": "Space Complexity: O(1)" }, { "code": null, "e": 6793, "s": 6371, "text": "This article is contributed by Aditya Ranjan. 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": 6799, "s": 6793, "text": "ukasp" }, { "code": null, "e": 6815, "s": 6799, "text": "rohitsingh07052" }, { "code": null, "e": 6831, "s": 6815, "text": "rohanthakurarmy" }, { "code": null, "e": 6852, "s": 6831, "text": "abhishekashware12517" }, { "code": null, "e": 6893, "s": 6852, "text": "lfgowq0nisa5m3d7n2fn2ivime50337q4e5eivbs" }, { "code": null, "e": 6902, "s": 6893, "text": "rkbhola5" }, { "code": null, "e": 6915, "s": 6902, "text": "simmytarika5" }, { "code": null, "e": 6924, "s": 6915, "text": "rotation" }, { "code": null, "e": 6931, "s": 6924, "text": "Arrays" }, { "code": null, "e": 6938, "s": 6931, "text": "Arrays" }, { "code": null, "e": 7036, "s": 6938, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7068, "s": 7036, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 7136, "s": 7068, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 7181, "s": 7136, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 7287, "s": 7181, "text": "Find the smallest positive integer value that cannot be represented as sum of any subset of a given array" }, { "code": null, "e": 7328, "s": 7287, "text": "Find a triplet that sum to a given value" }, { "code": null, "e": 7359, "s": 7328, "text": "Product of Array except itself" }, { "code": null, "e": 7382, "s": 7359, "text": "Introduction to Arrays" }, { "code": null, "e": 7403, "s": 7382, "text": "Linked List vs Array" }, { "code": null, "e": 7444, "s": 7403, "text": "Median of two sorted arrays of same size" } ]
Snowflakes Fractal using Python
23 Sep, 2021 To create Snowflake fractals using Python programmingWhat are fractals 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. Driven by recursion, fractals are images of dynamic systems – the pictures of Chaos. What is turtle programming in python?? Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzig and Seymour Papert in 1966.Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an import turtle, give it the command turtle.forward(15), and it moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as it moves. Give it the command turtle.right(25), and it rotates in-place 25 degrees clockwise.By combining together these and similar commands, intricate shapes and pictures can easily be drawn.The turtle module is an extended reimplementation of the same-named module from the Python standard distribution up to version Python 2.5.It tries to keep the merits of the old turtle module and to be (nearly) 100% compatible with it. This means in the first place to enable the learning programmer to use all the commands, classes and methods interactively when using the module from within IDLE run with the -n switch.The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. This Python Code allow you to create Snowflakes design by using its standard library Turtle for GUI designing. This code creates 20 (you can change it in the source code) snowflakes randomly of random size and color in random position of the screen. Python # Python code to draw snowflakes fractal.import turtleimport random # setup the window with a background colorwn = turtle.Screen()wn.bgcolor("cyan") # assign a name to your turtleelsa = turtle.Turtle()elsa.speed(15) # create a list of colourssfcolor = ["white", "blue", "purple", "grey", "magenta"] # create a function to create different size snowflakesdef snowflake(size): # move the pen into starting position elsa.penup() elsa.forward(10*size) elsa.left(45) elsa.pendown() elsa.color(random.choice(sfcolor)) # draw branch 8 times to make a snowflake for i in range(8): branch(size) elsa.left(45) # create one branch of the snowflakedef branch(size): for i in range(3): for i in range(3): elsa.forward(10.0*size/3) elsa.backward(10.0*size/3) elsa.right(45) elsa.left(90) elsa.backward(10.0*size/3) elsa.left(45) elsa.right(90) elsa.forward(10.0*size) # loop to create 20 different sized snowflakes# with different starting co-ordinatesfor i in range(20): x = random.randint(-200, 200) y = random.randint(-200, 200) sf_size = random.randint(1, 4) elsa.penup() elsa.goto(x, y) elsa.pendown() snowflake(sf_size) # leave the window open until you click to close wn.exitonclick() Output: This article is contributed by Subhajit Saha. 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. anikakapoor computer-graphics Fractal Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Sep, 2021" }, { "code": null, "e": 126, "s": 54, "text": "To create Snowflake fractals using Python programmingWhat are fractals " }, { "code": null, "e": 426, "s": 126, "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. Driven by recursion, fractals are images of dynamic systems – the pictures of Chaos." }, { "code": null, "e": 467, "s": 426, "text": "What is turtle programming in python?? " }, { "code": null, "e": 1686, "s": 467, "text": "Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzig and Seymour Papert in 1966.Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an import turtle, give it the command turtle.forward(15), and it moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as it moves. Give it the command turtle.right(25), and it rotates in-place 25 degrees clockwise.By combining together these and similar commands, intricate shapes and pictures can easily be drawn.The turtle module is an extended reimplementation of the same-named module from the Python standard distribution up to version Python 2.5.It tries to keep the merits of the old turtle module and to be (nearly) 100% compatible with it. This means in the first place to enable the learning programmer to use all the commands, classes and methods interactively when using the module from within IDLE run with the -n switch.The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support." }, { "code": null, "e": 1940, "s": 1688, "text": "This Python Code allow you to create Snowflakes design by using its standard library Turtle for GUI designing. This code creates 20 (you can change it in the source code) snowflakes randomly of random size and color in random position of the screen. " }, { "code": null, "e": 1951, "s": 1944, "text": "Python" }, { "code": "# Python code to draw snowflakes fractal.import turtleimport random # setup the window with a background colorwn = turtle.Screen()wn.bgcolor(\"cyan\") # assign a name to your turtleelsa = turtle.Turtle()elsa.speed(15) # create a list of colourssfcolor = [\"white\", \"blue\", \"purple\", \"grey\", \"magenta\"] # create a function to create different size snowflakesdef snowflake(size): # move the pen into starting position elsa.penup() elsa.forward(10*size) elsa.left(45) elsa.pendown() elsa.color(random.choice(sfcolor)) # draw branch 8 times to make a snowflake for i in range(8): branch(size) elsa.left(45) # create one branch of the snowflakedef branch(size): for i in range(3): for i in range(3): elsa.forward(10.0*size/3) elsa.backward(10.0*size/3) elsa.right(45) elsa.left(90) elsa.backward(10.0*size/3) elsa.left(45) elsa.right(90) elsa.forward(10.0*size) # loop to create 20 different sized snowflakes# with different starting co-ordinatesfor i in range(20): x = random.randint(-200, 200) y = random.randint(-200, 200) sf_size = random.randint(1, 4) elsa.penup() elsa.goto(x, y) elsa.pendown() snowflake(sf_size) # leave the window open until you click to close wn.exitonclick() ", "e": 3268, "s": 1951, "text": null }, { "code": null, "e": 3278, "s": 3268, "text": "Output: " }, { "code": null, "e": 3700, "s": 3278, "text": "This article is contributed by Subhajit Saha. 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": 3712, "s": 3700, "text": "anikakapoor" }, { "code": null, "e": 3730, "s": 3712, "text": "computer-graphics" }, { "code": null, "e": 3738, "s": 3730, "text": "Fractal" }, { "code": null, "e": 3743, "s": 3738, "text": "Misc" }, { "code": null, "e": 3748, "s": 3743, "text": "Misc" }, { "code": null, "e": 3753, "s": 3748, "text": "Misc" } ]
Difference between semantic and non-semantic elements
11 Sep, 2020 Semantic HTML elements:These elements simply mean, elements with meaning. The reason being, there definition in the code tells the browser and the developer what they are supposed to do. Framing in simpler words, these elements describe the type of content they are supposed to contain. Following is the list of some semantic elements : article aside details figcaption figure footer form header main mark nav table section Example: The following program contains some semantic elements to explain the context better: <!DOCTYPE html><html><head> <title>my web page</title> <style type="text/css"> h1{ color: green; font-weight: bold; } table, tr, td{ border: 1px solid black; } th{ font-weight: bold; color: red; } </style></head><body> <article> <h1>GeeksforGeeks</h1> <p>A Computer Science Portal for Geeks</p> </article> <table> <tr> <th>head1</th> <th>head2</th> </tr> <tr> <td>A</td> <td>0</td> </tr> <tr> <td>B</td> <td>1</td> </tr> </table></body></html> Output: Non-Semantic elements: Unlike, semantic elements they don’t have any meaning. They don’t tell anything about the content they contain. They can be used with different attributes to mark up semantics common to a group. Following is the list of some non-semantic elements: div span Example:The following code depicts how non-semantic elements work: <!DOCTYPE html><html><head> <title>my web page</title> <style type="text/css"> span{ color: green; font-size: 40px ; font-weight: bold; } </style></head><body> <div> <span>GeeksForGeeks</span> <br> A computer science portal for geeks </div></body></html> Output: Difference between semantic and non-semantic elements: HTML-Basics HTML-Misc Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Sep, 2020" }, { "code": null, "e": 339, "s": 52, "text": "Semantic HTML elements:These elements simply mean, elements with meaning. The reason being, there definition in the code tells the browser and the developer what they are supposed to do. Framing in simpler words, these elements describe the type of content they are supposed to contain." }, { "code": null, "e": 389, "s": 339, "text": "Following is the list of some semantic elements :" }, { "code": null, "e": 397, "s": 389, "text": "article" }, { "code": null, "e": 403, "s": 397, "text": "aside" }, { "code": null, "e": 411, "s": 403, "text": "details" }, { "code": null, "e": 422, "s": 411, "text": "figcaption" }, { "code": null, "e": 429, "s": 422, "text": "figure" }, { "code": null, "e": 436, "s": 429, "text": "footer" }, { "code": null, "e": 441, "s": 436, "text": "form" }, { "code": null, "e": 448, "s": 441, "text": "header" }, { "code": null, "e": 453, "s": 448, "text": "main" }, { "code": null, "e": 458, "s": 453, "text": "mark" }, { "code": null, "e": 462, "s": 458, "text": "nav" }, { "code": null, "e": 468, "s": 462, "text": "table" }, { "code": null, "e": 476, "s": 468, "text": "section" }, { "code": null, "e": 570, "s": 476, "text": "Example: The following program contains some semantic elements to explain the context better:" }, { "code": "<!DOCTYPE html><html><head> <title>my web page</title> <style type=\"text/css\"> h1{ color: green; font-weight: bold; } table, tr, td{ border: 1px solid black; } th{ font-weight: bold; color: red; } </style></head><body> <article> <h1>GeeksforGeeks</h1> <p>A Computer Science Portal for Geeks</p> </article> <table> <tr> <th>head1</th> <th>head2</th> </tr> <tr> <td>A</td> <td>0</td> </tr> <tr> <td>B</td> <td>1</td> </tr> </table></body></html>", "e": 1291, "s": 570, "text": null }, { "code": null, "e": 1299, "s": 1291, "text": "Output:" }, { "code": null, "e": 1517, "s": 1299, "text": "Non-Semantic elements: Unlike, semantic elements they don’t have any meaning. They don’t tell anything about the content they contain. They can be used with different attributes to mark up semantics common to a group." }, { "code": null, "e": 1570, "s": 1517, "text": "Following is the list of some non-semantic elements:" }, { "code": null, "e": 1574, "s": 1570, "text": "div" }, { "code": null, "e": 1579, "s": 1574, "text": "span" }, { "code": null, "e": 1646, "s": 1579, "text": "Example:The following code depicts how non-semantic elements work:" }, { "code": "<!DOCTYPE html><html><head> <title>my web page</title> <style type=\"text/css\"> span{ color: green; font-size: 40px ; font-weight: bold; } </style></head><body> <div> <span>GeeksForGeeks</span> <br> A computer science portal for geeks </div></body></html>", "e": 1971, "s": 1646, "text": null }, { "code": null, "e": 1979, "s": 1971, "text": "Output:" }, { "code": null, "e": 2034, "s": 1979, "text": "Difference between semantic and non-semantic elements:" }, { "code": null, "e": 2046, "s": 2034, "text": "HTML-Basics" }, { "code": null, "e": 2056, "s": 2046, "text": "HTML-Misc" }, { "code": null, "e": 2063, "s": 2056, "text": "Picked" }, { "code": null, "e": 2068, "s": 2063, "text": "HTML" }, { "code": null, "e": 2085, "s": 2068, "text": "Web Technologies" }, { "code": null, "e": 2090, "s": 2085, "text": "HTML" }, { "code": null, "e": 2188, "s": 2090, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2236, "s": 2188, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2298, "s": 2236, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2348, "s": 2298, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2372, "s": 2348, "text": "REST API (Introduction)" }, { "code": null, "e": 2425, "s": 2372, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2458, "s": 2425, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2520, "s": 2458, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2581, "s": 2520, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2631, "s": 2581, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Insert a node in Linked List before a given node
24 Sep, 2021 Given a node of Linked List N and a value K, the task is to insert the node with value K in the linked list before the given node N. Structure of the Node: C++ Java Python3 C# Javascript // Structure of Nodestruct Node { int data; Node* next; // Constructor of Node Node(int val, Node* link = 0) : data(val), next(link) { }}; // Structure of Nodepublic class Node{ public int data; public Node next; // Constructor of Node public Node(int val, Node link = null) { this.data = val; this.next = link; }} // This code is contributed by divyesh072019 # Structure of Nodeclass Node: # Constructor of Node def __init__(self, val, link = None): self.data = val self.next = link # This code is contributed by pratham76 // Structure of Nodepublic class Node{ public int data; public Node next; // Constructor of Node public Node(int val, Node link = null) { this.data = val; this.next = link; }}; // This code is contributed by rutvik_56 <script>// Structure of Nodeclass Node { // Constructor of Node constructor(val, link = null) { this.data = val; this.next = link; }} // This code is contributed by gauravrajput1</script> 5 8 6 In the given problem there might be two cases: Given node is the head node. Given node is any valid node except the head. The idea is to create a new node with the given value K. Then the next part of the new node will be updated with the pointer head. And finally, the head will be updated with the new node’s address. Below is the image of the same: The simplest approach is to traverse the given linked list to search the previous node of the given node. Then, create the new node with the given value K.Now, update the next part of the new node with the address of the given node and the next part of the previous node with the address of the new node. Below is an illustration of the approach with the help of image: Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; struct Node { int data; Node* next; // Constructor of Node Node(int val, Node* link = 0) : data(val), next(link) { }}; // Create a head nodeNode* head = new Node(5); // Function prints the linked list// starting from the given nodevoid printList(Node* n){ // Till n is not NULL while (n != NULL) { // Print the data cout << n->data << " "; n = n->next; }} // Function to add a node before the// given node other than head nodeNode* addBefore(Node* given_ptr, int val){ // First check if the given pointer // is the address of head if (head == given_ptr) { // Create a new node Node* n = new Node(val); // Point to next to current head n->next = head; // Update the head pointer head = n; return n; } // Otherwise traverse the list to // find previous node of given node else { Node *p, *n = head; // This loop will return p with // previous pointer of given node for (n, p; n != given_ptr; p = n, n = n->next) ; // Create a new node Node* m = new Node(val); // Update the m->next m->next = p->next; // Update previous node's next p->next = m; return m; }} // Driver Codeint main(){ // Head Node head->next = new Node(6); // Function Call addBefore(head->next, 8); // Print the linked List printList(head);} // Java program for the above approachimport java.util.*; class GFG{ static class Node{ int data; Node next; // Constructor of Node Node(int val) { this.data = val; this.next = null; }} static Node head = new Node(5); // Function prints the linked list// starting from the given nodestatic void printList(Node n){ // Till n is not null while (n != null) { // Print the data System.out.print(n.data + " "); n = n.next; }} // Function to add a node before the// given node other than head nodestatic Node addBefore(Node given_ptr, int val){ // First check if the given pointer // is the address of head if (head == given_ptr) { // Create a new node Node n = new Node(val); // Point to next to current head n.next = head; // Update the head pointer head = n; return n; } // Otherwise traverse the list to // find previous node of given node else { Node p = null; // This loop will return p with // previous pointer of given node for(Node n = head; n != given_ptr; p = n, n = n.next); // Create a new node Node m = new Node(val); // Update the m.next m.next = p.next; // Update previous node's next p.next = m; return m; }} // Driver Codepublic static void main(String[] args){ // Head Node head.next = new Node(6); // Function Call addBefore(head.next, 8); // Print the linked List printList(head);}} // This code is contributed by Amit Katiyar # Python3 program for the above approachclass Node: # Constructor of Node def __init__(self, val, link = None): self.data = val self.next = link # Create a head nodehead = Node(5); # Function prints the linked list# starting from the given nodedef printList(n): # Till n is not NULL while (n != None): # Print the data print(n.data, end = ' ') n = n.next; # Function to add a node before the# given node other than head nodedef addBefore(given_ptr, val): global head # First check if the given pointer # is the address of head if (head == given_ptr): # Create a node n = Node(val); # Point to next to current head n.next = head; # Update the head pointer head = n; return n; # Otherwise traverse the list to # find previous node of given node else: p = None n = head; # This loop will return p with # previous pointer of given node while(n != given_ptr): p = n n = n.next # Create a node m = Node(val); # Update the m.next m.next = p.next; # Update previous node's next p.next = m; return m; # Driver Codeif __name__=='__main__': # Head Node head.next = Node(6); # Function Call addBefore(head.next, 8); # Print the linked List printList(head); # This code is contributed by rutvik_56 // C# program for the// above approachusing System;class GFG{ class Node{ public int data; public Node next; // Constructor of Node public Node(int val) { this.data = val; this.next = null; }} static Node head = new Node(5); // Function prints the linked list// starting from the given nodestatic void printList(Node n){ // Till n is not null while (n != null) { // Print the data Console.Write(n.data + " "); n = n.next; }} // Function to add a node before the// given node other than head nodestatic Node addBefore(Node given_ptr, int val){ // First check if the given // pointer is the address of // head if (head == given_ptr) { // Create a new node Node n = new Node(val); // Point to next to current // head n.next = head; // Update the head pointer head = n; return n; } // Otherwise traverse the list // to find previous node of // given node else { Node p = null; // This loop will return p with // previous pointer of given node for(Node n = head; n != given_ptr; p = n, n = n.next); // Create a new node Node m = new Node(val); // Update the m.next m.next = p.next; // Update previous node's next p.next = m; return m; }} // Driver Codepublic static void Main(String[] args){ // Head Node head.next = new Node(6); // Function Call addBefore(head.next, 8); // Print the linked List printList(head);}} // This code is contributed by shikhasingrajput <script> // Javascript program for the above approach class Node { // Constructor of Node constructor(val) { this.data = val; this.next = null; } } var head = new Node(5); // Function prints the linked list // starting from the given node function printList(n) { // Till n is not null while (n != null) { // Print the data document.write(n.data + " "); n = n.next; } } // Function to add a node before the // given node other than head node function addBefore(given_ptr , val) { // First check if the given pointer // is the address of head if (head == given_ptr) { // Create a new node var n = new Node(val); // Point to next to current head n.next = head; // Update the head pointer head = n; return n; } // Otherwise traverse the list to // find previous node of given node else { var p = null; // This loop will return p with // previous pointer of given node for (n = head; n != given_ptr; p = n, n = n.next) ; // Create a new node var m = new Node(val); // Update the m.next m.next = p.next; // Update previous node's next p.next = m; return m; } } // Driver Code // Head Node head.next = new Node(6); // Function Call addBefore(head.next, 8); // Print the linked List printList(head); // This code is contributed by todaysgaurav </script> 5 8 6 Time Complexity: O(N) Auxiliary Space: O(1) amit143katiyar shikhasingrajput rutvik_56 pratham76 divyesh072019 GauravRajput1 todaysgaurav surinderdawra388 Linked Lists Data Structures Linked List Data Structures Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Sep, 2021" }, { "code": null, "e": 186, "s": 53, "text": "Given a node of Linked List N and a value K, the task is to insert the node with value K in the linked list before the given node N." }, { "code": null, "e": 209, "s": 186, "text": "Structure of the Node:" }, { "code": null, "e": 213, "s": 209, "text": "C++" }, { "code": null, "e": 218, "s": 213, "text": "Java" }, { "code": null, "e": 226, "s": 218, "text": "Python3" }, { "code": null, "e": 229, "s": 226, "text": "C#" }, { "code": null, "e": 240, "s": 229, "text": "Javascript" }, { "code": "// Structure of Nodestruct Node { int data; Node* next; // Constructor of Node Node(int val, Node* link = 0) : data(val), next(link) { }};", "e": 405, "s": 240, "text": null }, { "code": "// Structure of Nodepublic class Node{ public int data; public Node next; // Constructor of Node public Node(int val, Node link = null) { this.data = val; this.next = link; }} // This code is contributed by divyesh072019", "e": 661, "s": 405, "text": null }, { "code": "# Structure of Nodeclass Node: # Constructor of Node def __init__(self, val, link = None): self.data = val self.next = link # This code is contributed by pratham76", "e": 867, "s": 661, "text": null }, { "code": "// Structure of Nodepublic class Node{ public int data; public Node next; // Constructor of Node public Node(int val, Node link = null) { this.data = val; this.next = link; }}; // This code is contributed by rutvik_56", "e": 1120, "s": 867, "text": null }, { "code": "<script>// Structure of Nodeclass Node { // Constructor of Node constructor(val, link = null) { this.data = val; this.next = link; }} // This code is contributed by gauravrajput1</script>", "e": 1334, "s": 1120, "text": null }, { "code": null, "e": 1340, "s": 1334, "text": "5 8 6" }, { "code": null, "e": 1389, "s": 1342, "text": "In the given problem there might be two cases:" }, { "code": null, "e": 1418, "s": 1389, "text": "Given node is the head node." }, { "code": null, "e": 1464, "s": 1418, "text": "Given node is any valid node except the head." }, { "code": null, "e": 1694, "s": 1464, "text": "The idea is to create a new node with the given value K. Then the next part of the new node will be updated with the pointer head. And finally, the head will be updated with the new node’s address. Below is the image of the same:" }, { "code": null, "e": 2064, "s": 1694, "text": "The simplest approach is to traverse the given linked list to search the previous node of the given node. Then, create the new node with the given value K.Now, update the next part of the new node with the address of the given node and the next part of the previous node with the address of the new node. Below is an illustration of the approach with the help of image:" }, { "code": null, "e": 2115, "s": 2064, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2119, "s": 2115, "text": "C++" }, { "code": null, "e": 2124, "s": 2119, "text": "Java" }, { "code": null, "e": 2132, "s": 2124, "text": "Python3" }, { "code": null, "e": 2135, "s": 2132, "text": "C#" }, { "code": null, "e": 2146, "s": 2135, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; struct Node { int data; Node* next; // Constructor of Node Node(int val, Node* link = 0) : data(val), next(link) { }}; // Create a head nodeNode* head = new Node(5); // Function prints the linked list// starting from the given nodevoid printList(Node* n){ // Till n is not NULL while (n != NULL) { // Print the data cout << n->data << \" \"; n = n->next; }} // Function to add a node before the// given node other than head nodeNode* addBefore(Node* given_ptr, int val){ // First check if the given pointer // is the address of head if (head == given_ptr) { // Create a new node Node* n = new Node(val); // Point to next to current head n->next = head; // Update the head pointer head = n; return n; } // Otherwise traverse the list to // find previous node of given node else { Node *p, *n = head; // This loop will return p with // previous pointer of given node for (n, p; n != given_ptr; p = n, n = n->next) ; // Create a new node Node* m = new Node(val); // Update the m->next m->next = p->next; // Update previous node's next p->next = m; return m; }} // Driver Codeint main(){ // Head Node head->next = new Node(6); // Function Call addBefore(head->next, 8); // Print the linked List printList(head);}", "e": 3696, "s": 2146, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ static class Node{ int data; Node next; // Constructor of Node Node(int val) { this.data = val; this.next = null; }} static Node head = new Node(5); // Function prints the linked list// starting from the given nodestatic void printList(Node n){ // Till n is not null while (n != null) { // Print the data System.out.print(n.data + \" \"); n = n.next; }} // Function to add a node before the// given node other than head nodestatic Node addBefore(Node given_ptr, int val){ // First check if the given pointer // is the address of head if (head == given_ptr) { // Create a new node Node n = new Node(val); // Point to next to current head n.next = head; // Update the head pointer head = n; return n; } // Otherwise traverse the list to // find previous node of given node else { Node p = null; // This loop will return p with // previous pointer of given node for(Node n = head; n != given_ptr; p = n, n = n.next); // Create a new node Node m = new Node(val); // Update the m.next m.next = p.next; // Update previous node's next p.next = m; return m; }} // Driver Codepublic static void main(String[] args){ // Head Node head.next = new Node(6); // Function Call addBefore(head.next, 8); // Print the linked List printList(head);}} // This code is contributed by Amit Katiyar", "e": 5341, "s": 3696, "text": null }, { "code": "# Python3 program for the above approachclass Node: # Constructor of Node def __init__(self, val, link = None): self.data = val self.next = link # Create a head nodehead = Node(5); # Function prints the linked list# starting from the given nodedef printList(n): # Till n is not NULL while (n != None): # Print the data print(n.data, end = ' ') n = n.next; # Function to add a node before the# given node other than head nodedef addBefore(given_ptr, val): global head # First check if the given pointer # is the address of head if (head == given_ptr): # Create a node n = Node(val); # Point to next to current head n.next = head; # Update the head pointer head = n; return n; # Otherwise traverse the list to # find previous node of given node else: p = None n = head; # This loop will return p with # previous pointer of given node while(n != given_ptr): p = n n = n.next # Create a node m = Node(val); # Update the m.next m.next = p.next; # Update previous node's next p.next = m; return m; # Driver Codeif __name__=='__main__': # Head Node head.next = Node(6); # Function Call addBefore(head.next, 8); # Print the linked List printList(head); # This code is contributed by rutvik_56", "e": 6823, "s": 5341, "text": null }, { "code": "// C# program for the// above approachusing System;class GFG{ class Node{ public int data; public Node next; // Constructor of Node public Node(int val) { this.data = val; this.next = null; }} static Node head = new Node(5); // Function prints the linked list// starting from the given nodestatic void printList(Node n){ // Till n is not null while (n != null) { // Print the data Console.Write(n.data + \" \"); n = n.next; }} // Function to add a node before the// given node other than head nodestatic Node addBefore(Node given_ptr, int val){ // First check if the given // pointer is the address of // head if (head == given_ptr) { // Create a new node Node n = new Node(val); // Point to next to current // head n.next = head; // Update the head pointer head = n; return n; } // Otherwise traverse the list // to find previous node of // given node else { Node p = null; // This loop will return p with // previous pointer of given node for(Node n = head; n != given_ptr; p = n, n = n.next); // Create a new node Node m = new Node(val); // Update the m.next m.next = p.next; // Update previous node's next p.next = m; return m; }} // Driver Codepublic static void Main(String[] args){ // Head Node head.next = new Node(6); // Function Call addBefore(head.next, 8); // Print the linked List printList(head);}} // This code is contributed by shikhasingrajput", "e": 8330, "s": 6823, "text": null }, { "code": "<script> // Javascript program for the above approach class Node { // Constructor of Node constructor(val) { this.data = val; this.next = null; } } var head = new Node(5); // Function prints the linked list // starting from the given node function printList(n) { // Till n is not null while (n != null) { // Print the data document.write(n.data + \" \"); n = n.next; } } // Function to add a node before the // given node other than head node function addBefore(given_ptr , val) { // First check if the given pointer // is the address of head if (head == given_ptr) { // Create a new node var n = new Node(val); // Point to next to current head n.next = head; // Update the head pointer head = n; return n; } // Otherwise traverse the list to // find previous node of given node else { var p = null; // This loop will return p with // previous pointer of given node for (n = head; n != given_ptr; p = n, n = n.next) ; // Create a new node var m = new Node(val); // Update the m.next m.next = p.next; // Update previous node's next p.next = m; return m; } } // Driver Code // Head Node head.next = new Node(6); // Function Call addBefore(head.next, 8); // Print the linked List printList(head); // This code is contributed by todaysgaurav </script>", "e": 10004, "s": 8330, "text": null }, { "code": null, "e": 10010, "s": 10004, "text": "5 8 6" }, { "code": null, "e": 10057, "s": 10012, "text": "Time Complexity: O(N) Auxiliary Space: O(1) " }, { "code": null, "e": 10072, "s": 10057, "text": "amit143katiyar" }, { "code": null, "e": 10089, "s": 10072, "text": "shikhasingrajput" }, { "code": null, "e": 10099, "s": 10089, "text": "rutvik_56" }, { "code": null, "e": 10109, "s": 10099, "text": "pratham76" }, { "code": null, "e": 10123, "s": 10109, "text": "divyesh072019" }, { "code": null, "e": 10137, "s": 10123, "text": "GauravRajput1" }, { "code": null, "e": 10150, "s": 10137, "text": "todaysgaurav" }, { "code": null, "e": 10167, "s": 10150, "text": "surinderdawra388" }, { "code": null, "e": 10180, "s": 10167, "text": "Linked Lists" }, { "code": null, "e": 10196, "s": 10180, "text": "Data Structures" }, { "code": null, "e": 10208, "s": 10196, "text": "Linked List" }, { "code": null, "e": 10224, "s": 10208, "text": "Data Structures" }, { "code": null, "e": 10236, "s": 10224, "text": "Linked List" } ]
Difference between Queue and Deque in C++ - GeeksforGeeks
02 Nov, 2021 Queue: A Queue is a linear data structure that follows a First In First Out (FIFO) order in which the operations are performed. It is a type of container adaptor where elements are inserted into one end of the container and deleted from the other. Functions: empty(): Tests whether the queue is empty. size(): Returns the unsigned int, size of the queue. queue::front() and queue::back(): front() function returns a reference to the first element or the oldest of the queue. back() function returns a reference to the last or the newest element of the queue. push(k) and pop(): push() function adds the element ‘k’ at the end of the queue. pop() function deletes the element from the beginning of the queue and reduces its size by 1. swap(): exchanges the elements of two different queues of the same type but may or may not of the same size. emplace(): it is used to insert a new element at end of the queue. Syntax: queue <data_type> q Below is the program to illustrate the same: C++ // C++ program to demonstrate the// working of queue#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare a queue queue<int> q; // Insert elements in the queue q.push(10); q.push(5); q.push(15); q.push(1); // Delete elements from the queue q.pop(); q.pop(); cout << "Elements in Queue are: "; // Print the element stored // in queue while (!q.empty()) { cout << q.front() << ' '; // Pop the front element q.pop(); } return 0;} Elements in Queue are: 15 1 Deque: Deque is a sequence container with the ability of expansion and contraction on both ends. It is a template of Standard Template Library or STL in C++is. It is similar to vectors but are more efficient for the insertion and deletion of elements. Contiguous storage allocation in deque may not be guaranteed as in vectors. Functions: max_size(): Returns the maximum number of elements deque can contain. push_back() and push_front(): push_front( ) push the elements into a deque from the front and push_back( ) push elements into a deque from the back. pop_front() and pop_back(): pop_front() function is used to pop elements from a deque from the front and pop_back( ) function is used to pop elements from a deque from the back. clear() and erase(): clear is used to remove all the elements from the deque and erase is used to remove some specified elements. insert(): increases the container side by inserting element in the specified position. resize(): changes the size of the element’s container as per requirement. rbegin() and rend(): rbegin() points to the last element of the deque whereas rend points to the position before the beginning of the deque. at() and swap(): at() points to the position of the element given in the parameter and swap( ) is used two swap elements of two deques. emplace_front() and emplace_back(): these two functions are used to insert new elements in the container at the beginning and at the end of deque respectively. Syntax: deque<data_type> dq Below is the program to illustrate the same: C++ // C++ program to demonstrate the// working of deque#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare a deque deque<int> dq; // Insert element in the front dq.push_front(10); dq.push_front(5); dq.push_front(3); // Delete elements from the the front dq.pop_front(); dq.pop_front(); // Insert elements in the back dq.push_back(1); dq.push_back(50); dq.push_back(2); // Delete elements from the the back dq.pop_back(); dq.pop_back(); cout << "Elements in deque are: "; // Print the element stored // in deque while (!dq.empty()) { cout << " " << dq.front(); dq.pop_front(); } return 0;} Elements in deque are: 10 1 Below is the tabular difference between the queue and deque: Queue Deque harshpanwar1705 cpp-deque deque C++ Difference Between Queue Queue CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ Convert string to char array in C++ Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Difference between Process and Thread
[ { "code": null, "e": 24200, "s": 24172, "text": "\n02 Nov, 2021" }, { "code": null, "e": 24448, "s": 24200, "text": "Queue: A Queue is a linear data structure that follows a First In First Out (FIFO) order in which the operations are performed. It is a type of container adaptor where elements are inserted into one end of the container and deleted from the other." }, { "code": null, "e": 24459, "s": 24448, "text": "Functions:" }, { "code": null, "e": 24502, "s": 24459, "text": "empty(): Tests whether the queue is empty." }, { "code": null, "e": 24555, "s": 24502, "text": "size(): Returns the unsigned int, size of the queue." }, { "code": null, "e": 24759, "s": 24555, "text": "queue::front() and queue::back(): front() function returns a reference to the first element or the oldest of the queue. back() function returns a reference to the last or the newest element of the queue." }, { "code": null, "e": 24934, "s": 24759, "text": "push(k) and pop(): push() function adds the element ‘k’ at the end of the queue. pop() function deletes the element from the beginning of the queue and reduces its size by 1." }, { "code": null, "e": 25043, "s": 24934, "text": "swap(): exchanges the elements of two different queues of the same type but may or may not of the same size." }, { "code": null, "e": 25110, "s": 25043, "text": "emplace(): it is used to insert a new element at end of the queue." }, { "code": null, "e": 25118, "s": 25110, "text": "Syntax:" }, { "code": null, "e": 25138, "s": 25118, "text": "queue <data_type> q" }, { "code": null, "e": 25183, "s": 25138, "text": "Below is the program to illustrate the same:" }, { "code": null, "e": 25187, "s": 25183, "text": "C++" }, { "code": "// C++ program to demonstrate the// working of queue#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare a queue queue<int> q; // Insert elements in the queue q.push(10); q.push(5); q.push(15); q.push(1); // Delete elements from the queue q.pop(); q.pop(); cout << \"Elements in Queue are: \"; // Print the element stored // in queue while (!q.empty()) { cout << q.front() << ' '; // Pop the front element q.pop(); } return 0;}", "e": 25717, "s": 25187, "text": null }, { "code": null, "e": 25745, "s": 25717, "text": "Elements in Queue are: 15 1" }, { "code": null, "e": 26075, "s": 25747, "text": "Deque: Deque is a sequence container with the ability of expansion and contraction on both ends. It is a template of Standard Template Library or STL in C++is. It is similar to vectors but are more efficient for the insertion and deletion of elements. Contiguous storage allocation in deque may not be guaranteed as in vectors." }, { "code": null, "e": 26086, "s": 26075, "text": "Functions:" }, { "code": null, "e": 26156, "s": 26086, "text": "max_size(): Returns the maximum number of elements deque can contain." }, { "code": null, "e": 26305, "s": 26156, "text": "push_back() and push_front(): push_front( ) push the elements into a deque from the front and push_back( ) push elements into a deque from the back." }, { "code": null, "e": 26483, "s": 26305, "text": "pop_front() and pop_back(): pop_front() function is used to pop elements from a deque from the front and pop_back( ) function is used to pop elements from a deque from the back." }, { "code": null, "e": 26614, "s": 26483, "text": "clear() and erase(): clear is used to remove all the elements from the deque and erase is used to remove some specified elements." }, { "code": null, "e": 26701, "s": 26614, "text": "insert(): increases the container side by inserting element in the specified position." }, { "code": null, "e": 26775, "s": 26701, "text": "resize(): changes the size of the element’s container as per requirement." }, { "code": null, "e": 26916, "s": 26775, "text": "rbegin() and rend(): rbegin() points to the last element of the deque whereas rend points to the position before the beginning of the deque." }, { "code": null, "e": 27052, "s": 26916, "text": "at() and swap(): at() points to the position of the element given in the parameter and swap( ) is used two swap elements of two deques." }, { "code": null, "e": 27212, "s": 27052, "text": "emplace_front() and emplace_back(): these two functions are used to insert new elements in the container at the beginning and at the end of deque respectively." }, { "code": null, "e": 27220, "s": 27212, "text": "Syntax:" }, { "code": null, "e": 27240, "s": 27220, "text": "deque<data_type> dq" }, { "code": null, "e": 27285, "s": 27240, "text": "Below is the program to illustrate the same:" }, { "code": null, "e": 27289, "s": 27285, "text": "C++" }, { "code": "// C++ program to demonstrate the// working of deque#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare a deque deque<int> dq; // Insert element in the front dq.push_front(10); dq.push_front(5); dq.push_front(3); // Delete elements from the the front dq.pop_front(); dq.pop_front(); // Insert elements in the back dq.push_back(1); dq.push_back(50); dq.push_back(2); // Delete elements from the the back dq.pop_back(); dq.pop_back(); cout << \"Elements in deque are: \"; // Print the element stored // in deque while (!dq.empty()) { cout << \" \" << dq.front(); dq.pop_front(); } return 0;}", "e": 27992, "s": 27289, "text": null }, { "code": null, "e": 28021, "s": 27992, "text": "Elements in deque are: 10 1" }, { "code": null, "e": 28084, "s": 28023, "text": "Below is the tabular difference between the queue and deque:" }, { "code": null, "e": 28090, "s": 28084, "text": "Queue" }, { "code": null, "e": 28096, "s": 28090, "text": "Deque" }, { "code": null, "e": 28112, "s": 28096, "text": "harshpanwar1705" }, { "code": null, "e": 28122, "s": 28112, "text": "cpp-deque" }, { "code": null, "e": 28128, "s": 28122, "text": "deque" }, { "code": null, "e": 28132, "s": 28128, "text": "C++" }, { "code": null, "e": 28151, "s": 28132, "text": "Difference Between" }, { "code": null, "e": 28157, "s": 28151, "text": "Queue" }, { "code": null, "e": 28163, "s": 28157, "text": "Queue" }, { "code": null, "e": 28167, "s": 28163, "text": "CPP" }, { "code": null, "e": 28265, "s": 28167, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28293, "s": 28265, "text": "Operator Overloading in C++" }, { "code": null, "e": 28313, "s": 28293, "text": "Polymorphism in C++" }, { "code": null, "e": 28346, "s": 28313, "text": "Friend class and function in C++" }, { "code": null, "e": 28370, "s": 28346, "text": "Sorting a vector in C++" }, { "code": null, "e": 28406, "s": 28370, "text": "Convert string to char array in C++" }, { "code": null, "e": 28437, "s": 28406, "text": "Difference between BFS and DFS" }, { "code": null, "e": 28477, "s": 28437, "text": "Class method vs Static method in Python" }, { "code": null, "e": 28509, "s": 28477, "text": "Differences between TCP and UDP" }, { "code": null, "e": 28570, "s": 28509, "text": "Difference between var, let and const keywords in JavaScript" } ]
Make HTML5 Canvas fill the whole page
To make canvas fill the whole page, you need to be 100% in width and height of the page. * { margin: 0; padding: 0; } body, html { height:100%; } #canvas { position:absolute; height:100%; width:100%; }
[ { "code": null, "e": 1151, "s": 1062, "text": "To make canvas fill the whole page, you need to be 100% in width and height of the page." }, { "code": null, "e": 1279, "s": 1151, "text": "* {\n margin: 0;\n padding: 0;\n}\nbody, html {\n height:100%;\n}\n#canvas {\n position:absolute;\n height:100%; width:100%;\n}" } ]
Updating Data into MySQL Database
Data can be updated into MySQL tables by executing SQL UPDATE statement through PHP function mysql_query. Below is a simple example to update records into employee table. To update a record in any table it is required to locate that record by using a conditional clause. Below example uses primary key to match a record in employee table. Try out following example to understand update operation. You need to provide an employee ID to update an employee salary. <html> <head> <title>Update a Record in MySQL Database</title> </head> <body> <?php if(isset($_POST['update'])) { $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $emp_id = $_POST['emp_id']; $emp_salary = $_POST['emp_salary']; $sql = "UPDATE employee ". "SET emp_salary = $emp_salary ". "WHERE emp_id = $emp_id" ; mysql_select_db('test_db'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not update data: ' . mysql_error()); } echo "Updated data successfully\n"; mysql_close($conn); }else { ?> <form method = "post" action = "<?php $_PHP_SELF ?>"> <table width = "400" border =" 0" cellspacing = "1" cellpadding = "2"> <tr> <td width = "100">Employee ID</td> <td><input name = "emp_id" type = "text" id = "emp_id"></td> </tr> <tr> <td width = "100">Employee Salary</td> <td><input name = "emp_salary" type = "text" id = "emp_salary"></td> </tr> <tr> <td width = "100"> </td> <td> </td> </tr> <tr> <td width = "100"> </td> <td> <input name = "update" type = "submit" id = "update" value = "Update"> </td> </tr> </table> </form> <?php } ?> </body> </html> 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2863, "s": 2757, "text": "Data can be updated into MySQL tables by executing SQL UPDATE statement through PHP function mysql_query." }, { "code": null, "e": 3096, "s": 2863, "text": "Below is a simple example to update records into employee table. To update a record in any table it is required to locate that record by using a conditional clause. Below example uses primary key to match a record in employee table." }, { "code": null, "e": 3219, "s": 3096, "text": "Try out following example to understand update operation. You need to provide an employee ID to update an employee salary." }, { "code": null, "e": 5508, "s": 3219, "text": "<html>\n \n <head>\n <title>Update a Record in MySQL Database</title>\n </head>\n \n <body>\n <?php\n if(isset($_POST['update'])) {\n $dbhost = 'localhost:3036';\n $dbuser = 'root';\n $dbpass = 'rootpassword';\n \n $conn = mysql_connect($dbhost, $dbuser, $dbpass);\n \n if(! $conn ) {\n die('Could not connect: ' . mysql_error());\n }\n \n $emp_id = $_POST['emp_id'];\n $emp_salary = $_POST['emp_salary'];\n \n $sql = \"UPDATE employee \". \"SET emp_salary = $emp_salary \". \n \"WHERE emp_id = $emp_id\" ;\n mysql_select_db('test_db');\n $retval = mysql_query( $sql, $conn );\n \n if(! $retval ) {\n die('Could not update data: ' . mysql_error());\n }\n echo \"Updated data successfully\\n\";\n \n mysql_close($conn);\n }else {\n ?>\n <form method = \"post\" action = \"<?php $_PHP_SELF ?>\">\n <table width = \"400\" border =\" 0\" cellspacing = \"1\" \n cellpadding = \"2\">\n \n <tr>\n <td width = \"100\">Employee ID</td>\n <td><input name = \"emp_id\" type = \"text\" \n id = \"emp_id\"></td>\n </tr>\n \n <tr>\n <td width = \"100\">Employee Salary</td>\n <td><input name = \"emp_salary\" type = \"text\" \n id = \"emp_salary\"></td>\n </tr>\n \n <tr>\n <td width = \"100\"> </td>\n <td> </td>\n </tr>\n \n <tr>\n <td width = \"100\"> </td>\n <td>\n <input name = \"update\" type = \"submit\" \n id = \"update\" value = \"Update\">\n </td>\n </tr>\n \n </table>\n </form>\n <?php\n }\n ?>\n \n </body>\n</html>" }, { "code": null, "e": 5541, "s": 5508, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 5557, "s": 5541, "text": " Malhar Lathkar" }, { "code": null, "e": 5590, "s": 5557, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 5601, "s": 5590, "text": " Syed Raza" }, { "code": null, "e": 5636, "s": 5601, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5653, "s": 5636, "text": " Frahaan Hussain" }, { "code": null, "e": 5686, "s": 5653, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 5701, "s": 5686, "text": " Nivedita Jain" }, { "code": null, "e": 5736, "s": 5701, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 5748, "s": 5736, "text": " Azaz Patel" }, { "code": null, "e": 5783, "s": 5748, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5811, "s": 5783, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 5818, "s": 5811, "text": " Print" }, { "code": null, "e": 5829, "s": 5818, "text": " Add Notes" } ]
MongoDB - $pop Operator - GeeksforGeeks
10 May, 2020 MongoDB provides different types of array update operators to update the values of the array fields in the documents and $pop operator is one of them. This operator is used to remove the first or the last item from the array. Syntax: { $pop: { <field>: <-1 | 1>, ... } } Here, <field> can specify with dot notation in embedded/nested documents or an array. If you pass -1 value in $pop operator, then it will remove the first item from the array. If you pass 1 value in $pop operator, then it will remove the last item from the array. If the <field> is not an array, then this operator will fail. If $pop operator will remove the last item from the specified field, then the field holds an empty array. You can use this operator with methods like update(), findAndModify(), etc., according to your requirement. In the following examples, we are working with: Database: GeeksforGeeksCollection: contributorDocument: two documents that contain the details of the contributor in the form of field-value pairs. In this example, we are removing the first element of the language field in the document that matches the specified condition, i.e., name: “Rohit”, by setting the value of $pop operator to -1. db.contributor.update({name: "Rohit"}, {$pop: { language: -1}}) In this example, we are removing the last element of the language field in the document that matches the specified condition, i.e., name: “Sumit”, by setting the value of $pop operator to 1. db.contributor.update({name: "Sumit"}, {$pop: {language: 1}}) In this example, we are removing the last element of the personal.semesterMarks field in the nested document by setting the value of $pop operator to -1. db.contributor.update({name: "Sumit"}, {$pop: {"personal.semesterMarks": -1}}) MongoDB MongoDB-operators MongoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments MongoDB - Distinct() Method How to connect MongoDB with ReactJS ? MongoDB - limit() Method MongoDB - FindOne() Method MongoDB insertMany() Method - db.Collection.insertMany() MongoDB updateOne() Method - db.Collection.updateOne() MongoDB - Update() Method Create user and add role in MongoDB MongoDB - sort() Method
[ { "code": null, "e": 23879, "s": 23851, "text": "\n10 May, 2020" }, { "code": null, "e": 24105, "s": 23879, "text": "MongoDB provides different types of array update operators to update the values of the array fields in the documents and $pop operator is one of them. This operator is used to remove the first or the last item from the array." }, { "code": null, "e": 24113, "s": 24105, "text": "Syntax:" }, { "code": null, "e": 24150, "s": 24113, "text": "{ $pop: { <field>: <-1 | 1>, ... } }" }, { "code": null, "e": 24236, "s": 24150, "text": "Here, <field> can specify with dot notation in embedded/nested documents or an array." }, { "code": null, "e": 24326, "s": 24236, "text": "If you pass -1 value in $pop operator, then it will remove the first item from the array." }, { "code": null, "e": 24414, "s": 24326, "text": "If you pass 1 value in $pop operator, then it will remove the last item from the array." }, { "code": null, "e": 24476, "s": 24414, "text": "If the <field> is not an array, then this operator will fail." }, { "code": null, "e": 24582, "s": 24476, "text": "If $pop operator will remove the last item from the specified field, then the field holds an empty array." }, { "code": null, "e": 24690, "s": 24582, "text": "You can use this operator with methods like update(), findAndModify(), etc., according to your requirement." }, { "code": null, "e": 24738, "s": 24690, "text": "In the following examples, we are working with:" }, { "code": null, "e": 24886, "s": 24738, "text": "Database: GeeksforGeeksCollection: contributorDocument: two documents that contain the details of the contributor in the form of field-value pairs." }, { "code": null, "e": 25079, "s": 24886, "text": "In this example, we are removing the first element of the language field in the document that matches the specified condition, i.e., name: “Rohit”, by setting the value of $pop operator to -1." }, { "code": "db.contributor.update({name: \"Rohit\"}, {$pop: { language: -1}})", "e": 25143, "s": 25079, "text": null }, { "code": null, "e": 25334, "s": 25143, "text": "In this example, we are removing the last element of the language field in the document that matches the specified condition, i.e., name: “Sumit”, by setting the value of $pop operator to 1." }, { "code": "db.contributor.update({name: \"Sumit\"}, {$pop: {language: 1}})", "e": 25396, "s": 25334, "text": null }, { "code": null, "e": 25550, "s": 25396, "text": "In this example, we are removing the last element of the personal.semesterMarks field in the nested document by setting the value of $pop operator to -1." }, { "code": "db.contributor.update({name: \"Sumit\"}, {$pop: {\"personal.semesterMarks\": -1}})", "e": 25651, "s": 25550, "text": null }, { "code": null, "e": 25659, "s": 25651, "text": "MongoDB" }, { "code": null, "e": 25677, "s": 25659, "text": "MongoDB-operators" }, { "code": null, "e": 25685, "s": 25677, "text": "MongoDB" }, { "code": null, "e": 25783, "s": 25685, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25792, "s": 25783, "text": "Comments" }, { "code": null, "e": 25805, "s": 25792, "text": "Old Comments" }, { "code": null, "e": 25833, "s": 25805, "text": "MongoDB - Distinct() Method" }, { "code": null, "e": 25871, "s": 25833, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 25896, "s": 25871, "text": "MongoDB - limit() Method" }, { "code": null, "e": 25923, "s": 25896, "text": "MongoDB - FindOne() Method" }, { "code": null, "e": 25980, "s": 25923, "text": "MongoDB insertMany() Method - db.Collection.insertMany()" }, { "code": null, "e": 26035, "s": 25980, "text": "MongoDB updateOne() Method - db.Collection.updateOne()" }, { "code": null, "e": 26061, "s": 26035, "text": "MongoDB - Update() Method" }, { "code": null, "e": 26097, "s": 26061, "text": "Create user and add role in MongoDB" } ]
AWS Cloud Computing
The client-server model is an important concept in cloud computing. It is about many clients using services from a centralized server. Read about the Benefits of Cloud Computing at: Cloud Benefits The Client-Server model is about a client that interacts and makes requests to a computer server. A client is the way that the person interact with the server. Image created by Amazon Web Services The server does tasks for the client and returns information. Cloud computing is a computing service made available over the internet. Cloud computing is a pay-as-you-go model for delivering IT resources. You pay only for what you use. W3schools.com collaborates with Amazon Web Services to deliver digital training content to our students. There are three different kinds of deployment models: Cloud-based On-premises Hybrid The models are different ways of accessing compute services - over the internet, locally, or in a combination. Everything runs in the cloud. This model allows you to build new applications or move existing ones to the cloud. There are different levels of services ranging from low to high. The level of service has different requirements on your management, architecting, and infrastructure. For example, a company might create an application consisting of virtual servers, databases, and networking components entirely based in the cloud. Deploy resources by using virtualization and resource management tools. On-Premises Deployment is also known as private cloud deployment. For example, you might have applications that run on technology that is fully kept in your on-premises data center. Though this model is much like legacy IT infrastructure, its application management and virtualization technologies make it more effective. In a hybrid deployment, you connect cloud resources to an on-premises infrastructure. This approach is relevant in many situations. For example, you are working with sensitive data or are under specific government regulations. Insert the missing deployment model. Cloud-based, on-premises, and Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 68, "s": 0, "text": "The client-server model is an important concept in cloud computing." }, { "code": null, "e": 135, "s": 68, "text": "It is about many clients using services from a centralized server." }, { "code": null, "e": 197, "s": 135, "text": "Read about the Benefits of Cloud Computing at: Cloud Benefits" }, { "code": null, "e": 295, "s": 197, "text": "The Client-Server model is about a client that interacts and makes requests to a computer server." }, { "code": null, "e": 357, "s": 295, "text": "A client is the way that the person interact with the server." }, { "code": null, "e": 394, "s": 357, "text": "Image created by Amazon Web Services" }, { "code": null, "e": 456, "s": 394, "text": "The server does tasks for the client and returns information." }, { "code": null, "e": 529, "s": 456, "text": "Cloud computing is a computing service made available over the internet." }, { "code": null, "e": 599, "s": 529, "text": "Cloud computing is a pay-as-you-go model for delivering IT resources." }, { "code": null, "e": 630, "s": 599, "text": "You pay only for what you use." }, { "code": null, "e": 735, "s": 630, "text": "W3schools.com collaborates with Amazon Web Services to deliver digital training content to our students." }, { "code": null, "e": 789, "s": 735, "text": "There are three different kinds of deployment models:" }, { "code": null, "e": 801, "s": 789, "text": "Cloud-based" }, { "code": null, "e": 813, "s": 801, "text": "On-premises" }, { "code": null, "e": 820, "s": 813, "text": "Hybrid" }, { "code": null, "e": 931, "s": 820, "text": "The models are different ways of accessing compute services - over the internet, locally, or in a combination." }, { "code": null, "e": 961, "s": 931, "text": "Everything runs in the cloud." }, { "code": null, "e": 1045, "s": 961, "text": "This model allows you to build new applications or move existing ones to the cloud." }, { "code": null, "e": 1110, "s": 1045, "text": "There are different levels of services ranging from low to high." }, { "code": null, "e": 1212, "s": 1110, "text": "The level of service has different requirements on your management, architecting, and infrastructure." }, { "code": null, "e": 1360, "s": 1212, "text": "For example, a company might create an application consisting of virtual servers, databases, and networking components entirely based in the cloud." }, { "code": null, "e": 1432, "s": 1360, "text": "Deploy resources by using virtualization and resource management tools." }, { "code": null, "e": 1498, "s": 1432, "text": "On-Premises Deployment is also known as private cloud deployment." }, { "code": null, "e": 1614, "s": 1498, "text": "For example, you might have applications that run on technology that is fully kept in your on-premises data center." }, { "code": null, "e": 1754, "s": 1614, "text": "Though this model is much like legacy IT infrastructure, its application management and virtualization technologies make it more effective." }, { "code": null, "e": 1840, "s": 1754, "text": "In a hybrid deployment, you connect cloud resources to an on-premises infrastructure." }, { "code": null, "e": 1887, "s": 1840, "text": "This approach is relevant in many situations. " }, { "code": null, "e": 1982, "s": 1887, "text": "For example, you are working with sensitive data or are under specific government regulations." }, { "code": null, "e": 2019, "s": 1982, "text": "Insert the missing deployment model." }, { "code": null, "e": 2050, "s": 2019, "text": "Cloud-based, on-premises, and " }, { "code": null, "e": 2069, "s": 2050, "text": "Start the Exercise" }, { "code": null, "e": 2102, "s": 2069, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2144, "s": 2102, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2251, "s": 2144, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 2270, "s": 2251, "text": "help@w3schools.com" } ]
How to delete last element from a List in C++ STL - GeeksforGeeks
18 Jan, 2019 Given a List, the task is to remove the last element from this List in C++. Examples: Input: list = [10 20 30 70 80 90 100 40 50 60] Output: 10 20 30 40 50 60 70 80 90 Input: list = [1 2 3 4 5] Output: 1 2 3 4 Lists are a type of associative containers in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the list, though it is possible to remove and add the modified value of that element. The last element of the List can be deleted by by passing its iterator. Syntax: iterator erase (const_iterator positionOfElementToBeDeleted); Approach: One can easily delete the last element by passing its iterator to the erase function. To reach the iterator which points to the last element, there are two ways: Method 1:prev(listInt.end())Below is the implementation of the above approach:Program 1:// C++ program to delete last element// of a List by passing its iterator #include <iostream>#include <list>using namespace std; // Function to print the listvoid printList(list<int> mylist){ // Get the iterator list<int>::iterator it; // printing all the elements of the list for (it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; cout << '\n';} // Function to delete last element of list// using method 1void deleteByMethod1(list<int> mylist){ // printing all the elements of the list cout << "\nList originally: "; printList(mylist); // Get the iterator list<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 1 it = prev(mylist.end()); // Erase the last element // currently pointed by the iterator mylist.erase(it); // printing all the elements of the list cout << "List after deletion: "; printList(mylist);} // Driver codeint main(){ list<int> mylist; // Get the list for (int i = 1; i < 10; i++) mylist.push_back(i * 10); // Method 1 to get positionOfElementToBeDeleted deleteByMethod1(mylist); return 0;}Output:List originally: 10 20 30 40 50 60 70 80 90 List after deletion: 10 20 30 40 50 60 70 80 Method 2:list::iterator it = listInt.end(); --it; Below is the implementation of the above approach:Program 2:// C++ program to delete last element// of a List by passing its iterator #include <iostream>#include <list>using namespace std; // Function to print the listvoid printList(list<int> mylist){ // Get the iterator list<int>::iterator it; // printing all the elements of the list for (it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; cout << '\n';} // Function to delete last element of list// using method 2void deleteByMethod2(list<int> mylist){ // printing all the elements of the list cout << "\nList originally: "; printList(mylist); // Get the iterator list<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 2 it = --mylist.end(); // Erase the last element // currently pointed by the iterator mylist.erase(it); // printing all the elements of the list cout << "List after deletion: "; printList(mylist);} // Driver codeint main(){ list<int> mylist; // Get the list for (int i = 1; i < 10; i++) mylist.push_back(i * 10); // Method 2 to get positionOfElementToBeDeleted deleteByMethod2(mylist); return 0;}Output:List originally: 10 20 30 40 50 60 70 80 90 List after deletion: 10 20 30 40 50 60 70 80 My Personal Notes arrow_drop_upSave Method 1:prev(listInt.end())Below is the implementation of the above approach:Program 1:// C++ program to delete last element// of a List by passing its iterator #include <iostream>#include <list>using namespace std; // Function to print the listvoid printList(list<int> mylist){ // Get the iterator list<int>::iterator it; // printing all the elements of the list for (it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; cout << '\n';} // Function to delete last element of list// using method 1void deleteByMethod1(list<int> mylist){ // printing all the elements of the list cout << "\nList originally: "; printList(mylist); // Get the iterator list<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 1 it = prev(mylist.end()); // Erase the last element // currently pointed by the iterator mylist.erase(it); // printing all the elements of the list cout << "List after deletion: "; printList(mylist);} // Driver codeint main(){ list<int> mylist; // Get the list for (int i = 1; i < 10; i++) mylist.push_back(i * 10); // Method 1 to get positionOfElementToBeDeleted deleteByMethod1(mylist); return 0;}Output:List originally: 10 20 30 40 50 60 70 80 90 List after deletion: 10 20 30 40 50 60 70 80 prev(listInt.end()) Below is the implementation of the above approach: Program 1: // C++ program to delete last element// of a List by passing its iterator #include <iostream>#include <list>using namespace std; // Function to print the listvoid printList(list<int> mylist){ // Get the iterator list<int>::iterator it; // printing all the elements of the list for (it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; cout << '\n';} // Function to delete last element of list// using method 1void deleteByMethod1(list<int> mylist){ // printing all the elements of the list cout << "\nList originally: "; printList(mylist); // Get the iterator list<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 1 it = prev(mylist.end()); // Erase the last element // currently pointed by the iterator mylist.erase(it); // printing all the elements of the list cout << "List after deletion: "; printList(mylist);} // Driver codeint main(){ list<int> mylist; // Get the list for (int i = 1; i < 10; i++) mylist.push_back(i * 10); // Method 1 to get positionOfElementToBeDeleted deleteByMethod1(mylist); return 0;} List originally: 10 20 30 40 50 60 70 80 90 List after deletion: 10 20 30 40 50 60 70 80 Method 2:list::iterator it = listInt.end(); --it; Below is the implementation of the above approach:Program 2:// C++ program to delete last element// of a List by passing its iterator #include <iostream>#include <list>using namespace std; // Function to print the listvoid printList(list<int> mylist){ // Get the iterator list<int>::iterator it; // printing all the elements of the list for (it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; cout << '\n';} // Function to delete last element of list// using method 2void deleteByMethod2(list<int> mylist){ // printing all the elements of the list cout << "\nList originally: "; printList(mylist); // Get the iterator list<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 2 it = --mylist.end(); // Erase the last element // currently pointed by the iterator mylist.erase(it); // printing all the elements of the list cout << "List after deletion: "; printList(mylist);} // Driver codeint main(){ list<int> mylist; // Get the list for (int i = 1; i < 10; i++) mylist.push_back(i * 10); // Method 2 to get positionOfElementToBeDeleted deleteByMethod2(mylist); return 0;}Output:List originally: 10 20 30 40 50 60 70 80 90 List after deletion: 10 20 30 40 50 60 70 80 My Personal Notes arrow_drop_upSave list::iterator it = listInt.end(); --it; Below is the implementation of the above approach: Program 2: // C++ program to delete last element// of a List by passing its iterator #include <iostream>#include <list>using namespace std; // Function to print the listvoid printList(list<int> mylist){ // Get the iterator list<int>::iterator it; // printing all the elements of the list for (it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; cout << '\n';} // Function to delete last element of list// using method 2void deleteByMethod2(list<int> mylist){ // printing all the elements of the list cout << "\nList originally: "; printList(mylist); // Get the iterator list<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 2 it = --mylist.end(); // Erase the last element // currently pointed by the iterator mylist.erase(it); // printing all the elements of the list cout << "List after deletion: "; printList(mylist);} // Driver codeint main(){ list<int> mylist; // Get the list for (int i = 1; i < 10; i++) mylist.push_back(i * 10); // Method 2 to get positionOfElementToBeDeleted deleteByMethod2(mylist); return 0;} List originally: 10 20 30 40 50 60 70 80 90 List after deletion: 10 20 30 40 50 60 70 80 cpp-list STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inheritance in C++ Map in C++ Standard Template Library (STL) Multidimensional Arrays in C / C++ Socket Programming in C/C++ C++ Classes and Objects Operator Overloading in C++ Bitwise Operators in C/C++ Constructors in C++ Virtual Function in C++ Copy Constructor in C++
[ { "code": null, "e": 24599, "s": 24571, "text": "\n18 Jan, 2019" }, { "code": null, "e": 24675, "s": 24599, "text": "Given a List, the task is to remove the last element from this List in C++." }, { "code": null, "e": 24685, "s": 24675, "text": "Examples:" }, { "code": null, "e": 24811, "s": 24685, "text": "Input: list = [10 20 30 70 80 90 100 40 50 60]\nOutput: 10 20 30 40 50 60 70 80 90\n\nInput: list = [1 2 3 4 5]\nOutput: 1 2 3 4\n" }, { "code": null, "e": 25091, "s": 24811, "text": "Lists are a type of associative containers in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the list, though it is possible to remove and add the modified value of that element." }, { "code": null, "e": 25163, "s": 25091, "text": "The last element of the List can be deleted by by passing its iterator." }, { "code": null, "e": 25171, "s": 25163, "text": "Syntax:" }, { "code": null, "e": 25234, "s": 25171, "text": "iterator erase (const_iterator positionOfElementToBeDeleted);\n" }, { "code": null, "e": 25406, "s": 25234, "text": "Approach: One can easily delete the last element by passing its iterator to the erase function. To reach the iterator which points to the last element, there are two ways:" }, { "code": null, "e": 28167, "s": 25406, "text": "Method 1:prev(listInt.end())Below is the implementation of the above approach:Program 1:// C++ program to delete last element// of a List by passing its iterator #include <iostream>#include <list>using namespace std; // Function to print the listvoid printList(list<int> mylist){ // Get the iterator list<int>::iterator it; // printing all the elements of the list for (it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; cout << '\\n';} // Function to delete last element of list// using method 1void deleteByMethod1(list<int> mylist){ // printing all the elements of the list cout << \"\\nList originally: \"; printList(mylist); // Get the iterator list<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 1 it = prev(mylist.end()); // Erase the last element // currently pointed by the iterator mylist.erase(it); // printing all the elements of the list cout << \"List after deletion: \"; printList(mylist);} // Driver codeint main(){ list<int> mylist; // Get the list for (int i = 1; i < 10; i++) mylist.push_back(i * 10); // Method 1 to get positionOfElementToBeDeleted deleteByMethod1(mylist); return 0;}Output:List originally: 10 20 30 40 50 60 70 80 90\nList after deletion: 10 20 30 40 50 60 70 80\nMethod 2:list::iterator it = listInt.end(); \n--it;\nBelow is the implementation of the above approach:Program 2:// C++ program to delete last element// of a List by passing its iterator #include <iostream>#include <list>using namespace std; // Function to print the listvoid printList(list<int> mylist){ // Get the iterator list<int>::iterator it; // printing all the elements of the list for (it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; cout << '\\n';} // Function to delete last element of list// using method 2void deleteByMethod2(list<int> mylist){ // printing all the elements of the list cout << \"\\nList originally: \"; printList(mylist); // Get the iterator list<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 2 it = --mylist.end(); // Erase the last element // currently pointed by the iterator mylist.erase(it); // printing all the elements of the list cout << \"List after deletion: \"; printList(mylist);} // Driver codeint main(){ list<int> mylist; // Get the list for (int i = 1; i < 10; i++) mylist.push_back(i * 10); // Method 2 to get positionOfElementToBeDeleted deleteByMethod2(mylist); return 0;}Output:List originally: 10 20 30 40 50 60 70 80 90\nList after deletion: 10 20 30 40 50 60 70 80\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 29521, "s": 28167, "text": "Method 1:prev(listInt.end())Below is the implementation of the above approach:Program 1:// C++ program to delete last element// of a List by passing its iterator #include <iostream>#include <list>using namespace std; // Function to print the listvoid printList(list<int> mylist){ // Get the iterator list<int>::iterator it; // printing all the elements of the list for (it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; cout << '\\n';} // Function to delete last element of list// using method 1void deleteByMethod1(list<int> mylist){ // printing all the elements of the list cout << \"\\nList originally: \"; printList(mylist); // Get the iterator list<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 1 it = prev(mylist.end()); // Erase the last element // currently pointed by the iterator mylist.erase(it); // printing all the elements of the list cout << \"List after deletion: \"; printList(mylist);} // Driver codeint main(){ list<int> mylist; // Get the list for (int i = 1; i < 10; i++) mylist.push_back(i * 10); // Method 1 to get positionOfElementToBeDeleted deleteByMethod1(mylist); return 0;}Output:List originally: 10 20 30 40 50 60 70 80 90\nList after deletion: 10 20 30 40 50 60 70 80\n" }, { "code": null, "e": 29541, "s": 29521, "text": "prev(listInt.end())" }, { "code": null, "e": 29592, "s": 29541, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 29603, "s": 29592, "text": "Program 1:" }, { "code": "// C++ program to delete last element// of a List by passing its iterator #include <iostream>#include <list>using namespace std; // Function to print the listvoid printList(list<int> mylist){ // Get the iterator list<int>::iterator it; // printing all the elements of the list for (it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; cout << '\\n';} // Function to delete last element of list// using method 1void deleteByMethod1(list<int> mylist){ // printing all the elements of the list cout << \"\\nList originally: \"; printList(mylist); // Get the iterator list<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 1 it = prev(mylist.end()); // Erase the last element // currently pointed by the iterator mylist.erase(it); // printing all the elements of the list cout << \"List after deletion: \"; printList(mylist);} // Driver codeint main(){ list<int> mylist; // Get the list for (int i = 1; i < 10; i++) mylist.push_back(i * 10); // Method 1 to get positionOfElementToBeDeleted deleteByMethod1(mylist); return 0;}", "e": 30771, "s": 29603, "text": null }, { "code": null, "e": 30863, "s": 30771, "text": "List originally: 10 20 30 40 50 60 70 80 90\nList after deletion: 10 20 30 40 50 60 70 80\n" }, { "code": null, "e": 32271, "s": 30863, "text": "Method 2:list::iterator it = listInt.end(); \n--it;\nBelow is the implementation of the above approach:Program 2:// C++ program to delete last element// of a List by passing its iterator #include <iostream>#include <list>using namespace std; // Function to print the listvoid printList(list<int> mylist){ // Get the iterator list<int>::iterator it; // printing all the elements of the list for (it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; cout << '\\n';} // Function to delete last element of list// using method 2void deleteByMethod2(list<int> mylist){ // printing all the elements of the list cout << \"\\nList originally: \"; printList(mylist); // Get the iterator list<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 2 it = --mylist.end(); // Erase the last element // currently pointed by the iterator mylist.erase(it); // printing all the elements of the list cout << \"List after deletion: \"; printList(mylist);} // Driver codeint main(){ list<int> mylist; // Get the list for (int i = 1; i < 10; i++) mylist.push_back(i * 10); // Method 2 to get positionOfElementToBeDeleted deleteByMethod2(mylist); return 0;}Output:List originally: 10 20 30 40 50 60 70 80 90\nList after deletion: 10 20 30 40 50 60 70 80\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 32314, "s": 32271, "text": "list::iterator it = listInt.end(); \n--it;\n" }, { "code": null, "e": 32365, "s": 32314, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 32376, "s": 32365, "text": "Program 2:" }, { "code": "// C++ program to delete last element// of a List by passing its iterator #include <iostream>#include <list>using namespace std; // Function to print the listvoid printList(list<int> mylist){ // Get the iterator list<int>::iterator it; // printing all the elements of the list for (it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; cout << '\\n';} // Function to delete last element of list// using method 2void deleteByMethod2(list<int> mylist){ // printing all the elements of the list cout << \"\\nList originally: \"; printList(mylist); // Get the iterator list<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 2 it = --mylist.end(); // Erase the last element // currently pointed by the iterator mylist.erase(it); // printing all the elements of the list cout << \"List after deletion: \"; printList(mylist);} // Driver codeint main(){ list<int> mylist; // Get the list for (int i = 1; i < 10; i++) mylist.push_back(i * 10); // Method 2 to get positionOfElementToBeDeleted deleteByMethod2(mylist); return 0;}", "e": 33540, "s": 32376, "text": null }, { "code": null, "e": 33632, "s": 33540, "text": "List originally: 10 20 30 40 50 60 70 80 90\nList after deletion: 10 20 30 40 50 60 70 80\n" }, { "code": null, "e": 33641, "s": 33632, "text": "cpp-list" }, { "code": null, "e": 33645, "s": 33641, "text": "STL" }, { "code": null, "e": 33649, "s": 33645, "text": "C++" }, { "code": null, "e": 33653, "s": 33649, "text": "STL" }, { "code": null, "e": 33657, "s": 33653, "text": "CPP" }, { "code": null, "e": 33755, "s": 33657, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33764, "s": 33755, "text": "Comments" }, { "code": null, "e": 33777, "s": 33764, "text": "Old Comments" }, { "code": null, "e": 33796, "s": 33777, "text": "Inheritance in C++" }, { "code": null, "e": 33839, "s": 33796, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 33874, "s": 33839, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 33902, "s": 33874, "text": "Socket Programming in C/C++" }, { "code": null, "e": 33926, "s": 33902, "text": "C++ Classes and Objects" }, { "code": null, "e": 33954, "s": 33926, "text": "Operator Overloading in C++" }, { "code": null, "e": 33981, "s": 33954, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 34001, "s": 33981, "text": "Constructors in C++" }, { "code": null, "e": 34025, "s": 34001, "text": "Virtual Function in C++" } ]
Print sorted distinct elements of array - GeeksforGeeks
09 Jun, 2021 Given an array that might contain duplicates, print all distinct elements in sorted order. Examples: Input : 1, 3, 2, 2, 1 Output : 1 2 3 Input : 1, 1, 1, 2, 2, 3 Output : 1 2 3 Simple Solution is to sort the array first, then traverse the array and print only first occurrences of elements. Another Approach is to use set in C++ STL. C++ Java Python3 C# Javascript // CPP program to print sorted distinct// elements.#include <bits/stdc++.h>using namespace std; void printRepeating(int arr[], int size){ // Create a set using array elements set<int> s(arr, arr + size); // Print contents of the set. for (auto x : s) cout << x << " ";} // Driver codeint main(){ int arr[] = { 1, 3, 2, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); printRepeating(arr, n); return 0;} // Java program to print sorted distinct// elements.import java.io.*;import java.util.*; public class GFG { static void printRepeating(Integer []arr, int size) { // Create a set using array elements SortedSet<Integer> s = new TreeSet<>(); Collections.addAll(s, arr); // Print contents of the set. System.out.print(s); } // Driver code public static void main(String args[]) { Integer []arr = {1, 3, 2, 2, 1}; int n = arr.length; printRepeating(arr, n); }} // This code is contributed by// Manish Shaw (manishshaw1) # Python3 program to print# sorted distinct elements. def printRepeating(arr,size): # Create a set using array elements s = set() for i in range(size): if arr[i] not in s: s.add(arr[i]) # Print contents of the set. for i in s: print(i,end=" ") # Driver codeif __name__=='__main__': arr = [1,3,2,2,1] size = len(arr) printRepeating(arr,size) # This code is contributed by# Shrikant13 // C# program to print sorted distinct// elements.using System;using System.Collections.Generic;using System.Linq; class GFG { static void printRepeating(int []arr, int size) { // Create a set using array elements SortedSet<int> s = new SortedSet<int>(arr); // Print contents of the set. foreach (var n in s) { Console.Write(n + " "); } } // Driver code public static void Main() { int []arr = {1, 3, 2, 2, 1}; int n = arr.Length; printRepeating(arr, n); }} // This code is contributed by// Manish Shaw (manishshaw1) <script> // Javascript program to print sorted distinct// elements.function printRepeating(arr, size){ // Create a set using array elements var s = new Set(arr); // Print contents of the set. [...s].sort((a, b) => a - b).forEach(x => { document.write(x + " ") });} // Driver codevar arr = [ 1, 3, 2, 2, 1 ];var n = arr.length; printRepeating(arr, n); // This code is contributed by itsok </script> 1 2 3 manishshaw1 shrikanth13 itsok cpp-set Arrays Sorting Arrays Sorting 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 Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java
[ { "code": null, "e": 26921, "s": 26893, "text": "\n09 Jun, 2021" }, { "code": null, "e": 27012, "s": 26921, "text": "Given an array that might contain duplicates, print all distinct elements in sorted order." }, { "code": null, "e": 27023, "s": 27012, "text": "Examples: " }, { "code": null, "e": 27103, "s": 27023, "text": "Input : 1, 3, 2, 2, 1\nOutput : 1 2 3\n\nInput : 1, 1, 1, 2, 2, 3\nOutput : 1 2 3" }, { "code": null, "e": 27217, "s": 27103, "text": "Simple Solution is to sort the array first, then traverse the array and print only first occurrences of elements." }, { "code": null, "e": 27262, "s": 27217, "text": "Another Approach is to use set in C++ STL. " }, { "code": null, "e": 27266, "s": 27262, "text": "C++" }, { "code": null, "e": 27271, "s": 27266, "text": "Java" }, { "code": null, "e": 27279, "s": 27271, "text": "Python3" }, { "code": null, "e": 27282, "s": 27279, "text": "C#" }, { "code": null, "e": 27293, "s": 27282, "text": "Javascript" }, { "code": "// CPP program to print sorted distinct// elements.#include <bits/stdc++.h>using namespace std; void printRepeating(int arr[], int size){ // Create a set using array elements set<int> s(arr, arr + size); // Print contents of the set. for (auto x : s) cout << x << \" \";} // Driver codeint main(){ int arr[] = { 1, 3, 2, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); printRepeating(arr, n); return 0;}", "e": 27725, "s": 27293, "text": null }, { "code": "// Java program to print sorted distinct// elements.import java.io.*;import java.util.*; public class GFG { static void printRepeating(Integer []arr, int size) { // Create a set using array elements SortedSet<Integer> s = new TreeSet<>(); Collections.addAll(s, arr); // Print contents of the set. System.out.print(s); } // Driver code public static void main(String args[]) { Integer []arr = {1, 3, 2, 2, 1}; int n = arr.length; printRepeating(arr, n); }} // This code is contributed by// Manish Shaw (manishshaw1)", "e": 28339, "s": 27725, "text": null }, { "code": "# Python3 program to print# sorted distinct elements. def printRepeating(arr,size): # Create a set using array elements s = set() for i in range(size): if arr[i] not in s: s.add(arr[i]) # Print contents of the set. for i in s: print(i,end=\" \") # Driver codeif __name__=='__main__': arr = [1,3,2,2,1] size = len(arr) printRepeating(arr,size) # This code is contributed by# Shrikant13", "e": 28773, "s": 28339, "text": null }, { "code": "// C# program to print sorted distinct// elements.using System;using System.Collections.Generic;using System.Linq; class GFG { static void printRepeating(int []arr, int size) { // Create a set using array elements SortedSet<int> s = new SortedSet<int>(arr); // Print contents of the set. foreach (var n in s) { Console.Write(n + \" \"); } } // Driver code public static void Main() { int []arr = {1, 3, 2, 2, 1}; int n = arr.Length; printRepeating(arr, n); }} // This code is contributed by// Manish Shaw (manishshaw1)", "e": 29400, "s": 28773, "text": null }, { "code": "<script> // Javascript program to print sorted distinct// elements.function printRepeating(arr, size){ // Create a set using array elements var s = new Set(arr); // Print contents of the set. [...s].sort((a, b) => a - b).forEach(x => { document.write(x + \" \") });} // Driver codevar arr = [ 1, 3, 2, 2, 1 ];var n = arr.length; printRepeating(arr, n); // This code is contributed by itsok </script>", "e": 29826, "s": 29400, "text": null }, { "code": null, "e": 29832, "s": 29826, "text": "1 2 3" }, { "code": null, "e": 29846, "s": 29834, "text": "manishshaw1" }, { "code": null, "e": 29858, "s": 29846, "text": "shrikanth13" }, { "code": null, "e": 29864, "s": 29858, "text": "itsok" }, { "code": null, "e": 29872, "s": 29864, "text": "cpp-set" }, { "code": null, "e": 29879, "s": 29872, "text": "Arrays" }, { "code": null, "e": 29887, "s": 29879, "text": "Sorting" }, { "code": null, "e": 29894, "s": 29887, "text": "Arrays" }, { "code": null, "e": 29902, "s": 29894, "text": "Sorting" }, { "code": null, "e": 30000, "s": 29902, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30068, "s": 30000, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 30112, "s": 30068, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 30160, "s": 30112, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 30183, "s": 30160, "text": "Introduction to Arrays" } ]
Position monitor detector in Ubuntu(build with opencv on python3) | by Dmitriy Kisil | Towards Data Science
And keep distance appropriate, because sitting to close is not good for your eyes. After learning a bit of opencv library, I am thinking about the simple implementation of this idea. According to ergonomics tips(get it from here): Adjust the monitor height so that the top of the screen is at — or slightly below — eye level. Your eyes should look slightly downward when viewing the middle of the screen. Position the monitor at least 20 inches (51 cm) from your eyes — about an arm’s length distance. Let’s create a program in Python3, which will remind us each time when we sit down too close (distance<51 cm or 20 inches) to monitor and display a message with warning. So, for face recognition part we will use default classifier from opencv, and tkinter as a way to send message on the screen. Opencv is an awesome library, which allows you to do various operations on the image/video content such as convert to grayscale, make a mask, cropping, rescaling the image and many-many more. After looking at this example from opencv docs, I think, that this is especially what I need to succeed goal — make simple face detection. Just tweaking example a little bit — remove eyes classifier, and that’s all. The next problem is how to measure distance from face to camera. After searching a little, I found super article from pyimagesearch. In this material you can found that measuring distance could be calculated from height of the object now and knowing height of object from particular distance. For example, height of object in pixels are 100 from distance 1 m. If we run detection and see, that height of object are 50 pixels — then object approximately two times further. If 120 pixels — then object is a little closer then 1 meter. So we simple check if height of face now is more then knowing face height from a selected distance — then send a message with tkinter. Tkinter is a simple GUI tool, which get what we need: popup widget, which appeared if and only if face is detected and face too close to monitor. Just creating a one text widget with text of warning should be enough. So, let’s implement all of that! Install Tkinter: sudo apt-get install python3-tk Install additional python packages: pip3 install numpy opencv-python Create python script: touch distance_detector.py Fill script with the code below (added a lot of comments to code, so you can understood what’s going on here): Quick explanation: use argparse to allow set distance and known height from cmd(9–14);function, which create our tkinter message and return it(16–27);capture video from camera, grayscale it and make face detection(32–43);when no face detect(44–46) or face far away(56–59) — disable tkinter message. If don’t do that, warning message won’t disappear after one successful detection;when face detect — calculate a distance to detected face(48–52);if distance less then selected distance — enable tkinter message(53–55);show useful info in opencv window and close all after press Q (60–81). use argparse to allow set distance and known height from cmd(9–14); function, which create our tkinter message and return it(16–27); capture video from camera, grayscale it and make face detection(32–43); when no face detect(44–46) or face far away(56–59) — disable tkinter message. If don’t do that, warning message won’t disappear after one successful detection; when face detect — calculate a distance to detected face(48–52); if distance less then selected distance — enable tkinter message(53–55); show useful info in opencv window and close all after press Q (60–81). Before using we need to calibrate it according to your face. To doing that: run python3 distance_detector.py;sit down in a front of camera on distance, which will be limit for eyes;notice face_height parameter and close script (press Q in window);run python3 distance_detector.py with your face_height parameter. run python3 distance_detector.py; sit down in a front of camera on distance, which will be limit for eyes; notice face_height parameter and close script (press Q in window); run python3 distance_detector.py with your face_height parameter. For example, my face height in pixels is 300, when i sit from 51 cm. In my case, I need to run python3 distance_detector.py -f 300 -d 0.51. How it looks like: In this article you see, how after decomposition the idea into small chunks actual implementation became is not so hard. Yes, you can added more techniques to it to make detection work more accurate and improve performance — but as simple example of idea that’s should be enough. P.S.: If you wear glasses, be aware that detection will be less accurate. Thanks for your attention! Wish you have an awesome day=)
[ { "code": null, "e": 354, "s": 171, "text": "And keep distance appropriate, because sitting to close is not good for your eyes. After learning a bit of opencv library, I am thinking about the simple implementation of this idea." }, { "code": null, "e": 402, "s": 354, "text": "According to ergonomics tips(get it from here):" }, { "code": null, "e": 673, "s": 402, "text": "Adjust the monitor height so that the top of the screen is at — or slightly below — eye level. Your eyes should look slightly downward when viewing the middle of the screen. Position the monitor at least 20 inches (51 cm) from your eyes — about an arm’s length distance." }, { "code": null, "e": 969, "s": 673, "text": "Let’s create a program in Python3, which will remind us each time when we sit down too close (distance<51 cm or 20 inches) to monitor and display a message with warning. So, for face recognition part we will use default classifier from opencv, and tkinter as a way to send message on the screen." }, { "code": null, "e": 1161, "s": 969, "text": "Opencv is an awesome library, which allows you to do various operations on the image/video content such as convert to grayscale, make a mask, cropping, rescaling the image and many-many more." }, { "code": null, "e": 1377, "s": 1161, "text": "After looking at this example from opencv docs, I think, that this is especially what I need to succeed goal — make simple face detection. Just tweaking example a little bit — remove eyes classifier, and that’s all." }, { "code": null, "e": 1670, "s": 1377, "text": "The next problem is how to measure distance from face to camera. After searching a little, I found super article from pyimagesearch. In this material you can found that measuring distance could be calculated from height of the object now and knowing height of object from particular distance." }, { "code": null, "e": 2045, "s": 1670, "text": "For example, height of object in pixels are 100 from distance 1 m. If we run detection and see, that height of object are 50 pixels — then object approximately two times further. If 120 pixels — then object is a little closer then 1 meter. So we simple check if height of face now is more then knowing face height from a selected distance — then send a message with tkinter." }, { "code": null, "e": 2262, "s": 2045, "text": "Tkinter is a simple GUI tool, which get what we need: popup widget, which appeared if and only if face is detected and face too close to monitor. Just creating a one text widget with text of warning should be enough." }, { "code": null, "e": 2295, "s": 2262, "text": "So, let’s implement all of that!" }, { "code": null, "e": 2312, "s": 2295, "text": "Install Tkinter:" }, { "code": null, "e": 2344, "s": 2312, "text": "sudo apt-get install python3-tk" }, { "code": null, "e": 2380, "s": 2344, "text": "Install additional python packages:" }, { "code": null, "e": 2413, "s": 2380, "text": "pip3 install numpy opencv-python" }, { "code": null, "e": 2435, "s": 2413, "text": "Create python script:" }, { "code": null, "e": 2462, "s": 2435, "text": "touch distance_detector.py" }, { "code": null, "e": 2573, "s": 2462, "text": "Fill script with the code below (added a lot of comments to code, so you can understood what’s going on here):" }, { "code": null, "e": 2592, "s": 2573, "text": "Quick explanation:" }, { "code": null, "e": 3160, "s": 2592, "text": "use argparse to allow set distance and known height from cmd(9–14);function, which create our tkinter message and return it(16–27);capture video from camera, grayscale it and make face detection(32–43);when no face detect(44–46) or face far away(56–59) — disable tkinter message. If don’t do that, warning message won’t disappear after one successful detection;when face detect — calculate a distance to detected face(48–52);if distance less then selected distance — enable tkinter message(53–55);show useful info in opencv window and close all after press Q (60–81)." }, { "code": null, "e": 3228, "s": 3160, "text": "use argparse to allow set distance and known height from cmd(9–14);" }, { "code": null, "e": 3293, "s": 3228, "text": "function, which create our tkinter message and return it(16–27);" }, { "code": null, "e": 3365, "s": 3293, "text": "capture video from camera, grayscale it and make face detection(32–43);" }, { "code": null, "e": 3525, "s": 3365, "text": "when no face detect(44–46) or face far away(56–59) — disable tkinter message. If don’t do that, warning message won’t disappear after one successful detection;" }, { "code": null, "e": 3590, "s": 3525, "text": "when face detect — calculate a distance to detected face(48–52);" }, { "code": null, "e": 3663, "s": 3590, "text": "if distance less then selected distance — enable tkinter message(53–55);" }, { "code": null, "e": 3734, "s": 3663, "text": "show useful info in opencv window and close all after press Q (60–81)." }, { "code": null, "e": 3810, "s": 3734, "text": "Before using we need to calibrate it according to your face. To doing that:" }, { "code": null, "e": 4047, "s": 3810, "text": "run python3 distance_detector.py;sit down in a front of camera on distance, which will be limit for eyes;notice face_height parameter and close script (press Q in window);run python3 distance_detector.py with your face_height parameter." }, { "code": null, "e": 4081, "s": 4047, "text": "run python3 distance_detector.py;" }, { "code": null, "e": 4154, "s": 4081, "text": "sit down in a front of camera on distance, which will be limit for eyes;" }, { "code": null, "e": 4221, "s": 4154, "text": "notice face_height parameter and close script (press Q in window);" }, { "code": null, "e": 4287, "s": 4221, "text": "run python3 distance_detector.py with your face_height parameter." }, { "code": null, "e": 4427, "s": 4287, "text": "For example, my face height in pixels is 300, when i sit from 51 cm. In my case, I need to run python3 distance_detector.py -f 300 -d 0.51." }, { "code": null, "e": 4446, "s": 4427, "text": "How it looks like:" }, { "code": null, "e": 4726, "s": 4446, "text": "In this article you see, how after decomposition the idea into small chunks actual implementation became is not so hard. Yes, you can added more techniques to it to make detection work more accurate and improve performance — but as simple example of idea that’s should be enough." }, { "code": null, "e": 4800, "s": 4726, "text": "P.S.: If you wear glasses, be aware that detection will be less accurate." } ]
C# - Strings
In C#, you can use strings as array of characters, However, more common practice is to use the string keyword to declare a string variable. The string keyword is an alias for the System.String class. You can create string object using one of the following methods − By assigning a string literal to a String variable By assigning a string literal to a String variable By using a String class constructor By using a String class constructor By using the string concatenation operator (+) By using the string concatenation operator (+) By retrieving a property or calling a method that returns a string By retrieving a property or calling a method that returns a string By calling a formatting method to convert a value or an object to its string representation By calling a formatting method to convert a value or an object to its string representation The following example demonstrates this − using System; namespace StringApplication { class Program { static void Main(string[] args) { //from string literal and string concatenation string fname, lname; fname = "Rowan"; lname = "Atkinson"; char []letters= { 'H', 'e', 'l', 'l','o' }; string [] sarray={ "Hello", "From", "Tutorials", "Point" }; string fullname = fname + lname; Console.WriteLine("Full Name: {0}", fullname); //by using string constructor { 'H', 'e', 'l', 'l','o' }; string greetings = new string(letters); Console.WriteLine("Greetings: {0}", greetings); //methods returning string { "Hello", "From", "Tutorials", "Point" }; string message = String.Join(" ", sarray); Console.WriteLine("Message: {0}", message); //formatting method to convert a value DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1); string chat = String.Format("Message sent at {0:t} on {0:D}", waiting); Console.WriteLine("Message: {0}", chat); } } } When the above code is compiled and executed, it produces the following result − Full Name: RowanAtkinson Greetings: Hello Message: Hello From Tutorials Point Message: Message sent at 5:58 PM on Wednesday, October 10, 2012 The String class has the following two properties − Chars Gets the Char object at a specified position in the current String object. Length Gets the number of characters in the current String object. The String class has numerous methods that help you in working with the string objects. The following table provides some of the most commonly used methods − public static int Compare(string strA, string strB) Compares two specified string objects and returns an integer that indicates their relative position in the sort order. public static int Compare(string strA, string strB, bool ignoreCase ) Compares two specified string objects and returns an integer that indicates their relative position in the sort order. However, it ignores case if the Boolean parameter is true. public static string Concat(string str0, string str1) Concatenates two string objects. public static string Concat(string str0, string str1, string str2) Concatenates three string objects. public static string Concat(string str0, string str1, string str2, string str3) Concatenates four string objects. public bool Contains(string value) Returns a value indicating whether the specified String object occurs within this string. public static string Copy(string str) Creates a new String object with the same value as the specified string. public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) Copies a specified number of characters from a specified position of the String object to a specified position in an array of Unicode characters. public bool EndsWith(string value) Determines whether the end of the string object matches the specified string. public bool Equals(string value) Determines whether the current String object and the specified String object have the same value. public static bool Equals(string a, string b) Determines whether two specified String objects have the same value. public static string Format(string format, Object arg0) Replaces one or more format items in a specified string with the string representation of a specified object. public int IndexOf(char value) Returns the zero-based index of the first occurrence of the specified Unicode character in the current string. public int IndexOf(string value) Returns the zero-based index of the first occurrence of the specified string in this instance. public int IndexOf(char value, int startIndex) Returns the zero-based index of the first occurrence of the specified Unicode character in this string, starting search at the specified character position. public int IndexOf(string value, int startIndex) Returns the zero-based index of the first occurrence of the specified string in this instance, starting search at the specified character position. public int IndexOfAny(char[] anyOf) Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters. public int IndexOfAny(char[] anyOf, int startIndex) Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters, starting search at the specified character position. public string Insert(int startIndex, string value) Returns a new string in which a specified string is inserted at a specified index position in the current string object. public static bool IsNullOrEmpty(string value) Indicates whether the specified string is null or an Empty string. public static string Join(string separator, params string[] value) Concatenates all the elements of a string array, using the specified separator between each element. public static string Join(string separator, string[] value, int startIndex, int count) Concatenates the specified elements of a string array, using the specified separator between each element. public int LastIndexOf(char value) Returns the zero-based index position of the last occurrence of the specified Unicode character within the current string object. public int LastIndexOf(string value) Returns the zero-based index position of the last occurrence of a specified string within the current string object. public string Remove(int startIndex) Removes all the characters in the current instance, beginning at a specified position and continuing through the last position, and returns the string. public string Remove(int startIndex, int count) Removes the specified number of characters in the current string beginning at a specified position and returns the string. public string Replace(char oldChar, char newChar) Replaces all occurrences of a specified Unicode character in the current string object with the specified Unicode character and returns the new string. public string Replace(string oldValue, string newValue) Replaces all occurrences of a specified string in the current string object with the specified string and returns the new string. public string[] Split(params char[] separator) Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array. public string[] Split(char[] separator, int count) Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array. The int parameter specifies the maximum number of substrings to return. public bool StartsWith(string value) Determines whether the beginning of this string instance matches the specified string. public char[] ToCharArray() Returns a Unicode character array with all the characters in the current string object. public char[] ToCharArray(int startIndex, int length) Returns a Unicode character array with all the characters in the current string object, starting from the specified index and up to the specified length. public string ToLower() Returns a copy of this string converted to lowercase. public string ToUpper() Returns a copy of this string converted to uppercase. public string Trim() Removes all leading and trailing white-space characters from the current String object. You can visit MSDN library for the complete list of methods and String class constructors. The following example demonstrates some of the methods mentioned above − using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string str1 = "This is test"; string str2 = "This is text"; if (String.Compare(str1, str2) == 0) { Console.WriteLine(str1 + " and " + str2 + " are equal."); } else { Console.WriteLine(str1 + " and " + str2 + " are not equal."); } Console.ReadKey() ; } } } When the above code is compiled and executed, it produces the following result − This is test and This is text are not equal. using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string str = "This is test"; if (str.Contains("test")) { Console.WriteLine("The sequence 'test' was found."); } Console.ReadKey() ; } } } When the above code is compiled and executed, it produces the following result − The sequence 'test' was found. using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string str = "Last night I dreamt of San Pedro"; Console.WriteLine(str); string substr = str.Substring(23); Console.WriteLine(substr); } } } When the above code is compiled and executed, it produces the following result − San Pedro using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string[] starray = new string[]{"Down the way nights are dark", "And the sun shines daily on the mountain top", "I took a trip on a sailing ship", "And when I reached Jamaica", "I made a stop"}; string str = String.Join("\n", starray); Console.WriteLine(str); } } } When the above code is compiled and executed, it produces the following result − Down the way nights are dark And the sun shines daily on the mountain top I took a trip on a sailing ship And when I reached Jamaica I made a stop 119 Lectures 23.5 hours Raja Biswas 37 Lectures 13 hours Trevoir Williams 16 Lectures 1 hours Peter Jepson 159 Lectures 21.5 hours Ebenezer Ogbu 193 Lectures 17 hours Arnold Higuit 24 Lectures 2.5 hours Eric Frick Print Add Notes Bookmark this page
[ { "code": null, "e": 2470, "s": 2270, "text": "In C#, you can use strings as array of characters, However, more common practice is to use the string keyword to declare a string variable. The string keyword is an alias for the System.String class." }, { "code": null, "e": 2536, "s": 2470, "text": "You can create string object using one of the following methods −" }, { "code": null, "e": 2587, "s": 2536, "text": "By assigning a string literal to a String variable" }, { "code": null, "e": 2638, "s": 2587, "text": "By assigning a string literal to a String variable" }, { "code": null, "e": 2674, "s": 2638, "text": "By using a String class constructor" }, { "code": null, "e": 2710, "s": 2674, "text": "By using a String class constructor" }, { "code": null, "e": 2757, "s": 2710, "text": "By using the string concatenation operator (+)" }, { "code": null, "e": 2804, "s": 2757, "text": "By using the string concatenation operator (+)" }, { "code": null, "e": 2871, "s": 2804, "text": "By retrieving a property or calling a method that returns a string" }, { "code": null, "e": 2938, "s": 2871, "text": "By retrieving a property or calling a method that returns a string" }, { "code": null, "e": 3030, "s": 2938, "text": "By calling a formatting method to convert a value or an object to its string representation" }, { "code": null, "e": 3122, "s": 3030, "text": "By calling a formatting method to convert a value or an object to its string representation" }, { "code": null, "e": 3164, "s": 3122, "text": "The following example demonstrates this −" }, { "code": null, "e": 4296, "s": 3164, "text": "using System;\n\nnamespace StringApplication {\n\n class Program {\n \n static void Main(string[] args) {\n //from string literal and string concatenation\n string fname, lname;\n fname = \"Rowan\";\n lname = \"Atkinson\";\n\t\t\t\n char []letters= { 'H', 'e', 'l', 'l','o' };\n string [] sarray={ \"Hello\", \"From\", \"Tutorials\", \"Point\" };\n \n string fullname = fname + lname;\n Console.WriteLine(\"Full Name: {0}\", fullname);\n \n //by using string constructor { 'H', 'e', 'l', 'l','o' };\n string greetings = new string(letters);\n Console.WriteLine(\"Greetings: {0}\", greetings);\n \n //methods returning string { \"Hello\", \"From\", \"Tutorials\", \"Point\" };\n string message = String.Join(\" \", sarray);\n Console.WriteLine(\"Message: {0}\", message);\n \n //formatting method to convert a value\n DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);\n string chat = String.Format(\"Message sent at {0:t} on {0:D}\", waiting);\n Console.WriteLine(\"Message: {0}\", chat);\n }\n }\n}" }, { "code": null, "e": 4377, "s": 4296, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4520, "s": 4377, "text": "Full Name: RowanAtkinson\nGreetings: Hello\nMessage: Hello From Tutorials Point\nMessage: Message sent at 5:58 PM on Wednesday, October 10, 2012\n" }, { "code": null, "e": 4572, "s": 4520, "text": "The String class has the following two properties −" }, { "code": null, "e": 4578, "s": 4572, "text": "Chars" }, { "code": null, "e": 4653, "s": 4578, "text": "Gets the Char object at a specified position in the current String object." }, { "code": null, "e": 4660, "s": 4653, "text": "Length" }, { "code": null, "e": 4720, "s": 4660, "text": "Gets the number of characters in the current String object." }, { "code": null, "e": 4878, "s": 4720, "text": "The String class has numerous methods that help you in working with the string objects. The following table provides some of the most commonly used methods −" }, { "code": null, "e": 4930, "s": 4878, "text": "public static int Compare(string strA, string strB)" }, { "code": null, "e": 5049, "s": 4930, "text": "Compares two specified string objects and returns an integer that indicates their relative position in the sort order." }, { "code": null, "e": 5119, "s": 5049, "text": "public static int Compare(string strA, string strB, bool ignoreCase )" }, { "code": null, "e": 5297, "s": 5119, "text": "Compares two specified string objects and returns an integer that indicates their relative position in the sort order. However, it ignores case if the Boolean parameter is true." }, { "code": null, "e": 5351, "s": 5297, "text": "public static string Concat(string str0, string str1)" }, { "code": null, "e": 5384, "s": 5351, "text": "Concatenates two string objects." }, { "code": null, "e": 5451, "s": 5384, "text": "public static string Concat(string str0, string str1, string str2)" }, { "code": null, "e": 5486, "s": 5451, "text": "Concatenates three string objects." }, { "code": null, "e": 5566, "s": 5486, "text": "public static string Concat(string str0, string str1, string str2, string str3)" }, { "code": null, "e": 5600, "s": 5566, "text": "Concatenates four string objects." }, { "code": null, "e": 5635, "s": 5600, "text": "public bool Contains(string value)" }, { "code": null, "e": 5725, "s": 5635, "text": "Returns a value indicating whether the specified String object occurs within this string." }, { "code": null, "e": 5763, "s": 5725, "text": "public static string Copy(string str)" }, { "code": null, "e": 5836, "s": 5763, "text": "Creates a new String object with the same value as the specified string." }, { "code": null, "e": 5925, "s": 5836, "text": "public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)" }, { "code": null, "e": 6071, "s": 5925, "text": "Copies a specified number of characters from a specified position of the String object to a specified position in an array of Unicode characters." }, { "code": null, "e": 6106, "s": 6071, "text": "public bool EndsWith(string value)" }, { "code": null, "e": 6184, "s": 6106, "text": "Determines whether the end of the string object matches the specified string." }, { "code": null, "e": 6217, "s": 6184, "text": "public bool Equals(string value)" }, { "code": null, "e": 6315, "s": 6217, "text": "Determines whether the current String object and the specified String object have the same value." }, { "code": null, "e": 6361, "s": 6315, "text": "public static bool Equals(string a, string b)" }, { "code": null, "e": 6430, "s": 6361, "text": "Determines whether two specified String objects have the same value." }, { "code": null, "e": 6486, "s": 6430, "text": "public static string Format(string format, Object arg0)" }, { "code": null, "e": 6596, "s": 6486, "text": "Replaces one or more format items in a specified string with the string representation of a specified object." }, { "code": null, "e": 6627, "s": 6596, "text": "public int IndexOf(char value)" }, { "code": null, "e": 6738, "s": 6627, "text": "Returns the zero-based index of the first occurrence of the specified Unicode character in the current string." }, { "code": null, "e": 6771, "s": 6738, "text": "public int IndexOf(string value)" }, { "code": null, "e": 6866, "s": 6771, "text": "Returns the zero-based index of the first occurrence of the specified string in this instance." }, { "code": null, "e": 6913, "s": 6866, "text": "public int IndexOf(char value, int startIndex)" }, { "code": null, "e": 7070, "s": 6913, "text": "Returns the zero-based index of the first occurrence of the specified Unicode character in this string, starting search at the specified character position." }, { "code": null, "e": 7119, "s": 7070, "text": "public int IndexOf(string value, int startIndex)" }, { "code": null, "e": 7267, "s": 7119, "text": "Returns the zero-based index of the first occurrence of the specified string in this instance, starting search at the specified character position." }, { "code": null, "e": 7303, "s": 7267, "text": "public int IndexOfAny(char[] anyOf)" }, { "code": null, "e": 7434, "s": 7303, "text": "Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters." }, { "code": null, "e": 7486, "s": 7434, "text": "public int IndexOfAny(char[] anyOf, int startIndex)" }, { "code": null, "e": 7670, "s": 7486, "text": "Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters, starting search at the specified character position." }, { "code": null, "e": 7721, "s": 7670, "text": "public string Insert(int startIndex, string value)" }, { "code": null, "e": 7842, "s": 7721, "text": "Returns a new string in which a specified string is inserted at a specified index position in the current string object." }, { "code": null, "e": 7889, "s": 7842, "text": "public static bool IsNullOrEmpty(string value)" }, { "code": null, "e": 7956, "s": 7889, "text": "Indicates whether the specified string is null or an Empty string." }, { "code": null, "e": 8023, "s": 7956, "text": "public static string Join(string separator, params string[] value)" }, { "code": null, "e": 8124, "s": 8023, "text": "Concatenates all the elements of a string array, using the specified separator between each element." }, { "code": null, "e": 8211, "s": 8124, "text": "public static string Join(string separator, string[] value, int startIndex, int count)" }, { "code": null, "e": 8318, "s": 8211, "text": "Concatenates the specified elements of a string array, using the specified separator between each element." }, { "code": null, "e": 8353, "s": 8318, "text": "public int LastIndexOf(char value)" }, { "code": null, "e": 8483, "s": 8353, "text": "Returns the zero-based index position of the last occurrence of the specified Unicode character within the current string object." }, { "code": null, "e": 8520, "s": 8483, "text": "public int LastIndexOf(string value)" }, { "code": null, "e": 8637, "s": 8520, "text": "Returns the zero-based index position of the last occurrence of a specified string within the current string object." }, { "code": null, "e": 8674, "s": 8637, "text": "public string Remove(int startIndex)" }, { "code": null, "e": 8826, "s": 8674, "text": "Removes all the characters in the current instance, beginning at a specified position and continuing through the last position, and returns the string." }, { "code": null, "e": 8874, "s": 8826, "text": "public string Remove(int startIndex, int count)" }, { "code": null, "e": 8997, "s": 8874, "text": "Removes the specified number of characters in the current string beginning at a specified position and returns the string." }, { "code": null, "e": 9047, "s": 8997, "text": "public string Replace(char oldChar, char newChar)" }, { "code": null, "e": 9199, "s": 9047, "text": "Replaces all occurrences of a specified Unicode character in the current string object with the specified Unicode character and returns the new string." }, { "code": null, "e": 9255, "s": 9199, "text": "public string Replace(string oldValue, string newValue)" }, { "code": null, "e": 9385, "s": 9255, "text": "Replaces all occurrences of a specified string in the current string object with the specified string and returns the new string." }, { "code": null, "e": 9432, "s": 9385, "text": "public string[] Split(params char[] separator)" }, { "code": null, "e": 9576, "s": 9432, "text": "Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array." }, { "code": null, "e": 9627, "s": 9576, "text": "public string[] Split(char[] separator, int count)" }, { "code": null, "e": 9843, "s": 9627, "text": "Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array. The int parameter specifies the maximum number of substrings to return." }, { "code": null, "e": 9880, "s": 9843, "text": "public bool StartsWith(string value)" }, { "code": null, "e": 9967, "s": 9880, "text": "Determines whether the beginning of this string instance matches the specified string." }, { "code": null, "e": 9995, "s": 9967, "text": "public char[] ToCharArray()" }, { "code": null, "e": 10083, "s": 9995, "text": "Returns a Unicode character array with all the characters in the current string object." }, { "code": null, "e": 10137, "s": 10083, "text": "public char[] ToCharArray(int startIndex, int length)" }, { "code": null, "e": 10291, "s": 10137, "text": "Returns a Unicode character array with all the characters in the current string object, starting from the specified index and up to the specified length." }, { "code": null, "e": 10315, "s": 10291, "text": "public string ToLower()" }, { "code": null, "e": 10369, "s": 10315, "text": "Returns a copy of this string converted to lowercase." }, { "code": null, "e": 10393, "s": 10369, "text": "public string ToUpper()" }, { "code": null, "e": 10447, "s": 10393, "text": "Returns a copy of this string converted to uppercase." }, { "code": null, "e": 10468, "s": 10447, "text": "public string Trim()" }, { "code": null, "e": 10556, "s": 10468, "text": "Removes all leading and trailing white-space characters from the current String object." }, { "code": null, "e": 10647, "s": 10556, "text": "You can visit MSDN library for the complete list of methods and String class constructors." }, { "code": null, "e": 10720, "s": 10647, "text": "The following example demonstrates some of the methods mentioned above −" }, { "code": null, "e": 11177, "s": 10720, "text": "using System;\n\nnamespace StringApplication {\n\n class StringProg {\n \n static void Main(string[] args) {\n string str1 = \"This is test\";\n string str2 = \"This is text\";\n\n if (String.Compare(str1, str2) == 0) {\n Console.WriteLine(str1 + \" and \" + str2 + \" are equal.\");\n } else {\n Console.WriteLine(str1 + \" and \" + str2 + \" are not equal.\");\n }\n Console.ReadKey() ;\n }\n }\n}" }, { "code": null, "e": 11258, "s": 11177, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 11304, "s": 11258, "text": "This is test and This is text are not equal.\n" }, { "code": null, "e": 11621, "s": 11304, "text": "using System;\n\nnamespace StringApplication {\n\n class StringProg {\n \n static void Main(string[] args) {\n string str = \"This is test\";\n \n if (str.Contains(\"test\")) {\n Console.WriteLine(\"The sequence 'test' was found.\");\n }\n Console.ReadKey() ;\n }\n }\n}" }, { "code": null, "e": 11702, "s": 11621, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 11734, "s": 11702, "text": "The sequence 'test' was found.\n" }, { "code": null, "e": 12032, "s": 11734, "text": "using System;\n\nnamespace StringApplication {\n\n class StringProg {\n \n static void Main(string[] args) {\n string str = \"Last night I dreamt of San Pedro\";\n Console.WriteLine(str);\n string substr = str.Substring(23);\n Console.WriteLine(substr);\n }\n }\n}" }, { "code": null, "e": 12113, "s": 12032, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 12124, "s": 12113, "text": "San Pedro\n" }, { "code": null, "e": 12587, "s": 12124, "text": "using System;\n\nnamespace StringApplication {\n\n class StringProg {\n \n static void Main(string[] args) {\n string[] starray = new string[]{\"Down the way nights are dark\",\n \"And the sun shines daily on the mountain top\",\n \"I took a trip on a sailing ship\",\n \"And when I reached Jamaica\",\n \"I made a stop\"};\n\n string str = String.Join(\"\\n\", starray);\n Console.WriteLine(str);\n }\n }\n}" }, { "code": null, "e": 12668, "s": 12587, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 12816, "s": 12668, "text": "Down the way nights are dark\nAnd the sun shines daily on the mountain top\nI took a trip on a sailing ship\nAnd when I reached Jamaica\nI made a stop\n" }, { "code": null, "e": 12853, "s": 12816, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 12866, "s": 12853, "text": " Raja Biswas" }, { "code": null, "e": 12900, "s": 12866, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 12918, "s": 12900, "text": " Trevoir Williams" }, { "code": null, "e": 12951, "s": 12918, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 12965, "s": 12951, "text": " Peter Jepson" }, { "code": null, "e": 13002, "s": 12965, "text": "\n 159 Lectures \n 21.5 hours \n" }, { "code": null, "e": 13017, "s": 13002, "text": " Ebenezer Ogbu" }, { "code": null, "e": 13052, "s": 13017, "text": "\n 193 Lectures \n 17 hours \n" }, { "code": null, "e": 13067, "s": 13052, "text": " Arnold Higuit" }, { "code": null, "e": 13102, "s": 13067, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13114, "s": 13102, "text": " Eric Frick" }, { "code": null, "e": 13121, "s": 13114, "text": " Print" }, { "code": null, "e": 13132, "s": 13121, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: Using the animation-delay property
[]
How to use Style Sheet in HTML?
The stylesheet is used in HTML to describe how a document is presented on screen. With CSS, easily specify a number of style properties for an HTML element. Each property has a name and a value, which is separated by a colon (:). You can use CSS in three ways in your HTML document − External Style Sheet − Define style sheet rules in a separate .css file and then include that file in your HTML document using HTML <link> tag. Internal Style Sheet − Define style sheet rules in header section of the HTML document using <style> tag. Inline Style Sheet − Define style sheet rules directly along-with the HTML elements using style attribute. Just keep in mind each property declaration is separated by a semi-colon (;). Use the style attribute to add CSS to the HTML elements and attribute. This is how you can add inline style sheet and set text color − You can try to run the following code to add a style sheet to an HTML page <!DOCTYPE html> <html> <head> <title>HTML style sheet</title> </head> <body> <h1 style="color:red"> Heading </h1> <p style="color:blue"> This is demo text </p> </body> </html>
[ { "code": null, "e": 1292, "s": 1062, "text": "The stylesheet is used in HTML to describe how a document is presented on screen. With CSS, easily specify a number of style properties for an HTML element. Each property has a name and a value, which is separated by a colon (:)." }, { "code": null, "e": 1346, "s": 1292, "text": "You can use CSS in three ways in your HTML document −" }, { "code": null, "e": 1490, "s": 1346, "text": "External Style Sheet − Define style sheet rules in a separate .css file and then include that file in your HTML document using HTML <link> tag." }, { "code": null, "e": 1596, "s": 1490, "text": "Internal Style Sheet − Define style sheet rules in header section of the HTML document using <style> tag." }, { "code": null, "e": 1703, "s": 1596, "text": "Inline Style Sheet − Define style sheet rules directly along-with the HTML elements using style attribute." }, { "code": null, "e": 1916, "s": 1703, "text": "Just keep in mind each property declaration is separated by a semi-colon (;). Use the style attribute to add CSS to the HTML elements and attribute. This is how you can add inline style sheet and set text color −" }, { "code": null, "e": 1991, "s": 1916, "text": "You can try to run the following code to add a style sheet to an HTML page" }, { "code": null, "e": 2229, "s": 1991, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML style sheet</title>\n </head>\n \n <body>\n <h1 style=\"color:red\">\n Heading\n </h1>\n <p style=\"color:blue\">\n This is demo text\n </p>\n </body>\n</html>" } ]
java.time.ZonedDateTime. withZoneSameInstant() Method Example
The java.time.ZonedDateTime.withZoneSameInstant(ZoneId zone) method returns a copy of this date-time with a different time-zone, retaining the instant. Following is the declaration for java.time.ZonedDateTime.withZoneSameInstant(ZoneId zone) method. public ZonedDateTime withZoneSameInstant(ZoneId zone) zone − the time-zone to change to, not null. a ZonedDateTime based on this date with the requested zone, not null. DateTimeException − if the year value is invalid. The following example shows the usage of java.time.ZonedDateTime.withZoneSameInstant(ZoneId zone) method. package com.tutorialspoint; import java.time.ZoneId; import java.time.ZonedDateTime; public class ZonedDateTimeDemo { public static void main(String[] args) { ZonedDateTime date = ZonedDateTime.parse("2017-03-28T12:25:38.492+05:30[Asia/Calcutta]"); ZonedDateTime result = date.withZoneSameInstant(ZoneId.of("Z")); System.out.println(result); } } Let us compile and run the above program, this will produce the following result − 2017-03-28T06:55:38.492Z Print Add Notes Bookmark this page
[ { "code": null, "e": 2067, "s": 1915, "text": "The java.time.ZonedDateTime.withZoneSameInstant(ZoneId zone) method returns a copy of this date-time with a different time-zone, retaining the instant." }, { "code": null, "e": 2165, "s": 2067, "text": "Following is the declaration for java.time.ZonedDateTime.withZoneSameInstant(ZoneId zone) method." }, { "code": null, "e": 2220, "s": 2165, "text": "public ZonedDateTime withZoneSameInstant(ZoneId zone)\n" }, { "code": null, "e": 2265, "s": 2220, "text": "zone − the time-zone to change to, not null." }, { "code": null, "e": 2335, "s": 2265, "text": "a ZonedDateTime based on this date with the requested zone, not null." }, { "code": null, "e": 2385, "s": 2335, "text": "DateTimeException − if the year value is invalid." }, { "code": null, "e": 2491, "s": 2385, "text": "The following example shows the usage of java.time.ZonedDateTime.withZoneSameInstant(ZoneId zone) method." }, { "code": null, "e": 2872, "s": 2491, "text": "package com.tutorialspoint;\n\nimport java.time.ZoneId;\nimport java.time.ZonedDateTime;\n\npublic class ZonedDateTimeDemo {\n public static void main(String[] args) {\n \n ZonedDateTime date = ZonedDateTime.parse(\"2017-03-28T12:25:38.492+05:30[Asia/Calcutta]\");\n ZonedDateTime result = date.withZoneSameInstant(ZoneId.of(\"Z\"));\n System.out.println(result); \n }\n}" }, { "code": null, "e": 2955, "s": 2872, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 2981, "s": 2955, "text": "2017-03-28T06:55:38.492Z\n" }, { "code": null, "e": 2988, "s": 2981, "text": " Print" }, { "code": null, "e": 2999, "s": 2988, "text": " Add Notes" } ]
Magnitude Comparator in Digital Logic - GeeksforGeeks
19 Feb, 2021 A magnitude digital Comparator is a combinational circuit that compares two digital or binary numbers in order to find out whether one binary number is equal, less than or greater than the other binary number. We logically design a circuit for which we will have two inputs one for A and other for B and have three output terminals, one for A > B condition, one for A = B condition and one for A < B condition. A comparator used to compare two bits is called a single bit comparator. It consists of two inputs each for two single bit numbers and three outputs to generate less than, equal to and greater than between two binary numbers. The truth table for a 1-bit comparator is given below: From the above truth table logical expressions for each output can be expressed as follows: A>B: AB' A<B: A'B A=B: A'B' + AB From the above expressions we can derive the following formula: By using these Boolean expressions, we can implement a logic circuit for this comparator as given below: Logic Diagram is wrong A comparator used to compare two binary numbers each of two bits is called a 2-bit Magnitude comparator. It consists of four inputs and three outputs to generate less than, equal to and greater than between two binary numbers. The truth table for a 2-bit comparator is given below: From the above truth table K-map for each output can be drawn as follows: From the above K-maps logical expressions for each output can be expressed as follows: A>B:A1B1’ + A0B1’B0’ + A1A0B0’ A=B: A1’A0’B1’B0’ + A1’A0B1’B0 + A1A0B1B0 + A1A0’B1B0’ : A1’B1’ (A0’B0’ + A0B0) + A1B1 (A0B0 + A0’B0’) : (A0B0 + A0’B0’) (A1B1 + A1’B1’) : (A0 Ex-Nor B0) (A1 Ex-Nor B1) A<B:A1’B1 + A0’B1B0 + A1’A0’B0 By using these Boolean expressions, we can implement a logic circuit for this comparator as given below: A comparator used to compare two binary numbers each of four bits is called a 4-bit magnitude comparator. It consists of eight inputs each for two four bit numbers and three outputs to generate less than, equal to and greater than between two binary numbers. In a 4-bit comparator the condition of A>B can be possible in the following four cases: If A3 = 1 and B3 = 0If A3 = B3 and A2 = 1 and B2 = 0If A3 = B3, A2 = B2 and A1 = 1 and B1 = 0If A3 = B3, A2 = B2, A1 = B1 and A0 = 1 and B0 = 0 If A3 = 1 and B3 = 0 If A3 = B3 and A2 = 1 and B2 = 0 If A3 = B3, A2 = B2 and A1 = 1 and B1 = 0 If A3 = B3, A2 = B2, A1 = B1 and A0 = 1 and B0 = 0 Similarly the condition for A<B can be possible in the following four cases: If A3 = 0 and B3 = 1If A3 = B3 and A2 = 0 and B2 = 1If A3 = B3, A2 = B2 and A1 = 0 and B1 = 1If A3 = B3, A2 = B2, A1 = B1 and A0 = 0 and B0 = 1 If A3 = 0 and B3 = 1 If A3 = B3 and A2 = 0 and B2 = 1 If A3 = B3, A2 = B2 and A1 = 0 and B1 = 1 If A3 = B3, A2 = B2, A1 = B1 and A0 = 0 and B0 = 1 The condition of A=B is possible only when all the individual bits of one number exactly coincide with corresponding bits of another number. From the above statements logical expressions for each output can be expressed as follows: AA, 831331 r: (A3 EioNor 33)A2132′ a (A3 Ex-Nor 133) (A2 Ex-Nor 132)A131′ a (A3 Ex-Nor 33) (A2 ENor132) (Al Ex-Nor 31)A01301 ,13: A3’03 a (A3 Ex-Nor 33)A211:12 a (A3 Ex-Nor 83) (A2 Ex-Nor 132)Ar131 a (A3 Ex-Nor 33) (A2 Ex-Nor32) (Al Ex-Nor 131)A0N30 A=B: (A3 Ex-Nor B3) (A2 Ex-Nor 82) (Al Ex-Nor BI) (AO Ex-Nor BO) By using these Boolean expressions, we can implement a logic circuit for this comparator as given below: A comparator performing the comparison operation to more than four bits by cascading two or more 4-bit comparators is called cascading comparator. When two comparators are to be cascaded, the outputs of the lower-order comparator are connected to corresponding inputs of the higher-order comparator. Comparators are used in central processing units (CPUs) and microcontrollers (MCUs).These are used in control applications in which the binary numbers representing physical variables such as temperature, position, etc. are compared with a reference value.Comparators are also used as process controllers and for Servo motor control.Used in password verification and biometric applications. Comparators are used in central processing units (CPUs) and microcontrollers (MCUs). These are used in control applications in which the binary numbers representing physical variables such as temperature, position, etc. are compared with a reference value. Comparators are also used as process controllers and for Servo motor control. Used in password verification and biometric applications. References – Digital comparator – Wikipedia Comparator – epgp.inflibnet gyanendrarawat200 Digital Electronics & Logic Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments IEEE Standard 754 Floating Point Numbers 4-bit binary Adder-Subtractor Difference between RAM and ROM Analog to Digital Conversion Difference between Unipolar, Polar and Bipolar Line Coding Schemes Layers of OSI Model ACID Properties in DBMS Normal Forms in DBMS Types of Operating Systems
[ { "code": null, "e": 26754, "s": 26726, "text": "\n19 Feb, 2021" }, { "code": null, "e": 27166, "s": 26754, "text": "A magnitude digital Comparator is a combinational circuit that compares two digital or binary numbers in order to find out whether one binary number is equal, less than or greater than the other binary number. We logically design a circuit for which we will have two inputs one for A and other for B and have three output terminals, one for A > B condition, one for A = B condition and one for A < B condition. " }, { "code": null, "e": 27397, "s": 27170, "text": "A comparator used to compare two bits is called a single bit comparator. It consists of two inputs each for two single bit numbers and three outputs to generate less than, equal to and greater than between two binary numbers. " }, { "code": null, "e": 27453, "s": 27397, "text": "The truth table for a 1-bit comparator is given below: " }, { "code": null, "e": 27549, "s": 27455, "text": "From the above truth table logical expressions for each output can be expressed as follows: " }, { "code": null, "e": 27582, "s": 27549, "text": "A>B: AB'\nA<B: A'B\nA=B: A'B' + AB" }, { "code": null, "e": 27647, "s": 27582, "text": "From the above expressions we can derive the following formula: " }, { "code": null, "e": 27755, "s": 27649, "text": "By using these Boolean expressions, we can implement a logic circuit for this comparator as given below: " }, { "code": null, "e": 27780, "s": 27757, "text": "Logic Diagram is wrong" }, { "code": null, "e": 28010, "s": 27782, "text": "A comparator used to compare two binary numbers each of two bits is called a 2-bit Magnitude comparator. It consists of four inputs and three outputs to generate less than, equal to and greater than between two binary numbers. " }, { "code": null, "e": 28066, "s": 28010, "text": "The truth table for a 2-bit comparator is given below: " }, { "code": null, "e": 28143, "s": 28068, "text": "From the above truth table K-map for each output can be drawn as follows: " }, { "code": null, "e": 28238, "s": 28149, "text": "From the above K-maps logical expressions for each output can be expressed as follows: " }, { "code": null, "e": 28478, "s": 28238, "text": "A>B:A1B1’ + A0B1’B0’ + A1A0B0’\nA=B: A1’A0’B1’B0’ + A1’A0B1’B0 + A1A0B1B0 + A1A0’B1B0’\n : A1’B1’ (A0’B0’ + A0B0) + A1B1 (A0B0 + A0’B0’)\n : (A0B0 + A0’B0’) (A1B1 + A1’B1’)\n : (A0 Ex-Nor B0) (A1 Ex-Nor B1)\nA<B:A1’B1 + A0’B1B0 + A1’A0’B0" }, { "code": null, "e": 28584, "s": 28478, "text": "By using these Boolean expressions, we can implement a logic circuit for this comparator as given below: " }, { "code": null, "e": 28848, "s": 28588, "text": "A comparator used to compare two binary numbers each of four bits is called a 4-bit magnitude comparator. It consists of eight inputs each for two four bit numbers and three outputs to generate less than, equal to and greater than between two binary numbers. " }, { "code": null, "e": 28938, "s": 28848, "text": "In a 4-bit comparator the condition of A>B can be possible in the following four cases: " }, { "code": null, "e": 29082, "s": 28938, "text": "If A3 = 1 and B3 = 0If A3 = B3 and A2 = 1 and B2 = 0If A3 = B3, A2 = B2 and A1 = 1 and B1 = 0If A3 = B3, A2 = B2, A1 = B1 and A0 = 1 and B0 = 0" }, { "code": null, "e": 29103, "s": 29082, "text": "If A3 = 1 and B3 = 0" }, { "code": null, "e": 29136, "s": 29103, "text": "If A3 = B3 and A2 = 1 and B2 = 0" }, { "code": null, "e": 29178, "s": 29136, "text": "If A3 = B3, A2 = B2 and A1 = 1 and B1 = 0" }, { "code": null, "e": 29229, "s": 29178, "text": "If A3 = B3, A2 = B2, A1 = B1 and A0 = 1 and B0 = 0" }, { "code": null, "e": 29308, "s": 29229, "text": "Similarly the condition for A<B can be possible in the following four cases: " }, { "code": null, "e": 29452, "s": 29308, "text": "If A3 = 0 and B3 = 1If A3 = B3 and A2 = 0 and B2 = 1If A3 = B3, A2 = B2 and A1 = 0 and B1 = 1If A3 = B3, A2 = B2, A1 = B1 and A0 = 0 and B0 = 1" }, { "code": null, "e": 29473, "s": 29452, "text": "If A3 = 0 and B3 = 1" }, { "code": null, "e": 29506, "s": 29473, "text": "If A3 = B3 and A2 = 0 and B2 = 1" }, { "code": null, "e": 29548, "s": 29506, "text": "If A3 = B3, A2 = B2 and A1 = 0 and B1 = 1" }, { "code": null, "e": 29599, "s": 29548, "text": "If A3 = B3, A2 = B2, A1 = B1 and A0 = 0 and B0 = 1" }, { "code": null, "e": 29741, "s": 29599, "text": "The condition of A=B is possible only when all the individual bits of one number exactly coincide with corresponding bits of another number. " }, { "code": null, "e": 29833, "s": 29741, "text": "From the above statements logical expressions for each output can be expressed as follows: " }, { "code": null, "e": 30149, "s": 29833, "text": "AA, 831331 r: (A3 EioNor 33)A2132′ a (A3 Ex-Nor 133) (A2 Ex-Nor 132)A131′ a (A3 Ex-Nor 33) (A2 ENor132) (Al Ex-Nor 31)A01301 ,13: A3’03 a (A3 Ex-Nor 33)A211:12 a (A3 Ex-Nor 83) (A2 Ex-Nor 132)Ar131 a (A3 Ex-Nor 33) (A2 Ex-Nor32) (Al Ex-Nor 131)A0N30 A=B: (A3 Ex-Nor B3) (A2 Ex-Nor 82) (Al Ex-Nor BI) (AO Ex-Nor BO) " }, { "code": null, "e": 30255, "s": 30149, "text": "By using these Boolean expressions, we can implement a logic circuit for this comparator as given below: " }, { "code": null, "e": 30560, "s": 30259, "text": "A comparator performing the comparison operation to more than four bits by cascading two or more 4-bit comparators is called cascading comparator. When two comparators are to be cascaded, the outputs of the lower-order comparator are connected to corresponding inputs of the higher-order comparator. " }, { "code": null, "e": 30956, "s": 30566, "text": "Comparators are used in central processing units (CPUs) and microcontrollers (MCUs).These are used in control applications in which the binary numbers representing physical variables such as temperature, position, etc. are compared with a reference value.Comparators are also used as process controllers and for Servo motor control.Used in password verification and biometric applications." }, { "code": null, "e": 31041, "s": 30956, "text": "Comparators are used in central processing units (CPUs) and microcontrollers (MCUs)." }, { "code": null, "e": 31213, "s": 31041, "text": "These are used in control applications in which the binary numbers representing physical variables such as temperature, position, etc. are compared with a reference value." }, { "code": null, "e": 31291, "s": 31213, "text": "Comparators are also used as process controllers and for Servo motor control." }, { "code": null, "e": 31349, "s": 31291, "text": "Used in password verification and biometric applications." }, { "code": null, "e": 31422, "s": 31349, "text": "References – Digital comparator – Wikipedia Comparator – epgp.inflibnet " }, { "code": null, "e": 31442, "s": 31424, "text": "gyanendrarawat200" }, { "code": null, "e": 31477, "s": 31442, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 31485, "s": 31477, "text": "GATE CS" }, { "code": null, "e": 31583, "s": 31485, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31592, "s": 31583, "text": "Comments" }, { "code": null, "e": 31605, "s": 31592, "text": "Old Comments" }, { "code": null, "e": 31646, "s": 31605, "text": "IEEE Standard 754 Floating Point Numbers" }, { "code": null, "e": 31676, "s": 31646, "text": "4-bit binary Adder-Subtractor" }, { "code": null, "e": 31707, "s": 31676, "text": "Difference between RAM and ROM" }, { "code": null, "e": 31736, "s": 31707, "text": "Analog to Digital Conversion" }, { "code": null, "e": 31803, "s": 31736, "text": "Difference between Unipolar, Polar and Bipolar Line Coding Schemes" }, { "code": null, "e": 31823, "s": 31803, "text": "Layers of OSI Model" }, { "code": null, "e": 31847, "s": 31823, "text": "ACID Properties in DBMS" }, { "code": null, "e": 31868, "s": 31847, "text": "Normal Forms in DBMS" } ]
Change the size of MessageBox - Tkinter - GeeksforGeeks
21 Aug, 2021 Python have many libraries for GUI. Tkinter is one of the libraries that provides a Graphical user interface. For the Short Message, we can use the MessageBox Library. It has many functions for the effective interface. In this MessageBox library provide different type of functions to Display Message Box. showinfo():- To display some usual Informationshowwarning():- To display warning to the Usershowerror():- To display different type of Erroraskquestion():- to Ask Query to the User showinfo():- To display some usual Information showwarning():- To display warning to the User showerror():- To display different type of Error askquestion():- to Ask Query to the User Example: Python3 # MessageBox Illustration of showinfo() function from tkinter import *from tkinter import messagebox # creating window objecttop = Tk() def Button_1(): messagebox.showinfo("Status", "Button-1 Pressed") def Button_2(): messagebox.showinfo("Status", "Button-2 Pressed") # size for windowtop.geometry("100x100")B1 = Button(top, text = "Button-1", command = Button_1) B2 = Button(top, text = "Button-2", command = Button_2) B1.pack()B2.pack()top.mainloop() Output: By default, the size of the message box is Fix. We can’t change the size of that Message Box. Different Boxes have different sizes. However, we can use Different alternative methods for this purpose Message Widget By Changing ReadMe File 1. Message Widget MessageBox library doesn’t provide the functions to change the configuration of the box. We can use the other function. The message can also be used to display the information. The size of the message is the size of the window so that we can set the size of the message by geometry, pack. Python3 from tkinter import * main = Tk() # variable for textstr_var = StringVar() # Message Functionlabel = Message( main, textvariable=str_var, relief=RAISED ) # The size of the text determines# the size of the messageboxstr_var.set("You can't Change Your Profile Picture ")label.pack()main.mainloop() Output: 2. By Changing ReadMe File This is another alternative option of the Message Box. In this, We are Opening the file readme.txt the length of the content of the readme file determines the size of the messagebox. Input File: Python3 from tkinter import *from tkinter import messagebox top = Tk() def helpfile(filetype): if filetype==1: with open("read.txt") as f: # reading file readme = f.read() # Display whole message messagebox.showinfo(title="Title", message = str(readme)) # Driver codehelpfile(1)top.mainloop() Output: Akanksha_Rai simmytarika5 sumitgumber28 ruhelaa48 Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python Iterate over a list in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24372, "s": 24344, "text": "\n21 Aug, 2021" }, { "code": null, "e": 24678, "s": 24372, "text": "Python have many libraries for GUI. Tkinter is one of the libraries that provides a Graphical user interface. For the Short Message, we can use the MessageBox Library. It has many functions for the effective interface. In this MessageBox library provide different type of functions to Display Message Box." }, { "code": null, "e": 24859, "s": 24678, "text": "showinfo():- To display some usual Informationshowwarning():- To display warning to the Usershowerror():- To display different type of Erroraskquestion():- to Ask Query to the User" }, { "code": null, "e": 24906, "s": 24859, "text": "showinfo():- To display some usual Information" }, { "code": null, "e": 24953, "s": 24906, "text": "showwarning():- To display warning to the User" }, { "code": null, "e": 25002, "s": 24953, "text": "showerror():- To display different type of Error" }, { "code": null, "e": 25043, "s": 25002, "text": "askquestion():- to Ask Query to the User" }, { "code": null, "e": 25053, "s": 25043, "text": "Example: " }, { "code": null, "e": 25061, "s": 25053, "text": "Python3" }, { "code": "# MessageBox Illustration of showinfo() function from tkinter import *from tkinter import messagebox # creating window objecttop = Tk() def Button_1(): messagebox.showinfo(\"Status\", \"Button-1 Pressed\") def Button_2(): messagebox.showinfo(\"Status\", \"Button-2 Pressed\") # size for windowtop.geometry(\"100x100\")B1 = Button(top, text = \"Button-1\", command = Button_1) B2 = Button(top, text = \"Button-2\", command = Button_2) B1.pack()B2.pack()top.mainloop() ", "e": 25597, "s": 25061, "text": null }, { "code": null, "e": 25605, "s": 25597, "text": "Output:" }, { "code": null, "e": 25806, "s": 25605, "text": "By default, the size of the message box is Fix. We can’t change the size of that Message Box. Different Boxes have different sizes. However, we can use Different alternative methods for this purpose " }, { "code": null, "e": 25821, "s": 25806, "text": "Message Widget" }, { "code": null, "e": 25845, "s": 25821, "text": "By Changing ReadMe File" }, { "code": null, "e": 26154, "s": 25845, "text": "1. Message Widget MessageBox library doesn’t provide the functions to change the configuration of the box. We can use the other function. The message can also be used to display the information. The size of the message is the size of the window so that we can set the size of the message by geometry, pack. " }, { "code": null, "e": 26162, "s": 26154, "text": "Python3" }, { "code": "from tkinter import * main = Tk() # variable for textstr_var = StringVar() # Message Functionlabel = Message( main, textvariable=str_var, relief=RAISED ) # The size of the text determines# the size of the messageboxstr_var.set(\"You can't Change Your Profile Picture \")label.pack()main.mainloop()", "e": 26475, "s": 26162, "text": null }, { "code": null, "e": 26483, "s": 26475, "text": "Output:" }, { "code": null, "e": 26693, "s": 26483, "text": "2. By Changing ReadMe File This is another alternative option of the Message Box. In this, We are Opening the file readme.txt the length of the content of the readme file determines the size of the messagebox." }, { "code": null, "e": 26706, "s": 26693, "text": "Input File: " }, { "code": null, "e": 26714, "s": 26706, "text": "Python3" }, { "code": "from tkinter import *from tkinter import messagebox top = Tk() def helpfile(filetype): if filetype==1: with open(\"read.txt\") as f: # reading file readme = f.read() # Display whole message messagebox.showinfo(title=\"Title\", message = str(readme)) # Driver codehelpfile(1)top.mainloop()", "e": 27124, "s": 26714, "text": null }, { "code": null, "e": 27132, "s": 27124, "text": "Output:" }, { "code": null, "e": 27147, "s": 27134, "text": "Akanksha_Rai" }, { "code": null, "e": 27160, "s": 27147, "text": "simmytarika5" }, { "code": null, "e": 27174, "s": 27160, "text": "sumitgumber28" }, { "code": null, "e": 27184, "s": 27174, "text": "ruhelaa48" }, { "code": null, "e": 27199, "s": 27184, "text": "Python-tkinter" }, { "code": null, "e": 27206, "s": 27199, "text": "Python" }, { "code": null, "e": 27304, "s": 27206, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27313, "s": 27304, "text": "Comments" }, { "code": null, "e": 27326, "s": 27313, "text": "Old Comments" }, { "code": null, "e": 27344, "s": 27326, "text": "Python Dictionary" }, { "code": null, "e": 27379, "s": 27344, "text": "Read a file line by line in Python" }, { "code": null, "e": 27401, "s": 27379, "text": "Enumerate() in Python" }, { "code": null, "e": 27431, "s": 27401, "text": "Iterate over a list in Python" }, { "code": null, "e": 27463, "s": 27431, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27505, "s": 27463, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27531, "s": 27505, "text": "Python String | replace()" }, { "code": null, "e": 27568, "s": 27531, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27611, "s": 27568, "text": "Python program to convert a list to string" } ]
How to change Input characters to Upper Case while typing using CSS/jQuery ? - GeeksforGeeks
20 Dec, 2019 Given an input text area and the task is to transform the lowercase characters into uppercase characters while taking input from user. It can be done using CSS or JavaScript. The first approach uses CSS transform property and the second approach uses JavaScript to convert the lowercase character to upper case character. Approach 1: This approach uses CSS text-transform property to transform the lowercase characters into uppercase characters while taking input from the user. Example: This example implements the above approach. <!DOCTYPE HTML> <html> <head> <title> How to change Input character to Upper Case while typing using CSS/JavaScript ? </title></head> <body style = "text-align:center;"> <h1 style = "color: green"> GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 20px; font-weight: bold;"> Type in the input box in lower case to see the effect. </p> Type Here: <input id="yourid" style="text-transform: uppercase" type="text" /> <br><br> <p id = "GFG_DOWN" style = "color:green; font-size: 26px; font-weight: bold;"> </p></body> </html> Output: Before typing in input box: After typing lowercase letters in input box: Approach 2: Use keyup() method to trigger the keyup event when user releases the key from keyboard. Use toLocaleUpperCase() method to transform the input to uppercase and again set it to the input element. Example: This example implements the above approach. <!DOCTYPE HTML> <html> <head> <title> How to change Input character to Upper Case while typing using CSS/JavaScript ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style = "text-align:center;"> <h1 style = "color: green"> GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 20px; font-weight: bold;"> Type in the input box in lower case to see the effect. </p> Type Here: <input id="yourid" type="text" /> <br><br> <script> $(function() { $('input').keyup(function() { this.value = this.value.toLocaleUpperCase(); }); }); </script> </body> </html> Output: Before typing in input box: After typing lowercase letters in input box: jQuery-Misc JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples How to get the value in an input text box using jQuery ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 27089, "s": 27061, "text": "\n20 Dec, 2019" }, { "code": null, "e": 27411, "s": 27089, "text": "Given an input text area and the task is to transform the lowercase characters into uppercase characters while taking input from user. It can be done using CSS or JavaScript. The first approach uses CSS transform property and the second approach uses JavaScript to convert the lowercase character to upper case character." }, { "code": null, "e": 27568, "s": 27411, "text": "Approach 1: This approach uses CSS text-transform property to transform the lowercase characters into uppercase characters while taking input from the user." }, { "code": null, "e": 27621, "s": 27568, "text": "Example: This example implements the above approach." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to change Input character to Upper Case while typing using CSS/JavaScript ? </title></head> <body style = \"text-align:center;\"> <h1 style = \"color: green\"> GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 20px; font-weight: bold;\"> Type in the input box in lower case to see the effect. </p> Type Here: <input id=\"yourid\" style=\"text-transform: uppercase\" type=\"text\" /> <br><br> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 26px; font-weight: bold;\"> </p></body> </html>", "e": 28291, "s": 27621, "text": null }, { "code": null, "e": 28299, "s": 28291, "text": "Output:" }, { "code": null, "e": 28327, "s": 28299, "text": "Before typing in input box:" }, { "code": null, "e": 28372, "s": 28327, "text": "After typing lowercase letters in input box:" }, { "code": null, "e": 28384, "s": 28372, "text": "Approach 2:" }, { "code": null, "e": 28472, "s": 28384, "text": "Use keyup() method to trigger the keyup event when user releases the key from keyboard." }, { "code": null, "e": 28578, "s": 28472, "text": "Use toLocaleUpperCase() method to transform the input to uppercase and again set it to the input element." }, { "code": null, "e": 28631, "s": 28578, "text": "Example: This example implements the above approach." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to change Input character to Upper Case while typing using CSS/JavaScript ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style = \"text-align:center;\"> <h1 style = \"color: green\"> GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 20px; font-weight: bold;\"> Type in the input box in lower case to see the effect. </p> Type Here: <input id=\"yourid\" type=\"text\" /> <br><br> <script> $(function() { $('input').keyup(function() { this.value = this.value.toLocaleUpperCase(); }); }); </script> </body> </html>", "e": 29433, "s": 28631, "text": null }, { "code": null, "e": 29441, "s": 29433, "text": "Output:" }, { "code": null, "e": 29469, "s": 29441, "text": "Before typing in input box:" }, { "code": null, "e": 29514, "s": 29469, "text": "After typing lowercase letters in input box:" }, { "code": null, "e": 29526, "s": 29514, "text": "jQuery-Misc" }, { "code": null, "e": 29533, "s": 29526, "text": "JQuery" }, { "code": null, "e": 29550, "s": 29533, "text": "Web Technologies" }, { "code": null, "e": 29577, "s": 29550, "text": "Web technologies Questions" }, { "code": null, "e": 29675, "s": 29577, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29730, "s": 29675, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 29803, "s": 29730, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 29826, "s": 29803, "text": "jQuery | ajax() Method" }, { "code": null, "e": 29862, "s": 29826, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 29919, "s": 29862, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 29959, "s": 29919, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29992, "s": 29959, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30037, "s": 29992, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30080, "s": 30037, "text": "How to fetch data from an API in ReactJS ?" } ]
JavaScript - Void Keyword
void is an important keyword in JavaScript which can be used as a unary operator that appears before its single operand, which may be of any type. This operator specifies an expression to be evaluated without returning a value. The syntax of void can be either of the following two − <head> <script type = "text/javascript"> <!-- void func() javascript:void func() or: void(func()) javascript:void(func()) //--> </script> </head> The most common use of this operator is in a client-side javascript: URL, where it allows you to evaluate an expression for its side-effects without the browser displaying the value of the evaluated expression. Here the expression alert ('Warning!!!') is evaluated but it is not loaded back into the current document − <html> <head> <script type = "text/javascript"> <!-- //--> </script> </head> <body> <p>Click the following, This won't react at all...</p> <a href = "javascript:void(alert('Warning!!!'))">Click me!</a> </body> </html> Click the following, This won't react at all... Take a look at the following example. The following link does nothing because the expression "0" has no effect in JavaScript. Here the expression "0" is evaluated, but it is not loaded back into the current document. <html> <head> <script type = "text/javascript"> <!-- //--> </script> </head> <body> <p>Click the following, This won't react at all...</p> <a href = "javascript:void(0)">Click me!</a> </body> </html> Click the following, This won't react at all... Another use of void is to purposely generate the undefined value as follows. <html> <head> <script type = "text/javascript"> <!-- function getValue() { var a,b,c; a = void ( b = 5, c = 7 ); document.write('a = ' + a + ' b = ' + b +' c = ' + c ); } //--> </script> </head> <body> <p>Click the following to see the result:</p> <form> <input type = "button" value = "Click Me" onclick = "getValue();" /> </form> </body> </html> Click the following to see the result: 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2694, "s": 2466, "text": "void is an important keyword in JavaScript which can be used as a unary operator that appears before its single operand, which may be of any type. This operator specifies an expression to be evaluated without returning a value." }, { "code": null, "e": 2750, "s": 2694, "text": "The syntax of void can be either of the following two −" }, { "code": null, "e": 2960, "s": 2750, "text": "<head>\n <script type = \"text/javascript\">\n <!--\n void func()\n javascript:void func()\n or:\n void(func())\n javascript:void(func())\n //-->\n </script>\n</head>\n" }, { "code": null, "e": 3171, "s": 2960, "text": "The most common use of this operator is in a client-side javascript: URL, where it allows you to evaluate an expression for its side-effects without the browser displaying the value of the evaluated expression." }, { "code": null, "e": 3279, "s": 3171, "text": "Here the expression alert ('Warning!!!') is evaluated but it is not loaded back into the current document −" }, { "code": null, "e": 3572, "s": 3279, "text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n //-->\n </script> \n </head>\n \n <body> \n <p>Click the following, This won't react at all...</p>\n <a href = \"javascript:void(alert('Warning!!!'))\">Click me!</a> \n </body>\n</html>" }, { "code": null, "e": 3620, "s": 3572, "text": "Click the following, This won't react at all..." }, { "code": null, "e": 3837, "s": 3620, "text": "Take a look at the following example. The following link does nothing because the expression \"0\" has no effect in JavaScript. Here the expression \"0\" is evaluated, but it is not loaded back into the current document." }, { "code": null, "e": 4113, "s": 3837, "text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n //-->\n </script> \n </head>\n \n <body> \n <p>Click the following, This won't react at all...</p>\n <a href = \"javascript:void(0)\">Click me!</a> \n </body>\n</html>" }, { "code": null, "e": 4161, "s": 4113, "text": "Click the following, This won't react at all..." }, { "code": null, "e": 4238, "s": 4161, "text": "Another use of void is to purposely generate the undefined value as follows." }, { "code": null, "e": 4761, "s": 4238, "text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function getValue() {\n var a,b,c;\n \n a = void ( b = 5, c = 7 );\n document.write('a = ' + a + ' b = ' + b +' c = ' + c );\n }\n //-->\n </script> \n </head>\n \n <body>\n <p>Click the following to see the result:</p>\n <form>\n <input type = \"button\" value = \"Click Me\" onclick = \"getValue();\" />\n </form> \n </body>\n</html>" }, { "code": null, "e": 4800, "s": 4761, "text": "Click the following to see the result:" }, { "code": null, "e": 4835, "s": 4800, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4849, "s": 4835, "text": " Anadi Sharma" }, { "code": null, "e": 4883, "s": 4849, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 4897, "s": 4883, "text": " Lets Kode It" }, { "code": null, "e": 4932, "s": 4897, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4949, "s": 4932, "text": " Frahaan Hussain" }, { "code": null, "e": 4984, "s": 4949, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5001, "s": 4984, "text": " Frahaan Hussain" }, { "code": null, "e": 5034, "s": 5001, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 5062, "s": 5034, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5096, "s": 5062, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 5124, "s": 5096, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5131, "s": 5124, "text": " Print" }, { "code": null, "e": 5142, "s": 5131, "text": " Add Notes" } ]
How to use both Tailwind CSS and Bootstrap 4 at the same time ?
24 Dec, 2021 In this article, we will know how to use Bootstrap with Tailwind CSS, at a moment, in the same code. We can use both the CSS frameworks together but it is not recommended. Because few classes will contradict with each other like “container”, “clearfix”, etc. As we know that Bootstrap is a known CSS framework. Although the Tailwind CSS framework can also be used parallelly in comparison to Bootstrap. Tailwind CSS is basically a utility-first CSS framework that facilitates rapidly building custom user interfaces. So, in the development field, it is more familiar with the Tailwind rather than Bootstrap. There are significant differences in the Tailwind CSS vs Bootstrap. Suppose there is a pre-build website where the old developers have used Bootstrap and the new developers want to use Tailwind. In that case, the new developer has to be careful with the used Bootstrap classes, where the classes should not contradict each other. We will be using the below CDN links in the code example in order to use the various applicable Bootstrap & Tailwind CSS classes, & utilize them on a single page. Bootstrap CDN Link: <link rel=”stylesheet” href=“ https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css”> <script src=“ https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script> <script src=“ https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js”></script> <script src=“ https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js”></script> Tailwind CSS CDN Link: <link href=“ https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css” rel=”stylesheet”> Example: In this example, we will use Bootstrap for content alignment, & for text and background color, we will use Tailwind CSS. So both the frameworks will applicable. HTML <!DOCTYPE html><html> <head> <!-- Bootstrap CDN Links --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"> </script> <!-- Tailwind CSS CDN Links --> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body> <!-- Bootstrap Class --> <div class="col"> <div class="col-md-4"> <!-- Tailwind CSS Class --> <p class="bg-purple-300 p-2"> <b class="text-green-700">GeeksforGeeks</b> <br>This example illustrates the use of Bootstrap and Tailwind side by side. </p> </div> </div></body> </html> Output: surindertarika1234 Bootstrap-Questions Picked Tailwind CSS-Questions CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2021" }, { "code": null, "e": 704, "s": 28, "text": "In this article, we will know how to use Bootstrap with Tailwind CSS, at a moment, in the same code. We can use both the CSS frameworks together but it is not recommended. Because few classes will contradict with each other like “container”, “clearfix”, etc. As we know that Bootstrap is a known CSS framework. Although the Tailwind CSS framework can also be used parallelly in comparison to Bootstrap. Tailwind CSS is basically a utility-first CSS framework that facilitates rapidly building custom user interfaces. So, in the development field, it is more familiar with the Tailwind rather than Bootstrap. There are significant differences in the Tailwind CSS vs Bootstrap." }, { "code": null, "e": 1129, "s": 704, "text": "Suppose there is a pre-build website where the old developers have used Bootstrap and the new developers want to use Tailwind. In that case, the new developer has to be careful with the used Bootstrap classes, where the classes should not contradict each other. We will be using the below CDN links in the code example in order to use the various applicable Bootstrap & Tailwind CSS classes, & utilize them on a single page." }, { "code": null, "e": 1149, "s": 1129, "text": "Bootstrap CDN Link:" }, { "code": null, "e": 1535, "s": 1149, "text": "<link rel=”stylesheet” href=“ https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css”> <script src=“ https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script> <script src=“ https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js”></script> <script src=“ https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js”></script> " }, { "code": null, "e": 1558, "s": 1535, "text": "Tailwind CSS CDN Link:" }, { "code": null, "e": 1648, "s": 1558, "text": "<link href=“ https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css” rel=”stylesheet”> " }, { "code": null, "e": 1818, "s": 1648, "text": "Example: In this example, we will use Bootstrap for content alignment, & for text and background color, we will use Tailwind CSS. So both the frameworks will applicable." }, { "code": null, "e": 1823, "s": 1818, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Bootstrap CDN Links --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js\"> </script> <!-- Tailwind CSS CDN Links --> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body> <!-- Bootstrap Class --> <div class=\"col\"> <div class=\"col-md-4\"> <!-- Tailwind CSS Class --> <p class=\"bg-purple-300 p-2\"> <b class=\"text-green-700\">GeeksforGeeks</b> <br>This example illustrates the use of Bootstrap and Tailwind side by side. </p> </div> </div></body> </html>", "e": 2846, "s": 1823, "text": null }, { "code": null, "e": 2855, "s": 2846, "text": " Output:" }, { "code": null, "e": 2874, "s": 2855, "text": "surindertarika1234" }, { "code": null, "e": 2894, "s": 2874, "text": "Bootstrap-Questions" }, { "code": null, "e": 2901, "s": 2894, "text": "Picked" }, { "code": null, "e": 2924, "s": 2901, "text": "Tailwind CSS-Questions" }, { "code": null, "e": 2928, "s": 2924, "text": "CSS" }, { "code": null, "e": 2933, "s": 2928, "text": "HTML" }, { "code": null, "e": 2950, "s": 2933, "text": "Web Technologies" }, { "code": null, "e": 2955, "s": 2950, "text": "HTML" } ]
Program for Area Of Square
21 Jun, 2022 A square is a flat shape, in one plane, defined by four points at the four corners. A square has four sides all of equal length, and four corners, all right angles (90 degree angles). A square is a kind of rectangle. Examples : Input : 4 Output :16 Input :8 Output :64 Formula C++ Java Python3 C# PHP Javascript // CPP program to find// the area of the square#include <iostream>using namespace std; int areaSquare(int side){ int area = side * side; return area;} // Driver Codeint main(){ int side = 4; cout << areaSquare(side); return 0;} // Java program to find// the area of the squareimport java.util.*; class GFG{ static int areaSquare(int side) { int area = side * side; return area; } // Driver Code public static void main(String[] args) { int side = 5; System.out.println(areaSquare(4)); }} # Python3 code to find# the area of the square def areaSquare( side ): area = side * side return area # Driver Codeside = 4print(areaSquare(side)) # This code is contributed# by "Sharad_Bhardwaj". // C# program to find// the area of the squareusing System; class GFG{ static int areaSquare(int side) { int area = side * side; return area; } // Driver code public static void Main() { int side = 4; Console.WriteLine(areaSquare(side)); }} // This code is contributed by vt_m <?php// PHP program to find// the area of the square function areaSquare($side){ $area = $side * $side; return $area;} // Driver Code$side = 4;echo(areaSquare($side)); // This code is contributed by Ajit.?> <script> // Javascript program to find// the area of the square function areaSquare(side){ let area = side * side; return area;} // Driver Code let side = 4; document.write(areaSquare(side)); // This code is contributed by Mayank Tyagi</script> Output : 16 Time complexity : O(1) Auxiliary Space : O(1) This article is contributed by Ajay Puri. 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.. Rajinikanth Maila jit_t mayanktyagi1709 surinderdawra388 ajaymakvana Inautix Geometric School Programming Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for distance between two points on earth Find if two rectangles overlap Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Check whether triangle is valid or not if sides are given Program for Point of Intersection of Two Lines Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jun, 2022" }, { "code": null, "e": 273, "s": 54, "text": "A square is a flat shape, in one plane, defined by four points at the four corners. A square has four sides all of equal length, and four corners, all right angles (90 degree angles). A square is a kind of rectangle. " }, { "code": null, "e": 286, "s": 273, "text": "Examples : " }, { "code": null, "e": 328, "s": 286, "text": "Input : 4\nOutput :16\n\nInput :8\nOutput :64" }, { "code": null, "e": 340, "s": 330, "text": "Formula " }, { "code": null, "e": 344, "s": 340, "text": "C++" }, { "code": null, "e": 349, "s": 344, "text": "Java" }, { "code": null, "e": 357, "s": 349, "text": "Python3" }, { "code": null, "e": 360, "s": 357, "text": "C#" }, { "code": null, "e": 364, "s": 360, "text": "PHP" }, { "code": null, "e": 375, "s": 364, "text": "Javascript" }, { "code": "// CPP program to find// the area of the square#include <iostream>using namespace std; int areaSquare(int side){ int area = side * side; return area;} // Driver Codeint main(){ int side = 4; cout << areaSquare(side); return 0;}", "e": 618, "s": 375, "text": null }, { "code": "// Java program to find// the area of the squareimport java.util.*; class GFG{ static int areaSquare(int side) { int area = side * side; return area; } // Driver Code public static void main(String[] args) { int side = 5; System.out.println(areaSquare(4)); }}", "e": 924, "s": 618, "text": null }, { "code": "# Python3 code to find# the area of the square def areaSquare( side ): area = side * side return area # Driver Codeside = 4print(areaSquare(side)) # This code is contributed# by \"Sharad_Bhardwaj\".", "e": 1127, "s": 924, "text": null }, { "code": "// C# program to find// the area of the squareusing System; class GFG{ static int areaSquare(int side) { int area = side * side; return area; } // Driver code public static void Main() { int side = 4; Console.WriteLine(areaSquare(side)); }} // This code is contributed by vt_m", "e": 1467, "s": 1127, "text": null }, { "code": "<?php// PHP program to find// the area of the square function areaSquare($side){ $area = $side * $side; return $area;} // Driver Code$side = 4;echo(areaSquare($side)); // This code is contributed by Ajit.?>", "e": 1680, "s": 1467, "text": null }, { "code": "<script> // Javascript program to find// the area of the square function areaSquare(side){ let area = side * side; return area;} // Driver Code let side = 4; document.write(areaSquare(side)); // This code is contributed by Mayank Tyagi</script>", "e": 1938, "s": 1680, "text": null }, { "code": null, "e": 1949, "s": 1938, "text": "Output : " }, { "code": null, "e": 1952, "s": 1949, "text": "16" }, { "code": null, "e": 1998, "s": 1952, "text": "Time complexity : O(1) Auxiliary Space : O(1)" }, { "code": null, "e": 2417, "s": 1998, "text": "This article is contributed by Ajay Puri. 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": 2435, "s": 2417, "text": "Rajinikanth Maila" }, { "code": null, "e": 2441, "s": 2435, "text": "jit_t" }, { "code": null, "e": 2457, "s": 2441, "text": "mayanktyagi1709" }, { "code": null, "e": 2474, "s": 2457, "text": "surinderdawra388" }, { "code": null, "e": 2486, "s": 2474, "text": "ajaymakvana" }, { "code": null, "e": 2494, "s": 2486, "text": "Inautix" }, { "code": null, "e": 2504, "s": 2494, "text": "Geometric" }, { "code": null, "e": 2523, "s": 2504, "text": "School Programming" }, { "code": null, "e": 2533, "s": 2523, "text": "Geometric" }, { "code": null, "e": 2631, "s": 2533, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2680, "s": 2631, "text": "Program for distance between two points on earth" }, { "code": null, "e": 2711, "s": 2680, "text": "Find if two rectangles overlap" }, { "code": null, "e": 2762, "s": 2711, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 2820, "s": 2762, "text": "Check whether triangle is valid or not if sides are given" }, { "code": null, "e": 2867, "s": 2820, "text": "Program for Point of Intersection of Two Lines" }, { "code": null, "e": 2885, "s": 2867, "text": "Python Dictionary" }, { "code": null, "e": 2910, "s": 2885, "text": "Reverse a string in Java" }, { "code": null, "e": 2926, "s": 2910, "text": "Arrays in C/C++" }, { "code": null, "e": 2949, "s": 2926, "text": "Introduction To PYTHON" } ]
Handling the Divide by Zero Exception in C++
23 Jan, 2019 We use Exception Handling to overcome exceptions occurred in execution of a program in a systematic manner. Dividing a number by Zero is a mathematical error (not defined) and we can use exception handling to gracefully overcome such operations. If you write a code without using exception handling then the output of division by zero will be shown as infinity which cannot be further processed. Consider the code given below, the Division function returns the result of numerator divided by denominator which is stored in the variable result in the main and then displayed. This Division function does not have any rumination for denominator being zero. // Program to show division without using// Exception Handling #include <iostream>using namespace std; // Defining function Divisionfloat Division(float num, float den){ // return the result of division return (num / den); } // end Division int main(){ // storing 12.5 in numerator // and 0 in denominator float numerator = 12.5; float denominator = 0; float result; // calls Division function result = Division(numerator, denominator); // display the value stored in result cout << "The quotient of 12.5/0 is " << result << endl; } // end main The quotient of 12.5/0 is inf We can handle this exception in a number of different ways, some of which are listed below 1) Using the runtime_error classThe runtime_error class is a derived class of Standard Library class exception, defined in exception header file for representing runtime errors.Now we consider the exact same code but included with handling the division by zero possibility. Here, we have the try block inside main that calls the Division function. The Division function checks if the denominator passed is equal to zero if no it returns the quotient, if yes it throws a runtime_error exception. This Exception is caught by the catch block which prints the message “Exception occurred” and then calls the what function with runtime_error object e. The what() function {used in the code given below} is a virtual function of the class Standard exception defined in stdexcept header file, it is used to identify the exception. This prints the message “Math error: Attempted to divide by Zero”, after which the program resumes the ordinary sequence of instructions.// Program to depict how to handle// divide by zero exception #include <iostream>#include <stdexcept> // To use runtime_errorusing namespace std; // Defining function Divisionfloat Division(float num, float den){ // If denominator is Zero // throw runtime_error if (den == 0) { throw runtime_error("Math error: Attempted to divide by Zero\n"); } // Otherwise return the result of division return (num / den); } // end Division int main(){ float numerator, denominator, result; numerator = 12.5; denominator = 0; // try block calls the Division function try { result = Division(numerator, denominator); // this will not print in this example cout << "The quotient is " << result << endl; } // catch block catches exception thrown // by the Division function catch (runtime_error& e) { // prints that exception has occurred // calls the what function // using runtime_error object cout << "Exception occurred" << endl << e.what(); } } // end mainOutput:Exception occurred Math error: Attempted to divide by Zero The runtime_error class is a derived class of Standard Library class exception, defined in exception header file for representing runtime errors.Now we consider the exact same code but included with handling the division by zero possibility. Here, we have the try block inside main that calls the Division function. The Division function checks if the denominator passed is equal to zero if no it returns the quotient, if yes it throws a runtime_error exception. This Exception is caught by the catch block which prints the message “Exception occurred” and then calls the what function with runtime_error object e. The what() function {used in the code given below} is a virtual function of the class Standard exception defined in stdexcept header file, it is used to identify the exception. This prints the message “Math error: Attempted to divide by Zero”, after which the program resumes the ordinary sequence of instructions. // Program to depict how to handle// divide by zero exception #include <iostream>#include <stdexcept> // To use runtime_errorusing namespace std; // Defining function Divisionfloat Division(float num, float den){ // If denominator is Zero // throw runtime_error if (den == 0) { throw runtime_error("Math error: Attempted to divide by Zero\n"); } // Otherwise return the result of division return (num / den); } // end Division int main(){ float numerator, denominator, result; numerator = 12.5; denominator = 0; // try block calls the Division function try { result = Division(numerator, denominator); // this will not print in this example cout << "The quotient is " << result << endl; } // catch block catches exception thrown // by the Division function catch (runtime_error& e) { // prints that exception has occurred // calls the what function // using runtime_error object cout << "Exception occurred" << endl << e.what(); } } // end main Exception occurred Math error: Attempted to divide by Zero 2) Using User defined exception handlingHere we define a class Exception that publicly inherits from runtime_error class. Inside the class Exception, we define only a constructor that will display the message “Math error: Attempted to divide by Zero” when called using the class object. We define the Division function that calls the constructor of class Exception when denominator is zero otherwise returns the quotient. Inside of main we give some values to numerator and denominator, 12.5 and 0 respectively. Then we come to the try block that calls the Division function which will either return the quotient or throw an exception. The catch block catches the exception of type Exception, displays the message “Exception occurred” and then calls the what function. After the exception is handled the program resumes.// Program to depict user defined exception handling #include <iostream>#include <stdexcept>// For using runtime_error using namespace std; // User defined class for handling exception// Class Exception publicly inherits// the runtime_error class class Exception : public runtime_error {public: // Defining constructor of class Exception // that passes a string message to the runtime_error class Exception() : runtime_error("Math error: Attempted to divide by Zero\n") { }}; // defining Division functionfloat Division(float num, float den){ // If denominator is Zero // throw user defined exception of type Exception if (den == 0) throw Exception(); // otherwise return the result of division return (num / den); } // end Division int main(){ float numerator, denominator, result; numerator = 12.5; denominator = 0; // try block calls the Division function try { result = Division(numerator, denominator); // this will not print in this example cout << "The quotient is " << result << endl; } // catch block catches exception if any // of type Exception catch (Exception& e) { // prints that exception has occurred // calls the what function using object of // the user defined class called Exception cout << "Exception occurred" << endl << e.what(); } } // end mainOutput:Exception occurred Math error: Attempted to divide by Zero Here we define a class Exception that publicly inherits from runtime_error class. Inside the class Exception, we define only a constructor that will display the message “Math error: Attempted to divide by Zero” when called using the class object. We define the Division function that calls the constructor of class Exception when denominator is zero otherwise returns the quotient. Inside of main we give some values to numerator and denominator, 12.5 and 0 respectively. Then we come to the try block that calls the Division function which will either return the quotient or throw an exception. The catch block catches the exception of type Exception, displays the message “Exception occurred” and then calls the what function. After the exception is handled the program resumes. // Program to depict user defined exception handling #include <iostream>#include <stdexcept>// For using runtime_error using namespace std; // User defined class for handling exception// Class Exception publicly inherits// the runtime_error class class Exception : public runtime_error {public: // Defining constructor of class Exception // that passes a string message to the runtime_error class Exception() : runtime_error("Math error: Attempted to divide by Zero\n") { }}; // defining Division functionfloat Division(float num, float den){ // If denominator is Zero // throw user defined exception of type Exception if (den == 0) throw Exception(); // otherwise return the result of division return (num / den); } // end Division int main(){ float numerator, denominator, result; numerator = 12.5; denominator = 0; // try block calls the Division function try { result = Division(numerator, denominator); // this will not print in this example cout << "The quotient is " << result << endl; } // catch block catches exception if any // of type Exception catch (Exception& e) { // prints that exception has occurred // calls the what function using object of // the user defined class called Exception cout << "Exception occurred" << endl << e.what(); } } // end main Exception occurred Math error: Attempted to divide by Zero 3) Using Stack UnwindingIn stack unwinding we have the main inside which the try block calls the Division function which in turn calls the CheckDenominator function. The CheckDenominator function checks if denominator is zero, if true throws an exception otherwise returns the value of denominator. The Division function calculates the value of quotient {if non-zero value of denominator was passed} and returns the same to the main. The catch block catches any exception thrown and displays the message “Exception occurred” and calls the what function which prints “Math error: Attempted to divide by zero”. After this the program resumes.// Program to depict Exception Handling// Using stack unwinding #include <iostream>#include <stdexcept>using namespace std; // defining the CheckDenominator functionfloat CheckDenominator(float den){ // if denominator is zero // throw exception if (den == 0) { throw runtime_error("Math error: Attempted to divide by zero\n"); } else return den;} // end CheckDenominator // defining Division functionfloat Division(float num, float den){ // Division function calls CheckDenominator return (num / CheckDenominator(den)); } // end Division int main(){ float numerator, denominator, result; numerator = 12.5; denominator = 0; // try block calls the Division function try { result = Division(numerator, denominator); // This will not print in this example cout << "The quotient is " << result << endl; } // catch block catches exception if any catch (runtime_error& e) { // prints that exception has occurred // calls the what function using object of // runtime_error class cout << "Exception occurred" << endl << e.what(); }} // end mainOutput:Exception occurred Math error: Attempted to divide by zero In stack unwinding we have the main inside which the try block calls the Division function which in turn calls the CheckDenominator function. The CheckDenominator function checks if denominator is zero, if true throws an exception otherwise returns the value of denominator. The Division function calculates the value of quotient {if non-zero value of denominator was passed} and returns the same to the main. The catch block catches any exception thrown and displays the message “Exception occurred” and calls the what function which prints “Math error: Attempted to divide by zero”. After this the program resumes. // Program to depict Exception Handling// Using stack unwinding #include <iostream>#include <stdexcept>using namespace std; // defining the CheckDenominator functionfloat CheckDenominator(float den){ // if denominator is zero // throw exception if (den == 0) { throw runtime_error("Math error: Attempted to divide by zero\n"); } else return den;} // end CheckDenominator // defining Division functionfloat Division(float num, float den){ // Division function calls CheckDenominator return (num / CheckDenominator(den)); } // end Division int main(){ float numerator, denominator, result; numerator = 12.5; denominator = 0; // try block calls the Division function try { result = Division(numerator, denominator); // This will not print in this example cout << "The quotient is " << result << endl; } // catch block catches exception if any catch (runtime_error& e) { // prints that exception has occurred // calls the what function using object of // runtime_error class cout << "Exception occurred" << endl << e.what(); }} // end main Exception occurred Math error: Attempted to divide by zero 4) Using try and catch(...)In this code the try block calls the CheckDenominator function. In CheckDenominator function we check if denominator is zero, if true throw an exception by passing a string “Error”. This string is caught by the catch block and therefore prints the message “Exception occurred”. The catch block here is capable of catching exception of any type.// Program to depict use of try catch block #include <iostream>#include <stdexcept>using namespace std; // defining CheckDenominatorfloat CheckDenominator(float den){ if (den == 0) throw "Error"; else return den;} // end CheckDenominator int main(){ float numerator, denominator, result; numerator = 12.5; denominator = 0; // try block try { // calls the CheckDenominator function // by passing a string "Error" if (CheckDenominator(denominator)) { result = (numerator / denominator); cout << "The quotient is " << result << endl; } } // catch block // capable of catching any type of exception catch (...) { // Display a that exception has occurred cout << "Exception occurred" << endl; } } // end mainOutput:Exception occurred In this code the try block calls the CheckDenominator function. In CheckDenominator function we check if denominator is zero, if true throw an exception by passing a string “Error”. This string is caught by the catch block and therefore prints the message “Exception occurred”. The catch block here is capable of catching exception of any type. // Program to depict use of try catch block #include <iostream>#include <stdexcept>using namespace std; // defining CheckDenominatorfloat CheckDenominator(float den){ if (den == 0) throw "Error"; else return den;} // end CheckDenominator int main(){ float numerator, denominator, result; numerator = 12.5; denominator = 0; // try block try { // calls the CheckDenominator function // by passing a string "Error" if (CheckDenominator(denominator)) { result = (numerator / denominator); cout << "The quotient is " << result << endl; } } // catch block // capable of catching any type of exception catch (...) { // Display a that exception has occurred cout << "Exception occurred" << endl; } } // end main Exception occurred cpp-exception C++ Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jan, 2019" }, { "code": null, "e": 160, "s": 52, "text": "We use Exception Handling to overcome exceptions occurred in execution of a program in a systematic manner." }, { "code": null, "e": 448, "s": 160, "text": "Dividing a number by Zero is a mathematical error (not defined) and we can use exception handling to gracefully overcome such operations. If you write a code without using exception handling then the output of division by zero will be shown as infinity which cannot be further processed." }, { "code": null, "e": 707, "s": 448, "text": "Consider the code given below, the Division function returns the result of numerator divided by denominator which is stored in the variable result in the main and then displayed. This Division function does not have any rumination for denominator being zero." }, { "code": "// Program to show division without using// Exception Handling #include <iostream>using namespace std; // Defining function Divisionfloat Division(float num, float den){ // return the result of division return (num / den); } // end Division int main(){ // storing 12.5 in numerator // and 0 in denominator float numerator = 12.5; float denominator = 0; float result; // calls Division function result = Division(numerator, denominator); // display the value stored in result cout << \"The quotient of 12.5/0 is \" << result << endl; } // end main", "e": 1302, "s": 707, "text": null }, { "code": null, "e": 1333, "s": 1302, "text": "The quotient of 12.5/0 is inf\n" }, { "code": null, "e": 1424, "s": 1333, "text": "We can handle this exception in a number of different ways, some of which are listed below" }, { "code": null, "e": 3539, "s": 1424, "text": "1) Using the runtime_error classThe runtime_error class is a derived class of Standard Library class exception, defined in exception header file for representing runtime errors.Now we consider the exact same code but included with handling the division by zero possibility. Here, we have the try block inside main that calls the Division function. The Division function checks if the denominator passed is equal to zero if no it returns the quotient, if yes it throws a runtime_error exception. This Exception is caught by the catch block which prints the message “Exception occurred” and then calls the what function with runtime_error object e. The what() function {used in the code given below} is a virtual function of the class Standard exception defined in stdexcept header file, it is used to identify the exception. This prints the message “Math error: Attempted to divide by Zero”, after which the program resumes the ordinary sequence of instructions.// Program to depict how to handle// divide by zero exception #include <iostream>#include <stdexcept> // To use runtime_errorusing namespace std; // Defining function Divisionfloat Division(float num, float den){ // If denominator is Zero // throw runtime_error if (den == 0) { throw runtime_error(\"Math error: Attempted to divide by Zero\\n\"); } // Otherwise return the result of division return (num / den); } // end Division int main(){ float numerator, denominator, result; numerator = 12.5; denominator = 0; // try block calls the Division function try { result = Division(numerator, denominator); // this will not print in this example cout << \"The quotient is \" << result << endl; } // catch block catches exception thrown // by the Division function catch (runtime_error& e) { // prints that exception has occurred // calls the what function // using runtime_error object cout << \"Exception occurred\" << endl << e.what(); } } // end mainOutput:Exception occurred\nMath error: Attempted to divide by Zero\n" }, { "code": null, "e": 4469, "s": 3539, "text": "The runtime_error class is a derived class of Standard Library class exception, defined in exception header file for representing runtime errors.Now we consider the exact same code but included with handling the division by zero possibility. Here, we have the try block inside main that calls the Division function. The Division function checks if the denominator passed is equal to zero if no it returns the quotient, if yes it throws a runtime_error exception. This Exception is caught by the catch block which prints the message “Exception occurred” and then calls the what function with runtime_error object e. The what() function {used in the code given below} is a virtual function of the class Standard exception defined in stdexcept header file, it is used to identify the exception. This prints the message “Math error: Attempted to divide by Zero”, after which the program resumes the ordinary sequence of instructions." }, { "code": "// Program to depict how to handle// divide by zero exception #include <iostream>#include <stdexcept> // To use runtime_errorusing namespace std; // Defining function Divisionfloat Division(float num, float den){ // If denominator is Zero // throw runtime_error if (den == 0) { throw runtime_error(\"Math error: Attempted to divide by Zero\\n\"); } // Otherwise return the result of division return (num / den); } // end Division int main(){ float numerator, denominator, result; numerator = 12.5; denominator = 0; // try block calls the Division function try { result = Division(numerator, denominator); // this will not print in this example cout << \"The quotient is \" << result << endl; } // catch block catches exception thrown // by the Division function catch (runtime_error& e) { // prints that exception has occurred // calls the what function // using runtime_error object cout << \"Exception occurred\" << endl << e.what(); } } // end main", "e": 5557, "s": 4469, "text": null }, { "code": null, "e": 5617, "s": 5557, "text": "Exception occurred\nMath error: Attempted to divide by Zero\n" }, { "code": null, "e": 7927, "s": 5617, "text": "2) Using User defined exception handlingHere we define a class Exception that publicly inherits from runtime_error class. Inside the class Exception, we define only a constructor that will display the message “Math error: Attempted to divide by Zero” when called using the class object. We define the Division function that calls the constructor of class Exception when denominator is zero otherwise returns the quotient. Inside of main we give some values to numerator and denominator, 12.5 and 0 respectively. Then we come to the try block that calls the Division function which will either return the quotient or throw an exception. The catch block catches the exception of type Exception, displays the message “Exception occurred” and then calls the what function. After the exception is handled the program resumes.// Program to depict user defined exception handling #include <iostream>#include <stdexcept>// For using runtime_error using namespace std; // User defined class for handling exception// Class Exception publicly inherits// the runtime_error class class Exception : public runtime_error {public: // Defining constructor of class Exception // that passes a string message to the runtime_error class Exception() : runtime_error(\"Math error: Attempted to divide by Zero\\n\") { }}; // defining Division functionfloat Division(float num, float den){ // If denominator is Zero // throw user defined exception of type Exception if (den == 0) throw Exception(); // otherwise return the result of division return (num / den); } // end Division int main(){ float numerator, denominator, result; numerator = 12.5; denominator = 0; // try block calls the Division function try { result = Division(numerator, denominator); // this will not print in this example cout << \"The quotient is \" << result << endl; } // catch block catches exception if any // of type Exception catch (Exception& e) { // prints that exception has occurred // calls the what function using object of // the user defined class called Exception cout << \"Exception occurred\" << endl << e.what(); } } // end mainOutput:Exception occurred\nMath error: Attempted to divide by Zero\n" }, { "code": null, "e": 8708, "s": 7927, "text": "Here we define a class Exception that publicly inherits from runtime_error class. Inside the class Exception, we define only a constructor that will display the message “Math error: Attempted to divide by Zero” when called using the class object. We define the Division function that calls the constructor of class Exception when denominator is zero otherwise returns the quotient. Inside of main we give some values to numerator and denominator, 12.5 and 0 respectively. Then we come to the try block that calls the Division function which will either return the quotient or throw an exception. The catch block catches the exception of type Exception, displays the message “Exception occurred” and then calls the what function. After the exception is handled the program resumes." }, { "code": "// Program to depict user defined exception handling #include <iostream>#include <stdexcept>// For using runtime_error using namespace std; // User defined class for handling exception// Class Exception publicly inherits// the runtime_error class class Exception : public runtime_error {public: // Defining constructor of class Exception // that passes a string message to the runtime_error class Exception() : runtime_error(\"Math error: Attempted to divide by Zero\\n\") { }}; // defining Division functionfloat Division(float num, float den){ // If denominator is Zero // throw user defined exception of type Exception if (den == 0) throw Exception(); // otherwise return the result of division return (num / den); } // end Division int main(){ float numerator, denominator, result; numerator = 12.5; denominator = 0; // try block calls the Division function try { result = Division(numerator, denominator); // this will not print in this example cout << \"The quotient is \" << result << endl; } // catch block catches exception if any // of type Exception catch (Exception& e) { // prints that exception has occurred // calls the what function using object of // the user defined class called Exception cout << \"Exception occurred\" << endl << e.what(); } } // end main", "e": 10132, "s": 8708, "text": null }, { "code": null, "e": 10192, "s": 10132, "text": "Exception occurred\nMath error: Attempted to divide by Zero\n" }, { "code": null, "e": 12084, "s": 10192, "text": "3) Using Stack UnwindingIn stack unwinding we have the main inside which the try block calls the Division function which in turn calls the CheckDenominator function. The CheckDenominator function checks if denominator is zero, if true throws an exception otherwise returns the value of denominator. The Division function calculates the value of quotient {if non-zero value of denominator was passed} and returns the same to the main. The catch block catches any exception thrown and displays the message “Exception occurred” and calls the what function which prints “Math error: Attempted to divide by zero”. After this the program resumes.// Program to depict Exception Handling// Using stack unwinding #include <iostream>#include <stdexcept>using namespace std; // defining the CheckDenominator functionfloat CheckDenominator(float den){ // if denominator is zero // throw exception if (den == 0) { throw runtime_error(\"Math error: Attempted to divide by zero\\n\"); } else return den;} // end CheckDenominator // defining Division functionfloat Division(float num, float den){ // Division function calls CheckDenominator return (num / CheckDenominator(den)); } // end Division int main(){ float numerator, denominator, result; numerator = 12.5; denominator = 0; // try block calls the Division function try { result = Division(numerator, denominator); // This will not print in this example cout << \"The quotient is \" << result << endl; } // catch block catches exception if any catch (runtime_error& e) { // prints that exception has occurred // calls the what function using object of // runtime_error class cout << \"Exception occurred\" << endl << e.what(); }} // end mainOutput:Exception occurred\nMath error: Attempted to divide by zero\n" }, { "code": null, "e": 12701, "s": 12084, "text": "In stack unwinding we have the main inside which the try block calls the Division function which in turn calls the CheckDenominator function. The CheckDenominator function checks if denominator is zero, if true throws an exception otherwise returns the value of denominator. The Division function calculates the value of quotient {if non-zero value of denominator was passed} and returns the same to the main. The catch block catches any exception thrown and displays the message “Exception occurred” and calls the what function which prints “Math error: Attempted to divide by zero”. After this the program resumes." }, { "code": "// Program to depict Exception Handling// Using stack unwinding #include <iostream>#include <stdexcept>using namespace std; // defining the CheckDenominator functionfloat CheckDenominator(float den){ // if denominator is zero // throw exception if (den == 0) { throw runtime_error(\"Math error: Attempted to divide by zero\\n\"); } else return den;} // end CheckDenominator // defining Division functionfloat Division(float num, float den){ // Division function calls CheckDenominator return (num / CheckDenominator(den)); } // end Division int main(){ float numerator, denominator, result; numerator = 12.5; denominator = 0; // try block calls the Division function try { result = Division(numerator, denominator); // This will not print in this example cout << \"The quotient is \" << result << endl; } // catch block catches exception if any catch (runtime_error& e) { // prints that exception has occurred // calls the what function using object of // runtime_error class cout << \"Exception occurred\" << endl << e.what(); }} // end main", "e": 13887, "s": 12701, "text": null }, { "code": null, "e": 13947, "s": 13887, "text": "Exception occurred\nMath error: Attempted to divide by zero\n" }, { "code": null, "e": 15192, "s": 13947, "text": "4) Using try and catch(...)In this code the try block calls the CheckDenominator function. In CheckDenominator function we check if denominator is zero, if true throw an exception by passing a string “Error”. This string is caught by the catch block and therefore prints the message “Exception occurred”. The catch block here is capable of catching exception of any type.// Program to depict use of try catch block #include <iostream>#include <stdexcept>using namespace std; // defining CheckDenominatorfloat CheckDenominator(float den){ if (den == 0) throw \"Error\"; else return den;} // end CheckDenominator int main(){ float numerator, denominator, result; numerator = 12.5; denominator = 0; // try block try { // calls the CheckDenominator function // by passing a string \"Error\" if (CheckDenominator(denominator)) { result = (numerator / denominator); cout << \"The quotient is \" << result << endl; } } // catch block // capable of catching any type of exception catch (...) { // Display a that exception has occurred cout << \"Exception occurred\" << endl; } } // end mainOutput:Exception occurred\n" }, { "code": null, "e": 15537, "s": 15192, "text": "In this code the try block calls the CheckDenominator function. In CheckDenominator function we check if denominator is zero, if true throw an exception by passing a string “Error”. This string is caught by the catch block and therefore prints the message “Exception occurred”. The catch block here is capable of catching exception of any type." }, { "code": "// Program to depict use of try catch block #include <iostream>#include <stdexcept>using namespace std; // defining CheckDenominatorfloat CheckDenominator(float den){ if (den == 0) throw \"Error\"; else return den;} // end CheckDenominator int main(){ float numerator, denominator, result; numerator = 12.5; denominator = 0; // try block try { // calls the CheckDenominator function // by passing a string \"Error\" if (CheckDenominator(denominator)) { result = (numerator / denominator); cout << \"The quotient is \" << result << endl; } } // catch block // capable of catching any type of exception catch (...) { // Display a that exception has occurred cout << \"Exception occurred\" << endl; } } // end main", "e": 16385, "s": 15537, "text": null }, { "code": null, "e": 16405, "s": 16385, "text": "Exception occurred\n" }, { "code": null, "e": 16419, "s": 16405, "text": "cpp-exception" }, { "code": null, "e": 16432, "s": 16419, "text": "C++ Programs" } ]
Python String – removesuffix()
01 Nov, 2020 If the string ends with the suffix and the suffix is not empty, the str.removesuffix(suffix, /) function removes the suffix and returns the rest of the string. If the suffix string is not found then it returns the original string. It is introduced in Python 3.9.0 version. Syntax: str.removesuffix(suffix, /) Parameters: Suffix– suffix string that we are checking for. Return value: Returns: string[ : – len (suffix) ] if the string ends with suffix string and that suffix is not empty. Else it returns the copy of original string. Example 1: Python3 # Python 3.9 code explaining# str.removesuffix() # suffix existsprint('ComputerScience'.removesuffix('Science')) # suffix doesn't existprint('GeeksforGeeks'.removesuffix('for')) Output: Computer GeeksforGeeks Example 2: Python3 # Python 3.9 code explaining# str.removesuffix() # String for removesuffix()# If suffix exists then# then it remove suffix from the string# otherwise return original string string1 = "Welcome to python 3.9"print("Original String 1 : ", string1) # suffix existsresult = string1.removesuffix("3.9")print("New string : ", result) string2 = "Welcome Geek"print("Original String 2 : ", string2) # suffix doesn't existresult = string2.removesuffix("Welcome")print("New string : ", result) Output: Original String 1 : Welcome to python 3.9 New string : Welcome to python Original String 2 : Welcome Geek New string : Welcome Geek python-string Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Nov, 2020" }, { "code": null, "e": 301, "s": 28, "text": "If the string ends with the suffix and the suffix is not empty, the str.removesuffix(suffix, /) function removes the suffix and returns the rest of the string. If the suffix string is not found then it returns the original string. It is introduced in Python 3.9.0 version." }, { "code": null, "e": 337, "s": 301, "text": "Syntax: str.removesuffix(suffix, /)" }, { "code": null, "e": 349, "s": 337, "text": "Parameters:" }, { "code": null, "e": 397, "s": 349, "text": "Suffix– suffix string that we are checking for." }, { "code": null, "e": 411, "s": 397, "text": "Return value:" }, { "code": null, "e": 560, "s": 411, "text": "Returns: string[ : – len (suffix) ] if the string ends with suffix string and that suffix is not empty. Else it returns the copy of original string." }, { "code": null, "e": 571, "s": 560, "text": "Example 1:" }, { "code": null, "e": 579, "s": 571, "text": "Python3" }, { "code": "# Python 3.9 code explaining# str.removesuffix() # suffix existsprint('ComputerScience'.removesuffix('Science')) # suffix doesn't existprint('GeeksforGeeks'.removesuffix('for'))", "e": 759, "s": 579, "text": null }, { "code": null, "e": 767, "s": 759, "text": "Output:" }, { "code": null, "e": 791, "s": 767, "text": "Computer\nGeeksforGeeks\n" }, { "code": null, "e": 802, "s": 791, "text": "Example 2:" }, { "code": null, "e": 810, "s": 802, "text": "Python3" }, { "code": "# Python 3.9 code explaining# str.removesuffix() # String for removesuffix()# If suffix exists then# then it remove suffix from the string# otherwise return original string string1 = \"Welcome to python 3.9\"print(\"Original String 1 : \", string1) # suffix existsresult = string1.removesuffix(\"3.9\")print(\"New string : \", result) string2 = \"Welcome Geek\"print(\"Original String 2 : \", string2) # suffix doesn't existresult = string2.removesuffix(\"Welcome\")print(\"New string : \", result)", "e": 1298, "s": 810, "text": null }, { "code": null, "e": 1306, "s": 1298, "text": "Output:" }, { "code": null, "e": 1444, "s": 1306, "text": "Original String 1 : Welcome to python 3.9\nNew string : Welcome to python \nOriginal String 2 : Welcome Geek\nNew string : Welcome Geek\n" }, { "code": null, "e": 1458, "s": 1444, "text": "python-string" }, { "code": null, "e": 1482, "s": 1458, "text": "Technical Scripter 2020" }, { "code": null, "e": 1489, "s": 1482, "text": "Python" }, { "code": null, "e": 1508, "s": 1489, "text": "Technical Scripter" } ]
PHP | array_count_values() Function
09 Aug, 2019 The array_count_values() is an inbuilt function in PHP which is used to count all the values inside an array. In other words we can say that array_count_values() function is used to calculate the frequency of all of the elements of an array. Syntax: array array_count_values( $array ) Parameters: This function accepts single parameter $array. This parameter is the array for which we need to calculate the count of values present in it. Return Value: This function returns an associative array with key-value pairs in which keys are the elements of the array passed as parameter and values are the frequency of these elements in an array. Note: If the element is not a string or integer then an E_WARNING is thrown. Examples: Input : array = ("Geeks", "for", "Geeks", "Geeks", "Welcome", "for") Output : Array ( [Geeks] => 3 [for] => 2 [Welcome] => 1 ) Input : array = (1, 1, 2, 3 , 1 , 2 , 4, 5) Output : Array ( [1] => 3 [2] => 2 [3] => 1 [4] => 1 [5] => 1 ) Below program illustrates the working of array_count_values() function in PHP: <?php // PHP code to illustrate the working// of array_count_values() functionfunction Counting($array){ return(array_count_values($array));} // Driver Code$array = array("Geeks", "for", "Geeks", "Geeks", "Welcome", "for");print_r(Counting($array)); ?> Output: Array ( [Geeks] => 3 [for] => 2 [Welcome] => 1 ) Reference: http://php.net/manual/en/function.array-count-values.php PHP-array PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Aug, 2019" }, { "code": null, "e": 270, "s": 28, "text": "The array_count_values() is an inbuilt function in PHP which is used to count all the values inside an array. In other words we can say that array_count_values() function is used to calculate the frequency of all of the elements of an array." }, { "code": null, "e": 278, "s": 270, "text": "Syntax:" }, { "code": null, "e": 314, "s": 278, "text": "array array_count_values( $array )\n" }, { "code": null, "e": 467, "s": 314, "text": "Parameters: This function accepts single parameter $array. This parameter is the array for which we need to calculate the count of values present in it." }, { "code": null, "e": 669, "s": 467, "text": "Return Value: This function returns an associative array with key-value pairs in which keys are the elements of the array passed as parameter and values are the frequency of these elements in an array." }, { "code": null, "e": 746, "s": 669, "text": "Note: If the element is not a string or integer then an E_WARNING is thrown." }, { "code": null, "e": 756, "s": 746, "text": "Examples:" }, { "code": null, "e": 1115, "s": 756, "text": "Input : array = (\"Geeks\", \"for\", \"Geeks\", \"Geeks\", \"Welcome\", \"for\")\nOutput : \n Array\n (\n [Geeks] => 3\n [for] => 2\n [Welcome] => 1\n )\n\nInput : array = (1, 1, 2, 3 , 1 , 2 , 4, 5)\nOutput :\n Array\n (\n [1] => 3\n [2] => 2\n [3] => 1\n [4] => 1\n [5] => 1\n ) \n" }, { "code": null, "e": 1194, "s": 1115, "text": "Below program illustrates the working of array_count_values() function in PHP:" }, { "code": "<?php // PHP code to illustrate the working// of array_count_values() functionfunction Counting($array){ return(array_count_values($array));} // Driver Code$array = array(\"Geeks\", \"for\", \"Geeks\", \"Geeks\", \"Welcome\", \"for\");print_r(Counting($array)); ?>", "e": 1453, "s": 1194, "text": null }, { "code": null, "e": 1461, "s": 1453, "text": "Output:" }, { "code": null, "e": 1523, "s": 1461, "text": "Array\n(\n [Geeks] => 3\n [for] => 2\n [Welcome] => 1\n)\n" }, { "code": null, "e": 1591, "s": 1523, "text": "Reference: http://php.net/manual/en/function.array-count-values.php" }, { "code": null, "e": 1601, "s": 1591, "text": "PHP-array" }, { "code": null, "e": 1614, "s": 1601, "text": "PHP-function" }, { "code": null, "e": 1618, "s": 1614, "text": "PHP" }, { "code": null, "e": 1635, "s": 1618, "text": "Web Technologies" }, { "code": null, "e": 1639, "s": 1635, "text": "PHP" } ]
Java Math max() method with Examples
16 Apr, 2018 The Java.lang.math.max() function is an inbuilt function in Java which returns maximum of two numbers. The arguments are taken in int, double, float and long.If a negative and a positive number is passed as argument then the positive result is generated. And if both parameters passed are negative then the number with the lower magnitude is generated as result. Syntax: dataType max(dataType num1, dataType num2) The datatypes can be int, float, double or long. Parameters : The function accepts two parameters num1 and num2 among which the maximum is returned Return value:The function returns maximum of two numbers. The datatype will be the same as that of the arguments. Given below are the examples of the function max() // Java program to demonstrate the use of max() function// when two double data-type numbers are// passed as argumentspublic class Gfg { public static void main(String args[]) { double a = 12.123; double b = 12.456; // prints the maximum of two numbers System.out.println(Math.max(a, b)); }} Output: 12.456 // Java program to demonstrate the use of max() function// when one positive and one negative// integers are passed as argumentpublic class Gfg { public static void main(String args[]) { int a = 23; int b = -23; // prints the maximum of two numbers System.out.println(Math.max(a, b)); }} Output: 23 // Java program to demonstrate the use of max() function// when two negative integers are passed as argument.public class Gfg { public static void main(String args[]) { int a = -25; int b = -23; // prints the maximum of two numbers System.out.println(Math.max(a, b)); }} Output: -23 Java-lang package java-math Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Apr, 2018" }, { "code": null, "e": 416, "s": 53, "text": "The Java.lang.math.max() function is an inbuilt function in Java which returns maximum of two numbers. The arguments are taken in int, double, float and long.If a negative and a positive number is passed as argument then the positive result is generated. And if both parameters passed are negative then the number with the lower magnitude is generated as result." }, { "code": null, "e": 424, "s": 416, "text": "Syntax:" }, { "code": null, "e": 618, "s": 424, "text": "dataType max(dataType num1, dataType num2)\nThe datatypes can be int, float, double or long.\n\nParameters : The function accepts two parameters num1 and num2 \namong which the maximum is returned\n" }, { "code": null, "e": 732, "s": 618, "text": "Return value:The function returns maximum of two numbers. The datatype will be the same as that of the arguments." }, { "code": null, "e": 783, "s": 732, "text": "Given below are the examples of the function max()" }, { "code": "// Java program to demonstrate the use of max() function// when two double data-type numbers are// passed as argumentspublic class Gfg { public static void main(String args[]) { double a = 12.123; double b = 12.456; // prints the maximum of two numbers System.out.println(Math.max(a, b)); }}", "e": 1116, "s": 783, "text": null }, { "code": null, "e": 1124, "s": 1116, "text": "Output:" }, { "code": null, "e": 1132, "s": 1124, "text": "12.456\n" }, { "code": "// Java program to demonstrate the use of max() function// when one positive and one negative// integers are passed as argumentpublic class Gfg { public static void main(String args[]) { int a = 23; int b = -23; // prints the maximum of two numbers System.out.println(Math.max(a, b)); }}", "e": 1461, "s": 1132, "text": null }, { "code": null, "e": 1469, "s": 1461, "text": "Output:" }, { "code": null, "e": 1473, "s": 1469, "text": "23\n" }, { "code": "// Java program to demonstrate the use of max() function// when two negative integers are passed as argument.public class Gfg { public static void main(String args[]) { int a = -25; int b = -23; // prints the maximum of two numbers System.out.println(Math.max(a, b)); }}", "e": 1785, "s": 1473, "text": null }, { "code": null, "e": 1793, "s": 1785, "text": "Output:" }, { "code": null, "e": 1798, "s": 1793, "text": "-23\n" }, { "code": null, "e": 1816, "s": 1798, "text": "Java-lang package" }, { "code": null, "e": 1826, "s": 1816, "text": "java-math" }, { "code": null, "e": 1831, "s": 1826, "text": "Java" }, { "code": null, "e": 1836, "s": 1831, "text": "Java" } ]
Python | Pandas Index.is_unique
20 Feb, 2019 Pandas Index is an immutable ndarray implementing an ordered, sliceable set. It is the basic object which stores the axis labels for all pandas objects. Pandas Index.is_unique attribute return True if the underlying data in the given Index object is unique else it return False. Syntax: Index.is_unique Parameter : None Returns : boolean Example #1: Use Index.is_unique attribute to find out if the underlying data in the given Index object is unique or not. # importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Melbourne', 'Sanghai', 'Lisbon', 'Doha', 'Moscow']) # Print the indexprint(idx) Output : Now we will use Index.is_unique attribute to find out if the underlying data in the given Index object is unique or not. # check if the values in the Index# is unique or not.result = idx.is_unique # Print the resultprint(result) Output : As we can see in the output, the Index.is_unique attribute has returned True indicating that the underlying data of the given Index object is unique. Example #2 : Use Index.is_unique attribute to find out if the underlying data in the given Index object is unique or not. # importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index([900, 700, 620, 388, 900]) # Print the indexprint(idx) Output : Now we will use Index.is_unique attribute to find out if the underlying data in the given Index object is unique or not. # check if the values in the Index# is unique or not.result = idx.is_unique # Print the resultprint(result) Output :As we can see in the output, the Index.is_unique attribute has returned False indicating that the underlying data of the given Index object is not unique. Python pandas-indexing Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Feb, 2019" }, { "code": null, "e": 181, "s": 28, "text": "Pandas Index is an immutable ndarray implementing an ordered, sliceable set. It is the basic object which stores the axis labels for all pandas objects." }, { "code": null, "e": 307, "s": 181, "text": "Pandas Index.is_unique attribute return True if the underlying data in the given Index object is unique else it return False." }, { "code": null, "e": 331, "s": 307, "text": "Syntax: Index.is_unique" }, { "code": null, "e": 348, "s": 331, "text": "Parameter : None" }, { "code": null, "e": 366, "s": 348, "text": "Returns : boolean" }, { "code": null, "e": 487, "s": 366, "text": "Example #1: Use Index.is_unique attribute to find out if the underlying data in the given Index object is unique or not." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Melbourne', 'Sanghai', 'Lisbon', 'Doha', 'Moscow']) # Print the indexprint(idx)", "e": 650, "s": 487, "text": null }, { "code": null, "e": 659, "s": 650, "text": "Output :" }, { "code": null, "e": 780, "s": 659, "text": "Now we will use Index.is_unique attribute to find out if the underlying data in the given Index object is unique or not." }, { "code": "# check if the values in the Index# is unique or not.result = idx.is_unique # Print the resultprint(result)", "e": 889, "s": 780, "text": null }, { "code": null, "e": 898, "s": 889, "text": "Output :" }, { "code": null, "e": 1170, "s": 898, "text": "As we can see in the output, the Index.is_unique attribute has returned True indicating that the underlying data of the given Index object is unique. Example #2 : Use Index.is_unique attribute to find out if the underlying data in the given Index object is unique or not." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index([900, 700, 620, 388, 900]) # Print the indexprint(idx)", "e": 1306, "s": 1170, "text": null }, { "code": null, "e": 1315, "s": 1306, "text": "Output :" }, { "code": null, "e": 1436, "s": 1315, "text": "Now we will use Index.is_unique attribute to find out if the underlying data in the given Index object is unique or not." }, { "code": "# check if the values in the Index# is unique or not.result = idx.is_unique # Print the resultprint(result)", "e": 1545, "s": 1436, "text": null }, { "code": null, "e": 1708, "s": 1545, "text": "Output :As we can see in the output, the Index.is_unique attribute has returned False indicating that the underlying data of the given Index object is not unique." }, { "code": null, "e": 1731, "s": 1708, "text": "Python pandas-indexing" }, { "code": null, "e": 1745, "s": 1731, "text": "Python-pandas" }, { "code": null, "e": 1752, "s": 1745, "text": "Python" } ]
Scala List contains() method with example
26 Jul, 2019 The contains() method is utilized to check whether a certain element is present in the list or not. Method Definition: def contains(elem: Any): Boolean Return Type: It returns true if the element present in the contains method as argument is also present in the stated list else it returns false. Example #1: // Scala program of contains()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 3, 5, 2) // Applying contains method val res = m1.contains(1) // Displays output println(res) }} true Example #2: // Scala program of contains()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 3, 5, 2) // Applying contains method val res = m1.contains(7) // Displays output println(res) }} false Scala Scala-list Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jul, 2019" }, { "code": null, "e": 128, "s": 28, "text": "The contains() method is utilized to check whether a certain element is present in the list or not." }, { "code": null, "e": 180, "s": 128, "text": "Method Definition: def contains(elem: Any): Boolean" }, { "code": null, "e": 325, "s": 180, "text": "Return Type: It returns true if the element present in the contains method as argument is also present in the stated list else it returns false." }, { "code": null, "e": 337, "s": 325, "text": "Example #1:" }, { "code": "// Scala program of contains()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 3, 5, 2) // Applying contains method val res = m1.contains(1) // Displays output println(res) }}", "e": 676, "s": 337, "text": null }, { "code": null, "e": 682, "s": 676, "text": "true\n" }, { "code": null, "e": 694, "s": 682, "text": "Example #2:" }, { "code": "// Scala program of contains()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 3, 5, 2) // Applying contains method val res = m1.contains(7) // Displays output println(res) }}", "e": 1033, "s": 694, "text": null }, { "code": null, "e": 1040, "s": 1033, "text": "false\n" }, { "code": null, "e": 1046, "s": 1040, "text": "Scala" }, { "code": null, "e": 1057, "s": 1046, "text": "Scala-list" }, { "code": null, "e": 1070, "s": 1057, "text": "Scala-Method" }, { "code": null, "e": 1076, "s": 1070, "text": "Scala" } ]