title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Create an Impressive GitHub Profile README and Add Your Medium RSS Feed Using GitHub Action | Towards Data Science
1 Why do we need to create a GitHub profile README?2 What’s the Medium RSS feed? How do we get our Medium RSS site?3 How to create an impressive GitHub profile README?4 How to add Medium RSS feed in GitHub profile README?5 Conclusion6 References GitHub is actually a platform where anyone who interests in programming can share their codes to collaborate with others. Many open-source companies are using GitHub as their collaboration management system where developers across the world can contribute to project development. Those are Google, Facebook, Microsoft, Twitter, LinkedIn, Netflix, PostgreSQL, Apache, etc. They are using git to boost their project performance. However, many of us as the programmer or data scientist often use GitHub as the portfolio which means contains all of our previous projects. So, people who want to hire us as their talent can easily look at our projects. That’s the point where GitHub becomes not only for versioning and collaboration tools but also a portfolio. We need to design our GitHub as pretty as possible. On July, 17th 2020, GitHub just released a new feature: GitHub profile README! It helps us make our GitHub looks impressive and professional. Through this article, I would like to give you an example of how to add our Medium RSS feed on GitHub profile README. So, keep reading and keep focus! towardsdatascience.com As mentioned in the previous section, we will add the Medium RSS feed in GitHub profile README but what is the RSS feed? RSS which is an abbreviation for RDF Site Summary or Really Simple Syndication is a summary of the web information. The RSS feed is created using XML in a standardized format. Medium provides RSS feeds for user profiles, publications, and topic pages. Using an RSS feed URL, we can: Add a feed of our favorite author, publication, or topic we like to read about to our RSS feed reader Integrate the feed of our own profile or publication on Medium with our own website to show our latest stories We are able to look at our Medium RSS feed using a custom URL as follows. Fill the [username] with our own username and look at the result as our Medium RSS feed. Read the detailed explanation of the Medium RSS feed HERE. # URL to get Medium RSS feedhttp://medium.com/feed/@[username]# Sample URLhttp://medium.com/feed/@audhiaprilliant It shows the top ten latest articles that are written by us. It will let our readers know our up-to-date articles. That is the mechanism of the RSS feed. Finally, we are in the important section of this article. We will create an impressive GitHub profile README as our portfolio resume. It will allow our followers to know better about us regarding our projects, contributions on open source projects in GitHub, our activity in other platforms such as Medium, WordPress, etc. It sounds great! Those will be covered in our portfolio that contains information as follows. Profile identity — the brief description of ourselves. It can be our current company, projects, goals, interests, hobby, etc Social media — let people connect with us to share about a relevant subject related to our interests, projects, tools, tech information Hard skills — our abilities related to our projects in GitHub, our professional works, educational degree Professional tools — any software we are good at especially related to our day to day works, for instance as a Data Scientist, I usually use Python, R programming, shell scripting, and other tools Medium latest article — it will list our latest articles on Medium, so people can easily read those GitHub activity — the statistic of our activity in GitHub, such as total stars, total commits, total pull request, etc The following picture is an example of Medium and WordPress's latest article created by me in my GitHub profile README. That’s wonderful, right? Wanna try? Let’s go! First, to create a GitHub profile README, create files and a custom directory in GitHub that is displayed on the picture. .github/workflows — will contain the configuration for our Medium RSS feed workflow and others workflow .gitignore —can be ignored because we will not have an untracked file that git should ignore README.md — file to write our profile or portfolio Edit our README.md file using the following markdown template to create a GitHub profile README. You are able to modify the script as you like your preferences. However, there are several notes in order to modify the README.md script as follows. To embed a social media icon, you can easily use the template provided by GitHub using https://raw.githubusercontent.com/iconic/open-iconic/master/svg/[icon].svg. Replace the [icon] with the icon name you are looking for To embed a tool's icon, you can use the template provided by GitHub using https://raw.githubusercontent.com/github/explore/80688e429a7d4ef2fca1e82350fe8e3517d3494d/topics/python/[tool].png. Replace the [tool] with the icon name you are looking for For the Latest Medium Story section, you can replace the MEDIUM-STORY-LIST with your preference but important to remember that it will connect to the workflow 🔭 I’m currently working on a personal project! 🌱 I’m currently learning Data Science and Analytics 🤣 👯 I’m looking to collaborate with other content creators 🥅 2020 Goals: Give impact to society ⚡ Fun fact: I love blogging, reading books, and drawing For the section of GitHub Stat, it is as simple as replace my username (audhiaprilliant) with your own. It will show our GitHub statistics about the total of stars from our repo, total commits, total pull request, total issues, number of contributions to the open-source project, and the GitHub grade. Furthermore, the GitHub Stats has two settings: to show the icons and to show the image border which helps us to custom the image. Read more about GitHub stats HERE. https://github-readme-stats.vercel.app/api?username=audhiaprilliant&show_icons=true&hide_border=true Next, we need to interact with GitHub action in order to update the Medium RSS feed in GitHub. Previously, create a YAML file inside the .github/workflow named medium-story-workflow.yml or with your own filename. Further, this YAML file is created to define our workflow configuration. Read more about GitHub workflow HERE. Notes related to the Medium YAML file The workflow will run every hour for 60 days. After 60 days, we need to rerun the workflow manually It will update the README.md especially the MEDIUM-STORY-LIST section Replace the feed_list with your Medium RSS feed The YAML file will automatically check the Medium RSS feed and update the README.md file if there are an up-to-date article After making a YAML file, go over the GitHub Actions menu and we will find out the list of our workflow, namely Latest Medium story workflow. In order to run this workflow, left-click on Latest Medium story workflow and select the Run workflow menu on the right corner and left-click the green button. Slowly, the workflow will in the queue stage and a run stage. The output will display whether our workflow is done successfully or not. The green checklist indicates that the workflow is successful. Please direct to our GitHub profile README page and look at the Medium section. It should show the list of our latest Medium articles based on the Medium RSS feed. Unluckily, sometimes there will be an error regarding our workflow. Don't be worry! Further, GitHub will send us an email as a notification so we can rerun the workflow manually. Lastly, I want to thank Jesse for the tutorial he gave via codeSTACKr YouTube channel. For a detailed explanation, you can easily click the following video created by Jesse. Thank you! GitHub is such a wonderful platform, not only for collaboration and versioning but also to keep our projects. Luckily, on July, 17th 2020, GitHub just released a new feature: GitHub profile README and it adds the new function of GitHub, portfolio. Using GitHub profile README, we can describe our projects, tools, articles, etc over the world and let people connect with us. [1] Anonim. Using RSS feeds of profiles and publications, 2020. https://help.medium.com/. [2] GitHub Team. GitHub Actions, 2020. https://docs.github.com/en/.
[ { "code": null, "e": 417, "s": 171, "text": "1 Why do we need to create a GitHub profile README?2 What’s the Medium RSS feed? How do we get our Medium RSS site?3 How to create an impressive GitHub profile README?4 How to add Medium RSS feed in GitHub profile README?5 Conclusion6 References" }, { "code": null, "e": 844, "s": 417, "text": "GitHub is actually a platform where anyone who interests in programming can share their codes to collaborate with others. Many open-source companies are using GitHub as their collaboration management system where developers across the world can contribute to project development. Those are Google, Facebook, Microsoft, Twitter, LinkedIn, Netflix, PostgreSQL, Apache, etc. They are using git to boost their project performance." }, { "code": null, "e": 1225, "s": 844, "text": "However, many of us as the programmer or data scientist often use GitHub as the portfolio which means contains all of our previous projects. So, people who want to hire us as their talent can easily look at our projects. That’s the point where GitHub becomes not only for versioning and collaboration tools but also a portfolio. We need to design our GitHub as pretty as possible." }, { "code": null, "e": 1518, "s": 1225, "text": "On July, 17th 2020, GitHub just released a new feature: GitHub profile README! It helps us make our GitHub looks impressive and professional. Through this article, I would like to give you an example of how to add our Medium RSS feed on GitHub profile README. So, keep reading and keep focus!" }, { "code": null, "e": 1541, "s": 1518, "text": "towardsdatascience.com" }, { "code": null, "e": 1838, "s": 1541, "text": "As mentioned in the previous section, we will add the Medium RSS feed in GitHub profile README but what is the RSS feed? RSS which is an abbreviation for RDF Site Summary or Really Simple Syndication is a summary of the web information. The RSS feed is created using XML in a standardized format." }, { "code": null, "e": 1945, "s": 1838, "text": "Medium provides RSS feeds for user profiles, publications, and topic pages. Using an RSS feed URL, we can:" }, { "code": null, "e": 2047, "s": 1945, "text": "Add a feed of our favorite author, publication, or topic we like to read about to our RSS feed reader" }, { "code": null, "e": 2158, "s": 2047, "text": "Integrate the feed of our own profile or publication on Medium with our own website to show our latest stories" }, { "code": null, "e": 2380, "s": 2158, "text": "We are able to look at our Medium RSS feed using a custom URL as follows. Fill the [username] with our own username and look at the result as our Medium RSS feed. Read the detailed explanation of the Medium RSS feed HERE." }, { "code": null, "e": 2494, "s": 2380, "text": "# URL to get Medium RSS feedhttp://medium.com/feed/@[username]# Sample URLhttp://medium.com/feed/@audhiaprilliant" }, { "code": null, "e": 2648, "s": 2494, "text": "It shows the top ten latest articles that are written by us. It will let our readers know our up-to-date articles. That is the mechanism of the RSS feed." }, { "code": null, "e": 3065, "s": 2648, "text": "Finally, we are in the important section of this article. We will create an impressive GitHub profile README as our portfolio resume. It will allow our followers to know better about us regarding our projects, contributions on open source projects in GitHub, our activity in other platforms such as Medium, WordPress, etc. It sounds great! Those will be covered in our portfolio that contains information as follows." }, { "code": null, "e": 3190, "s": 3065, "text": "Profile identity — the brief description of ourselves. It can be our current company, projects, goals, interests, hobby, etc" }, { "code": null, "e": 3326, "s": 3190, "text": "Social media — let people connect with us to share about a relevant subject related to our interests, projects, tools, tech information" }, { "code": null, "e": 3432, "s": 3326, "text": "Hard skills — our abilities related to our projects in GitHub, our professional works, educational degree" }, { "code": null, "e": 3629, "s": 3432, "text": "Professional tools — any software we are good at especially related to our day to day works, for instance as a Data Scientist, I usually use Python, R programming, shell scripting, and other tools" }, { "code": null, "e": 3729, "s": 3629, "text": "Medium latest article — it will list our latest articles on Medium, so people can easily read those" }, { "code": null, "e": 3848, "s": 3729, "text": "GitHub activity — the statistic of our activity in GitHub, such as total stars, total commits, total pull request, etc" }, { "code": null, "e": 4014, "s": 3848, "text": "The following picture is an example of Medium and WordPress's latest article created by me in my GitHub profile README. That’s wonderful, right? Wanna try? Let’s go!" }, { "code": null, "e": 4136, "s": 4014, "text": "First, to create a GitHub profile README, create files and a custom directory in GitHub that is displayed on the picture." }, { "code": null, "e": 4240, "s": 4136, "text": ".github/workflows — will contain the configuration for our Medium RSS feed workflow and others workflow" }, { "code": null, "e": 4333, "s": 4240, "text": ".gitignore —can be ignored because we will not have an untracked file that git should ignore" }, { "code": null, "e": 4384, "s": 4333, "text": "README.md — file to write our profile or portfolio" }, { "code": null, "e": 4630, "s": 4384, "text": "Edit our README.md file using the following markdown template to create a GitHub profile README. You are able to modify the script as you like your preferences. However, there are several notes in order to modify the README.md script as follows." }, { "code": null, "e": 4851, "s": 4630, "text": "To embed a social media icon, you can easily use the template provided by GitHub using https://raw.githubusercontent.com/iconic/open-iconic/master/svg/[icon].svg. Replace the [icon] with the icon name you are looking for" }, { "code": null, "e": 5099, "s": 4851, "text": "To embed a tool's icon, you can use the template provided by GitHub using https://raw.githubusercontent.com/github/explore/80688e429a7d4ef2fca1e82350fe8e3517d3494d/topics/python/[tool].png. Replace the [tool] with the icon name you are looking for" }, { "code": null, "e": 5258, "s": 5099, "text": "For the Latest Medium Story section, you can replace the MEDIUM-STORY-LIST with your preference but important to remember that it will connect to the workflow" }, { "code": null, "e": 5305, "s": 5258, "text": "🔭 I’m currently working on a personal project!" }, { "code": null, "e": 5359, "s": 5305, "text": "🌱 I’m currently learning Data Science and Analytics 🤣" }, { "code": null, "e": 5416, "s": 5359, "text": "👯 I’m looking to collaborate with other content creators" }, { "code": null, "e": 5453, "s": 5416, "text": "🥅 2020 Goals: Give impact to society" }, { "code": null, "e": 5509, "s": 5453, "text": "⚡ Fun fact: I love blogging, reading books, and drawing" }, { "code": null, "e": 5958, "s": 5525, "text": "For the section of GitHub Stat, it is as simple as replace my username (audhiaprilliant) with your own. It will show our GitHub statistics about the total of stars from our repo, total commits, total pull request, total issues, number of contributions to the open-source project, and the GitHub grade. Furthermore, the GitHub Stats has two settings: to show the icons and to show the image border which helps us to custom the image." }, { "code": null, "e": 5993, "s": 5958, "text": "Read more about GitHub stats HERE." }, { "code": null, "e": 6094, "s": 5993, "text": "https://github-readme-stats.vercel.app/api?username=audhiaprilliant&show_icons=true&hide_border=true" }, { "code": null, "e": 6380, "s": 6094, "text": "Next, we need to interact with GitHub action in order to update the Medium RSS feed in GitHub. Previously, create a YAML file inside the .github/workflow named medium-story-workflow.yml or with your own filename. Further, this YAML file is created to define our workflow configuration." }, { "code": null, "e": 6418, "s": 6380, "text": "Read more about GitHub workflow HERE." }, { "code": null, "e": 6456, "s": 6418, "text": "Notes related to the Medium YAML file" }, { "code": null, "e": 6556, "s": 6456, "text": "The workflow will run every hour for 60 days. After 60 days, we need to rerun the workflow manually" }, { "code": null, "e": 6626, "s": 6556, "text": "It will update the README.md especially the MEDIUM-STORY-LIST section" }, { "code": null, "e": 6674, "s": 6626, "text": "Replace the feed_list with your Medium RSS feed" }, { "code": null, "e": 6798, "s": 6674, "text": "The YAML file will automatically check the Medium RSS feed and update the README.md file if there are an up-to-date article" }, { "code": null, "e": 7100, "s": 6798, "text": "After making a YAML file, go over the GitHub Actions menu and we will find out the list of our workflow, namely Latest Medium story workflow. In order to run this workflow, left-click on Latest Medium story workflow and select the Run workflow menu on the right corner and left-click the green button." }, { "code": null, "e": 7299, "s": 7100, "text": "Slowly, the workflow will in the queue stage and a run stage. The output will display whether our workflow is done successfully or not. The green checklist indicates that the workflow is successful." }, { "code": null, "e": 7463, "s": 7299, "text": "Please direct to our GitHub profile README page and look at the Medium section. It should show the list of our latest Medium articles based on the Medium RSS feed." }, { "code": null, "e": 7642, "s": 7463, "text": "Unluckily, sometimes there will be an error regarding our workflow. Don't be worry! Further, GitHub will send us an email as a notification so we can rerun the workflow manually." }, { "code": null, "e": 7827, "s": 7642, "text": "Lastly, I want to thank Jesse for the tutorial he gave via codeSTACKr YouTube channel. For a detailed explanation, you can easily click the following video created by Jesse. Thank you!" }, { "code": null, "e": 8202, "s": 7827, "text": "GitHub is such a wonderful platform, not only for collaboration and versioning but also to keep our projects. Luckily, on July, 17th 2020, GitHub just released a new feature: GitHub profile README and it adds the new function of GitHub, portfolio. Using GitHub profile README, we can describe our projects, tools, articles, etc over the world and let people connect with us." }, { "code": null, "e": 8292, "s": 8202, "text": "[1] Anonim. Using RSS feeds of profiles and publications, 2020. https://help.medium.com/." } ]
spaCy - Token Properties
In this chapter, we will learn about the properties with regards to the Token class in spaCy. The token properties are listed below along with their respective descriptions. Token.ancestors Used for the rightmost token of this token’s syntactic descendants. Token.conjuncts Used to return a tuple of coordinated tokens. Token.children Used to return a sequence of the token’s immediate syntactic children. Token.lefts Used for the leftward immediate children of the word. Token.rights Used for the rightward immediate children of the word. Token.n_rights Used for the number of rightward immediate children of the word. Token.n_lefts Used for the number of leftward immediate children of the word. Token.subtree This yields a sequence that contains the token and all the token’s syntactic descendants. Token.vector This represents a real-valued meaning. Token.vector_norm This represents the L2 norm of the token’s vector representation. This token property is used for the rightmost token of this token’s syntactic descendants. Example An example of Token.ancestors property is given below − import spacy nlp_model = spacy.load("en_core_web_sm") from spacy.tokens import Token doc = nlp_model("Give it back! He pleaded.") it_ancestors = doc[1].ancestors [t.text for t in it_ancestors] Output ['Give'] This token property is used to return a tuple of co-ordinated tokens. Here, the token itself would not be included. Example An example of Token.conjuncts property is as follows − import spacy nlp_model = spacy.load("en_core_web_sm") from spacy.tokens import Token doc = nlp_model("I like cars and bikes") cars_conjuncts = doc[2].conjuncts [t.text for t in cars_conjuncts] Output The output is mentioned below − ['bikes'] This token property is used to return a sequence of the token’s immediate syntactic children. Example An example of Token.children property is as follows − import spacy nlp_model = spacy.load("en_core_web_sm") from spacy.tokens import Token doc = nlp_model("This is Tutorialspoint.com.") give_child = doc[1].children [t.text for t in give_child] Output ['This', 'Tutorialspoint.com', '.'] This token property is used for the leftward immediate children of the word. It would be in the syntactic dependency parse. Example An example of Token.lefts property is as follows − import spacy nlp_model = spacy.load("en_core_web_sm") from spacy.tokens import Token doc = nlp_model("This is Tutorialspoint.com.") left_child = [t.text for t in doc[1].lefts] left_child Output You will get the following output − ['This'] This token property is used for the rightward immediate children of the word. It would be in the syntactic dependency parse. Example An example of Token.rights property is given below − import spacy nlp_model = spacy.load("en_core_web_sm") from spacy.tokens import Token doc = nlp_model("This is Tutorialspoint.com.") right_child = [t.text for t in doc[1].rights] right_child Output ['Tutorialspoint.com', '.'] This token property is used for the number of rightward immediate children of the word. It would be in the syntactic dependency parse. Example An example of Token.n_rights property is given below − import spacy nlp_model = spacy.load("en_core_web_sm") from spacy.tokens import Token doc = nlp_model("This is Tutorialspoint.com.") doc[1].n_rights Output 2 This token property is used for the number of leftward immediate children of the word. It would be in the syntactic dependency parse. Example An example of Token.n_lefts property is as follows − import spacy nlp_model = spacy.load("en_core_web_sm") from spacy.tokens import Token doc = nlp_model("This is Tutorialspoint.com.") doc[1].n_lefts Output The output is stated below − 1 This token property yields a sequence that contains the token and all the token’s syntactic descendants. Example An example of Token.subtree property is as follows − import spacy nlp_model = spacy.load("en_core_web_sm") from spacy.tokens import Token doc = nlp_model("This is Tutorialspoint.com.") subtree_doc = doc[1].subtree [t.text for t in subtree_doc] Output ['This', 'is', 'Tutorialspoint.com', '.'] This token property represents a real-valued meaning. It will return a one-dimensional array representing the token’s semantics. Example 1 An example of Token.vector property is as follows − import spacy nlp_model = spacy.load("en_core_web_sm") doc = nlp_model("The website is Tutorialspoint.com.") doc.vector.dtype Output The output is stated below − dtype('float32') Example 2 An another example of Token.vector property is given below − doc.vector.shape Output The output is stated below − (96,) This token property represents the L2 norm of the token’s vector representation. Example An example of Token.vector_norm property is given below − import spacy nlp_model = spacy.load("en_core_web_sm") doc1 = nlp_model("The website is Tutorialspoint.com.") doc2 = nlp_model("It is having best technical tutorials.") doc1[2].vector_norm !=doc2[2].vector_norm Output True Print Add Notes Bookmark this page
[ { "code": null, "e": 2166, "s": 2072, "text": "In this chapter, we will learn about the properties with regards to the Token class in spaCy." }, { "code": null, "e": 2246, "s": 2166, "text": "The token properties are listed below along with their respective descriptions." }, { "code": null, "e": 2262, "s": 2246, "text": "Token.ancestors" }, { "code": null, "e": 2330, "s": 2262, "text": "Used for the rightmost token of this token’s syntactic descendants." }, { "code": null, "e": 2346, "s": 2330, "text": "Token.conjuncts" }, { "code": null, "e": 2392, "s": 2346, "text": "Used to return a tuple of coordinated tokens." }, { "code": null, "e": 2407, "s": 2392, "text": "Token.children" }, { "code": null, "e": 2478, "s": 2407, "text": "Used to return a sequence of the token’s immediate syntactic children." }, { "code": null, "e": 2490, "s": 2478, "text": "Token.lefts" }, { "code": null, "e": 2544, "s": 2490, "text": "Used for the leftward immediate children of the word." }, { "code": null, "e": 2557, "s": 2544, "text": "Token.rights" }, { "code": null, "e": 2612, "s": 2557, "text": "Used for the rightward immediate children of the word." }, { "code": null, "e": 2627, "s": 2612, "text": "Token.n_rights" }, { "code": null, "e": 2692, "s": 2627, "text": "Used for the number of rightward immediate children of the word." }, { "code": null, "e": 2706, "s": 2692, "text": "Token.n_lefts" }, { "code": null, "e": 2770, "s": 2706, "text": "Used for the number of leftward immediate children of the word." }, { "code": null, "e": 2784, "s": 2770, "text": "Token.subtree" }, { "code": null, "e": 2874, "s": 2784, "text": "This yields a sequence that contains the token and all the token’s syntactic descendants." }, { "code": null, "e": 2887, "s": 2874, "text": "Token.vector" }, { "code": null, "e": 2926, "s": 2887, "text": "This represents a real-valued meaning." }, { "code": null, "e": 2944, "s": 2926, "text": "Token.vector_norm" }, { "code": null, "e": 3010, "s": 2944, "text": "This represents the L2 norm of the token’s vector representation." }, { "code": null, "e": 3101, "s": 3010, "text": "This token property is used for the rightmost token of this token’s syntactic descendants." }, { "code": null, "e": 3109, "s": 3101, "text": "Example" }, { "code": null, "e": 3165, "s": 3109, "text": "An example of Token.ancestors property is given below −" }, { "code": null, "e": 3359, "s": 3165, "text": "import spacy\nnlp_model = spacy.load(\"en_core_web_sm\")\nfrom spacy.tokens import Token\ndoc = nlp_model(\"Give it back! He pleaded.\")\n\nit_ancestors = doc[1].ancestors\n[t.text for t in it_ancestors]" }, { "code": null, "e": 3366, "s": 3359, "text": "Output" }, { "code": null, "e": 3376, "s": 3366, "text": "['Give']\n" }, { "code": null, "e": 3492, "s": 3376, "text": "This token property is used to return a tuple of co-ordinated tokens. Here, the token itself would not be included." }, { "code": null, "e": 3500, "s": 3492, "text": "Example" }, { "code": null, "e": 3555, "s": 3500, "text": "An example of Token.conjuncts property is as follows −" }, { "code": null, "e": 3748, "s": 3555, "text": "import spacy\nnlp_model = spacy.load(\"en_core_web_sm\")\nfrom spacy.tokens import Token\ndoc = nlp_model(\"I like cars and bikes\")\ncars_conjuncts = doc[2].conjuncts\n[t.text for t in cars_conjuncts]" }, { "code": null, "e": 3755, "s": 3748, "text": "Output" }, { "code": null, "e": 3787, "s": 3755, "text": "The output is mentioned below −" }, { "code": null, "e": 3798, "s": 3787, "text": "['bikes']\n" }, { "code": null, "e": 3892, "s": 3798, "text": "This token property is used to return a sequence of the token’s immediate syntactic children." }, { "code": null, "e": 3900, "s": 3892, "text": "Example" }, { "code": null, "e": 3954, "s": 3900, "text": "An example of Token.children property is as follows −" }, { "code": null, "e": 4144, "s": 3954, "text": "import spacy\nnlp_model = spacy.load(\"en_core_web_sm\")\nfrom spacy.tokens import Token\ndoc = nlp_model(\"This is Tutorialspoint.com.\")\ngive_child = doc[1].children\n[t.text for t in give_child]" }, { "code": null, "e": 4151, "s": 4144, "text": "Output" }, { "code": null, "e": 4188, "s": 4151, "text": "['This', 'Tutorialspoint.com', '.']\n" }, { "code": null, "e": 4312, "s": 4188, "text": "This token property is used for the leftward immediate children of the word. It would be in the syntactic dependency parse." }, { "code": null, "e": 4320, "s": 4312, "text": "Example" }, { "code": null, "e": 4371, "s": 4320, "text": "An example of Token.lefts property is as follows −" }, { "code": null, "e": 4558, "s": 4371, "text": "import spacy\nnlp_model = spacy.load(\"en_core_web_sm\")\nfrom spacy.tokens import Token\ndoc = nlp_model(\"This is Tutorialspoint.com.\")\nleft_child = [t.text for t in doc[1].lefts]\nleft_child" }, { "code": null, "e": 4565, "s": 4558, "text": "Output" }, { "code": null, "e": 4601, "s": 4565, "text": "You will get the following output −" }, { "code": null, "e": 4611, "s": 4601, "text": "['This']\n" }, { "code": null, "e": 4736, "s": 4611, "text": "This token property is used for the rightward immediate children of the word. It would be in the syntactic dependency parse." }, { "code": null, "e": 4744, "s": 4736, "text": "Example" }, { "code": null, "e": 4797, "s": 4744, "text": "An example of Token.rights property is given below −" }, { "code": null, "e": 4987, "s": 4797, "text": "import spacy\nnlp_model = spacy.load(\"en_core_web_sm\")\nfrom spacy.tokens import Token\ndoc = nlp_model(\"This is Tutorialspoint.com.\")\nright_child = [t.text for t in doc[1].rights]\nright_child" }, { "code": null, "e": 4994, "s": 4987, "text": "Output" }, { "code": null, "e": 5023, "s": 4994, "text": "['Tutorialspoint.com', '.']\n" }, { "code": null, "e": 5158, "s": 5023, "text": "This token property is used for the number of rightward immediate children of the word. It would be in the syntactic dependency parse." }, { "code": null, "e": 5166, "s": 5158, "text": "Example" }, { "code": null, "e": 5221, "s": 5166, "text": "An example of Token.n_rights property is given below −" }, { "code": null, "e": 5369, "s": 5221, "text": "import spacy\nnlp_model = spacy.load(\"en_core_web_sm\")\nfrom spacy.tokens import Token\ndoc = nlp_model(\"This is Tutorialspoint.com.\")\ndoc[1].n_rights" }, { "code": null, "e": 5376, "s": 5369, "text": "Output" }, { "code": null, "e": 5379, "s": 5376, "text": "2\n" }, { "code": null, "e": 5513, "s": 5379, "text": "This token property is used for the number of leftward immediate children of the word. It would be in the syntactic dependency parse." }, { "code": null, "e": 5521, "s": 5513, "text": "Example" }, { "code": null, "e": 5574, "s": 5521, "text": "An example of Token.n_lefts property is as follows −" }, { "code": null, "e": 5721, "s": 5574, "text": "import spacy\nnlp_model = spacy.load(\"en_core_web_sm\")\nfrom spacy.tokens import Token\ndoc = nlp_model(\"This is Tutorialspoint.com.\")\ndoc[1].n_lefts" }, { "code": null, "e": 5728, "s": 5721, "text": "Output" }, { "code": null, "e": 5757, "s": 5728, "text": "The output is stated below −" }, { "code": null, "e": 5760, "s": 5757, "text": "1\n" }, { "code": null, "e": 5865, "s": 5760, "text": "This token property yields a sequence that contains the token and all the token’s syntactic descendants." }, { "code": null, "e": 5873, "s": 5865, "text": "Example" }, { "code": null, "e": 5926, "s": 5873, "text": "An example of Token.subtree property is as follows −" }, { "code": null, "e": 6117, "s": 5926, "text": "import spacy\nnlp_model = spacy.load(\"en_core_web_sm\")\nfrom spacy.tokens import Token\ndoc = nlp_model(\"This is Tutorialspoint.com.\")\nsubtree_doc = doc[1].subtree\n[t.text for t in subtree_doc]" }, { "code": null, "e": 6124, "s": 6117, "text": "Output" }, { "code": null, "e": 6167, "s": 6124, "text": "['This', 'is', 'Tutorialspoint.com', '.']\n" }, { "code": null, "e": 6296, "s": 6167, "text": "This token property represents a real-valued meaning. It will return a one-dimensional array representing the token’s semantics." }, { "code": null, "e": 6306, "s": 6296, "text": "Example 1" }, { "code": null, "e": 6358, "s": 6306, "text": "An example of Token.vector property is as follows −" }, { "code": null, "e": 6483, "s": 6358, "text": "import spacy\nnlp_model = spacy.load(\"en_core_web_sm\")\ndoc = nlp_model(\"The website is Tutorialspoint.com.\")\ndoc.vector.dtype" }, { "code": null, "e": 6490, "s": 6483, "text": "Output" }, { "code": null, "e": 6519, "s": 6490, "text": "The output is stated below −" }, { "code": null, "e": 6537, "s": 6519, "text": "dtype('float32')\n" }, { "code": null, "e": 6547, "s": 6537, "text": "Example 2" }, { "code": null, "e": 6608, "s": 6547, "text": "An another example of Token.vector property is given below −" }, { "code": null, "e": 6625, "s": 6608, "text": "doc.vector.shape" }, { "code": null, "e": 6632, "s": 6625, "text": "Output" }, { "code": null, "e": 6661, "s": 6632, "text": "The output is stated below −" }, { "code": null, "e": 6668, "s": 6661, "text": "(96,)\n" }, { "code": null, "e": 6749, "s": 6668, "text": "This token property represents the L2 norm of the token’s vector representation." }, { "code": null, "e": 6757, "s": 6749, "text": "Example" }, { "code": null, "e": 6815, "s": 6757, "text": "An example of Token.vector_norm property is given below −" }, { "code": null, "e": 7025, "s": 6815, "text": "import spacy\nnlp_model = spacy.load(\"en_core_web_sm\")\ndoc1 = nlp_model(\"The website is Tutorialspoint.com.\")\ndoc2 = nlp_model(\"It is having best technical tutorials.\")\ndoc1[2].vector_norm !=doc2[2].vector_norm" }, { "code": null, "e": 7032, "s": 7025, "text": "Output" }, { "code": null, "e": 7038, "s": 7032, "text": "True\n" }, { "code": null, "e": 7045, "s": 7038, "text": " Print" }, { "code": null, "e": 7056, "s": 7045, "text": " Add Notes" } ]
AI Generates Trending Video Ideas | by Andre Ye | Towards Data Science
YouTube is a massive platform — videos that manage to gain the favor of the recommendation algorithm can get hundreds of millions of views. While content creators guess around in an attempt to create the next viral video, AI can generate as many trending video ideas as you’d like! In this article, I’ll show how anyone can create and train recurrent neural network to generate trending video ideas — in four lines of code! If you’re not interested in how Recurrent Neural Networks work, feel free to jump down to the implementation. A Recurrent Neural Network (RNN) is a type of neural network that specializes in processing sequences. Given a seed “She walked her ___”, an RNN might predict “dog”. The trick with RNNs in text generation is using predictions as seeds for further predictions. One issue with standard neural networks as it applies to text geneation is that it has a fixed input and output size. For example, in a convolutional neural net trained on the MNIST dataset, each training and testing example can only be 784 values — no more, no less. While this is practical in tasks like image recognition, it is certainly not for natural language processing tasks, where the input and output may vary between a few characters to several sentences or even more. RNNs allows for variable-length inputs and outputs. RNNs can look like any of the below, where red is the input, green is the RNN, and blue is the output: Whereas standard and convolutional neural networks have a different set of weights and biases for each input value or pixel, recurrent neural networks have the same set of weights and biases for all inputs. A RNN usually has three sets of weights and biases — one between the input and the hidden layers (red to green), one between a hidden layer to another hidden layer (green to green), and another one between a hidden layer and an output layer (green to blue). Because the same set of weights and biases is used over each layer-to-layer link, the number of cells in a layer, including the inputs and outputs, can be very easily adjusted. Because there are so little parameters, the optimal weights and biases can be honed in on. So why is the RNN so good at generating text? RNN text generation is based on the fundamental principle that the next word in a sentence is always applied with the same idea in mind. This makes sense — as an author, the next word you put down was put there with the same intent as the one before it. In the above graphic, the first sentence is written such that each word is placed with the same intent. The second sentence begins with the same intent but because it keeps on switching, the end result is nowhere near the original intent. By applying the same RNN on each set of words, the intent of the sentence (where it’s trying to go, what ideas it contains) as well as the phrasing of the sentence is maintained. If you want a more in-depth explanation of RNNs, check out some of these research papers. Recurrent Neural Network Based Language Model Extensions of Recurrent Neural Network Based Language Model All machine learning models require data. The dataset we will be using is the Trending YouTube Video Statistics dataset on Kaggle. When loading and viewing the dataset, we can get an idea for how the data is structured: import pandas as pddata = pd.read_csv('/kaggle/input/youtube-new/USvideos.csv')data.head() We are interested in the title column — this will provide data to train the RNN on. This data has 40,949 rows; this is not much in comparison to some larger datasets, but to keep the training time reasonable let’s reduce the training data down to 5,000 instances. In addition, we should narrow down what categories the training data is on: After looking at different categories, it becomes clear that some categories are dedicated for news, music videos, movie trailers, etc., which wouldn’t make sense in the context of an idea generator because news, song titles, music video titles, and so on either can’t be generated or wouldn’t make sense. Category IDs 22, 23, and 24 are dedicated towards comedy and shorter segments created by small content creators. These are more in-line with what we want to generate. The following code selects rows in data that belong to categories 22, 23, or 24 and puts them in a DataFrame called sub_data. sub_data = data[(data['category_id']==24) | (data['category_id']==23) | (data['category_id']==22)] There are still 16,631 rows — to reduce it down to five thousand rows, we will randomly shuffle the DataFrame several times and then select the top 5,000 rows for training data. sklearn’s handy shuffle function can help: from sklearn.utils import shufflesub_data = shuffle(shuffle(sub_data)) To feed the data into the model, it must be in a text file, with each new training instance on a separate line. The following code does just that: titles = open('title.txt','w+')for item in sub_data.head(5_000)['title']: titles.write(item) titles.write('\n')titles.close() Note that the .head(n) function selects the top n rows in a DataFrame. To view title.txt, we can call print(open(‘title.txt’,’r’).read()). Finally, the training file is ready. There are many powerful libraries that can implement RNNs like Keras (TensorFlow) and Pytorch, but we’ll be using a library that can skip the complexities of choosing a network architecture called textgenrnn. This module can be called, trained, and used in 3 lines of code (4 if you count installing from pip), at the cost of lack of customizability. !pip install textgenrnn ...installs the module in the Kaggle notebook environment. You may remove the ! if operating in other environments. Training is simple: from textgenrnn import textgenrnntextgen = textgenrnn()textgen.train_from_file('title.txt', num_epochs=50) Since textgenrnn is built on a Keras RNN framework, it will output a familiar Keras progress-tracking print: This takes about 2.5 hours to run through all 50 epochs. textgen.generate(temperature=0.5) ...can be used to generate examples. ‘Temperature’ is a measure of how original the generated example will be (the less, the more original). It is a balance of being creative (smaller temperature) but not straying too far from the nature of the task, the balance between underfitting and overfitting. To show the model’s progress over time, I’ll include three titles from (about) every 10 epochs, then leave you with a treasure trove of 50-epoch-model generated titles. 1 epoch (Loss: 1.9178) — The Moment To Make Me Make More Cat To Be Coming To The The Moment | The Moment | The Moments Keryn lost — Marlari Grace (Fi Wheel The Year Indieved) Reading Omarakhondras | Now Cultu 1010–75 10 epochs (Loss: 0.9409) — Grammy Dance of Series of Helping a Good Teass Shape | Will Smith and Season 5 Official Trailer Cardi Book Ad — Dancing on TBS Why Your Boyfriend In Handwarls 20 epochs (Loss: 0.5871) — My Mom Buys My Outfits! DINOSAUR YOGA CHALLENGE!! The Movie — All of Tam | Lele Pons & Hulue & Jurassic Contineest for Anime | E! 30 epochs (Loss: 0.3069) — Mirror-Polished Japanese Foil Ball Challenge Crushed in a Hydraulic Press-What’s Inside? Why Justin Bieber Was The Worst SNL Guest | WWHL The Most Famous Actor You’ve Never Seen 40 epochs (Loss: 0.1618) — Will Smith & Joel Edgerton Answer the Web’s Most Searched Questions | WIRED Adam and Jenna’s Cha Cha — Dancer Sharisons & Reveals Your Door ftta Answering Saffle Officers Bravon Goes Sneaker Shopping At Seoul Charman’s Fabar Things 2 ...and finally, the top five 50-epoch (Loss: 0.1561) generated titles! MY BOY DO MY MAKEUP 24 HOUR BOX FORT PRISON ESCAPE Liam Payne Goes Sneaker Shopping Star Wars: The Bachelor Finale Disney Princess Pushing A Truck ...this was a humorous example of the capabilities of RNNs. You may have noticed that as the amount of epochs went up, the ideas were less and less original — overfitting. This has to do with us restricting the number of training examples. If you’d like to experiment with this on your own (and have a couple hours of computing time to spare), you could try restricting only be category and not by number of training examples (or use the entire data) — the resulting generated titles will probably be much more interesting. If you enjoyed, you can check out some other fun applications of RNNs: Using RNNs to Generate a Shakespeare-Imitation Play (Uses TensorFlow) Using RNNs to Create a Debate Death Match Between AI Joe Biden and AI Bernie Sanders (Uses textgenrnn)
[ { "code": null, "e": 454, "s": 172, "text": "YouTube is a massive platform — videos that manage to gain the favor of the recommendation algorithm can get hundreds of millions of views. While content creators guess around in an attempt to create the next viral video, AI can generate as many trending video ideas as you’d like!" }, { "code": null, "e": 596, "s": 454, "text": "In this article, I’ll show how anyone can create and train recurrent neural network to generate trending video ideas — in four lines of code!" }, { "code": null, "e": 706, "s": 596, "text": "If you’re not interested in how Recurrent Neural Networks work, feel free to jump down to the implementation." }, { "code": null, "e": 966, "s": 706, "text": "A Recurrent Neural Network (RNN) is a type of neural network that specializes in processing sequences. Given a seed “She walked her ___”, an RNN might predict “dog”. The trick with RNNs in text generation is using predictions as seeds for further predictions." }, { "code": null, "e": 1446, "s": 966, "text": "One issue with standard neural networks as it applies to text geneation is that it has a fixed input and output size. For example, in a convolutional neural net trained on the MNIST dataset, each training and testing example can only be 784 values — no more, no less. While this is practical in tasks like image recognition, it is certainly not for natural language processing tasks, where the input and output may vary between a few characters to several sentences or even more." }, { "code": null, "e": 1601, "s": 1446, "text": "RNNs allows for variable-length inputs and outputs. RNNs can look like any of the below, where red is the input, green is the RNN, and blue is the output:" }, { "code": null, "e": 2066, "s": 1601, "text": "Whereas standard and convolutional neural networks have a different set of weights and biases for each input value or pixel, recurrent neural networks have the same set of weights and biases for all inputs. A RNN usually has three sets of weights and biases — one between the input and the hidden layers (red to green), one between a hidden layer to another hidden layer (green to green), and another one between a hidden layer and an output layer (green to blue)." }, { "code": null, "e": 2334, "s": 2066, "text": "Because the same set of weights and biases is used over each layer-to-layer link, the number of cells in a layer, including the inputs and outputs, can be very easily adjusted. Because there are so little parameters, the optimal weights and biases can be honed in on." }, { "code": null, "e": 2380, "s": 2334, "text": "So why is the RNN so good at generating text?" }, { "code": null, "e": 2634, "s": 2380, "text": "RNN text generation is based on the fundamental principle that the next word in a sentence is always applied with the same idea in mind. This makes sense — as an author, the next word you put down was put there with the same intent as the one before it." }, { "code": null, "e": 2873, "s": 2634, "text": "In the above graphic, the first sentence is written such that each word is placed with the same intent. The second sentence begins with the same intent but because it keeps on switching, the end result is nowhere near the original intent." }, { "code": null, "e": 3052, "s": 2873, "text": "By applying the same RNN on each set of words, the intent of the sentence (where it’s trying to go, what ideas it contains) as well as the phrasing of the sentence is maintained." }, { "code": null, "e": 3142, "s": 3052, "text": "If you want a more in-depth explanation of RNNs, check out some of these research papers." }, { "code": null, "e": 3188, "s": 3142, "text": "Recurrent Neural Network Based Language Model" }, { "code": null, "e": 3248, "s": 3188, "text": "Extensions of Recurrent Neural Network Based Language Model" }, { "code": null, "e": 3379, "s": 3248, "text": "All machine learning models require data. The dataset we will be using is the Trending YouTube Video Statistics dataset on Kaggle." }, { "code": null, "e": 3468, "s": 3379, "text": "When loading and viewing the dataset, we can get an idea for how the data is structured:" }, { "code": null, "e": 3559, "s": 3468, "text": "import pandas as pddata = pd.read_csv('/kaggle/input/youtube-new/USvideos.csv')data.head()" }, { "code": null, "e": 3823, "s": 3559, "text": "We are interested in the title column — this will provide data to train the RNN on. This data has 40,949 rows; this is not much in comparison to some larger datasets, but to keep the training time reasonable let’s reduce the training data down to 5,000 instances." }, { "code": null, "e": 3899, "s": 3823, "text": "In addition, we should narrow down what categories the training data is on:" }, { "code": null, "e": 4372, "s": 3899, "text": "After looking at different categories, it becomes clear that some categories are dedicated for news, music videos, movie trailers, etc., which wouldn’t make sense in the context of an idea generator because news, song titles, music video titles, and so on either can’t be generated or wouldn’t make sense. Category IDs 22, 23, and 24 are dedicated towards comedy and shorter segments created by small content creators. These are more in-line with what we want to generate." }, { "code": null, "e": 4498, "s": 4372, "text": "The following code selects rows in data that belong to categories 22, 23, or 24 and puts them in a DataFrame called sub_data." }, { "code": null, "e": 4597, "s": 4498, "text": "sub_data = data[(data['category_id']==24) | (data['category_id']==23) | (data['category_id']==22)]" }, { "code": null, "e": 4818, "s": 4597, "text": "There are still 16,631 rows — to reduce it down to five thousand rows, we will randomly shuffle the DataFrame several times and then select the top 5,000 rows for training data. sklearn’s handy shuffle function can help:" }, { "code": null, "e": 4889, "s": 4818, "text": "from sklearn.utils import shufflesub_data = shuffle(shuffle(sub_data))" }, { "code": null, "e": 5036, "s": 4889, "text": "To feed the data into the model, it must be in a text file, with each new training instance on a separate line. The following code does just that:" }, { "code": null, "e": 5168, "s": 5036, "text": "titles = open('title.txt','w+')for item in sub_data.head(5_000)['title']: titles.write(item) titles.write('\\n')titles.close()" }, { "code": null, "e": 5239, "s": 5168, "text": "Note that the .head(n) function selects the top n rows in a DataFrame." }, { "code": null, "e": 5307, "s": 5239, "text": "To view title.txt, we can call print(open(‘title.txt’,’r’).read())." }, { "code": null, "e": 5695, "s": 5307, "text": "Finally, the training file is ready. There are many powerful libraries that can implement RNNs like Keras (TensorFlow) and Pytorch, but we’ll be using a library that can skip the complexities of choosing a network architecture called textgenrnn. This module can be called, trained, and used in 3 lines of code (4 if you count installing from pip), at the cost of lack of customizability." }, { "code": null, "e": 5719, "s": 5695, "text": "!pip install textgenrnn" }, { "code": null, "e": 5835, "s": 5719, "text": "...installs the module in the Kaggle notebook environment. You may remove the ! if operating in other environments." }, { "code": null, "e": 5855, "s": 5835, "text": "Training is simple:" }, { "code": null, "e": 5962, "s": 5855, "text": "from textgenrnn import textgenrnntextgen = textgenrnn()textgen.train_from_file('title.txt', num_epochs=50)" }, { "code": null, "e": 6071, "s": 5962, "text": "Since textgenrnn is built on a Keras RNN framework, it will output a familiar Keras progress-tracking print:" }, { "code": null, "e": 6128, "s": 6071, "text": "This takes about 2.5 hours to run through all 50 epochs." }, { "code": null, "e": 6162, "s": 6128, "text": "textgen.generate(temperature=0.5)" }, { "code": null, "e": 6463, "s": 6162, "text": "...can be used to generate examples. ‘Temperature’ is a measure of how original the generated example will be (the less, the more original). It is a balance of being creative (smaller temperature) but not straying too far from the nature of the task, the balance between underfitting and overfitting." }, { "code": null, "e": 6632, "s": 6463, "text": "To show the model’s progress over time, I’ll include three titles from (about) every 10 epochs, then leave you with a treasure trove of 50-epoch-model generated titles." }, { "code": null, "e": 6657, "s": 6632, "text": "1 epoch (Loss: 1.9178) —" }, { "code": null, "e": 6751, "s": 6657, "text": "The Moment To Make Me Make More Cat To Be Coming To The The Moment | The Moment | The Moments" }, { "code": null, "e": 6807, "s": 6751, "text": "Keryn lost — Marlari Grace (Fi Wheel The Year Indieved)" }, { "code": null, "e": 6849, "s": 6807, "text": "Reading Omarakhondras | Now Cultu 1010–75" }, { "code": null, "e": 6876, "s": 6849, "text": "10 epochs (Loss: 0.9409) —" }, { "code": null, "e": 6972, "s": 6876, "text": "Grammy Dance of Series of Helping a Good Teass Shape | Will Smith and Season 5 Official Trailer" }, { "code": null, "e": 7003, "s": 6972, "text": "Cardi Book Ad — Dancing on TBS" }, { "code": null, "e": 7035, "s": 7003, "text": "Why Your Boyfriend In Handwarls" }, { "code": null, "e": 7062, "s": 7035, "text": "20 epochs (Loss: 0.5871) —" }, { "code": null, "e": 7086, "s": 7062, "text": "My Mom Buys My Outfits!" }, { "code": null, "e": 7112, "s": 7086, "text": "DINOSAUR YOGA CHALLENGE!!" }, { "code": null, "e": 7192, "s": 7112, "text": "The Movie — All of Tam | Lele Pons & Hulue & Jurassic Contineest for Anime | E!" }, { "code": null, "e": 7219, "s": 7192, "text": "30 epochs (Loss: 0.3069) —" }, { "code": null, "e": 7308, "s": 7219, "text": "Mirror-Polished Japanese Foil Ball Challenge Crushed in a Hydraulic Press-What’s Inside?" }, { "code": null, "e": 7357, "s": 7308, "text": "Why Justin Bieber Was The Worst SNL Guest | WWHL" }, { "code": null, "e": 7397, "s": 7357, "text": "The Most Famous Actor You’ve Never Seen" }, { "code": null, "e": 7424, "s": 7397, "text": "40 epochs (Loss: 0.1618) —" }, { "code": null, "e": 7500, "s": 7424, "text": "Will Smith & Joel Edgerton Answer the Web’s Most Searched Questions | WIRED" }, { "code": null, "e": 7595, "s": 7500, "text": "Adam and Jenna’s Cha Cha — Dancer Sharisons & Reveals Your Door ftta Answering Saffle Officers" }, { "code": null, "e": 7658, "s": 7595, "text": "Bravon Goes Sneaker Shopping At Seoul Charman’s Fabar Things 2" }, { "code": null, "e": 7729, "s": 7658, "text": "...and finally, the top five 50-epoch (Loss: 0.1561) generated titles!" }, { "code": null, "e": 7749, "s": 7729, "text": "MY BOY DO MY MAKEUP" }, { "code": null, "e": 7780, "s": 7749, "text": "24 HOUR BOX FORT PRISON ESCAPE" }, { "code": null, "e": 7813, "s": 7780, "text": "Liam Payne Goes Sneaker Shopping" }, { "code": null, "e": 7844, "s": 7813, "text": "Star Wars: The Bachelor Finale" }, { "code": null, "e": 7876, "s": 7844, "text": "Disney Princess Pushing A Truck" }, { "code": null, "e": 8400, "s": 7876, "text": "...this was a humorous example of the capabilities of RNNs. You may have noticed that as the amount of epochs went up, the ideas were less and less original — overfitting. This has to do with us restricting the number of training examples. If you’d like to experiment with this on your own (and have a couple hours of computing time to spare), you could try restricting only be category and not by number of training examples (or use the entire data) — the resulting generated titles will probably be much more interesting." }, { "code": null, "e": 8471, "s": 8400, "text": "If you enjoyed, you can check out some other fun applications of RNNs:" }, { "code": null, "e": 8541, "s": 8471, "text": "Using RNNs to Generate a Shakespeare-Imitation Play (Uses TensorFlow)" } ]
12 Tips to Optimize Java Code Performance - GeeksforGeeks
18 Aug, 2021 While working on any Java application we come across the concept of optimization. It is necessary that the code which we are writing is not only clean, without defects but also optimized i.e. the time taken by the code to execute should be within intended limits. In order to achieve this, we need to refer to the Java coding standards and review our code to make sure if it is as per the standards. But sometimes we are not having the time to actually review the code due to deadline constraints. In such cases, we are providing some tips which a developer can keep in mind while doing coding of any requirement so that he/she needs to make minimal changes to code for fixing the performance during the testing phase or before moving the same to production. The methods should not be too long and should be specific to perform single functionality. It is better for maintenance as well as performance since while class loading and during method call, the method is loaded in stack memory. If methods are large with too much processing it will consume memory as well as CPU cycles to execute. Try to break the methods into smaller ones at suitable logical points. We use conditional statements in our code for decision-making. The conditional statements should not be overused. If we are using too much conditional if-else statements it will impact performance since JVM will have to compare the conditions. This can become worse if the same are used in looping statements like for, while etc. If there are too many conditions in your business logic try to group the conditions and get the boolean outcome and use it in if statement. Also, we can think of using switch statement instead of multiple if-else if possible. Switch statement has performance advantage over if – else. The sample is provided below as an illustration which is to be avoided as follows: Illustration: if (condition1) { if (condition2) { if (condition3 || condition4) { execute ..} else { execute..} Note: Above sample is to be avoided and use this as follows: boolean result = (condition1 && condition2) && (condition3 || condition4) While iterating through any collection get the size of the collection beforehand and never get it during iteration. The sample is provided below as an illustration which is to be avoided as follows: Illustration: List<String> objList = getData(); for (int i = 0; i < objList.size(); i++) { execute code ..} Note: Above sample is to be avoided and use this as follows: List<String> objList = getData(); int size = objList.size(); for (int i = 0; i < size; i++) { execute code ..} String is an immutable class the object created of String cannot be reused. So if we need to create a large string in case of SQL queries etc it is bad practice to concatenate the String object using the ‘+’ operator. This will lead to multiple objects of String created leading to more usage of heap memory. In this case, we can use StringBuilder or StringBuffer, the former is preferential over the latter since it has a performance advantage due to non-synchronized methods. The sample is provided below as an illustration which is to be avoided as follows: Illustration: String query = String1+String2+String3; Note: Above sample is to be avoided and use this as follows: StringBuilder strBuilder = new StringBuilder(“”); strBuilder.append(String1).append(String2).append(String3); String query = strBuilder.toString(); Usage of primitive types over objects is beneficial since the primitive type data is stored on stack memory and the objects are stored on heap memory. If possible, we can use primitive types instead of objects since data access from stack memory is faster than heap memory. So it is always beneficial to use int over Integer or double over Double. We know that BigDecimal class provides the accurate precision for the decimal values. Over usage of this object hampers the performance drastically specifically when the same is used to calculate certain values in a loop. BigDecimal uses a lot of memory over long or double to perform calculations. If precision is not the constraint or if we are sure the range of the calculated value will not exceed long or double we can avoid using BigDecimal and use long or double with proper casting instead. There are certain classes which act as data holder within the application. These objects are heavy and their creation should be avoided multiple times. An example of such objects is the DB connection objects or system configuration objects or session objects for the user after login. These objects used a lot of resources while creating. We should reuse these objects instead of creation as creation will drastically hamper the application performance due to more memory usage. We should use the Singleton pattern wherever possible to create a single instance of the object and reuse it wherever required or either clone the object instead of creating a new one. It is better to write stored procedures instead of complex and long queries and call them while processing. Stored procedures are stored as objects in the database and pre-compiled. The execution time of the stored procedure is less compared to the query with the same business logic as a query is compiled and executed every time wherever it is called through the application. Also, stored procedure has an advantage in data transfer and network traffic since we are not transferring the complex query for execution every time to the database server. While executing the SQL query through the application we use JDBC API and classes for same. PreparedStatement has advantage over Statement for parameterized query execution since preparedstatement object is compiled once and executed multiple times. Statement object on other hand is compiled and executed every time it is called. Also, preparedstatement object is safe to avoid SQL injection attacks for Web Application security. Logging is an integral part of any application and needs to be implemented efficiently in order to avoid performance hits due to incorrect logging and log levels. We should avoid logging big objects into code. Logging should be limited to specific parameters we need to monitor and not the whole object. Also, the logging level should be kept to higher levels like DEBUG, ERROR, and not INFO. The sample is provided below as an illustration which is to be avoided as follows: Illustration: Logger.debug("User info : " + user.toString()); Logger.info("Method called for setting user data:" + user.getData()); Note: Above sample is to be avoided and use this as follows: Logger.debug(“User info : ” + user.getName() + ” : login ID : ” + user.getLoginId()); Logger.info(“Method called for setting user data”); While getting the data from database we use select query to get the data. Avoid selecting columns that are not necessary for further processing. Select only those columns which we will be required for further processing or display on the front end. Selecting too many columns causes a delay in query execution at the database end. Also, it increases network traffic from database to application which should be avoided. The sample is provided below as an illustration which is to be avoided as follows: Illustration: select * from users where user_id = 100; Note: Above sample is to be avoided and use this as follows: select user_name, user_age, user_gender, user_occupation, user_address from users where user_id = 100; While getting the data from multiple tables it is necessary to use the joins properly on tables. If the joins are not properly used or the tables are not normalized it will cause a delay in query execution leading to the performance hit for the application. Avoid using subqueries instead of joins as subqueries take more time for execution than joins. Create an index on columns of the table which are frequently used for improving the performance of query execution and reduce latency of the application. gabaa406 GBlog Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Front End Developer Skills That You Need in 2022 DSA Sheet by Love Babbar 6 Best IDE's For Python in 2022 GET and POST requests using Python Top 10 Projects For Beginners To Practice HTML and CSS Skills Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 24921, "s": 24893, "text": "\n18 Aug, 2021" }, { "code": null, "e": 25321, "s": 24921, "text": "While working on any Java application we come across the concept of optimization. It is necessary that the code which we are writing is not only clean, without defects but also optimized i.e. the time taken by the code to execute should be within intended limits. In order to achieve this, we need to refer to the Java coding standards and review our code to make sure if it is as per the standards." }, { "code": null, "e": 25680, "s": 25321, "text": "But sometimes we are not having the time to actually review the code due to deadline constraints. In such cases, we are providing some tips which a developer can keep in mind while doing coding of any requirement so that he/she needs to make minimal changes to code for fixing the performance during the testing phase or before moving the same to production." }, { "code": null, "e": 26085, "s": 25680, "text": "The methods should not be too long and should be specific to perform single functionality. It is better for maintenance as well as performance since while class loading and during method call, the method is loaded in stack memory. If methods are large with too much processing it will consume memory as well as CPU cycles to execute. Try to break the methods into smaller ones at suitable logical points." }, { "code": null, "e": 26783, "s": 26085, "text": "We use conditional statements in our code for decision-making. The conditional statements should not be overused. If we are using too much conditional if-else statements it will impact performance since JVM will have to compare the conditions. This can become worse if the same are used in looping statements like for, while etc. If there are too many conditions in your business logic try to group the conditions and get the boolean outcome and use it in if statement. Also, we can think of using switch statement instead of multiple if-else if possible. Switch statement has performance advantage over if – else. The sample is provided below as an illustration which is to be avoided as follows:" }, { "code": null, "e": 26797, "s": 26783, "text": "Illustration:" }, { "code": null, "e": 26918, "s": 26797, "text": "if (condition1) {\n\n if (condition2) {\n\n if (condition3 || condition4) { execute ..}\n\n else { execute..}" }, { "code": null, "e": 26979, "s": 26918, "text": "Note: Above sample is to be avoided and use this as follows:" }, { "code": null, "e": 27056, "s": 26979, "text": "boolean result = (condition1 && condition2) && (condition3 || condition4) " }, { "code": null, "e": 27255, "s": 27056, "text": "While iterating through any collection get the size of the collection beforehand and never get it during iteration. The sample is provided below as an illustration which is to be avoided as follows:" }, { "code": null, "e": 27269, "s": 27255, "text": "Illustration:" }, { "code": null, "e": 27363, "s": 27269, "text": "List<String> objList = getData();\nfor (int i = 0; i < objList.size(); i++) { execute code ..}" }, { "code": null, "e": 27424, "s": 27363, "text": "Note: Above sample is to be avoided and use this as follows:" }, { "code": null, "e": 27536, "s": 27424, "text": "List<String> objList = getData();\nint size = objList.size();\nfor (int i = 0; i < size; i++) { execute code ..} " }, { "code": null, "e": 28097, "s": 27536, "text": "String is an immutable class the object created of String cannot be reused. So if we need to create a large string in case of SQL queries etc it is bad practice to concatenate the String object using the ‘+’ operator. This will lead to multiple objects of String created leading to more usage of heap memory. In this case, we can use StringBuilder or StringBuffer, the former is preferential over the latter since it has a performance advantage due to non-synchronized methods. The sample is provided below as an illustration which is to be avoided as follows:" }, { "code": null, "e": 28111, "s": 28097, "text": "Illustration:" }, { "code": null, "e": 28152, "s": 28111, "text": " String query = String1+String2+String3;" }, { "code": null, "e": 28213, "s": 28152, "text": "Note: Above sample is to be avoided and use this as follows:" }, { "code": null, "e": 28263, "s": 28213, "text": "StringBuilder strBuilder = new StringBuilder(“”);" }, { "code": null, "e": 28323, "s": 28263, "text": "strBuilder.append(String1).append(String2).append(String3);" }, { "code": null, "e": 28373, "s": 28323, "text": "String query = strBuilder.toString(); " }, { "code": null, "e": 28721, "s": 28373, "text": "Usage of primitive types over objects is beneficial since the primitive type data is stored on stack memory and the objects are stored on heap memory. If possible, we can use primitive types instead of objects since data access from stack memory is faster than heap memory. So it is always beneficial to use int over Integer or double over Double." }, { "code": null, "e": 29220, "s": 28721, "text": "We know that BigDecimal class provides the accurate precision for the decimal values. Over usage of this object hampers the performance drastically specifically when the same is used to calculate certain values in a loop. BigDecimal uses a lot of memory over long or double to perform calculations. If precision is not the constraint or if we are sure the range of the calculated value will not exceed long or double we can avoid using BigDecimal and use long or double with proper casting instead." }, { "code": null, "e": 29884, "s": 29220, "text": "There are certain classes which act as data holder within the application. These objects are heavy and their creation should be avoided multiple times. An example of such objects is the DB connection objects or system configuration objects or session objects for the user after login. These objects used a lot of resources while creating. We should reuse these objects instead of creation as creation will drastically hamper the application performance due to more memory usage. We should use the Singleton pattern wherever possible to create a single instance of the object and reuse it wherever required or either clone the object instead of creating a new one." }, { "code": null, "e": 30436, "s": 29884, "text": "It is better to write stored procedures instead of complex and long queries and call them while processing. Stored procedures are stored as objects in the database and pre-compiled. The execution time of the stored procedure is less compared to the query with the same business logic as a query is compiled and executed every time wherever it is called through the application. Also, stored procedure has an advantage in data transfer and network traffic since we are not transferring the complex query for execution every time to the database server." }, { "code": null, "e": 30867, "s": 30436, "text": "While executing the SQL query through the application we use JDBC API and classes for same. PreparedStatement has advantage over Statement for parameterized query execution since preparedstatement object is compiled once and executed multiple times. Statement object on other hand is compiled and executed every time it is called. Also, preparedstatement object is safe to avoid SQL injection attacks for Web Application security." }, { "code": null, "e": 31343, "s": 30867, "text": "Logging is an integral part of any application and needs to be implemented efficiently in order to avoid performance hits due to incorrect logging and log levels. We should avoid logging big objects into code. Logging should be limited to specific parameters we need to monitor and not the whole object. Also, the logging level should be kept to higher levels like DEBUG, ERROR, and not INFO. The sample is provided below as an illustration which is to be avoided as follows:" }, { "code": null, "e": 31357, "s": 31343, "text": "Illustration:" }, { "code": null, "e": 31475, "s": 31357, "text": "Logger.debug(\"User info : \" + user.toString());\nLogger.info(\"Method called for setting user data:\" + user.getData());" }, { "code": null, "e": 31536, "s": 31475, "text": "Note: Above sample is to be avoided and use this as follows:" }, { "code": null, "e": 31622, "s": 31536, "text": "Logger.debug(“User info : ” + user.getName() + ” : login ID : ” + user.getLoginId());" }, { "code": null, "e": 31674, "s": 31622, "text": "Logger.info(“Method called for setting user data”);" }, { "code": null, "e": 32177, "s": 31674, "text": "While getting the data from database we use select query to get the data. Avoid selecting columns that are not necessary for further processing. Select only those columns which we will be required for further processing or display on the front end. Selecting too many columns causes a delay in query execution at the database end. Also, it increases network traffic from database to application which should be avoided. The sample is provided below as an illustration which is to be avoided as follows:" }, { "code": null, "e": 32191, "s": 32177, "text": "Illustration:" }, { "code": null, "e": 32232, "s": 32191, "text": "select * from users where user_id = 100;" }, { "code": null, "e": 32293, "s": 32232, "text": "Note: Above sample is to be avoided and use this as follows:" }, { "code": null, "e": 32396, "s": 32293, "text": "select user_name, user_age, user_gender, user_occupation, user_address from users where user_id = 100;" }, { "code": null, "e": 32903, "s": 32396, "text": "While getting the data from multiple tables it is necessary to use the joins properly on tables. If the joins are not properly used or the tables are not normalized it will cause a delay in query execution leading to the performance hit for the application. Avoid using subqueries instead of joins as subqueries take more time for execution than joins. Create an index on columns of the table which are frequently used for improving the performance of query execution and reduce latency of the application." }, { "code": null, "e": 32912, "s": 32903, "text": "gabaa406" }, { "code": null, "e": 32918, "s": 32912, "text": "GBlog" }, { "code": null, "e": 32923, "s": 32918, "text": "Java" }, { "code": null, "e": 32928, "s": 32923, "text": "Java" }, { "code": null, "e": 33026, "s": 32928, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33035, "s": 33026, "text": "Comments" }, { "code": null, "e": 33048, "s": 33035, "text": "Old Comments" }, { "code": null, "e": 33104, "s": 33048, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 33129, "s": 33104, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 33161, "s": 33129, "text": "6 Best IDE's For Python in 2022" }, { "code": null, "e": 33196, "s": 33161, "text": "GET and POST requests using Python" }, { "code": null, "e": 33258, "s": 33196, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33273, "s": 33258, "text": "Arrays in Java" }, { "code": null, "e": 33317, "s": 33273, "text": "Split() String method in Java with examples" }, { "code": null, "e": 33339, "s": 33317, "text": "For-each loop in Java" }, { "code": null, "e": 33364, "s": 33339, "text": "Reverse a string in Java" } ]
List indexOf() Method in Java with Examples - GeeksforGeeks
02 Jan, 2019 This method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Syntax: public int indexOf(Object o) Parameters: This function has a single parameter, i.e, the element to be searched in the list. Returns: This method returns the index of first occurrence of the given element in the list and returns “-1” if element is not in the list. Below programs show the implementation of this method. Program 1: // Java code to show the implementation of// indexOf method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a list of type Linkedlist List<Integer> l = new LinkedList<>(); l.add(1); l.add(3); l.add(5); l.add(7); System.out.println(l); System.out.println(l.indexOf(5)); }} [1, 3, 5, 7] 2 Program 2: Below is the code to show implementation of list.hashCode() using Linkedlist. // Java code to show the implementation of// indexOf method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a list of type Linkedlist List<String> l = new LinkedList<>(); l.add("10"); l.add("15"); l.add("20"); System.out.println(l); System.out.println(l.indexOf("20")); }} [10, 15, 20] 2 Reference:Oracle Docs Java - util package Java-Collections Java-Functions java-list Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java LinkedList in Java
[ { "code": null, "e": 24583, "s": 24555, "text": "\n02 Jan, 2019" }, { "code": null, "e": 24725, "s": 24583, "text": "This method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element." }, { "code": null, "e": 24733, "s": 24725, "text": "Syntax:" }, { "code": null, "e": 24762, "s": 24733, "text": "public int indexOf(Object o)" }, { "code": null, "e": 24857, "s": 24762, "text": "Parameters: This function has a single parameter, i.e, the element to be searched in the list." }, { "code": null, "e": 24997, "s": 24857, "text": "Returns: This method returns the index of first occurrence of the given element in the list and returns “-1” if element is not in the list." }, { "code": null, "e": 25052, "s": 24997, "text": "Below programs show the implementation of this method." }, { "code": null, "e": 25063, "s": 25052, "text": "Program 1:" }, { "code": "// Java code to show the implementation of// indexOf method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a list of type Linkedlist List<Integer> l = new LinkedList<>(); l.add(1); l.add(3); l.add(5); l.add(7); System.out.println(l); System.out.println(l.indexOf(5)); }}", "e": 25486, "s": 25063, "text": null }, { "code": null, "e": 25502, "s": 25486, "text": "[1, 3, 5, 7]\n2\n" }, { "code": null, "e": 25591, "s": 25502, "text": "Program 2: Below is the code to show implementation of list.hashCode() using Linkedlist." }, { "code": "// Java code to show the implementation of// indexOf method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a list of type Linkedlist List<String> l = new LinkedList<>(); l.add(\"10\"); l.add(\"15\"); l.add(\"20\"); System.out.println(l); System.out.println(l.indexOf(\"20\")); }}", "e": 26008, "s": 25591, "text": null }, { "code": null, "e": 26024, "s": 26008, "text": "[10, 15, 20]\n2\n" }, { "code": null, "e": 26046, "s": 26024, "text": "Reference:Oracle Docs" }, { "code": null, "e": 26066, "s": 26046, "text": "Java - util package" }, { "code": null, "e": 26083, "s": 26066, "text": "Java-Collections" }, { "code": null, "e": 26098, "s": 26083, "text": "Java-Functions" }, { "code": null, "e": 26108, "s": 26098, "text": "java-list" }, { "code": null, "e": 26113, "s": 26108, "text": "Java" }, { "code": null, "e": 26118, "s": 26113, "text": "Java" }, { "code": null, "e": 26135, "s": 26118, "text": "Java-Collections" }, { "code": null, "e": 26233, "s": 26135, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26242, "s": 26233, "text": "Comments" }, { "code": null, "e": 26255, "s": 26242, "text": "Old Comments" }, { "code": null, "e": 26306, "s": 26255, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26336, "s": 26306, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26367, "s": 26336, "text": "How to iterate any Map in Java" }, { "code": null, "e": 26399, "s": 26367, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26418, "s": 26399, "text": "Interfaces in Java" }, { "code": null, "e": 26436, "s": 26418, "text": "ArrayList in Java" }, { "code": null, "e": 26468, "s": 26436, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26488, "s": 26468, "text": "Stack Class in Java" }, { "code": null, "e": 26512, "s": 26488, "text": "Singleton Class in Java" } ]
Definition and Properties of Trees
Tree is a discrete structure that represents hierarchical relationships between individual elements or nodes. A tree in which a parent has no more than two children is called a binary tree. Definition − A Tree is a connected acyclic undirected graph. There is a unique path between every pair of vertices in G. A tree with N number of vertices contains (N-1) number of edges. The vertex which is of 0 degree is called root of the tree. The vertex which is of 1 degree is called leaf node of the tree and the degree of an internal node is at least 2. Example − The following is an example of a tree − The center of a tree is a vertex with minimal eccentricity. The eccentricity of a vertex X in a tree G is the maximum distance between the vertex X and any other vertex of the tree. The maximum eccentricity is the tree diameter. If a tree has only one center, it is called Central Tree and if a tree has only more than one centers, it is called Bi-central Tree. Every tree is either central or bi-central. Definition − A labeled tree is a tree the vertices of which are assigned unique numbers from 1 to n. We can count such trees for small values of n by hand so as to conjecture a general formula. The number of labeled trees of n number of vertices is nn-2. Two labeled trees are isomorphic if their graphs are isomorphic and the corresponding points of the two trees have the same labels. Definition − An unlabeled tree is a tree the vertices of which are not assigned any numbers. The number of labeled trees of n number of vertices is (2n)!(n+1)!n! (nth Catalan number) A rooted tree G is a connected acyclic graph with a special node that is called the root of the tree and every edge directly or indirectly originates from the root. An ordered rooted tree is a rooted tree where the children of each internal vertex are ordered. If every internal vertex of a rooted tree has not more than m children, it is called an m-ary tree. If every internal vertex of a rooted tree has exactly m children, it is called a full m-ary tree. If m = 2, the rooted tree is called a binary tree. Binary Search tree is a binary tree which satisfies the following property − X in left sub-tree of vertex V, Value(X) ≤ Value (V) Y in right sub-tree of vertex V, Value(Y) ≥ Value (V) So, the value of all the vertices of the left sub-tree of an internal node V are less than or equal to V and the value of all the vertices of the right sub-tree of the internal node V are greater than or equal to V. The number of links from the root node to the deepest node is the height of the Binary Search Tree. BST_Search(x, k) if ( x = NIL or k = Value[x] ) return x; if ( k < Value[x]) return BST_Search (left[x], k); else return BST_Search (right[x], k)
[ { "code": null, "e": 1252, "s": 1062, "text": "Tree is a discrete structure that represents hierarchical relationships between individual elements or nodes. A tree in which a parent has no more than two children is called a binary tree." }, { "code": null, "e": 1612, "s": 1252, "text": "Definition − A Tree is a connected acyclic undirected graph. There is a unique path between every pair of vertices in G. A tree with N number of vertices contains (N-1) number of edges. The vertex which is of 0 degree is called root of the tree. The vertex which is of 1 degree is called leaf node of the tree and the degree of an internal node is at least 2." }, { "code": null, "e": 1662, "s": 1612, "text": "Example − The following is an example of a tree −" }, { "code": null, "e": 2068, "s": 1662, "text": "The center of a tree is a vertex with minimal eccentricity. The eccentricity of a vertex X in a tree G is the maximum distance between the vertex X and any other vertex of the tree. The maximum eccentricity is the tree diameter. If a tree has only one center, it is called Central Tree and if a tree has only more than one centers, it is called Bi-central Tree. Every tree is either central or bi-central." }, { "code": null, "e": 2455, "s": 2068, "text": "Definition − A labeled tree is a tree the vertices of which are assigned unique numbers from 1 to n. We can count such trees for small values of n by hand so as to conjecture a general formula. The number of labeled trees of n number of vertices is nn-2. Two labeled trees are isomorphic if their graphs are isomorphic and the corresponding points of the two trees have the same labels." }, { "code": null, "e": 2638, "s": 2455, "text": "Definition − An unlabeled tree is a tree the vertices of which are not assigned any numbers. The number of labeled trees of n number of vertices is (2n)!(n+1)!n! (nth Catalan number)" }, { "code": null, "e": 3148, "s": 2638, "text": "A rooted tree G is a connected acyclic graph with a special node that is called the root of the tree and every edge directly or indirectly originates from the root. An ordered rooted tree is a rooted tree where the children of each internal vertex are ordered. If every internal vertex of a rooted tree has not more than m children, it is called an m-ary tree. If every internal vertex of a rooted tree has exactly m children, it is called a full m-ary tree. If m = 2, the rooted tree is called a binary tree." }, { "code": null, "e": 3225, "s": 3148, "text": "Binary Search tree is a binary tree which satisfies the following property −" }, { "code": null, "e": 3278, "s": 3225, "text": "X in left sub-tree of vertex V, Value(X) ≤ Value (V)" }, { "code": null, "e": 3332, "s": 3278, "text": "Y in right sub-tree of vertex V, Value(Y) ≥ Value (V)" }, { "code": null, "e": 3648, "s": 3332, "text": "So, the value of all the vertices of the left sub-tree of an internal node V are less than or equal to V and the value of all the vertices of the right sub-tree of the internal node V are greater than or equal to V. The number of links from the root node to the deepest node is the height of the Binary Search Tree." }, { "code": null, "e": 3803, "s": 3648, "text": "BST_Search(x, k)\nif ( x = NIL or k = Value[x] )\n return x;\nif ( k < Value[x])\n return BST_Search (left[x], k);\nelse\n return BST_Search (right[x], k)" } ]
Find position of set bit | Practice | GeeksforGeeks
Given a number N having only one ‘1’ and all other ’0’s in its binary representation, find position of the only set bit. If there are 0 or more than 1 set bit the answer should be -1. Position of set bit '1' should be counted starting with 1 from LSB side in binary representation of the number. Example 1: Input: N = 2 Output: 2 Explanation: 2 is represented as "10" in Binary. As we see there's only one set bit and it's in Position 2 and thus the Output 2. Example 2: Input: N = 5 Output: -1 Explanation: 5 is represented as "101" in Binary. As we see there's two set bits and thus the Output -1. Your Task: You don't need to read input or print anything. Your task is to complete the function findPosition() which takes an integer N as input and returns the answer. Expected Time Complexity: O(log(N)) Expected Auxiliary Space: O(1) Constraints: 0 <= N <= 108 0 aamchicoder2 days ago int findPosition(int N) { // code here if(N && !(N & N-1)){ return log2(N)+1; } return -1; } +1 shreepadbhuvad7914 days ago Easy java solution class Solution { static int findPosition(int N) { if(N==0)return -1; int b= N & (N-1); if(b==0){ int ans=(int)(Math.log(N) / Math.log(2)); return ans+1; } return -1; }}; 0 amarrajsmart1976 days ago int setbitcount(int n) { int count=0; while(n!=0) { n=n&(n-1); count++; } return count; } int findPosition(int N) { // code here if(setbitcount(N)>1||setbitcount(N)<1) { return -1; } int i=0; while(N) { i++; N=N>>1; } return i; } 0 rohanmeher1641 week ago class Solution { static int findPosition(int N) { int curr=1; int p=-1; int bit=0; while(N!=0) { if((N&1)==1) {p=curr; bit++; } if(bit>1) { p=-1; break; } N=N>>1; curr++; } return p; }} +1 ayushrkacholia1 week ago class Solution { public: int findPosition(int N) { if(N==0){ return -1; } int k = N; int pos =0; int c =0; while(k){ k=k&(k-1); c++; if(c>1){ return -1; } } while(N){ pos++; N=N>>1; } return pos; }}; Time taken = 0.01/1.12 +1 himanshukug19cs2 weeks ago if(N==0) return -1; int n=1; while(N>0&&(N&1)==0){ n++; N=N>>1; } N=N>>1; if(N!=0) return -1; else return n; 0 garvitchawla9122 weeks ago class Solution { static int findPosition(int N) { // code here if((N&(N-1))!=0)return -1; int res=1; for(int i=N;i>=0;i/=2){ if(i%2==0)res++; else break; } return res; }}; +1 negisachinsingh4 weeks ago int findPosition(int N) { // code here int k; k=log(N)/log(2); if(N==0) return -1; if((N & N-1) == 0) //while using this take care of N=0 case; return k+1; else return -1; } 0 sakesai301 month ago static int findPosition(int N) { if(N==1) return 1; if(N%2 != 0) return -1; int k = 0; int max =0; for(int i =N;i>0;i/=2){ if(i%2!=0) max++; k++; if(max>1) return -1; } if(k==0) return -1; return k; } 0 milindprajapatmst191 month ago class Solution { public: int findPosition(int N) { if (N == 0 || N & (N - 1)) return -1; int result, pos = 1; while (N) { if (N & 1) result = pos; pos++; N >>= 1; } return result; } }; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 535, "s": 238, "text": "Given a number N having only one ‘1’ and all other ’0’s in its binary representation, find position of the only set bit. If there are 0 or more than 1 set bit the answer should be -1. Position of set bit '1' should be counted starting with 1 from LSB side in binary representation of the number." }, { "code": null, "e": 546, "s": 535, "text": "Example 1:" }, { "code": null, "e": 699, "s": 546, "text": "Input:\nN = 2\nOutput:\n2\nExplanation:\n2 is represented as \"10\" in Binary.\nAs we see there's only one set bit\nand it's in Position 2 and thus the\nOutput 2." }, { "code": null, "e": 710, "s": 699, "text": "Example 2:" }, { "code": null, "e": 840, "s": 710, "text": "Input:\nN = 5\nOutput:\n-1\nExplanation:\n5 is represented as \"101\" in Binary.\nAs we see there's two set bits\nand thus the Output -1.\n" }, { "code": null, "e": 1010, "s": 840, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function findPosition() which takes an integer N as input and returns the answer." }, { "code": null, "e": 1077, "s": 1010, "text": "Expected Time Complexity: O(log(N))\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1104, "s": 1077, "text": "Constraints:\n0 <= N <= 108" }, { "code": null, "e": 1106, "s": 1104, "text": "0" }, { "code": null, "e": 1128, "s": 1106, "text": "aamchicoder2 days ago" }, { "code": null, "e": 1257, "s": 1128, "text": "int findPosition(int N) { // code here if(N && !(N & N-1)){ return log2(N)+1; } return -1; }" }, { "code": null, "e": 1260, "s": 1257, "text": "+1" }, { "code": null, "e": 1288, "s": 1260, "text": "shreepadbhuvad7914 days ago" }, { "code": null, "e": 1307, "s": 1288, "text": "Easy java solution" }, { "code": null, "e": 1524, "s": 1309, "text": "class Solution { static int findPosition(int N) { if(N==0)return -1; int b= N & (N-1); if(b==0){ int ans=(int)(Math.log(N) / Math.log(2)); return ans+1; } return -1; }};" }, { "code": null, "e": 1526, "s": 1524, "text": "0" }, { "code": null, "e": 1552, "s": 1526, "text": "amarrajsmart1976 days ago" }, { "code": null, "e": 1908, "s": 1552, "text": " int setbitcount(int n) { int count=0; while(n!=0) { n=n&(n-1); count++; } return count; } int findPosition(int N) { // code here if(setbitcount(N)>1||setbitcount(N)<1) { return -1; } int i=0; while(N) { i++; N=N>>1; } return i; }" }, { "code": null, "e": 1910, "s": 1908, "text": "0" }, { "code": null, "e": 1934, "s": 1910, "text": "rohanmeher1641 week ago" }, { "code": null, "e": 2309, "s": 1934, "text": "class Solution { static int findPosition(int N) { int curr=1; int p=-1; int bit=0; while(N!=0) { if((N&1)==1) {p=curr; bit++; } if(bit>1) { p=-1; break; } N=N>>1; curr++; } return p; }}" }, { "code": null, "e": 2312, "s": 2309, "text": "+1" }, { "code": null, "e": 2337, "s": 2312, "text": "ayushrkacholia1 week ago" }, { "code": null, "e": 2699, "s": 2337, "text": "class Solution { public: int findPosition(int N) { if(N==0){ return -1; } int k = N; int pos =0; int c =0; while(k){ k=k&(k-1); c++; if(c>1){ return -1; } } while(N){ pos++; N=N>>1; } return pos; }};" }, { "code": null, "e": 2724, "s": 2701, "text": "Time taken = 0.01/1.12" }, { "code": null, "e": 2727, "s": 2724, "text": "+1" }, { "code": null, "e": 2754, "s": 2727, "text": "himanshukug19cs2 weeks ago" }, { "code": null, "e": 2951, "s": 2754, "text": " if(N==0) return -1; int n=1; while(N>0&&(N&1)==0){ n++; N=N>>1; } N=N>>1; if(N!=0) return -1; else return n;" }, { "code": null, "e": 2953, "s": 2951, "text": "0" }, { "code": null, "e": 2980, "s": 2953, "text": "garvitchawla9122 weeks ago" }, { "code": null, "e": 3218, "s": 2980, "text": "class Solution { static int findPosition(int N) { // code here if((N&(N-1))!=0)return -1; int res=1; for(int i=N;i>=0;i/=2){ if(i%2==0)res++; else break; } return res; }};" }, { "code": null, "e": 3221, "s": 3218, "text": "+1" }, { "code": null, "e": 3248, "s": 3221, "text": "negisachinsingh4 weeks ago" }, { "code": null, "e": 3459, "s": 3248, "text": "int findPosition(int N) { // code here int k; k=log(N)/log(2); if(N==0) return -1; if((N & N-1) == 0) //while using this take care of N=0 case; return k+1; else return -1;" }, { "code": null, "e": 3478, "s": 3459, "text": " }" }, { "code": null, "e": 3480, "s": 3478, "text": "0" }, { "code": null, "e": 3501, "s": 3480, "text": "sakesai301 month ago" }, { "code": null, "e": 3782, "s": 3501, "text": "static int findPosition(int N) { if(N==1) return 1; if(N%2 != 0) return -1; int k = 0; int max =0; for(int i =N;i>0;i/=2){ if(i%2!=0) max++; k++; if(max>1) return -1; } if(k==0) return -1; return k; }" }, { "code": null, "e": 3784, "s": 3782, "text": "0" }, { "code": null, "e": 3815, "s": 3784, "text": "milindprajapatmst191 month ago" }, { "code": null, "e": 4098, "s": 3815, "text": "class Solution {\n public:\n int findPosition(int N) {\n if (N == 0 || N & (N - 1))\n return -1;\n int result, pos = 1;\n while (N) {\n if (N & 1) result = pos;\n pos++;\n N >>= 1;\n }\n return result;\n }\n};" }, { "code": null, "e": 4244, "s": 4098, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 4280, "s": 4244, "text": " Login to access your submissions. " }, { "code": null, "e": 4290, "s": 4280, "text": "\nProblem\n" }, { "code": null, "e": 4300, "s": 4290, "text": "\nContest\n" }, { "code": null, "e": 4363, "s": 4300, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4511, "s": 4363, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 4719, "s": 4511, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 4825, "s": 4719, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Java Program to convert integer to boolean
To convert integer to boolean, firstly let us initialize an integer. int val = 100; Now we will declare a variable with primitive boolean. While declaration, we will initialize it with the val value comparing it with an integer using the == operator. If the value matches, the value “True” is returned, else “False” is returned. boolean bool = (val == 100); Let us now see the complete example displaying how to convert integer to boolean. Live Demo public class Demo { public static void main(String[] args) { int val = 100; System.out.println("Integer: "+val); boolean bool = (val == 100); System.out.println("Converted to Bool: "+bool); } } Integer: 100 Converted to Bool: true
[ { "code": null, "e": 1131, "s": 1062, "text": "To convert integer to boolean, firstly let us initialize an integer." }, { "code": null, "e": 1146, "s": 1131, "text": "int val = 100;" }, { "code": null, "e": 1391, "s": 1146, "text": "Now we will declare a variable with primitive boolean. While declaration, we will initialize it with the val value comparing it with an integer using the == operator. If the value matches, the value “True” is returned, else “False” is returned." }, { "code": null, "e": 1420, "s": 1391, "text": "boolean bool = (val == 100);" }, { "code": null, "e": 1502, "s": 1420, "text": "Let us now see the complete example displaying how to convert integer to boolean." }, { "code": null, "e": 1513, "s": 1502, "text": " Live Demo" }, { "code": null, "e": 1737, "s": 1513, "text": "public class Demo {\n public static void main(String[] args) {\n int val = 100;\n System.out.println(\"Integer: \"+val);\n boolean bool = (val == 100);\n System.out.println(\"Converted to Bool: \"+bool);\n }\n}" }, { "code": null, "e": 1774, "s": 1737, "text": "Integer: 100\nConverted to Bool: true" } ]
Prefix match with other strings | Practice | GeeksforGeeks
Given an array of strings arr[] of size n and given s a string str and an integer k. The task is to find the count of strings in arr[] whose prefix of length k matches with the k length prefix of str. Example 1: Input: n = 6 arr[] = {“abba”, “abbb”, “abbc”, “abbd”, “abaa”, “abca”} str = “abbg” k = 3 Output: 4 Explanation: “abba”, “abbb”, “abbc” and “abbd” are the matching strings. Example 2: Input: n = 3 arr[] = {“geeks”, “geeksforgeeks”, “forgeeks”} str = “geeks” k = 2 Output: 2 Your Task: You don't need to read input or print anything. Your task is to complete the function klengthpref() which takes the array of strings arr[], its size n and an integer k, a string str as input parameters and returns the count of strings in arr[] whose prefix of length k matches with the k length prefix of str. Expected Time Complexity: O(n*l) where l is the length of the longest word in arr[]. Expected Auxiliary Space: O(n*l) where l is the length of the longest word in arr[]. Constraints: 1 <= n <= 1000 1 <= |arr[i]| , |str| <= 1000 1 <= k <= 1000 arr[i], str must contain only lowercase english alphabets 0 2017cstarun57053 days ago nodeJS return arr.map((i)=>{ return i.substring(0,k) === str.substring(0,k) ? 1 : 0 }).filter((j)=>{ return j === 1 }).length 0 artistdarkangel1 week ago Java Simple Solution | No need to use Trie concept. class Solution{ public int klengthpref(String[] arr, int n, int k, String str) { str=str.substring(0,k); int count=0; for(int i=0; i<n; i++) { if(arr[i].length()<k) continue; String temp = arr[i].substring(0,k); if(temp.equals(str)) count++; } return count; }} 0 rishavkumar44121 week ago Why am i getting wrong ans on submitting ? class node{ node link[]=new node[26]; int cntstartwith; node(){ cntstartwith=0; for(int i=0;i<26;i++){ link[i]=null; } }} class Solution{ public void insert(node root,String key){ int index; node temp=root; for(int i=0;i<key.length();i++){ index=key.charAt(i)-'a'; if(temp.link[index]==null){ temp.link[index]=new node(); temp.cntstartwith++; } temp=temp.link[index]; } } public int klengthpref(String[] arr, int n, int k, String str) { // code here node root=new node(); for(int i=0;i<n;i++){ insert(root,arr[i]); } int index; node temp=root; for(int i=0;i<k;i++){ index=str.charAt(i)-'a'; if(temp.link[index]==null){ return 0; }else{ temp=temp.link[index]; } } return temp.cntstartwith; }} 0 kshitijmagare193 weeks ago Total Time Taken: 0.7/8.61 JAVA : public int klengthpref(String[] arr, int n, int k, String str) { // code here String s = ""; for(int i = 0; i<k;i++){ s+=str.charAt(i); } //System.out.println(s); int count = 0; boolean b; for(int i = 0; i< n;i++){ b = arr[i].startsWith(s); if(b == true){ count++; } } return count; } 0 creator23031 month ago Easy C++ Solution :) int klengthpref(string arr[], int n, int k, string str){ string pat ; int t=k; for(int i=0 ;i<str.size();i++) { if(k==0) break; pat+=str[i] ; k-- ; } int cnt =0 ; k=t; for(int i=0 ;i<n;i++) { if(arr[i].substr(0, k) == pat) cnt++; } return cnt; } 0 himanshujain4572 months ago Java Solution Using Trie: class Solution{ class TrieNode{ int count=0; TrieNode child[]=new TrieNode[26]; TrieNode() { count=0; for(int i=0;i<26;i++) { child[i]=null; } } } TrieNode root=new TrieNode(); void BuildTrie(String[] arr, int n) { for(int i=0;i<n;i++) { String s=arr[i]; TrieNode temp=root; for(int k=0;k<s.length();k++) { char ch=s.charAt(k); if(temp.child[ch-'a']==null) { temp.child[ch-'a']=new TrieNode(); } temp=temp.child[ch-'a']; temp.count++; } } } public int klengthpref(String[] arr, int n, int k, String str) { BuildTrie(arr,n); TrieNode temp=root; for(int i=0;i<k;i++) { char ch=str.charAt(i); if(temp.child[ch-'a']==null) { return 0; } temp=temp.child[ch-'a']; } return temp.count; }} 0 paurushbatish2 months ago Easy Solution using Trie Data Structure Total Time Taken: 0.2/2.2 #define f(i,a,b) for(int i = a;i<b;i++) struct Node { int freq; Node* child[26]; Node(){ freq = 1; f(i,0,26)child[i] = NULL; } }; class Solution{ public: Node* t = new Node(); void insert(string s, Node* t){ f(i,0, s.size()){ int index = s[i] - 'a'; if(!t->child[index]){ t->child[index] = new Node(); }else{ t->child[index]->freq++; } t = t->child[index]; } } int getfreq(string s, Node*t){ f(i,0,s.size()){ int index = s[i] - 'a'; if(!t->child[index])return 0; t = t->child[index]; } return t->freq; } int klengthpref(string arr[], int n, int k, string str){ string s = str.substr(0, k); f(i,0,n)insert(arr[i],t); return getfreq(s,t); } }; 0 aadityapburujwale3 months ago public int klengthpref(String[] arr, int n, int k, String str) { str = str.substring(0,k); int ans = 0; for(String s:arr){ if(s.startsWith(str)) ans++; } return ans; } 0 hitentandon3 months ago Java: int count = 0; str=str.substring(0,k); for(String s:arr) count += s.indexOf(str)==0?1:0; return count; 0 abhishek11103 months ago Java Solution: public int klengthpref(String[] arr, int n, int k, String str) { str = str.substring(0, k); int count = 0; for (String s : arr) { if (k > s.length()) continue; String temp = s.substring(0, k); if (temp.equals(str)) { count++; } } return count; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 439, "s": 238, "text": "Given an array of strings arr[] of size n and given s a string str and an integer k. The task is to find the count of strings in arr[] whose prefix of length k matches with the k length prefix of str." }, { "code": null, "e": 451, "s": 439, "text": "\nExample 1:" }, { "code": null, "e": 628, "s": 451, "text": "Input:\nn = 6\narr[] = {“abba”, “abbb”, “abbc”, “abbd”, \n“abaa”, “abca”}\nstr = “abbg”\nk = 3\nOutput: 4 \nExplanation:\n“abba”, “abbb”, “abbc” and “abbd” are \nthe matching strings.\n\n" }, { "code": null, "e": 640, "s": 628, "text": "\nExample 2:" }, { "code": null, "e": 731, "s": 640, "text": "Input:\nn = 3\narr[] = {“geeks”, “geeksforgeeks”, “forgeeks”}\nstr = “geeks”\nk = 2\nOutput: 2\n" }, { "code": null, "e": 1055, "s": 731, "text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function klengthpref() which takes the array of strings arr[], its size n and an integer k, a string str as input parameters and returns the count of strings in arr[] whose prefix of length k matches with the k length prefix of str." }, { "code": null, "e": 1225, "s": 1055, "text": "Expected Time Complexity: O(n*l) where l is the length of the longest word in arr[].\nExpected Auxiliary Space: O(n*l) where l is the length of the longest word in arr[]." }, { "code": null, "e": 1360, "s": 1227, "text": "Constraints:\n1 <= n <= 1000\n1 <= |arr[i]| , |str| <= 1000\n1 <= k <= 1000\narr[i], str must contain only lowercase english alphabets\n " }, { "code": null, "e": 1362, "s": 1360, "text": "0" }, { "code": null, "e": 1388, "s": 1362, "text": "2017cstarun57053 days ago" }, { "code": null, "e": 1395, "s": 1388, "text": "nodeJS" }, { "code": null, "e": 1549, "s": 1397, "text": " return arr.map((i)=>{ return i.substring(0,k) === str.substring(0,k) ? 1 : 0 }).filter((j)=>{ return j === 1 }).length" }, { "code": null, "e": 1551, "s": 1549, "text": "0" }, { "code": null, "e": 1577, "s": 1551, "text": "artistdarkangel1 week ago" }, { "code": null, "e": 1629, "s": 1577, "text": "Java Simple Solution | No need to use Trie concept." }, { "code": null, "e": 1984, "s": 1631, "text": "class Solution{ public int klengthpref(String[] arr, int n, int k, String str) { str=str.substring(0,k); int count=0; for(int i=0; i<n; i++) { if(arr[i].length()<k) continue; String temp = arr[i].substring(0,k); if(temp.equals(str)) count++; } return count; }}" }, { "code": null, "e": 1986, "s": 1984, "text": "0" }, { "code": null, "e": 2012, "s": 1986, "text": "rishavkumar44121 week ago" }, { "code": null, "e": 2055, "s": 2012, "text": "Why am i getting wrong ans on submitting ?" }, { "code": null, "e": 2226, "s": 2055, "text": "class node{ node link[]=new node[26]; int cntstartwith; node(){ cntstartwith=0; for(int i=0;i<26;i++){ link[i]=null; } }}" }, { "code": null, "e": 3057, "s": 2226, "text": "class Solution{ public void insert(node root,String key){ int index; node temp=root; for(int i=0;i<key.length();i++){ index=key.charAt(i)-'a'; if(temp.link[index]==null){ temp.link[index]=new node(); temp.cntstartwith++; } temp=temp.link[index]; } } public int klengthpref(String[] arr, int n, int k, String str) { // code here node root=new node(); for(int i=0;i<n;i++){ insert(root,arr[i]); } int index; node temp=root; for(int i=0;i<k;i++){ index=str.charAt(i)-'a'; if(temp.link[index]==null){ return 0; }else{ temp=temp.link[index]; } } return temp.cntstartwith; }}" }, { "code": null, "e": 3059, "s": 3057, "text": "0" }, { "code": null, "e": 3086, "s": 3059, "text": "kshitijmagare193 weeks ago" }, { "code": null, "e": 3104, "s": 3086, "text": "Total Time Taken:" }, { "code": null, "e": 3113, "s": 3104, "text": "0.7/8.61" }, { "code": null, "e": 3120, "s": 3113, "text": "JAVA :" }, { "code": null, "e": 3534, "s": 3120, "text": "public int klengthpref(String[] arr, int n, int k, String str) { // code here String s = \"\"; for(int i = 0; i<k;i++){ s+=str.charAt(i); } //System.out.println(s); int count = 0; boolean b; for(int i = 0; i< n;i++){ b = arr[i].startsWith(s); if(b == true){ count++; } } return count; }" }, { "code": null, "e": 3536, "s": 3534, "text": "0" }, { "code": null, "e": 3559, "s": 3536, "text": "creator23031 month ago" }, { "code": null, "e": 3580, "s": 3559, "text": "Easy C++ Solution :)" }, { "code": null, "e": 4002, "s": 3582, "text": "int klengthpref(string arr[], int n, int k, string str){ \n string pat ;\n int t=k;\n for(int i=0 ;i<str.size();i++)\n {\n if(k==0)\n break;\n pat+=str[i] ;\n k-- ;\n }\n \n int cnt =0 ;\n k=t;\n for(int i=0 ;i<n;i++)\n {\n\n if(arr[i].substr(0, k) == pat)\n cnt++;\n }\n return cnt;\n }" }, { "code": null, "e": 4004, "s": 4002, "text": "0" }, { "code": null, "e": 4032, "s": 4004, "text": "himanshujain4572 months ago" }, { "code": null, "e": 4058, "s": 4032, "text": "Java Solution Using Trie:" }, { "code": null, "e": 5124, "s": 4058, "text": "class Solution{ class TrieNode{ int count=0; TrieNode child[]=new TrieNode[26]; TrieNode() { count=0; for(int i=0;i<26;i++) { child[i]=null; } } } TrieNode root=new TrieNode(); void BuildTrie(String[] arr, int n) { for(int i=0;i<n;i++) { String s=arr[i]; TrieNode temp=root; for(int k=0;k<s.length();k++) { char ch=s.charAt(k); if(temp.child[ch-'a']==null) { temp.child[ch-'a']=new TrieNode(); } temp=temp.child[ch-'a']; temp.count++; } } } public int klengthpref(String[] arr, int n, int k, String str) { BuildTrie(arr,n); TrieNode temp=root; for(int i=0;i<k;i++) { char ch=str.charAt(i); if(temp.child[ch-'a']==null) { return 0; } temp=temp.child[ch-'a']; } return temp.count; }}" }, { "code": null, "e": 5126, "s": 5124, "text": "0" }, { "code": null, "e": 5152, "s": 5126, "text": "paurushbatish2 months ago" }, { "code": null, "e": 5192, "s": 5152, "text": "Easy Solution using Trie Data Structure" }, { "code": null, "e": 5210, "s": 5192, "text": "Total Time Taken:" }, { "code": null, "e": 5218, "s": 5210, "text": "0.2/2.2" }, { "code": null, "e": 6108, "s": 5218, "text": "#define f(i,a,b) for(int i = a;i<b;i++)\nstruct Node {\n int freq;\n Node* child[26];\n Node(){\n freq = 1;\n f(i,0,26)child[i] = NULL;\n }\n};\nclass Solution{ \npublic:\n Node* t = new Node();\n void insert(string s, Node* t){\n f(i,0, s.size()){\n int index = s[i] - 'a';\n if(!t->child[index]){\n t->child[index] = new Node();\n }else{\n t->child[index]->freq++;\n }\n t = t->child[index];\n }\n }\n int getfreq(string s, Node*t){\n f(i,0,s.size()){\n int index = s[i] - 'a';\n if(!t->child[index])return 0;\n t = t->child[index];\n }\n return t->freq;\n }\n int klengthpref(string arr[], int n, int k, string str){ \n string s = str.substr(0, k);\n f(i,0,n)insert(arr[i],t);\n return getfreq(s,t);\n }\n};\n" }, { "code": null, "e": 6110, "s": 6108, "text": "0" }, { "code": null, "e": 6140, "s": 6110, "text": "aadityapburujwale3 months ago" }, { "code": null, "e": 6428, "s": 6140, "text": "public int klengthpref(String[] arr, int n, int k, String str)\n {\n \n str = str.substring(0,k);\n \n int ans = 0;\n\n for(String s:arr){\n if(s.startsWith(str))\n ans++;\n }\n \n return ans;\n }" }, { "code": null, "e": 6430, "s": 6428, "text": "0" }, { "code": null, "e": 6454, "s": 6430, "text": "hitentandon3 months ago" }, { "code": null, "e": 6460, "s": 6454, "text": "Java:" }, { "code": null, "e": 6601, "s": 6460, "text": "\t\tint count = 0;\n \tstr=str.substring(0,k);\n \tfor(String s:arr)\n count += s.indexOf(str)==0?1:0;\n return count;" }, { "code": null, "e": 6603, "s": 6601, "text": "0" }, { "code": null, "e": 6628, "s": 6603, "text": "abhishek11103 months ago" }, { "code": null, "e": 6643, "s": 6628, "text": "Java Solution:" }, { "code": null, "e": 7001, "s": 6643, "text": "public int klengthpref(String[] arr, int n, int k, String str)\n {\n str = str.substring(0, k);\n int count = 0;\n for (String s : arr) {\n if (k > s.length()) continue;\n String temp = s.substring(0, k);\n if (temp.equals(str)) {\n count++;\n }\n }\n return count;\n }" }, { "code": null, "e": 7147, "s": 7001, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 7183, "s": 7147, "text": " Login to access your submissions. " }, { "code": null, "e": 7193, "s": 7183, "text": "\nProblem\n" }, { "code": null, "e": 7203, "s": 7193, "text": "\nContest\n" }, { "code": null, "e": 7266, "s": 7203, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7414, "s": 7266, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7622, "s": 7414, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 7728, "s": 7622, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
C++ List Library - erase() Function
The C++ function std::list::erase() removes single element from the the list and decreases it's size by one. Following is the declaration for std::list::erase() function form std::list header. iterator erase (iterator position); iterator erase (const_iterator position); position − Iterator to the list element. Returns a random access iterator which points to the location from where element was removed. If position is invalid then behavior is undefined. Linear i.e. O(n) The following example shows the usage of std::list::erase() function. #include <iostream> #include <list> using namespace std; int main(void) { list<int> l = {1, 2, 3, 4, 5}; cout << "Size of list befor erase operation = " << l.size() << endl; l.erase(l.begin()); cout << "Size of list after erase operation = " << l.size() << endl; cout << "List contains following elements" << 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 − Size of list befor erase operation = 5 Size of list after erase operation = 4 List contains following elements 2 3 4 5 Print Add Notes Bookmark this page
[ { "code": null, "e": 2712, "s": 2603, "text": "The C++ function std::list::erase() removes single element from the the list and decreases it's size by one." }, { "code": null, "e": 2796, "s": 2712, "text": "Following is the declaration for std::list::erase() function form std::list header." }, { "code": null, "e": 2833, "s": 2796, "text": "iterator erase (iterator position);\n" }, { "code": null, "e": 2876, "s": 2833, "text": "iterator erase (const_iterator position);\n" }, { "code": null, "e": 2917, "s": 2876, "text": "position − Iterator to the list element." }, { "code": null, "e": 3011, "s": 2917, "text": "Returns a random access iterator which points to the location from where element was removed." }, { "code": null, "e": 3062, "s": 3011, "text": "If position is invalid then behavior is undefined." }, { "code": null, "e": 3079, "s": 3062, "text": "Linear i.e. O(n)" }, { "code": null, "e": 3149, "s": 3079, "text": "The following example shows the usage of std::list::erase() function." }, { "code": null, "e": 3579, "s": 3149, "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 << \"Size of list befor erase operation = \" << l.size() << endl;\n\n l.erase(l.begin());\n\n cout << \"Size of list after erase operation = \" << l.size() << endl;\n\n cout << \"List contains following elements\" << endl;\n\n for (auto it = l.begin(); it != l.end(); ++it)\n cout << *it << endl;\n\n return 0;\n}" }, { "code": null, "e": 3662, "s": 3579, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3782, "s": 3662, "text": "Size of list befor erase operation = 5\nSize of list after erase operation = 4\nList contains following elements\n2\n3\n4\n5\n" }, { "code": null, "e": 3789, "s": 3782, "text": " Print" }, { "code": null, "e": 3800, "s": 3789, "text": " Add Notes" } ]
Binary Tree | Set 1 (Introduction) - GeeksforGeeks
22 Nov, 2021 Trees: Unlike Arrays, Linked Lists, Stack and queues, which are linear data structures, trees are hierarchical data structures.Tree Vocabulary: The topmost node is called root of the tree. The elements that are directly under an element are called its children. The element directly above something is called its parent. For example, ‘a’ is a child of ‘f’, and ‘f’ is the parent of ‘a’. Finally, elements with no children are called leaves. tree ---- j <-- root / \ f k / \ \ a h z <-- leaves Why Trees? 1. One reason to use trees might be because you want to store information that naturally forms a hierarchy. For example, the file system on a computer: file system ----------- / <-- root / \ ... home / \ ugrad course / / | \ ... cs101 cs112 cs113 2. Trees (with some ordering e.g., BST) provide moderate access/search (quicker than Linked List and slower than arrays). 3. Trees provide moderate insertion/deletion (quicker than Arrays and slower than Unordered Linked Lists). 4. Like Linked Lists and unlike Arrays, Trees don’t have an upper limit on number of nodes as nodes are linked using pointers.Main applications of trees include: 1. Manipulate hierarchical data. 2. Make information easy to search (see tree traversal). 3. Manipulate sorted lists of data. 4. As a workflow for compositing digital images for visual effects. 5. Router algorithms 6. Form of a multi-stage decision-making (see business chess). Binary Tree: A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right child. Binary Tree Representation in C: A tree is represented by a pointer to the topmost node in tree. If the tree is empty, then value of root is NULL. A Tree node contains following parts. 1. Data 2. Pointer to left child 3. Pointer to right childIn C, we can represent a tree node using structures. Below is an example of a tree node with an integer data. C++ Python Java C# Javascript struct node{ int data; struct node* left; struct node* right;}; # A Python class that represents an individual node# in a Binary Treeclass Node: def __init__(self,key): self.left = None self.right = None self.val = key /* Class containing left and right child of current node and key value*/class Node{ int key; Node left, right; public Node(int item) { key = item; left = right = null; }} /* Class containing left and right childof current node and key value*/class Node{ int key; Node left, right; public Node(int item) { key = item; left = right = null; }} <script>/* Class containing left and right child of current node and key value*/class Node{ constructor(item) { this.key = item; this.left = this.right = null; }} // This code is contributed by umadevi9616</script> First Simple Tree in C Let us create a simple tree with 4 nodes in C. The created tree would be as following. tree ---- 1 <-- root / \ 2 3 / 4 C++ C Java Python C# Javascript #include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* left; struct Node* right; // val is the key or the value that // has to be added to the data part Node(int val) { data = val; // Left and right child for node // will be initialized to null left = NULL; right = NULL; }}; int main(){ /*create root*/ struct Node* root = new Node(1); /* following is the tree after above statement 1 / \ NULL NULL */ root->left = new Node(2); root->right = new Node(3); /* 2 and 3 become left and right children of 1 1 / \ 2 3 / \ / \ NULL NULL NULL NULL */ root->left->left = new Node(4); /* 4 becomes left child of 2 1 / \ 2 3 / \ / \ 4 NULL NULL NULL / \ NULL NULL */ return 0;} #include <stdio.h>#include <stdlib.h>struct node { int data; struct node* left; struct node* right;}; /* newNode() allocates a new nodewith the given data and NULL leftand right pointers. */struct node* newNode(int data){ // Allocate memory for new node struct node* node = (struct node*)malloc(sizeof(struct node)); // Assign data to this node node->data = data; // Initialize left and // right children as NULL node->left = NULL; node->right = NULL; return (node);} int main(){ /*create root*/ struct node* root = newNode(1); /* following is the tree after above statement 1 / \ NULL NULL */ root->left = newNode(2); root->right = newNode(3); /* 2 and 3 become left and right children of 1 1 / \ 2 3 / \ / \ NULL NULL NULL NULL */ root->left->left = newNode(4); /* 4 becomes left child of 2 1 / \ 2 3 / \ / \ 4 NULL NULL NULL / \ NULL NULL */ getchar(); return 0;} /* Class containing left and right child of current node and key value*/class Node{ int key; Node left, right; public Node(int item) { key = item; left = right = null; }} // A Java program to introduce Binary Treeclass BinaryTree{ // Root of Binary Tree Node root; // Constructors BinaryTree(int key) { root = new Node(key); } BinaryTree() { root = null; } public static void main(String[] args) { BinaryTree tree = new BinaryTree(); /*create root*/ tree.root = new Node(1); /* following is the tree after above statement 1 / \ null null */ tree.root.left = new Node(2); tree.root.right = new Node(3); /* 2 and 3 become left and right children of 1 1 / \ 2 3 / \ / \ null null null null */ tree.root.left.left = new Node(4); /* 4 becomes left child of 2 1 / \ 2 3 / \ / \ 4 null null null / \ null null */ }} # Python program to introduce Binary Tree # A class that represents an individual node in a# Binary Treeclass Node: def __init__(self,key): self.left = None self.right = None self.val = key # create rootroot = Node(1)''' following is the tree after above statement 1 / \ None None''' root.left = Node(2);root.right = Node(3); ''' 2 and 3 become left and right children of 1 1 / \ 2 3 / \ / \ None None None None''' root.left.left = Node(4);'''4 becomes left child of 2 1 / \ 2 3 / \ / \ 4 None None None / \None None''' // A C# program to introduce Binary Treeusing System; /* Class containing left and right childof current node and key value*/public class Node{ public int key; public Node left, right; public Node(int item) { key = item; left = right = null; }} public class BinaryTree{ // Root of Binary Tree Node root; // Constructors BinaryTree(int key) { root = new Node(key); } BinaryTree() { root = null; } // Driver Code public static void Main(String[] args) { BinaryTree tree = new BinaryTree(); /*create root*/ tree.root = new Node(1); /* following is the tree after above statement 1 / \ null null */ tree.root.left = new Node(2); tree.root.right = new Node(3); /* 2 and 3 become left and right children of 1 1 / \ 2 3 / \ / \ null null null null */ tree.root.left.left = new Node(4); /* 4 becomes left child of 2 1 / \ 2 3 / \ / \ 4 null null null / \ null null */ }} // This code is contributed by PrinciRaj1992 <script>/* Class containing left and right child of current node and key value*/ class Node { constructor(val) { this.key = val; this.left = null; this.right = null; } } // A javascript program to introduce Binary Tree // Root of Binary Tree var root = null; /*create root*/ root = new Node(1); /* following is the tree after above statement 1 / \ null null */ root.left = new Node(2); root.right = new Node(3); /* 2 and 3 become left and right children of 1 1 / \ 2 3 / \ / \ null null null null */ root.left.left = new Node(4); /* 4 becomes left child of 2 1 / \ 2 3 / \ / \ 4 null null null / \ null null */ // This code contributed by umadevi9616</script> Summary: Tree is a hierarchical data structure. Main uses of trees include maintaining hierarchical data, providing moderate access and insert/delete operations. Binary trees are special cases of tree where every node has at most two children. https://youtu.be/W6aZKAJcNJABelow are set 2 and set 3 of this post. Properties of Binary Tree Types of Binary TreePlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nsp92 princiraj1992 manikanta2901 Twinkl Bajaj anandpatel98260 umadevi9616 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Write a Program to Find the Maximum Depth or Height of a Tree A program to check if a binary tree is BST or not Decision Tree Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 BFS vs DFS for Binary Tree Binary Tree (Array implementation)
[ { "code": null, "e": 37368, "s": 37340, "text": "\n22 Nov, 2021" }, { "code": null, "e": 37810, "s": 37368, "text": "Trees: Unlike Arrays, Linked Lists, Stack and queues, which are linear data structures, trees are hierarchical data structures.Tree Vocabulary: The topmost node is called root of the tree. The elements that are directly under an element are called its children. The element directly above something is called its parent. For example, ‘a’ is a child of ‘f’, and ‘f’ is the parent of ‘a’. Finally, elements with no children are called leaves. " }, { "code": null, "e": 37924, "s": 37810, "text": " tree\n ----\n j <-- root\n / \\\n f k \n / \\ \\\n a h z <-- leaves" }, { "code": null, "e": 38088, "s": 37924, "text": "Why Trees? 1. One reason to use trees might be because you want to store information that naturally forms a hierarchy. For example, the file system on a computer: " }, { "code": null, "e": 38257, "s": 38088, "text": "file system\n-----------\n / <-- root\n / \\\n... home\n / \\\n ugrad course\n / / | \\\n ... cs101 cs112 cs113" }, { "code": null, "e": 39474, "s": 38257, "text": "2. Trees (with some ordering e.g., BST) provide moderate access/search (quicker than Linked List and slower than arrays). 3. Trees provide moderate insertion/deletion (quicker than Arrays and slower than Unordered Linked Lists). 4. Like Linked Lists and unlike Arrays, Trees don’t have an upper limit on number of nodes as nodes are linked using pointers.Main applications of trees include: 1. Manipulate hierarchical data. 2. Make information easy to search (see tree traversal). 3. Manipulate sorted lists of data. 4. As a workflow for compositing digital images for visual effects. 5. Router algorithms 6. Form of a multi-stage decision-making (see business chess). Binary Tree: A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right child. Binary Tree Representation in C: A tree is represented by a pointer to the topmost node in tree. If the tree is empty, then value of root is NULL. A Tree node contains following parts. 1. Data 2. Pointer to left child 3. Pointer to right childIn C, we can represent a tree node using structures. Below is an example of a tree node with an integer data." }, { "code": null, "e": 39478, "s": 39474, "text": "C++" }, { "code": null, "e": 39485, "s": 39478, "text": "Python" }, { "code": null, "e": 39490, "s": 39485, "text": "Java" }, { "code": null, "e": 39493, "s": 39490, "text": "C#" }, { "code": null, "e": 39504, "s": 39493, "text": "Javascript" }, { "code": "struct node{ int data; struct node* left; struct node* right;};", "e": 39577, "s": 39504, "text": null }, { "code": "# A Python class that represents an individual node# in a Binary Treeclass Node: def __init__(self,key): self.left = None self.right = None self.val = key", "e": 39756, "s": 39577, "text": null }, { "code": "/* Class containing left and right child of current node and key value*/class Node{ int key; Node left, right; public Node(int item) { key = item; left = right = null; }}", "e": 39959, "s": 39756, "text": null }, { "code": "/* Class containing left and right childof current node and key value*/class Node{ int key; Node left, right; public Node(int item) { key = item; left = right = null; }}", "e": 40159, "s": 39959, "text": null }, { "code": "<script>/* Class containing left and right child of current node and key value*/class Node{ constructor(item) { this.key = item; this.left = this.right = null; }} // This code is contributed by umadevi9616</script>", "e": 40399, "s": 40159, "text": null }, { "code": null, "e": 40511, "s": 40399, "text": "First Simple Tree in C Let us create a simple tree with 4 nodes in C. The created tree would be as following. " }, { "code": null, "e": 40591, "s": 40511, "text": " tree\n ----\n 1 <-- root\n / \\\n 2 3 \n / \n 4" }, { "code": null, "e": 40595, "s": 40591, "text": "C++" }, { "code": null, "e": 40597, "s": 40595, "text": "C" }, { "code": null, "e": 40602, "s": 40597, "text": "Java" }, { "code": null, "e": 40609, "s": 40602, "text": "Python" }, { "code": null, "e": 40612, "s": 40609, "text": "C#" }, { "code": null, "e": 40623, "s": 40612, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* left; struct Node* right; // val is the key or the value that // has to be added to the data part Node(int val) { data = val; // Left and right child for node // will be initialized to null left = NULL; right = NULL; }}; int main(){ /*create root*/ struct Node* root = new Node(1); /* following is the tree after above statement 1 / \\ NULL NULL */ root->left = new Node(2); root->right = new Node(3); /* 2 and 3 become left and right children of 1 1 / \\ 2 3 / \\ / \\ NULL NULL NULL NULL */ root->left->left = new Node(4); /* 4 becomes left child of 2 1 / \\ 2 3 / \\ / \\ 4 NULL NULL NULL / \\ NULL NULL */ return 0;}", "e": 41623, "s": 40623, "text": null }, { "code": "#include <stdio.h>#include <stdlib.h>struct node { int data; struct node* left; struct node* right;}; /* newNode() allocates a new nodewith the given data and NULL leftand right pointers. */struct node* newNode(int data){ // Allocate memory for new node struct node* node = (struct node*)malloc(sizeof(struct node)); // Assign data to this node node->data = data; // Initialize left and // right children as NULL node->left = NULL; node->right = NULL; return (node);} int main(){ /*create root*/ struct node* root = newNode(1); /* following is the tree after above statement 1 / \\ NULL NULL */ root->left = newNode(2); root->right = newNode(3); /* 2 and 3 become left and right children of 1 1 / \\ 2 3 / \\ / \\ NULL NULL NULL NULL */ root->left->left = newNode(4); /* 4 becomes left child of 2 1 / \\ 2 3 / \\ / \\ 4 NULL NULL NULL / \\ NULL NULL */ getchar(); return 0;}", "e": 42695, "s": 41623, "text": null }, { "code": "/* Class containing left and right child of current node and key value*/class Node{ int key; Node left, right; public Node(int item) { key = item; left = right = null; }} // A Java program to introduce Binary Treeclass BinaryTree{ // Root of Binary Tree Node root; // Constructors BinaryTree(int key) { root = new Node(key); } BinaryTree() { root = null; } public static void main(String[] args) { BinaryTree tree = new BinaryTree(); /*create root*/ tree.root = new Node(1); /* following is the tree after above statement 1 / \\ null null */ tree.root.left = new Node(2); tree.root.right = new Node(3); /* 2 and 3 become left and right children of 1 1 / \\ 2 3 / \\ / \\ null null null null */ tree.root.left.left = new Node(4); /* 4 becomes left child of 2 1 / \\ 2 3 / \\ / \\ 4 null null null / \\ null null */ }}", "e": 43893, "s": 42695, "text": null }, { "code": "# Python program to introduce Binary Tree # A class that represents an individual node in a# Binary Treeclass Node: def __init__(self,key): self.left = None self.right = None self.val = key # create rootroot = Node(1)''' following is the tree after above statement 1 / \\ None None''' root.left = Node(2);root.right = Node(3); ''' 2 and 3 become left and right children of 1 1 / \\ 2 3 / \\ / \\ None None None None''' root.left.left = Node(4);'''4 becomes left child of 2 1 / \\ 2 3 / \\ / \\ 4 None None None / \\None None'''", "e": 44572, "s": 43893, "text": null }, { "code": "// A C# program to introduce Binary Treeusing System; /* Class containing left and right childof current node and key value*/public class Node{ public int key; public Node left, right; public Node(int item) { key = item; left = right = null; }} public class BinaryTree{ // Root of Binary Tree Node root; // Constructors BinaryTree(int key) { root = new Node(key); } BinaryTree() { root = null; } // Driver Code public static void Main(String[] args) { BinaryTree tree = new BinaryTree(); /*create root*/ tree.root = new Node(1); /* following is the tree after above statement 1 / \\ null null */ tree.root.left = new Node(2); tree.root.right = new Node(3); /* 2 and 3 become left and right children of 1 1 / \\ 2 3 / \\ / \\ null null null null */ tree.root.left.left = new Node(4); /* 4 becomes left child of 2 1 / \\ 2 3 / \\ / \\ 4 null null null / \\ null null */ }} // This code is contributed by PrinciRaj1992", "e": 45835, "s": 44572, "text": null }, { "code": "<script>/* Class containing left and right child of current node and key value*/ class Node { constructor(val) { this.key = val; this.left = null; this.right = null; } } // A javascript program to introduce Binary Tree // Root of Binary Tree var root = null; /*create root*/ root = new Node(1); /* following is the tree after above statement 1 / \\ null null */ root.left = new Node(2); root.right = new Node(3); /* 2 and 3 become left and right children of 1 1 / \\ 2 3 / \\ / \\ null null null null */ root.left.left = new Node(4); /* 4 becomes left child of 2 1 / \\ 2 3 / \\ / \\ 4 null null null / \\ null null */ // This code contributed by umadevi9616</script>", "e": 46861, "s": 45835, "text": null }, { "code": null, "e": 47345, "s": 46861, "text": "Summary: Tree is a hierarchical data structure. Main uses of trees include maintaining hierarchical data, providing moderate access and insert/delete operations. Binary trees are special cases of tree where every node has at most two children. https://youtu.be/W6aZKAJcNJABelow are set 2 and set 3 of this post. Properties of Binary Tree Types of Binary TreePlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 47351, "s": 47345, "text": "nsp92" }, { "code": null, "e": 47365, "s": 47351, "text": "princiraj1992" }, { "code": null, "e": 47379, "s": 47365, "text": "manikanta2901" }, { "code": null, "e": 47392, "s": 47379, "text": "Twinkl Bajaj" }, { "code": null, "e": 47408, "s": 47392, "text": "anandpatel98260" }, { "code": null, "e": 47420, "s": 47408, "text": "umadevi9616" }, { "code": null, "e": 47425, "s": 47420, "text": "Tree" }, { "code": null, "e": 47430, "s": 47425, "text": "Tree" }, { "code": null, "e": 47528, "s": 47430, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47537, "s": 47528, "text": "Comments" }, { "code": null, "e": 47550, "s": 47537, "text": "Old Comments" }, { "code": null, "e": 47584, "s": 47550, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 47613, "s": 47584, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 47675, "s": 47613, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" }, { "code": null, "e": 47725, "s": 47675, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 47739, "s": 47725, "text": "Decision Tree" }, { "code": null, "e": 47822, "s": 47739, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 47858, "s": 47822, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 47906, "s": 47858, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" }, { "code": null, "e": 47933, "s": 47906, "text": "BFS vs DFS for Binary Tree" } ]
Automatically Download Email Attachment with Python | by KahEm Chu | Towards Data Science
Have you been in a position where you search over your mailbox to download all the attachments needed? Then maybe you leave and come back forgot where you have stopped? Perhaps you still have to save them to different directories or folder afterwards? I have been in that position before. That is why I want to automate the process of downloading the attachment to the correct directory. After that, perform a transformation to the email’s attachment accordingly. In this article, I would compare the possible Python libraries for the solution and share how I automate the process with Python. smtplib is not one of the choices in my case, as its only capable of sending emails, while imaplib require a username and password which is not favorable. Hence, I chose pywin32. There is no official documentation for pywin32 available. For now, we can only refer to the reference of the Outlook MailItem in Visual Basic for Application (VBA) to learn about the available functions to manipulate the mailbox and the mails. Then, the example cannot be used directly when you are scripting in Python. There is also some good application example of pywin32 on various technical writing websites, but they are not complete. This article covers all the basic stuff you need to know to use pywin32 for accessing your Outlook Mailbox. Import Modules Import Modules The very first step. # pip install pywin32 #if you not installed yetimport win32com.client 2. Establish a Connection to Outlook # set up connection to outlookoutlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") 3. Some Basic Methods / Properties on MailItem Manipulation (1) Accessing to the Inbox. inbox = outlook.GetDefaultFolder(6)# for sub folder, add <.folder("your folder name")>inbox = outlook.GetDefaultFolder(6).folders("Testing") 6 is the index of the inbox. The index of other common items is as below. 3 Deleted Items4 Outbox 5 Sent Items6 Inbox16 Drafts You may check the index of other folders by using the source code below. (Reference C2) import win32com.clientoutlook=win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")for i in range(50): try: box = outlook.GetDefaultFolder(i) name = box.Name print(i, name) except: pass (2) Read the Email # Access to the email in the inboxmessages = inbox.Items# get the first emailmessage = messages.GetFirst()# get the last email#message = messages.GetLast()# to loop thru the email in the inbox while True: try: print(message.subject) # get the subject of the email # if you use messages.GetFirst() earlier message = messages.GetNext() # if you use messages.GetPrevious() earlier #message = messages.GetPrevious() except: # if you use messages.GetFirst() earlier message = messages.GetNext() # if you use messages.GetPrevious() earlier #message = messages.GetPrevious() The above example shows how to print the subject of all of the email in the Inbox. Other than the subject, there are other properties we can print or use as criteria to define a conditional statement. The below shown some of the common properties. message.subjectmessage.senton # return the date & time email sentmessage.senton.date()message.senton.time()message.sendermessage.SenderEmailAddressmessage.Attachments # return all attachments in the email Note that the messages.GetFirst() or messages.GetNext() which end with a pair of parenthesis is referring to a method we can use to manipulate the mailbox, while the message.subject or message.senton is referring to the properties of the email, and it is not case sensitive when you using Python. Hence, you may refer to the documentation of MailItem in VB which can be found in Reference C1 at the bottom, for the complete MailItem properties list. (I haven’t tried all of it, but most of it can be applies.) (3) Download an Email Attachment. attachments = message.Attachments# return the first item in attachmentsattachment = attachments.Item(1)# the name of attachment file attachment_name = str(attachment).lower()attachment.SaveASFile(path+ '\\' + attachment_name) 4. Complete Example # import librariesimport win32com.clientimport re# set up connection to outlookoutlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")inbox = outlook.GetDefaultFolder(6)messages = inbox.Itemsmessage = messages.GetFirst()today_date = str(datetime.date.today())while True: try: current_sender = str(message.Sender).lower() current_subject = str(message.Subject).lower() # find the email from a specific sender with a specific subject # condition if re.search('Subject Title',current_subject) != None and re.search(sender_name,current_sender) != None: print(current_subject) # verify the subject print(current_sender) # verify the sender attachments = message.Attachments attachment = attachments.Item(1) attachment_name = str(attachment).lower() attachment.SaveASFile(path + '\\' + attachment_name) else: pass message = messages.GetNext() except: message = messages.GetNext()exit The above is the complete example to download an email from a specific sender with a specific title to a specific path. You may change the condition according to your situation, for example, you may use message.senton.date() to obtain the email received on the date defined. Also, you may use nested if-else statement to save attachments in different directories, which is pretty handy when you are going to download a lot of attachments. Subscribe on YouTube Documentation for smtplib Documentation for imaplib MailItem Interface (Visual Basic for Application reference for all Outlook MailItem object properties, methods and events)Clearly documented reading of emails functionality with python win32com outlook (Contained most of the basic properties you will need for accessing the mails and attachments in Outlook) MailItem Interface (Visual Basic for Application reference for all Outlook MailItem object properties, methods and events) Clearly documented reading of emails functionality with python win32com outlook (Contained most of the basic properties you will need for accessing the mails and attachments in Outlook) If you are interested in how to use pywin32 to automate Microsoft Excel Report, you may refer to this article, “Automate Excel with Python”. If you are interested to create a chart or PivotChart with Python and share it as an email attachment automatically, Automate Excel Chart with Python. Congrats and thanks for reading to the end. Hope you enjoy this article. ☺️
[ { "code": null, "e": 424, "s": 172, "text": "Have you been in a position where you search over your mailbox to download all the attachments needed? Then maybe you leave and come back forgot where you have stopped? Perhaps you still have to save them to different directories or folder afterwards?" }, { "code": null, "e": 636, "s": 424, "text": "I have been in that position before. That is why I want to automate the process of downloading the attachment to the correct directory. After that, perform a transformation to the email’s attachment accordingly." }, { "code": null, "e": 766, "s": 636, "text": "In this article, I would compare the possible Python libraries for the solution and share how I automate the process with Python." }, { "code": null, "e": 945, "s": 766, "text": "smtplib is not one of the choices in my case, as its only capable of sending emails, while imaplib require a username and password which is not favorable. Hence, I chose pywin32." }, { "code": null, "e": 1386, "s": 945, "text": "There is no official documentation for pywin32 available. For now, we can only refer to the reference of the Outlook MailItem in Visual Basic for Application (VBA) to learn about the available functions to manipulate the mailbox and the mails. Then, the example cannot be used directly when you are scripting in Python. There is also some good application example of pywin32 on various technical writing websites, but they are not complete." }, { "code": null, "e": 1494, "s": 1386, "text": "This article covers all the basic stuff you need to know to use pywin32 for accessing your Outlook Mailbox." }, { "code": null, "e": 1509, "s": 1494, "text": "Import Modules" }, { "code": null, "e": 1524, "s": 1509, "text": "Import Modules" }, { "code": null, "e": 1545, "s": 1524, "text": "The very first step." }, { "code": null, "e": 1616, "s": 1545, "text": "# pip install pywin32 #if you not installed yetimport win32com.client" }, { "code": null, "e": 1653, "s": 1616, "text": "2. Establish a Connection to Outlook" }, { "code": null, "e": 1762, "s": 1653, "text": "# set up connection to outlookoutlook = win32com.client.Dispatch(\"Outlook.Application\").GetNamespace(\"MAPI\")" }, { "code": null, "e": 1822, "s": 1762, "text": "3. Some Basic Methods / Properties on MailItem Manipulation" }, { "code": null, "e": 1850, "s": 1822, "text": "(1) Accessing to the Inbox." }, { "code": null, "e": 1991, "s": 1850, "text": "inbox = outlook.GetDefaultFolder(6)# for sub folder, add <.folder(\"your folder name\")>inbox = outlook.GetDefaultFolder(6).folders(\"Testing\")" }, { "code": null, "e": 2065, "s": 1991, "text": "6 is the index of the inbox. The index of other common items is as below." }, { "code": null, "e": 2118, "s": 2065, "text": "3 Deleted Items4 Outbox 5 Sent Items6 Inbox16 Drafts" }, { "code": null, "e": 2206, "s": 2118, "text": "You may check the index of other folders by using the source code below. (Reference C2)" }, { "code": null, "e": 2421, "s": 2206, "text": "import win32com.clientoutlook=win32com.client.Dispatch(\"Outlook.Application\").GetNamespace(\"MAPI\")for i in range(50): try: box = outlook.GetDefaultFolder(i) name = box.Name print(i, name) except: pass" }, { "code": null, "e": 2440, "s": 2421, "text": "(2) Read the Email" }, { "code": null, "e": 3041, "s": 2440, "text": "# Access to the email in the inboxmessages = inbox.Items# get the first emailmessage = messages.GetFirst()# get the last email#message = messages.GetLast()# to loop thru the email in the inbox while True: try: print(message.subject) # get the subject of the email # if you use messages.GetFirst() earlier message = messages.GetNext() # if you use messages.GetPrevious() earlier #message = messages.GetPrevious() except: # if you use messages.GetFirst() earlier message = messages.GetNext() # if you use messages.GetPrevious() earlier #message = messages.GetPrevious()" }, { "code": null, "e": 3289, "s": 3041, "text": "The above example shows how to print the subject of all of the email in the Inbox. Other than the subject, there are other properties we can print or use as criteria to define a conditional statement. The below shown some of the common properties." }, { "code": null, "e": 3517, "s": 3289, "text": "message.subjectmessage.senton # return the date & time email sentmessage.senton.date()message.senton.time()message.sendermessage.SenderEmailAddressmessage.Attachments # return all attachments in the email" }, { "code": null, "e": 4027, "s": 3517, "text": "Note that the messages.GetFirst() or messages.GetNext() which end with a pair of parenthesis is referring to a method we can use to manipulate the mailbox, while the message.subject or message.senton is referring to the properties of the email, and it is not case sensitive when you using Python. Hence, you may refer to the documentation of MailItem in VB which can be found in Reference C1 at the bottom, for the complete MailItem properties list. (I haven’t tried all of it, but most of it can be applies.)" }, { "code": null, "e": 4061, "s": 4027, "text": "(3) Download an Email Attachment." }, { "code": null, "e": 4292, "s": 4061, "text": "attachments = message.Attachments# return the first item in attachmentsattachment = attachments.Item(1)# the name of attachment file attachment_name = str(attachment).lower()attachment.SaveASFile(path+ '\\\\' + attachment_name)" }, { "code": null, "e": 4312, "s": 4292, "text": "4. Complete Example" }, { "code": null, "e": 5278, "s": 4312, "text": "# import librariesimport win32com.clientimport re# set up connection to outlookoutlook = win32com.client.Dispatch(\"Outlook.Application\").GetNamespace(\"MAPI\")inbox = outlook.GetDefaultFolder(6)messages = inbox.Itemsmessage = messages.GetFirst()today_date = str(datetime.date.today())while True: try: current_sender = str(message.Sender).lower() current_subject = str(message.Subject).lower() # find the email from a specific sender with a specific subject # condition if re.search('Subject Title',current_subject) != None and re.search(sender_name,current_sender) != None: print(current_subject) # verify the subject print(current_sender) # verify the sender attachments = message.Attachments attachment = attachments.Item(1) attachment_name = str(attachment).lower() attachment.SaveASFile(path + '\\\\' + attachment_name) else: pass message = messages.GetNext() except: message = messages.GetNext()exit" }, { "code": null, "e": 5717, "s": 5278, "text": "The above is the complete example to download an email from a specific sender with a specific title to a specific path. You may change the condition according to your situation, for example, you may use message.senton.date() to obtain the email received on the date defined. Also, you may use nested if-else statement to save attachments in different directories, which is pretty handy when you are going to download a lot of attachments." }, { "code": null, "e": 5738, "s": 5717, "text": "Subscribe on YouTube" }, { "code": null, "e": 5764, "s": 5738, "text": "Documentation for smtplib" }, { "code": null, "e": 5790, "s": 5764, "text": "Documentation for imaplib" }, { "code": null, "e": 6098, "s": 5790, "text": "MailItem Interface (Visual Basic for Application reference for all Outlook MailItem object properties, methods and events)Clearly documented reading of emails functionality with python win32com outlook (Contained most of the basic properties you will need for accessing the mails and attachments in Outlook)" }, { "code": null, "e": 6221, "s": 6098, "text": "MailItem Interface (Visual Basic for Application reference for all Outlook MailItem object properties, methods and events)" }, { "code": null, "e": 6407, "s": 6221, "text": "Clearly documented reading of emails functionality with python win32com outlook (Contained most of the basic properties you will need for accessing the mails and attachments in Outlook)" }, { "code": null, "e": 6548, "s": 6407, "text": "If you are interested in how to use pywin32 to automate Microsoft Excel Report, you may refer to this article, “Automate Excel with Python”." }, { "code": null, "e": 6699, "s": 6548, "text": "If you are interested to create a chart or PivotChart with Python and share it as an email attachment automatically, Automate Excel Chart with Python." } ]
Tryit Editor v3.7
Tryit: HTML short quotations
[]
Pointers and References in C++ - GeeksforGeeks
01 Jun, 2021 Pointers in C++: Pointers are a symbolic representation of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Its general declaration in C/C++ has the format: Syntax: Pointers in C++: Pointers are a symbolic representation of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Its general declaration in C/C++ has the format: Syntax: datatype *var_name; Example: Example: Example: // ptr can point to an address // which holds int data int *ptr; More on Pointers in C++: This article would provide a further insight into Pointers, on how it works and explains the mathematical background of it. Pointers store address of variables or a memory location. More on Pointers in C++: This article would provide a further insight into Pointers, on how it works and explains the mathematical background of it. Pointers store address of variables or a memory location. // General syntax datatype *var_name; // An example pointer "ptr" that holds // address of an integer variable or holds // address of a memory whose value(s) can // be accessed as integer values through "ptr" int *ptr; Applications of Pointers in C/C++: A pointer has various applications like: To pass arguments by reference: Passing by reference serves two purposesFor accessing array elements: Compiler internally uses pointers to access array elements.To return multiple values: For example in returning square and the square root of numbers.Dynamic memory allocation: We can use pointers to dynamically allocate memory. The advantage of dynamically allocated memory is, it is not deleted until we explicitly delete it.To implement data structures.To do system-level programming where memory addresses are useful.Features and Use of Pointers in C/C++: The Pointers share few important features like it saves memory space, they are used to allocate memory dynamically, it is used for file handling etc. Pointers store address of variables or a memory location. Syntax: Applications of Pointers in C/C++: A pointer has various applications like: To pass arguments by reference: Passing by reference serves two purposesFor accessing array elements: Compiler internally uses pointers to access array elements.To return multiple values: For example in returning square and the square root of numbers.Dynamic memory allocation: We can use pointers to dynamically allocate memory. The advantage of dynamically allocated memory is, it is not deleted until we explicitly delete it.To implement data structures.To do system-level programming where memory addresses are useful. To pass arguments by reference: Passing by reference serves two purposes For accessing array elements: Compiler internally uses pointers to access array elements. To return multiple values: For example in returning square and the square root of numbers. Dynamic memory allocation: We can use pointers to dynamically allocate memory. The advantage of dynamically allocated memory is, it is not deleted until we explicitly delete it. To implement data structures. To do system-level programming where memory addresses are useful. Features and Use of Pointers in C/C++: The Pointers share few important features like it saves memory space, they are used to allocate memory dynamically, it is used for file handling etc. Pointers store address of variables or a memory location. Syntax: datatype *var_name; Example: pointer “ptr” holds the address of an integer variable or holds the address of memory whose value(s) can be accessed as integer values through “ptr” Example: pointer “ptr” holds the address of an integer variable or holds the address of memory whose value(s) can be accessed as integer values through “ptr” int *ptr; ‘this’ Pointer in C++ The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name). Even if only one member of each function exists which is used by multiple objects, the compiler supplies an implicit pointer along with the names of the functions as ‘this’. Declaration: ‘this’ Pointer in C++ The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name). Even if only one member of each function exists which is used by multiple objects, the compiler supplies an implicit pointer along with the names of the functions as ‘this’. Declaration: this->x = x; References in C++: When a variable is declared as reference, it becomes an alternative name for an existing variable. A variable can be declared as reference by putting ‘&’ in the declaration. There are 3 ways to pass C++ arguments to a function: call-by-valuecall-by-reference with pointer argumentcall-by-reference with reference argumentPointers vs References in C++: This article lays proper ground of differences between Pointer and Reference. Both references and pointers can be used to change local variables of one function inside another function. Both of them can also be used to save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain. Despite the above similarities, there are the following differences between references and pointers. A pointer can be declared as void but a reference can never be void Example: References in C++: When a variable is declared as reference, it becomes an alternative name for an existing variable. A variable can be declared as reference by putting ‘&’ in the declaration. There are 3 ways to pass C++ arguments to a function: call-by-valuecall-by-reference with pointer argumentcall-by-reference with reference argument call-by-value call-by-reference with pointer argument call-by-reference with reference argument Pointers vs References in C++: This article lays proper ground of differences between Pointer and Reference. Both references and pointers can be used to change local variables of one function inside another function. Both of them can also be used to save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain. Despite the above similarities, there are the following differences between references and pointers. A pointer can be declared as void but a reference can never be void Example: A pointer can be declared as void but a reference can never be void Example: int a = 10; void* aa = &a;. //it is valid void &ar = a; // it is not valid References are less powerful than pointers Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers. References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing. A reference must be initialized when declared. There is no such restriction with pointers Passing by pointer Vs Passing by Reference in C++: In C++, we can pass parameters to a function either by pointers or by reference. In both the cases, we get the same result. So what should be preferred and why?Passing Reference to a Pointer in C++: In this article let’s compare the usage of a “pointer to pointer” VS “Reference to pointer” in some cases. Passing by pointer Vs Passing by Reference in C++: In C++, we can pass parameters to a function either by pointers or by reference. In both the cases, we get the same result. So what should be preferred and why? Passing Reference to a Pointer in C++: In this article let’s compare the usage of a “pointer to pointer” VS “Reference to pointer” in some cases. simmytarika5 cpp-pointer cpp-references C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ List in C++ Standard Template Library (STL) Convert string to char array in C++ Pair in C++ Standard Template Library (STL) Destructors in C++ new and delete operators in C++ for dynamic memory Queue in C++ Standard Template Library (STL)
[ { "code": null, "e": 23733, "s": 23705, "text": "\n01 Jun, 2021" }, { "code": null, "e": 23974, "s": 23733, "text": "Pointers in C++: Pointers are a symbolic representation of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Its general declaration in C/C++ has the format: Syntax: " }, { "code": null, "e": 24215, "s": 23974, "text": "Pointers in C++: Pointers are a symbolic representation of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Its general declaration in C/C++ has the format: Syntax: " }, { "code": null, "e": 24236, "s": 24215, "text": "datatype *var_name; " }, { "code": null, "e": 24247, "s": 24236, "text": "Example: " }, { "code": null, "e": 24258, "s": 24247, "text": "Example: " }, { "code": null, "e": 24269, "s": 24258, "text": "Example: " }, { "code": null, "e": 24337, "s": 24269, "text": "// ptr can point to an address\n// which holds int data\nint *ptr; " }, { "code": null, "e": 24547, "s": 24337, "text": " More on Pointers in C++: This article would provide a further insight into Pointers, on how it works and explains the mathematical background of it. Pointers store address of variables or a memory location. " }, { "code": null, "e": 24760, "s": 24551, "text": "More on Pointers in C++: This article would provide a further insight into Pointers, on how it works and explains the mathematical background of it. Pointers store address of variables or a memory location. " }, { "code": null, "e": 24983, "s": 24762, "text": "// General syntax\ndatatype *var_name; \n\n// An example pointer \"ptr\" that holds\n// address of an integer variable or holds\n// address of a memory whose value(s) can\n// be accessed as integer values through \"ptr\"\nint *ptr;" }, { "code": null, "e": 25839, "s": 24983, "text": " Applications of Pointers in C/C++: A pointer has various applications like: To pass arguments by reference: Passing by reference serves two purposesFor accessing array elements: Compiler internally uses pointers to access array elements.To return multiple values: For example in returning square and the square root of numbers.Dynamic memory allocation: We can use pointers to dynamically allocate memory. The advantage of dynamically allocated memory is, it is not deleted until we explicitly delete it.To implement data structures.To do system-level programming where memory addresses are useful.Features and Use of Pointers in C/C++: The Pointers share few important features like it saves memory space, they are used to allocate memory dynamically, it is used for file handling etc. Pointers store address of variables or a memory location. Syntax: " }, { "code": null, "e": 26440, "s": 25841, "text": "Applications of Pointers in C/C++: A pointer has various applications like: To pass arguments by reference: Passing by reference serves two purposesFor accessing array elements: Compiler internally uses pointers to access array elements.To return multiple values: For example in returning square and the square root of numbers.Dynamic memory allocation: We can use pointers to dynamically allocate memory. The advantage of dynamically allocated memory is, it is not deleted until we explicitly delete it.To implement data structures.To do system-level programming where memory addresses are useful." }, { "code": null, "e": 26513, "s": 26440, "text": "To pass arguments by reference: Passing by reference serves two purposes" }, { "code": null, "e": 26603, "s": 26513, "text": "For accessing array elements: Compiler internally uses pointers to access array elements." }, { "code": null, "e": 26694, "s": 26603, "text": "To return multiple values: For example in returning square and the square root of numbers." }, { "code": null, "e": 26872, "s": 26694, "text": "Dynamic memory allocation: We can use pointers to dynamically allocate memory. The advantage of dynamically allocated memory is, it is not deleted until we explicitly delete it." }, { "code": null, "e": 26902, "s": 26872, "text": "To implement data structures." }, { "code": null, "e": 26968, "s": 26902, "text": "To do system-level programming where memory addresses are useful." }, { "code": null, "e": 27225, "s": 26968, "text": "Features and Use of Pointers in C/C++: The Pointers share few important features like it saves memory space, they are used to allocate memory dynamically, it is used for file handling etc. Pointers store address of variables or a memory location. Syntax: " }, { "code": null, "e": 27246, "s": 27225, "text": "datatype *var_name; " }, { "code": null, "e": 27406, "s": 27246, "text": "Example: pointer “ptr” holds the address of an integer variable or holds the address of memory whose value(s) can be accessed as integer values through “ptr” " }, { "code": null, "e": 27566, "s": 27406, "text": "Example: pointer “ptr” holds the address of an integer variable or holds the address of memory whose value(s) can be accessed as integer values through “ptr” " }, { "code": null, "e": 27578, "s": 27568, "text": "int *ptr;" }, { "code": null, "e": 28098, "s": 27578, "text": " ‘this’ Pointer in C++ The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name). Even if only one member of each function exists which is used by multiple objects, the compiler supplies an implicit pointer along with the names of the functions as ‘this’. Declaration: " }, { "code": null, "e": 28619, "s": 28100, "text": "‘this’ Pointer in C++ The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name). Even if only one member of each function exists which is used by multiple objects, the compiler supplies an implicit pointer along with the names of the functions as ‘this’. Declaration: " }, { "code": null, "e": 28633, "s": 28619, "text": "this->x = x; " }, { "code": null, "e": 29522, "s": 28633, "text": " References in C++: When a variable is declared as reference, it becomes an alternative name for an existing variable. A variable can be declared as reference by putting ‘&’ in the declaration. There are 3 ways to pass C++ arguments to a function: call-by-valuecall-by-reference with pointer argumentcall-by-reference with reference argumentPointers vs References in C++: This article lays proper ground of differences between Pointer and Reference. Both references and pointers can be used to change local variables of one function inside another function. Both of them can also be used to save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain. Despite the above similarities, there are the following differences between references and pointers. A pointer can be declared as void but a reference can never be void Example: " }, { "code": null, "e": 29865, "s": 29524, "text": "References in C++: When a variable is declared as reference, it becomes an alternative name for an existing variable. A variable can be declared as reference by putting ‘&’ in the declaration. There are 3 ways to pass C++ arguments to a function: call-by-valuecall-by-reference with pointer argumentcall-by-reference with reference argument" }, { "code": null, "e": 29879, "s": 29865, "text": "call-by-value" }, { "code": null, "e": 29919, "s": 29879, "text": "call-by-reference with pointer argument" }, { "code": null, "e": 29961, "s": 29919, "text": "call-by-reference with reference argument" }, { "code": null, "e": 30509, "s": 29961, "text": "Pointers vs References in C++: This article lays proper ground of differences between Pointer and Reference. Both references and pointers can be used to change local variables of one function inside another function. Both of them can also be used to save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain. Despite the above similarities, there are the following differences between references and pointers. A pointer can be declared as void but a reference can never be void Example: " }, { "code": null, "e": 30588, "s": 30509, "text": "A pointer can be declared as void but a reference can never be void Example: " }, { "code": null, "e": 30665, "s": 30590, "text": "int a = 10;\nvoid* aa = &a;. //it is valid\nvoid &ar = a; // it is not valid" }, { "code": null, "e": 30708, "s": 30665, "text": "References are less powerful than pointers" }, { "code": null, "e": 30847, "s": 30708, "text": "Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers." }, { "code": null, "e": 30962, "s": 30847, "text": "References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing." }, { "code": null, "e": 31052, "s": 30962, "text": "A reference must be initialized when declared. There is no such restriction with pointers" }, { "code": null, "e": 31409, "s": 31052, "text": "Passing by pointer Vs Passing by Reference in C++: In C++, we can pass parameters to a function either by pointers or by reference. In both the cases, we get the same result. So what should be preferred and why?Passing Reference to a Pointer in C++: In this article let’s compare the usage of a “pointer to pointer” VS “Reference to pointer” in some cases." }, { "code": null, "e": 31621, "s": 31409, "text": "Passing by pointer Vs Passing by Reference in C++: In C++, we can pass parameters to a function either by pointers or by reference. In both the cases, we get the same result. So what should be preferred and why?" }, { "code": null, "e": 31767, "s": 31621, "text": "Passing Reference to a Pointer in C++: In this article let’s compare the usage of a “pointer to pointer” VS “Reference to pointer” in some cases." }, { "code": null, "e": 31780, "s": 31767, "text": "simmytarika5" }, { "code": null, "e": 31792, "s": 31780, "text": "cpp-pointer" }, { "code": null, "e": 31807, "s": 31792, "text": "cpp-references" }, { "code": null, "e": 31811, "s": 31807, "text": "C++" }, { "code": null, "e": 31815, "s": 31811, "text": "CPP" }, { "code": null, "e": 31913, "s": 31815, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31922, "s": 31913, "text": "Comments" }, { "code": null, "e": 31935, "s": 31922, "text": "Old Comments" }, { "code": null, "e": 31963, "s": 31935, "text": "Operator Overloading in C++" }, { "code": null, "e": 31987, "s": 31963, "text": "Sorting a vector in C++" }, { "code": null, "e": 32007, "s": 31987, "text": "Polymorphism in C++" }, { "code": null, "e": 32040, "s": 32007, "text": "Friend class and function in C++" }, { "code": null, "e": 32084, "s": 32040, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 32120, "s": 32084, "text": "Convert string to char array in C++" }, { "code": null, "e": 32164, "s": 32120, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 32183, "s": 32164, "text": "Destructors in C++" }, { "code": null, "e": 32234, "s": 32183, "text": "new and delete operators in C++ for dynamic memory" } ]
How to exclude extra margin between points and the axes for a plot created by using ggplot2 in R?
In a plot created by using ggplot package there exists an extra area around all the sides of the plot which uses extra space, thus we might want to get rid of that space by removing that extra margin area. It can be done by setting the scale for both the axes to zero with the help of scale_x_continuous and scale_y_continuous function. Consider the below data frame − Live Demo set.seed(151) x<-rnorm(20,5,1) y<-rnorm(20,5,2) df<-data.frame(x,y) df x y 1 4.948461 2.255857 2 5.765737 1.726474 3 4.853260 4.280697 4 4.886814 7.402230 5 4.604489 3.708252 6 5.782276 3.978782 7 3.602522 3.801754 8 3.981162 6.091206 9 5.229476 4.017412 10 5.672173 5.383071 11 4.515448 3.882945 12 5.560609 6.845399 13 5.066156 7.307996 14 3.650124 2.255179 15 4.757084 7.580363 16 3.763259 7.309804 17 3.525322 7.891359 18 7.437159 5.522026 19 5.673526 8.858292 20 5.310040 3.800228 Loading ggplot2 package and creating scatterplot between x and y − library(ggplot2) ggplot(df,aes(x,y))+geom_point() Creating scatterplot between x and y by excluding the extra margin area − ggplot(df,aes(x,y))+geom_point()+scale_x_continuous(expand=c(0,0))+scale_y_continuous(expand=c(0,0))
[ { "code": null, "e": 1399, "s": 1062, "text": "In a plot created by using ggplot package there exists an extra area around all the sides of the plot which uses extra space, thus we might want to get rid of that space by removing that extra margin area. It can be done by setting the scale for both the axes to zero with the help of scale_x_continuous and scale_y_continuous function." }, { "code": null, "e": 1431, "s": 1399, "text": "Consider the below data frame −" }, { "code": null, "e": 1442, "s": 1431, "text": " Live Demo" }, { "code": null, "e": 1513, "s": 1442, "text": "set.seed(151)\nx<-rnorm(20,5,1)\ny<-rnorm(20,5,2)\ndf<-data.frame(x,y)\ndf" }, { "code": null, "e": 1951, "s": 1513, "text": " x y\n1 4.948461 2.255857\n2 5.765737 1.726474\n3 4.853260 4.280697\n4 4.886814 7.402230\n5 4.604489 3.708252\n6 5.782276 3.978782\n7 3.602522 3.801754\n8 3.981162 6.091206\n9 5.229476 4.017412\n10 5.672173 5.383071\n11 4.515448 3.882945\n12 5.560609 6.845399\n13 5.066156 7.307996\n14 3.650124 2.255179\n15 4.757084 7.580363\n16 3.763259 7.309804\n17 3.525322 7.891359\n18 7.437159 5.522026\n19 5.673526 8.858292\n20 5.310040 3.800228" }, { "code": null, "e": 2018, "s": 1951, "text": "Loading ggplot2 package and creating scatterplot between x and y −" }, { "code": null, "e": 2068, "s": 2018, "text": "library(ggplot2)\nggplot(df,aes(x,y))+geom_point()" }, { "code": null, "e": 2142, "s": 2068, "text": "Creating scatterplot between x and y by excluding the extra margin area −" }, { "code": null, "e": 2243, "s": 2142, "text": "ggplot(df,aes(x,y))+geom_point()+scale_x_continuous(expand=c(0,0))+scale_y_continuous(expand=c(0,0))" } ]
A hitchhiker guide to python NumPy Arrays | by Deepak K Gupta (DAKSH) | Towards Data Science
If you’re using python for data science, either you have used NumPy or must have heard about it. Most of the statistical analysis which needs data to be stored in memory uses Numpy. Questions may be asked as why NumPy? Isn’t python lists or other data structures can do the same things? Well Yes and No, there is nothing in NumPy which can’t be done via python lists or by using other data structures, however, NumPy provides an efficient storage and better way handling of the data for mathematical operations using simple API’s, the benefit of which far out-weights writing your own. NumPy provides efficient storage and better ways of handling data for Mathematical Operations NumPy is meant for creating homogeneous n-dimensional arrays (n = 1..n). Unlike Python lists, all elements of a NumPy array should be of same type. so the following code is not valid if data type is provided numpy_arr = np.array([1,2,"Hello",3,"World"], dtype=np.int32) # Error However, for python lists, this is a valid code py_arr = [1,2,"Hello",3,"World"] # Valid Code NumPy arrays are made to be created as homogeneous arrays, considering the mathematical operations that can be performed on them. It would not be possible with heterogeneous data sets. Let’s see what additional benefits NumPy provides us and how it eases our programming life, especially the ones dealing with mathematical calculations. The NumPy arrays takes significantly less amount of memory as compared to python lists. It also provides a mechanism of specifying the data types of the contents, which allows further optimisation of the code. As an example, we can create a simple array of six elements using a python list as well as by using numpy.array(...) , The difference in amount of memory occupied by it is quite astounding. See the example below If this difference seems intimidating then prepare to have more. It’s possible to do further optimisation on the NumPy arrays if we know the maximum number of individual data we’re planning to have. In the example above, NumPy by default considers these integers as 8 Bytes integers, however, we can provide data types with NumPy arrays if we know the maximum range of the data. For example, we can use 1 Byte integer for storing numbers upto 255 and 2 Bytes integer for numbers upto 65535 The optimized memory allocation is not limited to storing numbers, it also expands to storing strings. However, since NumPy arrays are mostly used for mathematical calculations, string will be stored and used rarely. Nevertheless, it’s good to know if the requirement arises Similarly, NumPy arrays provide considerable savings in storing floating point values. Now we know that memory benefits of NumPy, lets now move on to understand how it allows us to create multi dimension arrays An n-dimension array is generally used for creating a matrix or tensors, again mainly for the mathematical calculation purpose. Compare to python list base n-dimension arrays, NumPy not only saves the memory usage, it provide a significant number of additional benefits which makes it easy to mathematical calculations Here is a list of things we can do with NumPy n-dimensional arrays which is otherwise difficult to do. The dimensions of the array can be changed at runtime as long as the multiplicity factor produces the same number of elements. For example, a 2 * 5 matrix can be converted into 5 * 2 and a 1 * 4 into 2 * 2. This can be done by calling the NumPy .reshape(...) function on the arrays NumPy can also generate a predefined set of number for an array. A predefined set of numbers with steps (including decimal steps can be generated using numpy.arange(...) function. The output of this function will always be a single dimension set of numbers. However, we can use reshape on this output to generate dimension of our choice. NumPy provides the API for creating n-dimension arrays using pre-filled ones and zeros where all members of the matrix are either zero or one. One of the most probable usage of this is to create a Sparse or Dense matrix for machine learning . By default, NumPy uses floating point float64 data type for creating ones and zeros, however, the data type can be changed to integer using dtype option as depicted below As .reshape(x,y) can convert an array into multi dimensional array, similarly, its possible to create a single dimensional array from any any multi dimensional array using the function .ravel() As stated earlier, NumPy is not only about efficient storing the data, it also makes it extremely easy to perform mathematical operations on it. Any actions on n-dimension arrays behaves exactly similar to mathematical operations. NumPy n-dimensional arrays makes it extremely easy to perform mathematical operations on it This is the main USP of NumPy because of which it’s widely used in data analytic community. The python lists are nowhere near to what it can do. Let for example, consider multiplying a python list by 2. Here is what we’ll get py_arr = [1,2,3] * 2# Generates [1,2,3,1,2,3] Whereas a numpy array produces the output, which each array elements are multiplied by 2 np_arr = np.array([1,2,3]) * 2# Generates [2,4,6] Similarly, we can also do other mathematical operations on numpy arrays like addition, subtractions and divisions np_arr = np.array([1,2,3]) + 2# Generates [3,4,5] A Multi dimensional matrix operations are as easy as we do using two numbers np_arr1 = np.array([[1,2,3],[4,5,6]])np_arr2 = np.array([[1,2,3],[4,5,6]])np_arr3 = np_arr1 * np_arr2#Generates# [[ 1 4 9]# [16 25 36]]np_arr3 = np_arr1 + np_arr2#Generates# [[ 2 4 6]# [ 8 10 12]] NumPy built-in mathematical functions also allow us to perform complex mathematical operations like sqrt, mean and median. np.sqrt(np_arr1)#generates# [1. 1.41421356 1.73205081]# [2. 2.23606798 2.44948974]]np.mean(np_arr1) #generates 3.5np.median(np_arr1) #generates 3.5 There are additional in-built members functions to get more details of the arrays, including sum, min and max np_arr1.sum() # 21np_arr1.min() # 1np_arr1.max() # 6 While working with data sets there will be times when we need to find specific data from the available data set. Though NumPy provides multiple functions for the same, three of them will be used more often than others. They are where, nonzeroand count_nonzero Where and nonzero functions returns the index associated with the True statement. for example np_arr = np.array([1,2,0,4,5])find = np.where(np_arr > 2)#returns [3,4] and np_arr = np.array([1,2,0,4,5])find = np.nonzero(np_arr)# return [0,1,3,4] And finally one can count the number of non zero elements in a numpy array by using count_nonzero(...) function n_arr = np.array([1,2,3,0,3,0,2,0,0,2])np.count_nonzero(n_arr) # returns 6 These methods are very useful in cases like calculating the sparsity or the density of a matrix. The final method which has its own usage in machine learning is to find the shape of the NumPy array. This is done using .shape . For example n_arr = np.array([1,2,3,0,3,0,2,0,0,2])n_arr.shape# Generates => (10,)n_arr = np.array([[1,2],[3,0]])# Generates => (2,2) The examples provided above depicts only a minimal set of NumPy functionalities. Though not comprehensive, but should give enough feel about what is NumPy and why should we be learning and using it. That’s all for this particular post. Will come up with another set of interesting NumPy functionalities in another post Thanks for Reading ...!!!
[ { "code": null, "e": 353, "s": 171, "text": "If you’re using python for data science, either you have used NumPy or must have heard about it. Most of the statistical analysis which needs data to be stored in memory uses Numpy." }, { "code": null, "e": 458, "s": 353, "text": "Questions may be asked as why NumPy? Isn’t python lists or other data structures can do the same things?" }, { "code": null, "e": 757, "s": 458, "text": "Well Yes and No, there is nothing in NumPy which can’t be done via python lists or by using other data structures, however, NumPy provides an efficient storage and better way handling of the data for mathematical operations using simple API’s, the benefit of which far out-weights writing your own." }, { "code": null, "e": 851, "s": 757, "text": "NumPy provides efficient storage and better ways of handling data for Mathematical Operations" }, { "code": null, "e": 1059, "s": 851, "text": "NumPy is meant for creating homogeneous n-dimensional arrays (n = 1..n). Unlike Python lists, all elements of a NumPy array should be of same type. so the following code is not valid if data type is provided" }, { "code": null, "e": 1130, "s": 1059, "text": "numpy_arr = np.array([1,2,\"Hello\",3,\"World\"], dtype=np.int32) # Error" }, { "code": null, "e": 1178, "s": 1130, "text": "However, for python lists, this is a valid code" }, { "code": null, "e": 1225, "s": 1178, "text": "py_arr = [1,2,\"Hello\",3,\"World\"] # Valid Code" }, { "code": null, "e": 1410, "s": 1225, "text": "NumPy arrays are made to be created as homogeneous arrays, considering the mathematical operations that can be performed on them. It would not be possible with heterogeneous data sets." }, { "code": null, "e": 1562, "s": 1410, "text": "Let’s see what additional benefits NumPy provides us and how it eases our programming life, especially the ones dealing with mathematical calculations." }, { "code": null, "e": 1772, "s": 1562, "text": "The NumPy arrays takes significantly less amount of memory as compared to python lists. It also provides a mechanism of specifying the data types of the contents, which allows further optimisation of the code." }, { "code": null, "e": 1984, "s": 1772, "text": "As an example, we can create a simple array of six elements using a python list as well as by using numpy.array(...) , The difference in amount of memory occupied by it is quite astounding. See the example below" }, { "code": null, "e": 2183, "s": 1984, "text": "If this difference seems intimidating then prepare to have more. It’s possible to do further optimisation on the NumPy arrays if we know the maximum number of individual data we’re planning to have." }, { "code": null, "e": 2474, "s": 2183, "text": "In the example above, NumPy by default considers these integers as 8 Bytes integers, however, we can provide data types with NumPy arrays if we know the maximum range of the data. For example, we can use 1 Byte integer for storing numbers upto 255 and 2 Bytes integer for numbers upto 65535" }, { "code": null, "e": 2749, "s": 2474, "text": "The optimized memory allocation is not limited to storing numbers, it also expands to storing strings. However, since NumPy arrays are mostly used for mathematical calculations, string will be stored and used rarely. Nevertheless, it’s good to know if the requirement arises" }, { "code": null, "e": 2836, "s": 2749, "text": "Similarly, NumPy arrays provide considerable savings in storing floating point values." }, { "code": null, "e": 2960, "s": 2836, "text": "Now we know that memory benefits of NumPy, lets now move on to understand how it allows us to create multi dimension arrays" }, { "code": null, "e": 3279, "s": 2960, "text": "An n-dimension array is generally used for creating a matrix or tensors, again mainly for the mathematical calculation purpose. Compare to python list base n-dimension arrays, NumPy not only saves the memory usage, it provide a significant number of additional benefits which makes it easy to mathematical calculations" }, { "code": null, "e": 3382, "s": 3279, "text": "Here is a list of things we can do with NumPy n-dimensional arrays which is otherwise difficult to do." }, { "code": null, "e": 3664, "s": 3382, "text": "The dimensions of the array can be changed at runtime as long as the multiplicity factor produces the same number of elements. For example, a 2 * 5 matrix can be converted into 5 * 2 and a 1 * 4 into 2 * 2. This can be done by calling the NumPy .reshape(...) function on the arrays" }, { "code": null, "e": 4002, "s": 3664, "text": "NumPy can also generate a predefined set of number for an array. A predefined set of numbers with steps (including decimal steps can be generated using numpy.arange(...) function. The output of this function will always be a single dimension set of numbers. However, we can use reshape on this output to generate dimension of our choice." }, { "code": null, "e": 4245, "s": 4002, "text": "NumPy provides the API for creating n-dimension arrays using pre-filled ones and zeros where all members of the matrix are either zero or one. One of the most probable usage of this is to create a Sparse or Dense matrix for machine learning ." }, { "code": null, "e": 4416, "s": 4245, "text": "By default, NumPy uses floating point float64 data type for creating ones and zeros, however, the data type can be changed to integer using dtype option as depicted below" }, { "code": null, "e": 4610, "s": 4416, "text": "As .reshape(x,y) can convert an array into multi dimensional array, similarly, its possible to create a single dimensional array from any any multi dimensional array using the function .ravel()" }, { "code": null, "e": 4841, "s": 4610, "text": "As stated earlier, NumPy is not only about efficient storing the data, it also makes it extremely easy to perform mathematical operations on it. Any actions on n-dimension arrays behaves exactly similar to mathematical operations." }, { "code": null, "e": 4933, "s": 4841, "text": "NumPy n-dimensional arrays makes it extremely easy to perform mathematical operations on it" }, { "code": null, "e": 5159, "s": 4933, "text": "This is the main USP of NumPy because of which it’s widely used in data analytic community. The python lists are nowhere near to what it can do. Let for example, consider multiplying a python list by 2. Here is what we’ll get" }, { "code": null, "e": 5205, "s": 5159, "text": "py_arr = [1,2,3] * 2# Generates [1,2,3,1,2,3]" }, { "code": null, "e": 5294, "s": 5205, "text": "Whereas a numpy array produces the output, which each array elements are multiplied by 2" }, { "code": null, "e": 5344, "s": 5294, "text": "np_arr = np.array([1,2,3]) * 2# Generates [2,4,6]" }, { "code": null, "e": 5458, "s": 5344, "text": "Similarly, we can also do other mathematical operations on numpy arrays like addition, subtractions and divisions" }, { "code": null, "e": 5508, "s": 5458, "text": "np_arr = np.array([1,2,3]) + 2# Generates [3,4,5]" }, { "code": null, "e": 5585, "s": 5508, "text": "A Multi dimensional matrix operations are as easy as we do using two numbers" }, { "code": null, "e": 5786, "s": 5585, "text": "np_arr1 = np.array([[1,2,3],[4,5,6]])np_arr2 = np.array([[1,2,3],[4,5,6]])np_arr3 = np_arr1 * np_arr2#Generates# [[ 1 4 9]# [16 25 36]]np_arr3 = np_arr1 + np_arr2#Generates# [[ 2 4 6]# [ 8 10 12]]" }, { "code": null, "e": 5909, "s": 5786, "text": "NumPy built-in mathematical functions also allow us to perform complex mathematical operations like sqrt, mean and median." }, { "code": null, "e": 6073, "s": 5909, "text": "np.sqrt(np_arr1)#generates# [1. 1.41421356 1.73205081]# [2. 2.23606798 2.44948974]]np.mean(np_arr1) #generates 3.5np.median(np_arr1) #generates 3.5" }, { "code": null, "e": 6183, "s": 6073, "text": "There are additional in-built members functions to get more details of the arrays, including sum, min and max" }, { "code": null, "e": 6239, "s": 6183, "text": "np_arr1.sum() # 21np_arr1.min() # 1np_arr1.max() # 6" }, { "code": null, "e": 6499, "s": 6239, "text": "While working with data sets there will be times when we need to find specific data from the available data set. Though NumPy provides multiple functions for the same, three of them will be used more often than others. They are where, nonzeroand count_nonzero" }, { "code": null, "e": 6593, "s": 6499, "text": "Where and nonzero functions returns the index associated with the True statement. for example" }, { "code": null, "e": 6665, "s": 6593, "text": "np_arr = np.array([1,2,0,4,5])find = np.where(np_arr > 2)#returns [3,4]" }, { "code": null, "e": 6669, "s": 6665, "text": "and" }, { "code": null, "e": 6743, "s": 6669, "text": "np_arr = np.array([1,2,0,4,5])find = np.nonzero(np_arr)# return [0,1,3,4]" }, { "code": null, "e": 6855, "s": 6743, "text": "And finally one can count the number of non zero elements in a numpy array by using count_nonzero(...) function" }, { "code": null, "e": 6930, "s": 6855, "text": "n_arr = np.array([1,2,3,0,3,0,2,0,0,2])np.count_nonzero(n_arr) # returns 6" }, { "code": null, "e": 7027, "s": 6930, "text": "These methods are very useful in cases like calculating the sparsity or the density of a matrix." }, { "code": null, "e": 7169, "s": 7027, "text": "The final method which has its own usage in machine learning is to find the shape of the NumPy array. This is done using .shape . For example" }, { "code": null, "e": 7291, "s": 7169, "text": "n_arr = np.array([1,2,3,0,3,0,2,0,0,2])n_arr.shape# Generates => (10,)n_arr = np.array([[1,2],[3,0]])# Generates => (2,2)" }, { "code": null, "e": 7490, "s": 7291, "text": "The examples provided above depicts only a minimal set of NumPy functionalities. Though not comprehensive, but should give enough feel about what is NumPy and why should we be learning and using it." }, { "code": null, "e": 7610, "s": 7490, "text": "That’s all for this particular post. Will come up with another set of interesting NumPy functionalities in another post" } ]
Everything You Ever Wanted To Know About Computer Vision. | by Ilija Mihajlovic | Towards Data Science
One of the most powerful and compelling types of AI is computer vision which you’ve almost surely experienced in any number of ways without even knowing. Here’s a look at what it is, how it works, and why it’s so awesome (and is only going to get better). Computer vision is the field of computer science that focuses on replicating parts of the complexity of the human vision system and enabling computers to identify and process objects in images and videos in the same way that humans do. Until recently, computer vision only worked in limited capacity. Thanks to advances in artificial intelligence and innovations in deep learning and neural networks, the field has been able to take great leaps in recent years and has been able to surpass humans in some tasks related to detecting and labeling objects. One of the driving factors behind the growth of computer vision is the amount of data we generate today that is then used to train and make computer vision better. Along with a tremendous amount of visual data (more than 3 billion images are shared online every day), the computing power required to analyze the data is now accessible. As the field of computer vision has grown with new hardware and algorithms so has the accuracy rates for object identification. In less than a decade, today’s systems have reached 99 percent accuracy from 50 percent making them more accurate than humans at quickly reacting to visual inputs. Early experiments in computer vision started in the 1950s and it was first put to use commercially to distinguish between typed and handwritten text by the 1970s, today the applications for computer vision have grown exponentially. By 2022, the computer vision and hardware market is expected to reach $48.6 billion One of the major open questions in both Neuroscience and Machine Learning is: How exactly do our brains work, and how can we approximate that with our own algorithms? The reality is that there are very few working and comprehensive theories of brain computation; so despite the fact that Neural Nets are supposed to “mimic the way the brain works,” nobody is quite sure if that’s actually true. The same paradox holds true for computer vision — since we’re not decided on how the brain and eyes process images, it’s difficult to say how well the algorithms used in production approximate our own internal mental processes. On a certain level Computer vision is all about pattern recognition. So one way to train a computer how to understand visual data is to feed it images, lots of images thousands, millions if possible that have been labeled, and then subject those to various software techniques, or algorithms, that allow the computer to hunt down patterns in all the elements that relate to those labels. So, for example, if you feed a computer a million images of cats (we all love them😄😹), it will subject them all to algorithms that let them analyze the colors in the photo, the shapes, the distances between the shapes, where objects border each other, and so on, so that it identifies a profile of what “cat” means. When it’s finished, the computer will (in theory) be able to use its experience if fed other unlabeled images to find the ones that are of cat. Let’s leave our fluffy cat friends for a moment on the side and let’s get more technical🤔😹. Below is a simple illustration of the grayscale image buffer which stores our image of Abraham Lincoln. Each pixel’s brightness is represented by a single 8-bit number, whose range is from 0 (black) to 255 (white): {157, 153, 174, 168, 150, 152, 129, 151, 172, 161, 155, 156, 155, 182, 163, 74, 75, 62, 33, 17, 110, 210, 180, 154, 180, 180, 50, 14, 34, 6, 10, 33, 48, 106, 159, 181, 206, 109, 5, 124, 131, 111, 120, 204, 166, 15, 56, 180, 194, 68, 137, 251, 237, 239, 239, 228, 227, 87, 71, 201, 172, 105, 207, 233, 233, 214, 220, 239, 228, 98, 74, 206, 188, 88, 179, 209, 185, 215, 211, 158, 139, 75, 20, 169, 189, 97, 165, 84, 10, 168, 134, 11, 31, 62, 22, 148, 199, 168, 191, 193, 158, 227, 178, 143, 182, 106, 36, 190, 205, 174, 155, 252, 236, 231, 149, 178, 228, 43, 95, 234, 190, 216, 116, 149, 236, 187, 86, 150, 79, 38, 218, 241, 190, 224, 147, 108, 227, 210, 127, 102, 36, 101, 255, 224, 190, 214, 173, 66, 103, 143, 96, 50, 2, 109, 249, 215, 187, 196, 235, 75, 1, 81, 47, 0, 6, 217, 255, 211, 183, 202, 237, 145, 0, 0, 12, 108, 200, 138, 243, 236, 195, 206, 123, 207, 177, 121, 123, 200, 175, 13, 96, 218}; This way of storing image data may run counter to your expectations, since the data certainly appears to be two-dimensional when it is displayed. Yet, this is the case, since computer memory consists simply of an ever-increasing linear list of address spaces. Let’s go back to the first picture again and imagine adding a colored one. Now things start to get more complicated. Computers usually read color as a series of 3 values — red, green, and blue (RGB) — on that same 0–255 scale. Now, each pixel actually has 3 values for the computer to store in addition to its position. If we were to colorize President Lincoln, that would lead to 12 x 16 x 3 values, or 576 numbers. That’s a lot of memory to require for one image, and a lot of pixels for an algorithm to iterate over. But to train a model with meaningful accuracy especially when you’re talking about Deep Learning you’d usually need tens of thousands of images, and the more the merrier. Before the advent of deep learning, the tasks that computer vision could perform were very limited and required a lot of manual coding and effort by developers and human operators. For instance, if you wanted to perform facial recognition, you would have to perform the following steps: Create a database: You had to capture individual images of all the subjects you wanted to track in a specific format. Annotate images: Then for every individual image, you would have to enter several key data points, such as distance between the eyes, the width of nose bridge, distance between upper-lip and nose, and dozens of other measurements that define the unique characteristics of each person. Capture new images: Next, you would have to capture new images, whether from photographs or video content. And then you had to go through the measurement process again, marking the key points on the image. You also had to factor in the angle the image was taken. After all this manual work, the application would finally be able to compare the measurements in the new image with the ones stored in its database and tell you whether it corresponded with any of the profiles it was tracking. In fact, there was very little automation involved and most of the work was being done manually. And the error margin was still large. Machine learning provided a different approach to solving computer vision problems. With machine learning, developers no longer needed to manually code every single rule into their vision applications. Instead they programmed “features,” smaller applications that could detect specific patterns in images. They then used a statistical learning algorithm such as linear regression, logistic regression, decision trees or support vector machines (SVM) to detect patterns and classify images and detect objects in them. Machine learning helped solve many problems that were historically challenging for classical software development tools and approaches. For instance, years ago, machine learning engineers were able to create a software that could predict breast cancer survival windows better than human experts. However building the features of the software required the efforts of dozens of engineers and breast cancer experts and took a lot of time develop. Deep learning provided a fundamentally different approach to doing machine learning. Deep learning relies on neural networks, a general-purpose function that can solve any problem representable through examples. When you provide a neural network with many labeled examples of a specific kind of data, it’ll be able to extract common patterns between those examples and transform it into a mathematical equation that will help classify future pieces of information. For instance, creating a facial recognition application with deep learning only requires you to develop or choose a preconstructed algorithm and train it with examples of the faces of the people it must detect. Given enough examples (lots of examples), the neural network will be able to detect faces without further instructions on features or measurements. Deep learning is a very effective method to do computer vision. In most cases, creating a good deep learning algorithm comes down to gathering a large amount of labeled training data and tuning the parameters such as the type and number of layers of neural networks and training epochs. Compared to previous types of machine learning, deep learning is both easier and faster to develop and deploy. Most of current computer vision applications such as cancer detection, self-driving cars and facial recognition make use of deep learning. Deep learning and deep neural networks have moved from the conceptual realm into practical applications thanks to availability and advances in hardware and cloud computing resources. In short not much. That’s the key to why computer vision is so thrilling: Whereas in the past even supercomputers might take days or weeks or even months to chug through all the calculations required, today’s ultra-fast chips and related hardware, along with the a speedy, reliable internet and cloud networks, make the process lightning fast. Once crucial factor has been the willingness of many of the big companies doing AI research to share their work Facebook, Google, IBM, and Microsoft, notably by open sourcing some of their machine learning work. This allows others to build on their work rather than starting from scratch. As a result, the AI industry is cooking along, and experiments that not long ago took weeks to run might take 15 minutes today. And for many real-world applications of computer vision, this process all happens continuously in microseconds, so that a computer today is able to be what scientists call “situationally aware.” Computer vision is one of the areas in Machine Learning where core concepts are already being integrated into major products that we use every day. But it’s not just tech companies that are leverage Machine Learning for image applications. Computer vision enables self-driving cars to make sense of their surroundings. Cameras capture video from different angles around the car and feed it to computer vision software, which then processes the images in real-time to find the extremities of roads, read traffic signs, detect other cars, objects and pedestrians. The self-driving car can then steer its way on streets and highways, avoid hitting obstacles, and (hopefully) safely drive its passengers to their destination. Computer vision also plays an important role in facial recognition applications, the technology that enables computers to match images of people’s faces to their identities. Computer vision algorithms detect facial features in images and compare them with databases of face profiles. Consumer devices use facial recognition to authenticate the identities of their owners. Social media apps use facial recognition to detect and tag users. Law enforcement agencies also rely on facial recognition technology to identify criminals in video feeds. Computer vision also plays an important role in augmented and mixed reality, the technology that enables computing devices such as smartphones, tablets and smart glasses to overlay and embed virtual objects on real world imagery. Using computer vision, AR gear detect objects in real world in order to determine the locations on a device’s display to place a virtual object. For instance, computer vision algorithms can help AR applications detect planes such as tabletops, walls and floors, a very important part of establishing depth and dimensions and placing virtual objects in physical world. Computer vision has also been an important part of advances in health-tech. Computer vision algorithms can help automate tasks such as detecting cancerous moles in skin images or finding symptoms in x-ray and MRI scans. Helping computers to see turns out to be very hard. Inventing a machine that sees like we do is a deceptively difficult task, not just because it’s hard to make computers do it, but because we’re not entirely sure how human vision works in the first place. Studying biological vision requires an understanding of the perception organs like the eyes, as well as the interpretation of the perception within the brain. Much progress has been made, both in charting the process and in terms of discovering the tricks and shortcuts used by the system, although like any study that involves the brain, there is a long way to go. Many popular computer vision applications involve trying to recognize things in photographs; for example: Object Classification: What broad category of object is in this photograph? Object Identification: Which type of a given object is in this photograph? Object Verification: Is the object in the photograph? Object Detection: Where are the objects in the photograph? Object Landmark Detection: What are the key points for the object in the photograph? Object Segmentation: What pixels belong to the object in the image? Object Recognition: What objects are in this photograph and where are they? Outside of just recognition, other methods of analysis include: Video motion analysis uses computer vision to estimate the velocity of objects in a video, or the camera itself. In image segmentation, algorithms partition images into multiple sets of views. Scene reconstruction creates a 3D model of a scene inputted through images or video. In image restoration, noise such as blurring is removed from photos using Machine Learning based filters. Any other application that involves understanding pixels through software can safely be labeled as computer vision. Despite the recent progress, which has been impressive, we’re still not even close to solving computer vision. However, there are already multiple healthcare institutions and enterprises that have found ways to apply CV systems, powered by CNNs, to real-world problems. And this trend is not likely to stop anytime soon. If you want to get in touch and by the way, you know a good joke you can connect with me on Twitter or LinkedIn. Thanks for reading!😄 🙌
[ { "code": null, "e": 428, "s": 172, "text": "One of the most powerful and compelling types of AI is computer vision which you’ve almost surely experienced in any number of ways without even knowing. Here’s a look at what it is, how it works, and why it’s so awesome (and is only going to get better)." }, { "code": null, "e": 729, "s": 428, "text": "Computer vision is the field of computer science that focuses on replicating parts of the complexity of the human vision system and enabling computers to identify and process objects in images and videos in the same way that humans do. Until recently, computer vision only worked in limited capacity." }, { "code": null, "e": 982, "s": 729, "text": "Thanks to advances in artificial intelligence and innovations in deep learning and neural networks, the field has been able to take great leaps in recent years and has been able to surpass humans in some tasks related to detecting and labeling objects." }, { "code": null, "e": 1146, "s": 982, "text": "One of the driving factors behind the growth of computer vision is the amount of data we generate today that is then used to train and make computer vision better." }, { "code": null, "e": 1610, "s": 1146, "text": "Along with a tremendous amount of visual data (more than 3 billion images are shared online every day), the computing power required to analyze the data is now accessible. As the field of computer vision has grown with new hardware and algorithms so has the accuracy rates for object identification. In less than a decade, today’s systems have reached 99 percent accuracy from 50 percent making them more accurate than humans at quickly reacting to visual inputs." }, { "code": null, "e": 1842, "s": 1610, "text": "Early experiments in computer vision started in the 1950s and it was first put to use commercially to distinguish between typed and handwritten text by the 1970s, today the applications for computer vision have grown exponentially." }, { "code": null, "e": 1926, "s": 1842, "text": "By 2022, the computer vision and hardware market is expected to reach $48.6 billion" }, { "code": null, "e": 2321, "s": 1926, "text": "One of the major open questions in both Neuroscience and Machine Learning is: How exactly do our brains work, and how can we approximate that with our own algorithms? The reality is that there are very few working and comprehensive theories of brain computation; so despite the fact that Neural Nets are supposed to “mimic the way the brain works,” nobody is quite sure if that’s actually true." }, { "code": null, "e": 2549, "s": 2321, "text": "The same paradox holds true for computer vision — since we’re not decided on how the brain and eyes process images, it’s difficult to say how well the algorithms used in production approximate our own internal mental processes." }, { "code": null, "e": 2937, "s": 2549, "text": "On a certain level Computer vision is all about pattern recognition. So one way to train a computer how to understand visual data is to feed it images, lots of images thousands, millions if possible that have been labeled, and then subject those to various software techniques, or algorithms, that allow the computer to hunt down patterns in all the elements that relate to those labels." }, { "code": null, "e": 3397, "s": 2937, "text": "So, for example, if you feed a computer a million images of cats (we all love them😄😹), it will subject them all to algorithms that let them analyze the colors in the photo, the shapes, the distances between the shapes, where objects border each other, and so on, so that it identifies a profile of what “cat” means. When it’s finished, the computer will (in theory) be able to use its experience if fed other unlabeled images to find the ones that are of cat." }, { "code": null, "e": 3704, "s": 3397, "text": "Let’s leave our fluffy cat friends for a moment on the side and let’s get more technical🤔😹. Below is a simple illustration of the grayscale image buffer which stores our image of Abraham Lincoln. Each pixel’s brightness is represented by a single 8-bit number, whose range is from 0 (black) to 255 (white):" }, { "code": null, "e": 4666, "s": 3704, "text": "{157, 153, 174, 168, 150, 152, 129, 151, 172, 161, 155, 156, 155, 182, 163, 74, 75, 62, 33, 17, 110, 210, 180, 154, 180, 180, 50, 14, 34, 6, 10, 33, 48, 106, 159, 181, 206, 109, 5, 124, 131, 111, 120, 204, 166, 15, 56, 180, 194, 68, 137, 251, 237, 239, 239, 228, 227, 87, 71, 201, 172, 105, 207, 233, 233, 214, 220, 239, 228, 98, 74, 206, 188, 88, 179, 209, 185, 215, 211, 158, 139, 75, 20, 169, 189, 97, 165, 84, 10, 168, 134, 11, 31, 62, 22, 148, 199, 168, 191, 193, 158, 227, 178, 143, 182, 106, 36, 190, 205, 174, 155, 252, 236, 231, 149, 178, 228, 43, 95, 234, 190, 216, 116, 149, 236, 187, 86, 150, 79, 38, 218, 241, 190, 224, 147, 108, 227, 210, 127, 102, 36, 101, 255, 224, 190, 214, 173, 66, 103, 143, 96, 50, 2, 109, 249, 215, 187, 196, 235, 75, 1, 81, 47, 0, 6, 217, 255, 211, 183, 202, 237, 145, 0, 0, 12, 108, 200, 138, 243, 236, 195, 206, 123, 207, 177, 121, 123, 200, 175, 13, 96, 218};" }, { "code": null, "e": 4926, "s": 4666, "text": "This way of storing image data may run counter to your expectations, since the data certainly appears to be two-dimensional when it is displayed. Yet, this is the case, since computer memory consists simply of an ever-increasing linear list of address spaces." }, { "code": null, "e": 5343, "s": 4926, "text": "Let’s go back to the first picture again and imagine adding a colored one. Now things start to get more complicated. Computers usually read color as a series of 3 values — red, green, and blue (RGB) — on that same 0–255 scale. Now, each pixel actually has 3 values for the computer to store in addition to its position. If we were to colorize President Lincoln, that would lead to 12 x 16 x 3 values, or 576 numbers." }, { "code": null, "e": 5617, "s": 5343, "text": "That’s a lot of memory to require for one image, and a lot of pixels for an algorithm to iterate over. But to train a model with meaningful accuracy especially when you’re talking about Deep Learning you’d usually need tens of thousands of images, and the more the merrier." }, { "code": null, "e": 5904, "s": 5617, "text": "Before the advent of deep learning, the tasks that computer vision could perform were very limited and required a lot of manual coding and effort by developers and human operators. For instance, if you wanted to perform facial recognition, you would have to perform the following steps:" }, { "code": null, "e": 6022, "s": 5904, "text": "Create a database: You had to capture individual images of all the subjects you wanted to track in a specific format." }, { "code": null, "e": 6307, "s": 6022, "text": "Annotate images: Then for every individual image, you would have to enter several key data points, such as distance between the eyes, the width of nose bridge, distance between upper-lip and nose, and dozens of other measurements that define the unique characteristics of each person." }, { "code": null, "e": 6570, "s": 6307, "text": "Capture new images: Next, you would have to capture new images, whether from photographs or video content. And then you had to go through the measurement process again, marking the key points on the image. You also had to factor in the angle the image was taken." }, { "code": null, "e": 6932, "s": 6570, "text": "After all this manual work, the application would finally be able to compare the measurements in the new image with the ones stored in its database and tell you whether it corresponded with any of the profiles it was tracking. In fact, there was very little automation involved and most of the work was being done manually. And the error margin was still large." }, { "code": null, "e": 7449, "s": 6932, "text": "Machine learning provided a different approach to solving computer vision problems. With machine learning, developers no longer needed to manually code every single rule into their vision applications. Instead they programmed “features,” smaller applications that could detect specific patterns in images. They then used a statistical learning algorithm such as linear regression, logistic regression, decision trees or support vector machines (SVM) to detect patterns and classify images and detect objects in them." }, { "code": null, "e": 7893, "s": 7449, "text": "Machine learning helped solve many problems that were historically challenging for classical software development tools and approaches. For instance, years ago, machine learning engineers were able to create a software that could predict breast cancer survival windows better than human experts. However building the features of the software required the efforts of dozens of engineers and breast cancer experts and took a lot of time develop." }, { "code": null, "e": 8358, "s": 7893, "text": "Deep learning provided a fundamentally different approach to doing machine learning. Deep learning relies on neural networks, a general-purpose function that can solve any problem representable through examples. When you provide a neural network with many labeled examples of a specific kind of data, it’ll be able to extract common patterns between those examples and transform it into a mathematical equation that will help classify future pieces of information." }, { "code": null, "e": 8717, "s": 8358, "text": "For instance, creating a facial recognition application with deep learning only requires you to develop or choose a preconstructed algorithm and train it with examples of the faces of the people it must detect. Given enough examples (lots of examples), the neural network will be able to detect faces without further instructions on features or measurements." }, { "code": null, "e": 9115, "s": 8717, "text": "Deep learning is a very effective method to do computer vision. In most cases, creating a good deep learning algorithm comes down to gathering a large amount of labeled training data and tuning the parameters such as the type and number of layers of neural networks and training epochs. Compared to previous types of machine learning, deep learning is both easier and faster to develop and deploy." }, { "code": null, "e": 9437, "s": 9115, "text": "Most of current computer vision applications such as cancer detection, self-driving cars and facial recognition make use of deep learning. Deep learning and deep neural networks have moved from the conceptual realm into practical applications thanks to availability and advances in hardware and cloud computing resources." }, { "code": null, "e": 9993, "s": 9437, "text": "In short not much. That’s the key to why computer vision is so thrilling: Whereas in the past even supercomputers might take days or weeks or even months to chug through all the calculations required, today’s ultra-fast chips and related hardware, along with the a speedy, reliable internet and cloud networks, make the process lightning fast. Once crucial factor has been the willingness of many of the big companies doing AI research to share their work Facebook, Google, IBM, and Microsoft, notably by open sourcing some of their machine learning work." }, { "code": null, "e": 10393, "s": 9993, "text": "This allows others to build on their work rather than starting from scratch. As a result, the AI industry is cooking along, and experiments that not long ago took weeks to run might take 15 minutes today. And for many real-world applications of computer vision, this process all happens continuously in microseconds, so that a computer today is able to be what scientists call “situationally aware.”" }, { "code": null, "e": 10541, "s": 10393, "text": "Computer vision is one of the areas in Machine Learning where core concepts are already being integrated into major products that we use every day." }, { "code": null, "e": 10633, "s": 10541, "text": "But it’s not just tech companies that are leverage Machine Learning for image applications." }, { "code": null, "e": 11115, "s": 10633, "text": "Computer vision enables self-driving cars to make sense of their surroundings. Cameras capture video from different angles around the car and feed it to computer vision software, which then processes the images in real-time to find the extremities of roads, read traffic signs, detect other cars, objects and pedestrians. The self-driving car can then steer its way on streets and highways, avoid hitting obstacles, and (hopefully) safely drive its passengers to their destination." }, { "code": null, "e": 11659, "s": 11115, "text": "Computer vision also plays an important role in facial recognition applications, the technology that enables computers to match images of people’s faces to their identities. Computer vision algorithms detect facial features in images and compare them with databases of face profiles. Consumer devices use facial recognition to authenticate the identities of their owners. Social media apps use facial recognition to detect and tag users. Law enforcement agencies also rely on facial recognition technology to identify criminals in video feeds." }, { "code": null, "e": 12257, "s": 11659, "text": "Computer vision also plays an important role in augmented and mixed reality, the technology that enables computing devices such as smartphones, tablets and smart glasses to overlay and embed virtual objects on real world imagery. Using computer vision, AR gear detect objects in real world in order to determine the locations on a device’s display to place a virtual object. For instance, computer vision algorithms can help AR applications detect planes such as tabletops, walls and floors, a very important part of establishing depth and dimensions and placing virtual objects in physical world." }, { "code": null, "e": 12477, "s": 12257, "text": "Computer vision has also been an important part of advances in health-tech. Computer vision algorithms can help automate tasks such as detecting cancerous moles in skin images or finding symptoms in x-ray and MRI scans." }, { "code": null, "e": 12529, "s": 12477, "text": "Helping computers to see turns out to be very hard." }, { "code": null, "e": 12734, "s": 12529, "text": "Inventing a machine that sees like we do is a deceptively difficult task, not just because it’s hard to make computers do it, but because we’re not entirely sure how human vision works in the first place." }, { "code": null, "e": 13100, "s": 12734, "text": "Studying biological vision requires an understanding of the perception organs like the eyes, as well as the interpretation of the perception within the brain. Much progress has been made, both in charting the process and in terms of discovering the tricks and shortcuts used by the system, although like any study that involves the brain, there is a long way to go." }, { "code": null, "e": 13206, "s": 13100, "text": "Many popular computer vision applications involve trying to recognize things in photographs; for example:" }, { "code": null, "e": 13282, "s": 13206, "text": "Object Classification: What broad category of object is in this photograph?" }, { "code": null, "e": 13357, "s": 13282, "text": "Object Identification: Which type of a given object is in this photograph?" }, { "code": null, "e": 13411, "s": 13357, "text": "Object Verification: Is the object in the photograph?" }, { "code": null, "e": 13470, "s": 13411, "text": "Object Detection: Where are the objects in the photograph?" }, { "code": null, "e": 13555, "s": 13470, "text": "Object Landmark Detection: What are the key points for the object in the photograph?" }, { "code": null, "e": 13623, "s": 13555, "text": "Object Segmentation: What pixels belong to the object in the image?" }, { "code": null, "e": 13699, "s": 13623, "text": "Object Recognition: What objects are in this photograph and where are they?" }, { "code": null, "e": 13763, "s": 13699, "text": "Outside of just recognition, other methods of analysis include:" }, { "code": null, "e": 13876, "s": 13763, "text": "Video motion analysis uses computer vision to estimate the velocity of objects in a video, or the camera itself." }, { "code": null, "e": 13956, "s": 13876, "text": "In image segmentation, algorithms partition images into multiple sets of views." }, { "code": null, "e": 14041, "s": 13956, "text": "Scene reconstruction creates a 3D model of a scene inputted through images or video." }, { "code": null, "e": 14147, "s": 14041, "text": "In image restoration, noise such as blurring is removed from photos using Machine Learning based filters." }, { "code": null, "e": 14263, "s": 14147, "text": "Any other application that involves understanding pixels through software can safely be labeled as computer vision." }, { "code": null, "e": 14584, "s": 14263, "text": "Despite the recent progress, which has been impressive, we’re still not even close to solving computer vision. However, there are already multiple healthcare institutions and enterprises that have found ways to apply CV systems, powered by CNNs, to real-world problems. And this trend is not likely to stop anytime soon." }, { "code": null, "e": 14697, "s": 14584, "text": "If you want to get in touch and by the way, you know a good joke you can connect with me on Twitter or LinkedIn." } ]
IEEE-CIS Fraud Detection - Top 5% Solution | by Arun Mohan | Towards Data Science
I know that you or anyone around you have been the victim of some fraud activities. Directly we can’t control people on making easy money through fraud activities. Online transactions are one of the areas where fraud transactions can occur and can lead to loss of money. In this competition, we will detect online fraudulent transactions using machine learning techniques. Our objective is to implement a solution that comes under the top 5% in Kaggle leaderboard which is not an easy task. IEEE-CIS Fraud Detection is a Kaggle competition organized by the IEEE Computational Intelligence Society. Vesta Corporation who is one of the forerunners in guaranteed e-commerce payment solutions provided the dataset for this competition. In this blog, I will give a good overview of how I reached out to the top 5% result. I won't be explaining each and every line of code. But rather I will give a good overview of my solution. You can always refer to my code here. The data is broken into two files identity and transaction, which are joined by TransactionID each for train and test. Thus we have 4 files — train transactions, train identity, test transactions, and test identity. It is important to note that all transaction does not have corresponding identity information. Let us get familiarity with various columns present: Transaction data Transaction id: Id related to the transaction TransactionDT: timedelta from a given reference datetime (not an actual timestamp) TransactionAMT: transaction payment amount in USD ProductCD [Categorical]: product code(the product for each transaction) card1–6 [Categorical]: payment card related information like card type, country etc addr1, addr2 [Categorical]: address information dist1,dist2: some distance information P_emaildomain [Categorical]: email domain of purchaser. R_emaildomain [Categorical]: email domain of the recipient. C1-C14: counting, such as how many addresses are found to be associated with the payment card, etc. The actual meaning is masked. D1-D15: time delta, such as days between the previous transactions, etc. M1-M9 [Categorical]: match, such as names on card and address, etc. Vxxx: Vesta engineered rich features, including ranking, counting, and other entity relations. Identity data Transaction id: Id related to the transaction DeviceType [Categorical]: Type of device used for the transaction DeviceInfo [Categorical]: More information about device used id 1–38 [Categorical+numeric]: network connection information,browser information etc (id 12–38 are categorical information) Note: Actually we don't have access to exact information about columns. Mostly it is because of security purposes as we are handling transaction data. The main business objective of finding fraud transactions can be following: If a fraud transaction is found out, the company should immediately block that card.We should be able to predict the probability of fraud transactionWe should not predict fraud transactions as nonfraud. Also the vice versa. So precision and recall should be taken care of. If a fraud transaction is found out, the company should immediately block that card. We should be able to predict the probability of fraud transaction We should not predict fraud transactions as nonfraud. Also the vice versa. So precision and recall should be taken care of. Do exploratory data analysis on each and every column and understand the impact of each feature.Build a baseline model.Create new features and see whether those features improve the performance of the model. If yes retain the features or else drop those features. I used forward feature selection for that.Iteratively continue this approach until we get a good score. Do exploratory data analysis on each and every column and understand the impact of each feature. Build a baseline model. Create new features and see whether those features improve the performance of the model. If yes retain the features or else drop those features. I used forward feature selection for that. Iteratively continue this approach until we get a good score. It's not ideal to explain the analysis of each and every feature here. I will explain some of my interesting observations. You can find the rest of the analysis from my repository. Let us load the data first Now let us load the saved files We have train data of shape (590540, 434) and test data of shape (590540, 434). Let us see how many values are missing in train and test data We will see columns with more than 90 % values missing. We can see that columns like id_21,id_22,id_23,id_24,id_25,id_26,id_27,id_01,id_07,id_08 have more than 99 percent missing values. Its better we drop those features. Is_Fraud (Target feature) This is the target variable which we need to predict. Let us see how it is distributed. Observations: As expected we can see that class is heavily imbalanced. Here 96.5% of transactions are not fraud and the rest 3.5% of transactions are fraudulent. We will choose Area under the ROC curve (AUC) as a metric for our ML problem. Why accuracy not for imbalanced datasets? Consider a scenario like this where we have an imbalanced data set. For example, consider the case of credit card fraud detection with 98% percentage of points as non-fraud(1) and the rest 2% points as fraud(1). In such cases even if we predict all the points as non-fraud also we will get 98% accuracy. But actually, it is not the case. So we can’t use accuracy as a metric. What is AUC ROC? AUC is the area under the ROC curve. It tells how much the model is capable of distinguishing between classes. Higher the AUC, the better the model is at predicting 0s as 0s and 1s as 1s. The ROC curve is plotted with TPR against the FPR where TPR is on the y-axis and FPR is on the x-axis. On analysis, one other thing I found was that in most of the cases for a client if one of the transactions is fraud all of his/her earlier transactions are marked as fraud. But this is not true for all the cases. There are also exceptions in it. This makes our prediction harder. Note: I’m able to identify the clients by creating my own uid. I will explain as we proceed further. Transaction Date This indicates a time delta from a given reference DateTime. For example, 86400 can be 86400 seconds from a particular time, for eg: from 2/12/2010 12:05:09 pm. Here we have to check the data obtained in train and test is continuous with time. This is important for the train-test split. That means training data should be from an earlier period and test data should be from a later period of time. Observations: There is a slight gap in between, but otherwise, the training set is from an earlier period of time and test data from a later period of time. This can impact train validation split or cross-validation techniques should be used. Another observation is that there are certain days in which the number of transactions is more than 10000 Now let us see fraudulent transactions on different days of the week as well as among different hours. We can see that on the 3rd fay fraudulent transactions are very less, similarly, in the 7th hour, the percentage of fraudulent transactions is high compared to other hours. Transaction Amt This is the amount associated with each transaction. Let us see how the transaction Amount is distributed. (I also took a log of the transaction amount which gives a better idea to interpret) Observations: We can see that there is one point in train data where the amount > 30000. It's better we remove the outlier since it can affect our models(especially distance-based algorithms like logistic regression, knn etc.) in prediction. Also, Outliers like this can cause an overfitting problem. For instance, tree-based models can put these outliers in leaf nodes, which are noise and not part of a general pattern. Therefore, I decided to remove the values larger than 30,000 in the training set. It seems that the transactions with ‘LogTransactionAmt’ larger than 5.5 (244 dollars) and smaller than 3.3 (27 dollars) have a higher frequency and probability density of being fraudulent. On the other hand, the ones with ‘LogTransactionAmt’ from 3.3 to 5.5 have a higher chance of being legit. Product CD This is the product code associated with each transaction. Let us see how much percent of transactions are fraud among different product codes. We can see that among transactions related to product code C about 12 percent are fraud transactions. similarly close to 6% of transactions are fraud among product codes. D Columns We have D columns from D1 to D15. These represent time deltas such as days between previous transaction and current transaction, days between current and first transaction, etc. Even though they have not given a clear understanding regarding D cols, we got some insights after a good analysis. We assume D1 as the day since credit card usage has begun. Subtracting this from Transaction day will result in content value per client. df_train['D1n'] = df_train['D1'] - df_train.TransactionDT/np.float32(24*60*60) We did a normalization of all D cols and allowed the model to decide which are important and which are not. Card1- Card6 These columns represent payment information related to cards. Some interesting observations from these features are: There is a wide range of values in card1. If we see the distribution there are overlapping's. card1 alone cannot distinguish between fraudulent and nonfraudulent transactions. No missing values are there in card1. A small percent of data is missing in card2. Similar to card1 a lot of unique values are present in card2 also. card3 has a low correlation with other card columns. card 4 indicates which type of card do client uses visa, Mastercard, American Express, or discover. Similarly, card6 indicates the type of card- debit or credit. P-email domain and R-email domain: These are email domains of purchaser and recipient respectively. About 76% of values are missing in the R-email domain. In purchaser email domains most mails are from gmail.com. Among those More fraud transactions comes from domain protonmail.com which is more than 90% which is a serious issue. addr1 and addr2: These are some address-related information related to the client. Around 11% of data is missing from both addr1 and addr2. There are about 332 unique values in addr1 and 74 in the case of addr2. dist1 and dist2: This might indicate the distance between transaction location and card owner address. This is just my assumption. We have about 93% of values missing in dist2. There is no correlation between dist1 and dist2. While dist2 is very weakly correlated with all other attributes. C1-C14: These are information such as counting. C3 is somewhat different from other Cxx features. For c3, from box pot, it is clear that there is no value beyond 3 in train data for fraudulent transactions. For no fraudulent transactions, the value ranges from 0 to 26. Also, C3 is very weakly co-related with other Cxx columns. M1-M9: More than 50 percent of values are missing among M columns. These features do not clearly distinguish between fraudulent and nonfraudulent transactions. V1-V399: These are vesta-engineered features. These are masked information that can be ranking, counting, or other entity relations. There exist a strong correlation (>0.9) between many features. If possible It's better we reduce the number of these features as it can reduce the computational complexity of the model. As a baseline, we created 3 models. — Logistic regression, Random Forest and XG Boost. We obtained the following results after a small hyperparameter tuning. Logistic regression: 0.84018(Train AUC), 0.84245(Test AUC) Random Forest: 0.9030(Train AUC), 0.8600(Test AUC) Xgboost: 0.994(Train AUC), 0.9234(Test AUC) As Xgboost gives better performance, we decided to stick to it. We also plotted feature importance to get a basic idea of the influence of various features. For Xgboost we got a Public leaderboard score of 0.9004 and 0.9238 for private LB. Both columns are unique. One is time-related information and the other is a unique id. Adding this to the model doesn't make much sense. So we removed those features. From our Xgboost model, after plotting feature importance we came to know that all V cols do not contribute much to the model. Also on analysis, we found that there exists a strong correlation between several ‘Vxx’ columns. So we decided to reduce the number of columns by doing a correlation analysis. How to reduce columns based on NaN values? Group columns based on a number of missing values Eg. if there are 4 columns v1,v2,v3, and v4. If v1 and v3 have 56 missing values and v2 have 21 and v4 have 5 missing values, we have 3 groups [‘v1’,’v3'], [‘v2’] and [‘v4’] In each group, For each column in that group find the correlation with other columns and take only columns with a correlation coefficient > 0.75. Take the largest list with common elements as a subgroup. Each group contains several subgroups. For eg: if we have [[v1,v2],[v6],[v1,v4,v2,v5],[v5,v4]] ,our output will be [[v1,v2,v4,v5],[v6]]. Now from each subgroup choose the column with the most number of unique values. For eg, In subgroup [v1,v2,v4,v5], let v2 have the most unique values. So out output becomes [v2,v6]. The above figure indicates some part of our output. We will do correlation analysis on each group to reduce the number of columns. Here columns ‘V35’, ‘V40’, ‘V41’, ‘V39’, ‘V38’, ‘V51’, ‘V37’, ‘V52’, ‘V36’, ‘V50’, ‘V48’, ‘V42’,‘V43’, ‘V44’, ‘V46’, ‘V47’, ‘V45’, ‘V49’ 168969 missing values. So they form a group. Now we will plot a correlation matrix. Next, we will group them based on correlation. We will consider columns with a correlation >0.75 to be in the same group. [[‘V35’,’V36'],[‘V37’,’V38'],[‘V39’,’V40',’V42',’V43',’V50',’V51',’V52'],[‘V41’],[‘V44’,’V45'],[‘V46’,’V47'],[‘V48’,’V49']] We will reduce this using the above function and will end up with the following columns: [‘V36’, ‘V37’, ‘V40’, ‘V41’, ‘V44’, ‘V47’, ‘V48’]. Similarly, we will do for all the groups and finally end up with the following V columns. ['V1', 'V3', 'V4', 'V6', 'V8', 'V11', 'V13', 'V14', 'V17', 'V20','V23', 'V26', 'V27', 'V30', 'V36', 'V37', 'V40', 'V41', 'V44', 'V47', 'V48', 'V54', 'V56', 'V59','V62', 'V65', 'V67', 'V68', 'V70', 'V76', 'V78', 'V80', 'V82', 'V86', 'V88', 'V89', 'V91', 'V96','V98', 'V99', 'V104', 'V107', 'V108', 'V111', 'V115', 'V117', 'V120', 'V121', 'V123', 'V124', 'V127','V129', 'V130', 'V136', 'V138', 'V139', 'V142', 'V147', 'V156', 'V162', 'V165', 'V160', 'V166', 'V178','V176', 'V173', 'V182', 'V187', 'V203', 'V205', 'V207', 'V215', 'V169', 'V171', 'V175', 'V180', 'V185','V188', 'V198', 'V210', 'V209', 'V218', 'V223', 'V224', 'V226', 'V228', 'V229', 'V235', 'V240', 'V258','V257', 'V253', 'V252', 'V260', 'V261', 'V264', 'V266', 'V267', 'V274', 'V277', 'V220', 'V221', 'V234','V238', 'V250', 'V271', 'V294', 'V284', 'V285', 'V286', 'V291','V297', 'V303', 'V305', 'V307', 'V309', 'V310', 'V320', 'V281', 'V283', 'V289', 'V296', 'V301', 'V314', 'V332', 'V325', 'V335', 'V338'] Reducing V cols doesn’t decrease the score on local validation. We got 0.993 AUC on train data and 0.9231 on cv data. Even though it reduced the Private LB score by 0.001, we were able to reduce 211 columns and thus improved the computational complexity of the model. So dropping those features is a better approach. I also tried to reduced C and M cols in a similar way. But it decreased the score by more than 0.002 AUC. So as of now, I kept it. From Kaggle's discussions, I came to know that D1 is the day since credit card usage began. Subtracting this from Transaction Day will make it an almost constant value per client. I did the same approach for all the D cols. To check the newly created features are helpful or not I did a forward feature selection. How to select D cols which are to be modified? We know that our baseline provides an AUC of 0.923. This will be our initial bese_score On the first iteration, I added normalized D1 and removed the original D1, and created a model out of it and the test AUC is noted. Now, this is repeated for all Dcols from D1 to D15. Each time AUC is noted and choose the Dcol which improves the AUC from baseline (0.923)more. This AUC becomes our best_score. On the next iteration, the earlier D col is included and step 1 is repeated for all the remaining columns along with D1. Iterations are repeated until the AUC is not improved. Finally, we end up with normalizing ‘D15’, ’D4', ’D2', ’D 11', and ‘D10’. Our local AUC became 0.934. Next, I created the following features: day of the week: Day of the week in which transaction occurred hour: Hour in which transaction occurred cent: cents associated with the transaction amount LogTransactionAmt: Log of the transaction amount P_email_company: company to which P_email_domain belongs. It is obtained from the internet. Device_corp: I created this column from Device Info. It is basically parent company details obtained from device info. Hour fraud status: From the graph, we obtained while doing EDA, we know the percentage of fraudulent transactions in each hour. Based on this I created 4 categories very low, low, medium, and high so that each hour falls on any of these categories. Then I used FFS and see which of the features improve the result. But only the hour column improved the score to 0.9338. The function for forward feature selection looks as follows: Next, I created some encoding features. Before that let us familiarize ourselves with the following functions. Based on these I created about 45 features. Then I did a forward feature selection and selected those features which improved model performance. As a result, I ended up with the following 6 new features card4_addr1_R_emaildomain', 'card2_FE','card1_FE', 'card1_addr1_R_emaildomain', 'card3_addr1_P_emaildomain', 'card1_addr1','card4_addr1_P_emaildomain_FE' These improved my local validation score to 0.9634. Why UID(identifying clients) based features will work? Suppose we have the following data: Here if we construct a decision tree, it can look as follows In this case, we can see that out of 11 points, 8 points are correctly classified. Suppose we can identify individual clients. I will explain to you how I am able to find it. If I am able to find such uid’s our data look as follows. Let us create a new group aggregate from this uid. Let us construct a decision tree based on that. We can see that in this case, all 11 points are classified correctly. Even though in real case this won't be as accurate, definitely it can lead to improving the performance of the model. So finding the uid is key in improving our score. On Analysis I understood that card1, D1, and addr1 will help me to identify the client. So I combined all those 3 columns and used as uid. Now I created several means, standard deviation, and count aggregations of several features with this uid. I used the following function for making aggregations. I created about 100 aggregation features based on uid. But after Forward feature selection on different subsets, I end up with 9 new features. 'M9_uid_mean' , 'M5_uid_mean' , 'D2_uid_mean' , 'D15_uid_mean' , 'C13_uid_mean' , 'C9_uid_mean' , 'C1_uid_mean' , 'C11_uid_mean' , 'TransactionAmt_uid_std' This improved my Local cv score to 0.9470. The results from the private leader board and public leader board were 0.9158 and 0.9423 respectively. From analysis, it was clear that no uid is perfect. So I tried to create a new uid just by combining card1 with addr1. Then I created similar aggregations using new uid and see which of those new features improves the result of Forward feature selection. I end up with the following 4 new features: 'M4_uid2_mean' , 'M1_uid2_mean' , 'M7_uid2_mean' , 'M8_uid2_std' This improved my local CV to 0.9481. Also, new private and public LB scores had become 0.917 and 0.940 respectively. Thus UID based features really help us to improve the performance of the model. These are the two important techniques that literally improved the performance of my algorithm. As you know our model was tuned earlier, but currently, a lot of new features have been introduced. Let us find out the best parameters that fit the model. For that, I used Randomized Search Cv from Sklearn. After a randomized search, we end up with the following parameters n_estimators=5000,max_depth=12,learning_rate=0.002,subsample=0.8, colsample_bytree=0.4 First, we created a new column that indicates the month of the transaction. We will predict test.csv using GroupKFold with months as groups. The training data are the months December 2017, January 2018, February 2018, March 2018, April 2018, and May 2018. We refer to these months as 12, 13, 14, 15, 16, 17. Fold one in GroupKFold will train on months 13 thru 17 and predict month 12. Note that the only purpose of month 12 is to tell XGB when to early_stop we don't actually care about the backward time predictions. The model trained on months 13 thru 17 will also predict test.csv which is forward in time. Our code looks as follows: Finally, our local CV score after cross-validation has become 0.951265. New Private and Public LB score has become 0.928873 and 0.954825 respectively. It ranked roughly 226 among 6351.(Top 3.5%). Our progress throughout the project is as follows: You can check my entire code at https://github.com/arunm8489/IEE-CIS-Fraud-detection. It's not the end. Still, there is a score of improvement. Some of the approaches I have not tried: My entire work was around the XgBoost algorithm. You can try other algorithms like Lightgbm, cat boost etc. I have reduced v cols based on the number of NaN values and Pearsons-correlation coefficient. You can also try PCA in each NaN groups and see whether it improves the performance I have applied forward feature selection to select important features. I applied it to different subsets. Trying it on different subsets can yield different results.
[ { "code": null, "e": 442, "s": 171, "text": "I know that you or anyone around you have been the victim of some fraud activities. Directly we can’t control people on making easy money through fraud activities. Online transactions are one of the areas where fraud transactions can occur and can lead to loss of money." }, { "code": null, "e": 903, "s": 442, "text": "In this competition, we will detect online fraudulent transactions using machine learning techniques. Our objective is to implement a solution that comes under the top 5% in Kaggle leaderboard which is not an easy task. IEEE-CIS Fraud Detection is a Kaggle competition organized by the IEEE Computational Intelligence Society. Vesta Corporation who is one of the forerunners in guaranteed e-commerce payment solutions provided the dataset for this competition." }, { "code": null, "e": 1132, "s": 903, "text": "In this blog, I will give a good overview of how I reached out to the top 5% result. I won't be explaining each and every line of code. But rather I will give a good overview of my solution. You can always refer to my code here." }, { "code": null, "e": 1443, "s": 1132, "text": "The data is broken into two files identity and transaction, which are joined by TransactionID each for train and test. Thus we have 4 files — train transactions, train identity, test transactions, and test identity. It is important to note that all transaction does not have corresponding identity information." }, { "code": null, "e": 1496, "s": 1443, "text": "Let us get familiarity with various columns present:" }, { "code": null, "e": 1513, "s": 1496, "text": "Transaction data" }, { "code": null, "e": 1559, "s": 1513, "text": "Transaction id: Id related to the transaction" }, { "code": null, "e": 1642, "s": 1559, "text": "TransactionDT: timedelta from a given reference datetime (not an actual timestamp)" }, { "code": null, "e": 1692, "s": 1642, "text": "TransactionAMT: transaction payment amount in USD" }, { "code": null, "e": 1764, "s": 1692, "text": "ProductCD [Categorical]: product code(the product for each transaction)" }, { "code": null, "e": 1848, "s": 1764, "text": "card1–6 [Categorical]: payment card related information like card type, country etc" }, { "code": null, "e": 1896, "s": 1848, "text": "addr1, addr2 [Categorical]: address information" }, { "code": null, "e": 1935, "s": 1896, "text": "dist1,dist2: some distance information" }, { "code": null, "e": 1991, "s": 1935, "text": "P_emaildomain [Categorical]: email domain of purchaser." }, { "code": null, "e": 2051, "s": 1991, "text": "R_emaildomain [Categorical]: email domain of the recipient." }, { "code": null, "e": 2181, "s": 2051, "text": "C1-C14: counting, such as how many addresses are found to be associated with the payment card, etc. The actual meaning is masked." }, { "code": null, "e": 2254, "s": 2181, "text": "D1-D15: time delta, such as days between the previous transactions, etc." }, { "code": null, "e": 2322, "s": 2254, "text": "M1-M9 [Categorical]: match, such as names on card and address, etc." }, { "code": null, "e": 2417, "s": 2322, "text": "Vxxx: Vesta engineered rich features, including ranking, counting, and other entity relations." }, { "code": null, "e": 2431, "s": 2417, "text": "Identity data" }, { "code": null, "e": 2477, "s": 2431, "text": "Transaction id: Id related to the transaction" }, { "code": null, "e": 2543, "s": 2477, "text": "DeviceType [Categorical]: Type of device used for the transaction" }, { "code": null, "e": 2604, "s": 2543, "text": "DeviceInfo [Categorical]: More information about device used" }, { "code": null, "e": 2729, "s": 2604, "text": "id 1–38 [Categorical+numeric]: network connection information,browser information etc (id 12–38 are categorical information)" }, { "code": null, "e": 2880, "s": 2729, "text": "Note: Actually we don't have access to exact information about columns. Mostly it is because of security purposes as we are handling transaction data." }, { "code": null, "e": 2956, "s": 2880, "text": "The main business objective of finding fraud transactions can be following:" }, { "code": null, "e": 3229, "s": 2956, "text": "If a fraud transaction is found out, the company should immediately block that card.We should be able to predict the probability of fraud transactionWe should not predict fraud transactions as nonfraud. Also the vice versa. So precision and recall should be taken care of." }, { "code": null, "e": 3314, "s": 3229, "text": "If a fraud transaction is found out, the company should immediately block that card." }, { "code": null, "e": 3380, "s": 3314, "text": "We should be able to predict the probability of fraud transaction" }, { "code": null, "e": 3504, "s": 3380, "text": "We should not predict fraud transactions as nonfraud. Also the vice versa. So precision and recall should be taken care of." }, { "code": null, "e": 3872, "s": 3504, "text": "Do exploratory data analysis on each and every column and understand the impact of each feature.Build a baseline model.Create new features and see whether those features improve the performance of the model. If yes retain the features or else drop those features. I used forward feature selection for that.Iteratively continue this approach until we get a good score." }, { "code": null, "e": 3969, "s": 3872, "text": "Do exploratory data analysis on each and every column and understand the impact of each feature." }, { "code": null, "e": 3993, "s": 3969, "text": "Build a baseline model." }, { "code": null, "e": 4181, "s": 3993, "text": "Create new features and see whether those features improve the performance of the model. If yes retain the features or else drop those features. I used forward feature selection for that." }, { "code": null, "e": 4243, "s": 4181, "text": "Iteratively continue this approach until we get a good score." }, { "code": null, "e": 4424, "s": 4243, "text": "It's not ideal to explain the analysis of each and every feature here. I will explain some of my interesting observations. You can find the rest of the analysis from my repository." }, { "code": null, "e": 4451, "s": 4424, "text": "Let us load the data first" }, { "code": null, "e": 4483, "s": 4451, "text": "Now let us load the saved files" }, { "code": null, "e": 4625, "s": 4483, "text": "We have train data of shape (590540, 434) and test data of shape (590540, 434). Let us see how many values are missing in train and test data" }, { "code": null, "e": 4681, "s": 4625, "text": "We will see columns with more than 90 % values missing." }, { "code": null, "e": 4847, "s": 4681, "text": "We can see that columns like id_21,id_22,id_23,id_24,id_25,id_26,id_27,id_01,id_07,id_08 have more than 99 percent missing values. Its better we drop those features." }, { "code": null, "e": 4873, "s": 4847, "text": "Is_Fraud (Target feature)" }, { "code": null, "e": 4961, "s": 4873, "text": "This is the target variable which we need to predict. Let us see how it is distributed." }, { "code": null, "e": 4975, "s": 4961, "text": "Observations:" }, { "code": null, "e": 5201, "s": 4975, "text": "As expected we can see that class is heavily imbalanced. Here 96.5% of transactions are not fraud and the rest 3.5% of transactions are fraudulent. We will choose Area under the ROC curve (AUC) as a metric for our ML problem." }, { "code": null, "e": 5243, "s": 5201, "text": "Why accuracy not for imbalanced datasets?" }, { "code": null, "e": 5619, "s": 5243, "text": "Consider a scenario like this where we have an imbalanced data set. For example, consider the case of credit card fraud detection with 98% percentage of points as non-fraud(1) and the rest 2% points as fraud(1). In such cases even if we predict all the points as non-fraud also we will get 98% accuracy. But actually, it is not the case. So we can’t use accuracy as a metric." }, { "code": null, "e": 5636, "s": 5619, "text": "What is AUC ROC?" }, { "code": null, "e": 5927, "s": 5636, "text": "AUC is the area under the ROC curve. It tells how much the model is capable of distinguishing between classes. Higher the AUC, the better the model is at predicting 0s as 0s and 1s as 1s. The ROC curve is plotted with TPR against the FPR where TPR is on the y-axis and FPR is on the x-axis." }, { "code": null, "e": 6207, "s": 5927, "text": "On analysis, one other thing I found was that in most of the cases for a client if one of the transactions is fraud all of his/her earlier transactions are marked as fraud. But this is not true for all the cases. There are also exceptions in it. This makes our prediction harder." }, { "code": null, "e": 6308, "s": 6207, "text": "Note: I’m able to identify the clients by creating my own uid. I will explain as we proceed further." }, { "code": null, "e": 6325, "s": 6308, "text": "Transaction Date" }, { "code": null, "e": 6724, "s": 6325, "text": "This indicates a time delta from a given reference DateTime. For example, 86400 can be 86400 seconds from a particular time, for eg: from 2/12/2010 12:05:09 pm. Here we have to check the data obtained in train and test is continuous with time. This is important for the train-test split. That means training data should be from an earlier period and test data should be from a later period of time." }, { "code": null, "e": 6738, "s": 6724, "text": "Observations:" }, { "code": null, "e": 6967, "s": 6738, "text": "There is a slight gap in between, but otherwise, the training set is from an earlier period of time and test data from a later period of time. This can impact train validation split or cross-validation techniques should be used." }, { "code": null, "e": 7073, "s": 6967, "text": "Another observation is that there are certain days in which the number of transactions is more than 10000" }, { "code": null, "e": 7176, "s": 7073, "text": "Now let us see fraudulent transactions on different days of the week as well as among different hours." }, { "code": null, "e": 7349, "s": 7176, "text": "We can see that on the 3rd fay fraudulent transactions are very less, similarly, in the 7th hour, the percentage of fraudulent transactions is high compared to other hours." }, { "code": null, "e": 7365, "s": 7349, "text": "Transaction Amt" }, { "code": null, "e": 7557, "s": 7365, "text": "This is the amount associated with each transaction. Let us see how the transaction Amount is distributed. (I also took a log of the transaction amount which gives a better idea to interpret)" }, { "code": null, "e": 7571, "s": 7557, "text": "Observations:" }, { "code": null, "e": 7799, "s": 7571, "text": "We can see that there is one point in train data where the amount > 30000. It's better we remove the outlier since it can affect our models(especially distance-based algorithms like logistic regression, knn etc.) in prediction." }, { "code": null, "e": 8061, "s": 7799, "text": "Also, Outliers like this can cause an overfitting problem. For instance, tree-based models can put these outliers in leaf nodes, which are noise and not part of a general pattern. Therefore, I decided to remove the values larger than 30,000 in the training set." }, { "code": null, "e": 8356, "s": 8061, "text": "It seems that the transactions with ‘LogTransactionAmt’ larger than 5.5 (244 dollars) and smaller than 3.3 (27 dollars) have a higher frequency and probability density of being fraudulent. On the other hand, the ones with ‘LogTransactionAmt’ from 3.3 to 5.5 have a higher chance of being legit." }, { "code": null, "e": 8367, "s": 8356, "text": "Product CD" }, { "code": null, "e": 8511, "s": 8367, "text": "This is the product code associated with each transaction. Let us see how much percent of transactions are fraud among different product codes." }, { "code": null, "e": 8682, "s": 8511, "text": "We can see that among transactions related to product code C about 12 percent are fraud transactions. similarly close to 6% of transactions are fraud among product codes." }, { "code": null, "e": 8692, "s": 8682, "text": "D Columns" }, { "code": null, "e": 8986, "s": 8692, "text": "We have D columns from D1 to D15. These represent time deltas such as days between previous transaction and current transaction, days between current and first transaction, etc. Even though they have not given a clear understanding regarding D cols, we got some insights after a good analysis." }, { "code": null, "e": 9124, "s": 8986, "text": "We assume D1 as the day since credit card usage has begun. Subtracting this from Transaction day will result in content value per client." }, { "code": null, "e": 9206, "s": 9124, "text": "df_train['D1n'] = df_train['D1'] - df_train.TransactionDT/np.float32(24*60*60)" }, { "code": null, "e": 9314, "s": 9206, "text": "We did a normalization of all D cols and allowed the model to decide which are important and which are not." }, { "code": null, "e": 9327, "s": 9314, "text": "Card1- Card6" }, { "code": null, "e": 9444, "s": 9327, "text": "These columns represent payment information related to cards. Some interesting observations from these features are:" }, { "code": null, "e": 9658, "s": 9444, "text": "There is a wide range of values in card1. If we see the distribution there are overlapping's. card1 alone cannot distinguish between fraudulent and nonfraudulent transactions. No missing values are there in card1." }, { "code": null, "e": 9823, "s": 9658, "text": "A small percent of data is missing in card2. Similar to card1 a lot of unique values are present in card2 also. card3 has a low correlation with other card columns." }, { "code": null, "e": 9985, "s": 9823, "text": "card 4 indicates which type of card do client uses visa, Mastercard, American Express, or discover. Similarly, card6 indicates the type of card- debit or credit." }, { "code": null, "e": 10316, "s": 9985, "text": "P-email domain and R-email domain: These are email domains of purchaser and recipient respectively. About 76% of values are missing in the R-email domain. In purchaser email domains most mails are from gmail.com. Among those More fraud transactions comes from domain protonmail.com which is more than 90% which is a serious issue." }, { "code": null, "e": 10528, "s": 10316, "text": "addr1 and addr2: These are some address-related information related to the client. Around 11% of data is missing from both addr1 and addr2. There are about 332 unique values in addr1 and 74 in the case of addr2." }, { "code": null, "e": 10819, "s": 10528, "text": "dist1 and dist2: This might indicate the distance between transaction location and card owner address. This is just my assumption. We have about 93% of values missing in dist2. There is no correlation between dist1 and dist2. While dist2 is very weakly correlated with all other attributes." }, { "code": null, "e": 11148, "s": 10819, "text": "C1-C14: These are information such as counting. C3 is somewhat different from other Cxx features. For c3, from box pot, it is clear that there is no value beyond 3 in train data for fraudulent transactions. For no fraudulent transactions, the value ranges from 0 to 26. Also, C3 is very weakly co-related with other Cxx columns." }, { "code": null, "e": 11308, "s": 11148, "text": "M1-M9: More than 50 percent of values are missing among M columns. These features do not clearly distinguish between fraudulent and nonfraudulent transactions." }, { "code": null, "e": 11627, "s": 11308, "text": "V1-V399: These are vesta-engineered features. These are masked information that can be ranking, counting, or other entity relations. There exist a strong correlation (>0.9) between many features. If possible It's better we reduce the number of these features as it can reduce the computational complexity of the model." }, { "code": null, "e": 11785, "s": 11627, "text": "As a baseline, we created 3 models. — Logistic regression, Random Forest and XG Boost. We obtained the following results after a small hyperparameter tuning." }, { "code": null, "e": 11844, "s": 11785, "text": "Logistic regression: 0.84018(Train AUC), 0.84245(Test AUC)" }, { "code": null, "e": 11895, "s": 11844, "text": "Random Forest: 0.9030(Train AUC), 0.8600(Test AUC)" }, { "code": null, "e": 11939, "s": 11895, "text": "Xgboost: 0.994(Train AUC), 0.9234(Test AUC)" }, { "code": null, "e": 12179, "s": 11939, "text": "As Xgboost gives better performance, we decided to stick to it. We also plotted feature importance to get a basic idea of the influence of various features. For Xgboost we got a Public leaderboard score of 0.9004 and 0.9238 for private LB." }, { "code": null, "e": 12346, "s": 12179, "text": "Both columns are unique. One is time-related information and the other is a unique id. Adding this to the model doesn't make much sense. So we removed those features." }, { "code": null, "e": 12649, "s": 12346, "text": "From our Xgboost model, after plotting feature importance we came to know that all V cols do not contribute much to the model. Also on analysis, we found that there exists a strong correlation between several ‘Vxx’ columns. So we decided to reduce the number of columns by doing a correlation analysis." }, { "code": null, "e": 12692, "s": 12649, "text": "How to reduce columns based on NaN values?" }, { "code": null, "e": 12916, "s": 12692, "text": "Group columns based on a number of missing values Eg. if there are 4 columns v1,v2,v3, and v4. If v1 and v3 have 56 missing values and v2 have 21 and v4 have 5 missing values, we have 3 groups [‘v1’,’v3'], [‘v2’] and [‘v4’]" }, { "code": null, "e": 13439, "s": 12916, "text": "In each group, For each column in that group find the correlation with other columns and take only columns with a correlation coefficient > 0.75. Take the largest list with common elements as a subgroup. Each group contains several subgroups. For eg: if we have [[v1,v2],[v6],[v1,v4,v2,v5],[v5,v4]] ,our output will be [[v1,v2,v4,v5],[v6]]. Now from each subgroup choose the column with the most number of unique values. For eg, In subgroup [v1,v2,v4,v5], let v2 have the most unique values. So out output becomes [v2,v6]." }, { "code": null, "e": 13570, "s": 13439, "text": "The above figure indicates some part of our output. We will do correlation analysis on each group to reduce the number of columns." }, { "code": null, "e": 13791, "s": 13570, "text": "Here columns ‘V35’, ‘V40’, ‘V41’, ‘V39’, ‘V38’, ‘V51’, ‘V37’, ‘V52’, ‘V36’, ‘V50’, ‘V48’, ‘V42’,‘V43’, ‘V44’, ‘V46’, ‘V47’, ‘V45’, ‘V49’ 168969 missing values. So they form a group. Now we will plot a correlation matrix." }, { "code": null, "e": 13913, "s": 13791, "text": "Next, we will group them based on correlation. We will consider columns with a correlation >0.75 to be in the same group." }, { "code": null, "e": 14037, "s": 13913, "text": "[[‘V35’,’V36'],[‘V37’,’V38'],[‘V39’,’V40',’V42',’V43',’V50',’V51',’V52'],[‘V41’],[‘V44’,’V45'],[‘V46’,’V47'],[‘V48’,’V49']]" }, { "code": null, "e": 14126, "s": 14037, "text": "We will reduce this using the above function and will end up with the following columns:" }, { "code": null, "e": 14177, "s": 14126, "text": "[‘V36’, ‘V37’, ‘V40’, ‘V41’, ‘V44’, ‘V47’, ‘V48’]." }, { "code": null, "e": 14267, "s": 14177, "text": "Similarly, we will do for all the groups and finally end up with the following V columns." }, { "code": null, "e": 15238, "s": 14267, "text": "['V1', 'V3', 'V4', 'V6', 'V8', 'V11', 'V13', 'V14', 'V17', 'V20','V23', 'V26', 'V27', 'V30', 'V36', 'V37', 'V40', 'V41', 'V44', 'V47', 'V48', 'V54', 'V56', 'V59','V62', 'V65', 'V67', 'V68', 'V70', 'V76', 'V78', 'V80', 'V82', 'V86', 'V88', 'V89', 'V91', 'V96','V98', 'V99', 'V104', 'V107', 'V108', 'V111', 'V115', 'V117', 'V120', 'V121', 'V123', 'V124', 'V127','V129', 'V130', 'V136', 'V138', 'V139', 'V142', 'V147', 'V156', 'V162', 'V165', 'V160', 'V166', 'V178','V176', 'V173', 'V182', 'V187', 'V203', 'V205', 'V207', 'V215', 'V169', 'V171', 'V175', 'V180', 'V185','V188', 'V198', 'V210', 'V209', 'V218', 'V223', 'V224', 'V226', 'V228', 'V229', 'V235', 'V240', 'V258','V257', 'V253', 'V252', 'V260', 'V261', 'V264', 'V266', 'V267', 'V274', 'V277', 'V220', 'V221', 'V234','V238', 'V250', 'V271', 'V294', 'V284', 'V285', 'V286', 'V291','V297', 'V303', 'V305', 'V307', 'V309', 'V310', 'V320', 'V281', 'V283', 'V289', 'V296', 'V301', 'V314', 'V332', 'V325', 'V335', 'V338']" }, { "code": null, "e": 15555, "s": 15238, "text": "Reducing V cols doesn’t decrease the score on local validation. We got 0.993 AUC on train data and 0.9231 on cv data. Even though it reduced the Private LB score by 0.001, we were able to reduce 211 columns and thus improved the computational complexity of the model. So dropping those features is a better approach." }, { "code": null, "e": 15686, "s": 15555, "text": "I also tried to reduced C and M cols in a similar way. But it decreased the score by more than 0.002 AUC. So as of now, I kept it." }, { "code": null, "e": 16000, "s": 15686, "text": "From Kaggle's discussions, I came to know that D1 is the day since credit card usage began. Subtracting this from Transaction Day will make it an almost constant value per client. I did the same approach for all the D cols. To check the newly created features are helpful or not I did a forward feature selection." }, { "code": null, "e": 16047, "s": 16000, "text": "How to select D cols which are to be modified?" }, { "code": null, "e": 16135, "s": 16047, "text": "We know that our baseline provides an AUC of 0.923. This will be our initial bese_score" }, { "code": null, "e": 16445, "s": 16135, "text": "On the first iteration, I added normalized D1 and removed the original D1, and created a model out of it and the test AUC is noted. Now, this is repeated for all Dcols from D1 to D15. Each time AUC is noted and choose the Dcol which improves the AUC from baseline (0.923)more. This AUC becomes our best_score." }, { "code": null, "e": 16566, "s": 16445, "text": "On the next iteration, the earlier D col is included and step 1 is repeated for all the remaining columns along with D1." }, { "code": null, "e": 16621, "s": 16566, "text": "Iterations are repeated until the AUC is not improved." }, { "code": null, "e": 16723, "s": 16621, "text": "Finally, we end up with normalizing ‘D15’, ’D4', ’D2', ’D 11', and ‘D10’. Our local AUC became 0.934." }, { "code": null, "e": 16763, "s": 16723, "text": "Next, I created the following features:" }, { "code": null, "e": 16826, "s": 16763, "text": "day of the week: Day of the week in which transaction occurred" }, { "code": null, "e": 16867, "s": 16826, "text": "hour: Hour in which transaction occurred" }, { "code": null, "e": 16918, "s": 16867, "text": "cent: cents associated with the transaction amount" }, { "code": null, "e": 16967, "s": 16918, "text": "LogTransactionAmt: Log of the transaction amount" }, { "code": null, "e": 17059, "s": 16967, "text": "P_email_company: company to which P_email_domain belongs. It is obtained from the internet." }, { "code": null, "e": 17178, "s": 17059, "text": "Device_corp: I created this column from Device Info. It is basically parent company details obtained from device info." }, { "code": null, "e": 17427, "s": 17178, "text": "Hour fraud status: From the graph, we obtained while doing EDA, we know the percentage of fraudulent transactions in each hour. Based on this I created 4 categories very low, low, medium, and high so that each hour falls on any of these categories." }, { "code": null, "e": 17609, "s": 17427, "text": "Then I used FFS and see which of the features improve the result. But only the hour column improved the score to 0.9338. The function for forward feature selection looks as follows:" }, { "code": null, "e": 17720, "s": 17609, "text": "Next, I created some encoding features. Before that let us familiarize ourselves with the following functions." }, { "code": null, "e": 17764, "s": 17720, "text": "Based on these I created about 45 features." }, { "code": null, "e": 17923, "s": 17764, "text": "Then I did a forward feature selection and selected those features which improved model performance. As a result, I ended up with the following 6 new features" }, { "code": null, "e": 18077, "s": 17923, "text": "card4_addr1_R_emaildomain', 'card2_FE','card1_FE', 'card1_addr1_R_emaildomain', 'card3_addr1_P_emaildomain', 'card1_addr1','card4_addr1_P_emaildomain_FE'" }, { "code": null, "e": 18129, "s": 18077, "text": "These improved my local validation score to 0.9634." }, { "code": null, "e": 18184, "s": 18129, "text": "Why UID(identifying clients) based features will work?" }, { "code": null, "e": 18220, "s": 18184, "text": "Suppose we have the following data:" }, { "code": null, "e": 18281, "s": 18220, "text": "Here if we construct a decision tree, it can look as follows" }, { "code": null, "e": 18514, "s": 18281, "text": "In this case, we can see that out of 11 points, 8 points are correctly classified. Suppose we can identify individual clients. I will explain to you how I am able to find it. If I am able to find such uid’s our data look as follows." }, { "code": null, "e": 18613, "s": 18514, "text": "Let us create a new group aggregate from this uid. Let us construct a decision tree based on that." }, { "code": null, "e": 18851, "s": 18613, "text": "We can see that in this case, all 11 points are classified correctly. Even though in real case this won't be as accurate, definitely it can lead to improving the performance of the model. So finding the uid is key in improving our score." }, { "code": null, "e": 18990, "s": 18851, "text": "On Analysis I understood that card1, D1, and addr1 will help me to identify the client. So I combined all those 3 columns and used as uid." }, { "code": null, "e": 19152, "s": 18990, "text": "Now I created several means, standard deviation, and count aggregations of several features with this uid. I used the following function for making aggregations." }, { "code": null, "e": 19295, "s": 19152, "text": "I created about 100 aggregation features based on uid. But after Forward feature selection on different subsets, I end up with 9 new features." }, { "code": null, "e": 19459, "s": 19295, "text": "'M9_uid_mean' , 'M5_uid_mean' , 'D2_uid_mean' , 'D15_uid_mean' , 'C13_uid_mean' , 'C9_uid_mean' , 'C1_uid_mean' , 'C11_uid_mean' , 'TransactionAmt_uid_std'" }, { "code": null, "e": 19605, "s": 19459, "text": "This improved my Local cv score to 0.9470. The results from the private leader board and public leader board were 0.9158 and 0.9423 respectively." }, { "code": null, "e": 19904, "s": 19605, "text": "From analysis, it was clear that no uid is perfect. So I tried to create a new uid just by combining card1 with addr1. Then I created similar aggregations using new uid and see which of those new features improves the result of Forward feature selection. I end up with the following 4 new features:" }, { "code": null, "e": 19973, "s": 19904, "text": "'M4_uid2_mean' , 'M1_uid2_mean' , 'M7_uid2_mean' , 'M8_uid2_std' " }, { "code": null, "e": 20170, "s": 19973, "text": "This improved my local CV to 0.9481. Also, new private and public LB scores had become 0.917 and 0.940 respectively. Thus UID based features really help us to improve the performance of the model." }, { "code": null, "e": 20474, "s": 20170, "text": "These are the two important techniques that literally improved the performance of my algorithm. As you know our model was tuned earlier, but currently, a lot of new features have been introduced. Let us find out the best parameters that fit the model. For that, I used Randomized Search Cv from Sklearn." }, { "code": null, "e": 20541, "s": 20474, "text": "After a randomized search, we end up with the following parameters" }, { "code": null, "e": 20628, "s": 20541, "text": "n_estimators=5000,max_depth=12,learning_rate=0.002,subsample=0.8, colsample_bytree=0.4" }, { "code": null, "e": 20704, "s": 20628, "text": "First, we created a new column that indicates the month of the transaction." }, { "code": null, "e": 21238, "s": 20704, "text": "We will predict test.csv using GroupKFold with months as groups. The training data are the months December 2017, January 2018, February 2018, March 2018, April 2018, and May 2018. We refer to these months as 12, 13, 14, 15, 16, 17. Fold one in GroupKFold will train on months 13 thru 17 and predict month 12. Note that the only purpose of month 12 is to tell XGB when to early_stop we don't actually care about the backward time predictions. The model trained on months 13 thru 17 will also predict test.csv which is forward in time." }, { "code": null, "e": 21265, "s": 21238, "text": "Our code looks as follows:" }, { "code": null, "e": 21461, "s": 21265, "text": "Finally, our local CV score after cross-validation has become 0.951265. New Private and Public LB score has become 0.928873 and 0.954825 respectively. It ranked roughly 226 among 6351.(Top 3.5%)." }, { "code": null, "e": 21512, "s": 21461, "text": "Our progress throughout the project is as follows:" }, { "code": null, "e": 21697, "s": 21512, "text": "You can check my entire code at https://github.com/arunm8489/IEE-CIS-Fraud-detection. It's not the end. Still, there is a score of improvement. Some of the approaches I have not tried:" }, { "code": null, "e": 21805, "s": 21697, "text": "My entire work was around the XgBoost algorithm. You can try other algorithms like Lightgbm, cat boost etc." }, { "code": null, "e": 21983, "s": 21805, "text": "I have reduced v cols based on the number of NaN values and Pearsons-correlation coefficient. You can also try PCA in each NaN groups and see whether it improves the performance" } ]
TestNG - Basic Annotations - BeforeTest
@BeforeTest annotated method will be run before any test method belonging to the classes inside the <test> tag is run. The following is a list of attributes supported by the @BeforeTest annotation: alwaysRun For before methods (beforeSuite, beforeTest, beforeTestClass and beforeTestMethod, but not beforeGroups): If set to true, this configuration method will be run regardless of what groups it belongs to. For after methods (afterSuite, afterClass, ...): If set to true, this configuration method will be run even if one or more methods invoked previously failed or was skipped. dependsOnGroups The list of groups this method depends on. dependsOnMethods The list of methods this method depends on. enabled Whether methods on this class/method are enabled. groups The list of groups this class/method belongs to. inheritGroups If true, this method will belong to groups specified in the @Test annotation at the class level. onlyForGroups Only for @BeforeMethod and @AfterMethod. If specified, then this setup/teardown method will only be invoked if the corresponding test method belongs to one of the listed groups. Create a java class to be tested, say, MessageUtil.java in /work/testng/src. /* * This class prints the given message on console. */ public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message) { this.message = message; } // prints the message public String printMessage() { System.out.println(message); return message; } } Create a java test class, say, TestAnnotationBeforeTest.java in /work/testng/src. Create a java test class, say, TestAnnotationBeforeTest.java in /work/testng/src. Add a test method testMethod() to your test class. Add a test method testMethod() to your test class. Add an Annotation @Test to method testMethod(). Add an Annotation @Test to method testMethod(). Add a method beforeTest to the test class with annotation @BeforeTest Add a method beforeTest to the test class with annotation @BeforeTest Implement the test condition and check the behaviour of @BeforeTest annotation. Implement the test condition and check the behaviour of @BeforeTest annotation. Following are the TestAnnotationBeforeTest.java contents: import org.testng.Assert; import org.testng.annotations.Test; import org.testng.annotations.BeforeTest; public class TestAnnotationBeforeTest { MessageUtil messageUtil = new MessageUtil("Test method"); @BeforeTest public void BeforeTest(){ System.out.println("Before Test method"); } @Test public void testMethod(){ Assert.assertEquals("Test method", messageUtil.printMessage()); } } Next, let's create testng.xml file in /work/testng/src, to execute test case(s). This file captures your entire testing in XML. This file makes it easy to describe all your test suites and their parameters in one file, which you can check in your code repository or e-mail to coworkers. It also makes it easy to extract subsets of your tests or split several runtime configurations (e.g., testngdatabase.xml would run only tests that exercise your database). <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd"> <suite name="Suite"> <test thread-count="5" name="Test"> <classes> <class name="TestAnnotationBeforeTest"/> </classes> </test> <!-- Test --> </suite> <!-- Suite --> Compile the test case using javac. /work/testng/src$ javac TestAnnotationBeforeTest.java MessageUtil.java Now, run the testng.xml, which will run the test case defined in <test> tag. As you can see the @BeforeTest is called before all other test cases. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. Before Test method Test method =============================================== Suite Total tests run: 1, Passes: 1, Failures: 0, Skips: 0 =============================================== 38 Lectures 4.5 hours Lets Kode It 15 Lectures 1.5 hours Quaatso Learning 28 Lectures 3 hours Dezlearn Education Print Add Notes Bookmark this page
[ { "code": null, "e": 2179, "s": 2060, "text": "@BeforeTest annotated method will be run before any test method belonging to the classes inside the <test> tag is run." }, { "code": null, "e": 2258, "s": 2179, "text": "The following is a list of attributes supported by the @BeforeTest annotation:" }, { "code": null, "e": 2268, "s": 2258, "text": "alwaysRun" }, { "code": null, "e": 2469, "s": 2268, "text": "For before methods (beforeSuite, beforeTest, beforeTestClass and beforeTestMethod, but not beforeGroups): If set to true, this configuration method will be run regardless of what groups it belongs to." }, { "code": null, "e": 2642, "s": 2469, "text": "For after methods (afterSuite, afterClass, ...): If set to true, this configuration method will be run even if one or more methods invoked previously failed or was skipped." }, { "code": null, "e": 2658, "s": 2642, "text": "dependsOnGroups" }, { "code": null, "e": 2701, "s": 2658, "text": "The list of groups this method depends on." }, { "code": null, "e": 2718, "s": 2701, "text": "dependsOnMethods" }, { "code": null, "e": 2762, "s": 2718, "text": "The list of methods this method depends on." }, { "code": null, "e": 2770, "s": 2762, "text": "enabled" }, { "code": null, "e": 2820, "s": 2770, "text": "Whether methods on this class/method are enabled." }, { "code": null, "e": 2827, "s": 2820, "text": "groups" }, { "code": null, "e": 2876, "s": 2827, "text": "The list of groups this class/method belongs to." }, { "code": null, "e": 2890, "s": 2876, "text": "inheritGroups" }, { "code": null, "e": 2987, "s": 2890, "text": "If true, this method will belong to groups specified in the @Test annotation at the class level." }, { "code": null, "e": 3001, "s": 2987, "text": "onlyForGroups" }, { "code": null, "e": 3179, "s": 3001, "text": "Only for @BeforeMethod and @AfterMethod. If specified, then this setup/teardown method will only be invoked if the corresponding test method belongs to one of the listed groups." }, { "code": null, "e": 3256, "s": 3179, "text": "Create a java class to be tested, say, MessageUtil.java in /work/testng/src." }, { "code": null, "e": 3619, "s": 3256, "text": "/*\n* This class prints the given message on console.\n*/\n\npublic class MessageUtil {\n\n private String message;\n\n //Constructor\n //@param message to be printed\n public MessageUtil(String message) {\n this.message = message;\n }\n\n // prints the message\n public String printMessage() {\n System.out.println(message);\n return message;\n }\n}" }, { "code": null, "e": 3701, "s": 3619, "text": "Create a java test class, say, TestAnnotationBeforeTest.java in /work/testng/src." }, { "code": null, "e": 3783, "s": 3701, "text": "Create a java test class, say, TestAnnotationBeforeTest.java in /work/testng/src." }, { "code": null, "e": 3834, "s": 3783, "text": "Add a test method testMethod() to your test class." }, { "code": null, "e": 3885, "s": 3834, "text": "Add a test method testMethod() to your test class." }, { "code": null, "e": 3933, "s": 3885, "text": "Add an Annotation @Test to method testMethod()." }, { "code": null, "e": 3981, "s": 3933, "text": "Add an Annotation @Test to method testMethod()." }, { "code": null, "e": 4051, "s": 3981, "text": "Add a method beforeTest to the test class with annotation @BeforeTest" }, { "code": null, "e": 4121, "s": 4051, "text": "Add a method beforeTest to the test class with annotation @BeforeTest" }, { "code": null, "e": 4201, "s": 4121, "text": "Implement the test condition and check the behaviour of @BeforeTest annotation." }, { "code": null, "e": 4281, "s": 4201, "text": "Implement the test condition and check the behaviour of @BeforeTest annotation." }, { "code": null, "e": 4339, "s": 4281, "text": "Following are the TestAnnotationBeforeTest.java contents:" }, { "code": null, "e": 4775, "s": 4339, "text": " import org.testng.Assert;\n import org.testng.annotations.Test;\n import org.testng.annotations.BeforeTest;\n\n public class TestAnnotationBeforeTest {\n MessageUtil messageUtil = new MessageUtil(\"Test method\");\n @BeforeTest\n public void BeforeTest(){\n System.out.println(\"Before Test method\");\n }\n @Test\n public void testMethod(){\n Assert.assertEquals(\"Test method\", messageUtil.printMessage());\n }\n\n }" }, { "code": null, "e": 5234, "s": 4775, "text": "Next, let's create testng.xml file in /work/testng/src, to execute test case(s). This file captures your entire testing in XML. This file makes it easy to describe all your test suites and their parameters in one file, which you can check in your code repository or e-mail to coworkers. It also makes it easy to extract subsets of your tests or split several runtime configurations (e.g., testngdatabase.xml would run only tests that exercise your database)." }, { "code": null, "e": 5534, "s": 5234, "text": " <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <!DOCTYPE suite SYSTEM \"https://testng.org/testng-1.0.dtd\">\n <suite name=\"Suite\">\n <test thread-count=\"5\" name=\"Test\">\n <classes>\n <class name=\"TestAnnotationBeforeTest\"/>\n </classes>\n </test> <!-- Test -->\n </suite> <!-- Suite -->" }, { "code": null, "e": 5569, "s": 5534, "text": "Compile the test case using javac." }, { "code": null, "e": 5641, "s": 5569, "text": "/work/testng/src$ javac TestAnnotationBeforeTest.java MessageUtil.java\n" }, { "code": null, "e": 5788, "s": 5641, "text": "Now, run the testng.xml, which will run the test case defined in <test> tag. As you can see the @BeforeTest is called before all other test cases." }, { "code": null, "e": 5841, "s": 5788, "text": "/work/testng/src$ java org.testng.TestNG testng.xml\n" }, { "code": null, "e": 5860, "s": 5841, "text": "Verify the output." }, { "code": null, "e": 6060, "s": 5860, "text": " Before Test method\n Test method\n\n ===============================================\n Suite\n Total tests run: 1, Passes: 1, Failures: 0, Skips: 0\n ===============================================\n" }, { "code": null, "e": 6095, "s": 6060, "text": "\n 38 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6109, "s": 6095, "text": " Lets Kode It" }, { "code": null, "e": 6144, "s": 6109, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6162, "s": 6144, "text": " Quaatso Learning" }, { "code": null, "e": 6195, "s": 6162, "text": "\n 28 Lectures \n 3 hours \n" }, { "code": null, "e": 6215, "s": 6195, "text": " Dezlearn Education" }, { "code": null, "e": 6222, "s": 6215, "text": " Print" }, { "code": null, "e": 6233, "s": 6222, "text": " Add Notes" } ]
Basic Algorithms — Finding the Closest Pair | by Keita Miyaki | Towards Data Science
Writing cost-efficient algorithms is one of the keys to succeed as a data scientist, and in the previous article we used split-conquer method in counting inversions in an array, which is far less costly than brute force method. This time, we will see how another split-conquer algorithm finds the closest pair of points from a set of points on a two-dimensional plane. Looking up at the sky at Times Square or downtown Tokyo, we would find the closest pair of stars quite easily, because you can see only a few stars there. If you are in the middle of nowhere, the infinite number of stars in the dark night sky would make it impossible to determine the pair. It is no different for computers; when they determine the closest pairs of points on a plane, the more points the dataset has, the longer it takes for algorithms to find the couple with the least distance. The cost increase is more than linear to the number of points, and we try to write an algorithm which contains the cost growth as low as possible. The split-conquer method works well in this challenge, in a similar way with the algorithm to count inversions. The brute-force way is, like one that counts inversions in an array, to calculate the distances of every pair of points in the universe. For n number of points, we would need to measure n(n-1)/2 distances and the cost is square to n, or Θ(n2). With two loops, the code for this algorithm can be written as follows. def find_closest_brute_force(array): result = {} result["p1"] = array[0] result["p2"] = array[1] result["distance"] = np.sqrt((array[0][0]-array[1][0])**2 +(array[0][1]-array[1][1])**2) for i in range(len(array)-1): for j in range(i+1, len(array)): distance = np.sqrt((array[i][0]-array[j][0])**2 +(array[i][1]-array[j][1])**2) if distance < result["distance"]: result["p1"] = array[i] result["p2"] = array[j] result["distance"] = distance return resultreturn result Now we think of a better way whose cost would be O(nlgn). It is possible with presorting and the split-conquer method. To presort the array on one of the coordinates, we also use the slit-conquer method, the merge-sort algorithm. We sort the arrays with an algorithm called merge-sort, which is faster than brute-force sorting algorithms. The merge-sort algorithm splits the array, sorts the subarrays (as a recursive step), compares the youngest numbers in two subarrays and picks the younger, and repeats it until both subarrays are exhausted. Each of the recursive steps costs just Θ(n) so that the total cost of the algorithm stays at Θ(nlgn). def merge_sort(array, coordinate=0): length = len(array) if length == 1: return array if length == 2: if array[0][coordinate] > array[1][coordinate]: return np.array([array[1], array[0]]) else: return array elif length > 2: array_l = array[:length//2] array_r = array[length//2:] array_l_sorted = merge_sort(array_l, coordinate) array_r_sorted = merge_sort(array_r, coordinate) l_length = len(array_l) r_length = len(array_r) l = 0 r = 0 sorted_list = [] for i in range(length): if r == r_length: sorted_list.append(array_l_sorted[l]) l += 1 elif l == l_length: sorted_list.append(array_r_sorted[r]) r += 1 elif array_l_sorted[l][coordinate] > array_r_sorted[r][coordinate]: sorted_list.append(array_r_sorted[r]) r += 1 elif array_l_sorted[l][coordinate] < array_r_sorted[r][coordinate]: sorted_list.append(array_l_sorted[l]) l += 1 return np.array(sorted_list) As stated above, we aim to write an algorithm which finds the closest pair of points at a cost of O(nlgn). With a split-conquer algorithm whose recursive steps cost O(n) each would suffice. The algorithm divides the array into subarrays and the key is to see if the closest pair across the two subarrays. The split conquer algorithm sorts the array by X coordinate, divides the sorted array into two, apply the algorithm recursively to the subarrays, and check whether or not there exists a pair with a shorter distance than that found in subarrays. def find_closest_nest(array): X = merge_sort(array, 0) length = len(X) if length < 4: return find_closest_brute_force(array) else: array_l = X[:length//2] array_r = X[length//2:] dict_l = find_closest_nest(array_l) dict_r = find_closest_nest(array_r) if dict_l["distance"] > dict_r["distance"]: dict_both = dict_r else: dict_both = dict_l Y_list = [] for i in range(length): if X[length//2-1][0]-dict_both["distance"] < array[i][0] < X[length//2-1][0]+dict_both["distance"]: Y_list.append(array[i]) Y = merge_sort(np.array(Y_list), 1) if len(Y) == 1: dict_final = dict_both elif len(Y) < 8: dict_y = find_closest_brute_force(Y) if dict_both["distance"] > dict_y["distance"]: dict_final = dict_y else: dict_final = dict_both else: for i in range(len(Y)-7): dict_y = find_closest_brute_force(Y[i:i+7]) if dict_both["distance"] > dict_y["distance"]: dict_final = dict_y else: dict_final = dict_both return dict_final The last step, looking at the pairs across subarrays, needs some tricks to keep the cost at a linear level (e.g. O(n)). First, we will make a subset of the input, which consists of points within d distance from the midpoint in terms of X coordinate; d is the shortest distance between the pair within subarrays. If we find the closest pair across the subarrays, the pair of points should exist within distance d from the line dividing the array into subarrays. In the example shown in the right hand side, the closest pair within subarrays is determined in the right subarray (note that the point on the dashed line belongs to the left subarray) and its distance is d. If the closest pair exists across the left and right subarrays, the points should be within the range of d from the dashed line dividing the array into the two subarrays. Therefore, we can look at the subset within the shaded range. Second, we sort the subset we obtained in the previous step by Y coordinate. We show that we have to look at sets of only eight consecutive points each in the sorted subset. As shown in the figure, the maximum number of points that can exist in 2d*d rectangle across right and left subarrays is eight (points on the dashed line duplicate; two belong to the left subarray and another two are in the right). Third, we look at each set of eight consecutive points in the subset sorted on the Y coordinate. If we find a pair whose distance is less than d, it means the closest pair exists across the subarrays. This step costs O(n), and the total cost of this recursive algorithm stays at O(nlgn). We learned that the split-conquer algorithm we developed performs faster than brute-force one. Let’s compare the actual performance of two algorithms. In the chart below, the cost (execution time) of two algorithms are shown by different sizes of arrays. The two lines clearly indicate that the split-conquer method has an advantage as the sample size increases. This result proves the importance of coding efficiently, as discussed in the previous article too.
[ { "code": null, "e": 541, "s": 172, "text": "Writing cost-efficient algorithms is one of the keys to succeed as a data scientist, and in the previous article we used split-conquer method in counting inversions in an array, which is far less costly than brute force method. This time, we will see how another split-conquer algorithm finds the closest pair of points from a set of points on a two-dimensional plane." }, { "code": null, "e": 832, "s": 541, "text": "Looking up at the sky at Times Square or downtown Tokyo, we would find the closest pair of stars quite easily, because you can see only a few stars there. If you are in the middle of nowhere, the infinite number of stars in the dark night sky would make it impossible to determine the pair." }, { "code": null, "e": 1297, "s": 832, "text": "It is no different for computers; when they determine the closest pairs of points on a plane, the more points the dataset has, the longer it takes for algorithms to find the couple with the least distance. The cost increase is more than linear to the number of points, and we try to write an algorithm which contains the cost growth as low as possible. The split-conquer method works well in this challenge, in a similar way with the algorithm to count inversions." }, { "code": null, "e": 1612, "s": 1297, "text": "The brute-force way is, like one that counts inversions in an array, to calculate the distances of every pair of points in the universe. For n number of points, we would need to measure n(n-1)/2 distances and the cost is square to n, or Θ(n2). With two loops, the code for this algorithm can be written as follows." }, { "code": null, "e": 2239, "s": 1612, "text": "def find_closest_brute_force(array): result = {} result[\"p1\"] = array[0] result[\"p2\"] = array[1] result[\"distance\"] = np.sqrt((array[0][0]-array[1][0])**2 +(array[0][1]-array[1][1])**2) for i in range(len(array)-1): for j in range(i+1, len(array)): distance = np.sqrt((array[i][0]-array[j][0])**2 +(array[i][1]-array[j][1])**2) if distance < result[\"distance\"]: result[\"p1\"] = array[i] result[\"p2\"] = array[j] result[\"distance\"] = distance return resultreturn result" }, { "code": null, "e": 2469, "s": 2239, "text": "Now we think of a better way whose cost would be O(nlgn). It is possible with presorting and the split-conquer method. To presort the array on one of the coordinates, we also use the slit-conquer method, the merge-sort algorithm." }, { "code": null, "e": 2887, "s": 2469, "text": "We sort the arrays with an algorithm called merge-sort, which is faster than brute-force sorting algorithms. The merge-sort algorithm splits the array, sorts the subarrays (as a recursive step), compares the youngest numbers in two subarrays and picks the younger, and repeats it until both subarrays are exhausted. Each of the recursive steps costs just Θ(n) so that the total cost of the algorithm stays at Θ(nlgn)." }, { "code": null, "e": 4130, "s": 2887, "text": "def merge_sort(array, coordinate=0): length = len(array) if length == 1: return array if length == 2: if array[0][coordinate] > array[1][coordinate]: return np.array([array[1], array[0]]) else: return array elif length > 2: array_l = array[:length//2] array_r = array[length//2:] array_l_sorted = merge_sort(array_l, coordinate) array_r_sorted = merge_sort(array_r, coordinate) l_length = len(array_l) r_length = len(array_r) l = 0 r = 0 sorted_list = [] for i in range(length): if r == r_length: sorted_list.append(array_l_sorted[l]) l += 1 elif l == l_length: sorted_list.append(array_r_sorted[r]) r += 1 elif array_l_sorted[l][coordinate] > array_r_sorted[r][coordinate]: sorted_list.append(array_r_sorted[r]) r += 1 elif array_l_sorted[l][coordinate] < array_r_sorted[r][coordinate]: sorted_list.append(array_l_sorted[l]) l += 1 return np.array(sorted_list)" }, { "code": null, "e": 4435, "s": 4130, "text": "As stated above, we aim to write an algorithm which finds the closest pair of points at a cost of O(nlgn). With a split-conquer algorithm whose recursive steps cost O(n) each would suffice. The algorithm divides the array into subarrays and the key is to see if the closest pair across the two subarrays." }, { "code": null, "e": 4680, "s": 4435, "text": "The split conquer algorithm sorts the array by X coordinate, divides the sorted array into two, apply the algorithm recursively to the subarrays, and check whether or not there exists a pair with a shorter distance than that found in subarrays." }, { "code": null, "e": 6008, "s": 4680, "text": "def find_closest_nest(array): X = merge_sort(array, 0) length = len(X) if length < 4: return find_closest_brute_force(array) else: array_l = X[:length//2] array_r = X[length//2:] dict_l = find_closest_nest(array_l) dict_r = find_closest_nest(array_r) if dict_l[\"distance\"] > dict_r[\"distance\"]: dict_both = dict_r else: dict_both = dict_l Y_list = [] for i in range(length): if X[length//2-1][0]-dict_both[\"distance\"] < array[i][0] < X[length//2-1][0]+dict_both[\"distance\"]: Y_list.append(array[i]) Y = merge_sort(np.array(Y_list), 1) if len(Y) == 1: dict_final = dict_both elif len(Y) < 8: dict_y = find_closest_brute_force(Y) if dict_both[\"distance\"] > dict_y[\"distance\"]: dict_final = dict_y else: dict_final = dict_both else: for i in range(len(Y)-7): dict_y = find_closest_brute_force(Y[i:i+7]) if dict_both[\"distance\"] > dict_y[\"distance\"]: dict_final = dict_y else: dict_final = dict_both return dict_final" }, { "code": null, "e": 6469, "s": 6008, "text": "The last step, looking at the pairs across subarrays, needs some tricks to keep the cost at a linear level (e.g. O(n)). First, we will make a subset of the input, which consists of points within d distance from the midpoint in terms of X coordinate; d is the shortest distance between the pair within subarrays. If we find the closest pair across the subarrays, the pair of points should exist within distance d from the line dividing the array into subarrays." }, { "code": null, "e": 6677, "s": 6469, "text": "In the example shown in the right hand side, the closest pair within subarrays is determined in the right subarray (note that the point on the dashed line belongs to the left subarray) and its distance is d." }, { "code": null, "e": 6910, "s": 6677, "text": "If the closest pair exists across the left and right subarrays, the points should be within the range of d from the dashed line dividing the array into the two subarrays. Therefore, we can look at the subset within the shaded range." }, { "code": null, "e": 7084, "s": 6910, "text": "Second, we sort the subset we obtained in the previous step by Y coordinate. We show that we have to look at sets of only eight consecutive points each in the sorted subset." }, { "code": null, "e": 7316, "s": 7084, "text": "As shown in the figure, the maximum number of points that can exist in 2d*d rectangle across right and left subarrays is eight (points on the dashed line duplicate; two belong to the left subarray and another two are in the right)." }, { "code": null, "e": 7604, "s": 7316, "text": "Third, we look at each set of eight consecutive points in the subset sorted on the Y coordinate. If we find a pair whose distance is less than d, it means the closest pair exists across the subarrays. This step costs O(n), and the total cost of this recursive algorithm stays at O(nlgn)." } ]
Design Patterns - Interpreter Pattern
Interpreter pattern provides a way to evaluate language grammar or expression. This type of pattern comes under behavioral pattern. This pattern involves implementing an expression interface which tells to interpret a particular context. This pattern is used in SQL parsing, symbol processing engine etc. We are going to create an interface Expression and concrete classes implementing the Expression interface. A class TerminalExpression is defined which acts as a main interpreter of context in question. Other classes OrExpression, AndExpression are used to create combinational expressions. InterpreterPatternDemo, our demo class, will use Expression class to create rules and demonstrate parsing of expressions. Create an expression interface. Expression.java public interface Expression { public boolean interpret(String context); } Create concrete classes implementing the above interface. TerminalExpression.java public class TerminalExpression implements Expression { private String data; public TerminalExpression(String data){ this.data = data; } @Override public boolean interpret(String context) { if(context.contains(data)){ return true; } return false; } } OrExpression.java public class OrExpression implements Expression { private Expression expr1 = null; private Expression expr2 = null; public OrExpression(Expression expr1, Expression expr2) { this.expr1 = expr1; this.expr2 = expr2; } @Override public boolean interpret(String context) { return expr1.interpret(context) || expr2.interpret(context); } } AndExpression.java public class AndExpression implements Expression { private Expression expr1 = null; private Expression expr2 = null; public AndExpression(Expression expr1, Expression expr2) { this.expr1 = expr1; this.expr2 = expr2; } @Override public boolean interpret(String context) { return expr1.interpret(context) && expr2.interpret(context); } } InterpreterPatternDemo uses Expression class to create rules and then parse them. InterpreterPatternDemo.java public class InterpreterPatternDemo { //Rule: Robert and John are male public static Expression getMaleExpression(){ Expression robert = new TerminalExpression("Robert"); Expression john = new TerminalExpression("John"); return new OrExpression(robert, john); } //Rule: Julie is a married women public static Expression getMarriedWomanExpression(){ Expression julie = new TerminalExpression("Julie"); Expression married = new TerminalExpression("Married"); return new AndExpression(julie, married); } public static void main(String[] args) { Expression isMale = getMaleExpression(); Expression isMarriedWoman = getMarriedWomanExpression(); System.out.println("John is male? " + isMale.interpret("John")); System.out.println("Julie is a married women? " + isMarriedWoman.interpret("Married Julie")); } } Verify the output. John is male? true Julie is a married women? true 102 Lectures 10 hours Arnab Chakraborty 30 Lectures 3 hours Arnab Chakraborty 31 Lectures 4 hours Arnab Chakraborty 43 Lectures 1.5 hours Manoj Kumar 7 Lectures 1 hours Zach Miller 54 Lectures 4 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 3056, "s": 2751, "text": "Interpreter pattern provides a way to evaluate language grammar or expression. This type of pattern comes under behavioral pattern. This pattern involves implementing an expression interface which tells to interpret a particular context. This pattern is used in SQL parsing, symbol processing engine etc." }, { "code": null, "e": 3348, "s": 3056, "text": "We are going to create an interface Expression and concrete classes implementing the Expression interface. A class TerminalExpression is defined which acts as a main interpreter of context in question. Other classes OrExpression, AndExpression are used to create combinational expressions." }, { "code": null, "e": 3470, "s": 3348, "text": "InterpreterPatternDemo, our demo class, will use Expression class to create rules and demonstrate parsing of expressions." }, { "code": null, "e": 3502, "s": 3470, "text": "Create an expression interface." }, { "code": null, "e": 3518, "s": 3502, "text": "Expression.java" }, { "code": null, "e": 3595, "s": 3518, "text": "public interface Expression {\n public boolean interpret(String context);\n}" }, { "code": null, "e": 3653, "s": 3595, "text": "Create concrete classes implementing the above interface." }, { "code": null, "e": 3677, "s": 3653, "text": "TerminalExpression.java" }, { "code": null, "e": 3988, "s": 3677, "text": "public class TerminalExpression implements Expression {\n\t\n private String data;\n\n public TerminalExpression(String data){\n this.data = data; \n }\n\n @Override\n public boolean interpret(String context) {\n \n if(context.contains(data)){\n return true;\n }\n return false;\n }\n}" }, { "code": null, "e": 4006, "s": 3988, "text": "OrExpression.java" }, { "code": null, "e": 4387, "s": 4006, "text": "public class OrExpression implements Expression {\n\t \n private Expression expr1 = null;\n private Expression expr2 = null;\n\n public OrExpression(Expression expr1, Expression expr2) { \n this.expr1 = expr1;\n this.expr2 = expr2;\n }\n\n @Override\n public boolean interpret(String context) {\t\t\n return expr1.interpret(context) || expr2.interpret(context);\n }\n}" }, { "code": null, "e": 4406, "s": 4387, "text": "AndExpression.java" }, { "code": null, "e": 4789, "s": 4406, "text": "public class AndExpression implements Expression {\n\t \n private Expression expr1 = null;\n private Expression expr2 = null;\n\n public AndExpression(Expression expr1, Expression expr2) { \n this.expr1 = expr1;\n this.expr2 = expr2;\n }\n\n @Override\n public boolean interpret(String context) {\t\t\n return expr1.interpret(context) && expr2.interpret(context);\n }\n}" }, { "code": null, "e": 4871, "s": 4789, "text": "InterpreterPatternDemo uses Expression class to create rules and then parse them." }, { "code": null, "e": 4899, "s": 4871, "text": "InterpreterPatternDemo.java" }, { "code": null, "e": 5794, "s": 4899, "text": "public class InterpreterPatternDemo {\n\n //Rule: Robert and John are male\n public static Expression getMaleExpression(){\n Expression robert = new TerminalExpression(\"Robert\");\n Expression john = new TerminalExpression(\"John\");\n return new OrExpression(robert, john);\t\t\n }\n\n //Rule: Julie is a married women\n public static Expression getMarriedWomanExpression(){\n Expression julie = new TerminalExpression(\"Julie\");\n Expression married = new TerminalExpression(\"Married\");\n return new AndExpression(julie, married);\t\t\n }\n\n public static void main(String[] args) {\n Expression isMale = getMaleExpression();\n Expression isMarriedWoman = getMarriedWomanExpression();\n\n System.out.println(\"John is male? \" + isMale.interpret(\"John\"));\n System.out.println(\"Julie is a married women? \" + isMarriedWoman.interpret(\"Married Julie\"));\n }\n}" }, { "code": null, "e": 5813, "s": 5794, "text": "Verify the output." }, { "code": null, "e": 5864, "s": 5813, "text": "John is male? true\nJulie is a married women? true\n" }, { "code": null, "e": 5899, "s": 5864, "text": "\n 102 Lectures \n 10 hours \n" }, { "code": null, "e": 5918, "s": 5899, "text": " Arnab Chakraborty" }, { "code": null, "e": 5951, "s": 5918, "text": "\n 30 Lectures \n 3 hours \n" }, { "code": null, "e": 5970, "s": 5951, "text": " Arnab Chakraborty" }, { "code": null, "e": 6003, "s": 5970, "text": "\n 31 Lectures \n 4 hours \n" }, { "code": null, "e": 6022, "s": 6003, "text": " Arnab Chakraborty" }, { "code": null, "e": 6057, "s": 6022, "text": "\n 43 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6070, "s": 6057, "text": " Manoj Kumar" }, { "code": null, "e": 6102, "s": 6070, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 6115, "s": 6102, "text": " Zach Miller" }, { "code": null, "e": 6148, "s": 6115, "text": "\n 54 Lectures \n 4 hours \n" }, { "code": null, "e": 6162, "s": 6148, "text": " Sasha Miller" }, { "code": null, "e": 6169, "s": 6162, "text": " Print" }, { "code": null, "e": 6180, "s": 6169, "text": " Add Notes" } ]
Working with Array and Vectors using STL in C++
Array and vectors are very important data structures in competitive programming for solving problems. And the STL (Standard Template Library) in c++ programming provide some functions to perform operations of arrays and vectors. Let’s see some of these functions in action, Finding sum, Min and Max of the array/vector − In STL there are function that helps you to find the sum, max, and min of the array/vector. Functions with there function, accumulate(startIndex, endIndex, initialSum) *max_element(startIndex, endIndex) *min_element(startIndex, endIndex) Program to perform operations on array − Live Demo #include <bits/stdc++.h> using namespace std; int main(){ int array[] = {65, 7,12, 90, 31, 113 }; int l = sizeof(array) / sizeof(array[0]); cout<<"The elments of the array are : "; for(int i = 0; i<l; i++) cout<<array[i]<<"\t"; cout<<endl; cout<<"The sum of all elements of the array: "<<accumulate(array, array + l, 0)<<endl; cout<<"The element with maximum value in array: "<<*max_element(array, array + l)<<endl; cout<<"The element with minimum value in array: "<<*min_element(array, array + l)<<endl; return 0; } The elments of the array are : 65 7 12 90 31 113 The sum of all elements of the array: 318 The element with maximum value in array: 113 The element with minimum value in array: 7 Program to perform operations on vector − Live Demo #include <bits/stdc++.h> using namespace std; int main(){ vector<int> vec= {65, 7,12, 90, 31, 113 }; cout<<"The sum of all elments of the vector: "<<accumulate(vec.begin(), vec.end() + 1, 0)<<endl; cout<<"The element with maximum value in vector: "<<*max_element(vec.begin(), vec.end())<<endl; cout<<"The element with minimum value in vector: "<<*min_element(vec.begin(), vec.end())<<endl; return 0; } The sum of all elments of the vector: 318 The element with maximum value in vector: 113 The element with minimum value in vector: 7 Sorting elements of the array/vector − In STL, there is a function sort() which can be used to sort elements of the array/vector. The function uses quick sort technique for sorting array/vector. sort(startIndex, endIndex) Program to sort elements of the array − Live Demo #include <bits/stdc++.h> using namespace std; int main(){ int array[] = {65, 7,12, 90, 31, 113 }; int l = sizeof(array) / sizeof(array[0]); cout<<"The elments of the array are : "; for(int i = 0; i<l; i++) cout<<array[i]<<"\t"; cout<<endl; cout<<"\nSorting elements of the array...\n\n"; sort(array, array+l); cout<<"The sorted array is : "; for(int i = 0; i<l; i++) cout<<array[i]<<"\t"; cout<<endl; return 0; } The elments of the array are : 65 7 12 90 31 113 Sorting elements of the array... The sorted array is : 7 12 31 65 90 113 Program to sort elements of vector − Live Demo #include <bits/stdc++.h> using namespace std; int main(){ vector<int> vec = {65, 7,12, 90, 31, 113 }; cout<<"The elments of the vector are : "; for(int i = 0; i<vec.size(); i++) cout<<vec[i]<<"\t"; cout<<endl; cout<<"\nSorting elements of the vector...\n\n"; sort(vec.begin(), vec.end()); cout<<"The sorted vector is : "; for(int i = 0; i<vec.size(); i++) cout<<vec[i]<<"\t"; cout<<endl; return 0; } The elments of the vector are : 65 7 12 90 31 113 Sorting elements of the vector... The sorted vector is : 7 12 31 65 90 113
[ { "code": null, "e": 1291, "s": 1062, "text": "Array and vectors are very important data structures in competitive programming for solving problems. And the STL (Standard Template Library) in c++ programming provide some functions to perform operations of arrays and vectors." }, { "code": null, "e": 1336, "s": 1291, "text": "Let’s see some of these functions in action," }, { "code": null, "e": 1506, "s": 1336, "text": "Finding sum, Min and Max of the array/vector − In STL there are function that helps you to find the sum, max, and min of the array/vector. Functions with there function," }, { "code": null, "e": 1551, "s": 1506, "text": "accumulate(startIndex, endIndex, initialSum)" }, { "code": null, "e": 1586, "s": 1551, "text": "*max_element(startIndex, endIndex)" }, { "code": null, "e": 1621, "s": 1586, "text": "*min_element(startIndex, endIndex)" }, { "code": null, "e": 1662, "s": 1621, "text": "Program to perform operations on array −" }, { "code": null, "e": 1673, "s": 1662, "text": " Live Demo" }, { "code": null, "e": 2220, "s": 1673, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n int array[] = {65, 7,12, 90, 31, 113 };\n int l = sizeof(array) / sizeof(array[0]);\n cout<<\"The elments of the array are : \";\n for(int i = 0; i<l; i++)\n cout<<array[i]<<\"\\t\";\n cout<<endl;\n cout<<\"The sum of all elements of the array: \"<<accumulate(array, array + l, 0)<<endl;\n cout<<\"The element with maximum value in array: \"<<*max_element(array, array + l)<<endl;\n cout<<\"The element with minimum value in array: \"<<*min_element(array, array + l)<<endl;\n return 0;\n}" }, { "code": null, "e": 2399, "s": 2220, "text": "The elments of the array are : 65 7 12 90 31 113\nThe sum of all elements of the array: 318\nThe element with maximum value in array: 113\nThe element with minimum value in array: 7" }, { "code": null, "e": 2441, "s": 2399, "text": "Program to perform operations on vector −" }, { "code": null, "e": 2452, "s": 2441, "text": " Live Demo" }, { "code": null, "e": 2869, "s": 2452, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n vector<int> vec= {65, 7,12, 90, 31, 113 };\n cout<<\"The sum of all elments of the vector: \"<<accumulate(vec.begin(), vec.end() + 1, 0)<<endl;\n cout<<\"The element with maximum value in vector: \"<<*max_element(vec.begin(), vec.end())<<endl;\n cout<<\"The element with minimum value in vector: \"<<*min_element(vec.begin(), vec.end())<<endl;\n return 0;\n}" }, { "code": null, "e": 3001, "s": 2869, "text": "The sum of all elments of the vector: 318\nThe element with maximum value in vector: 113\nThe element with minimum value in vector: 7" }, { "code": null, "e": 3040, "s": 3001, "text": "Sorting elements of the array/vector −" }, { "code": null, "e": 3196, "s": 3040, "text": "In STL, there is a function sort() which can be used to sort elements of the array/vector. The function uses quick sort technique for sorting array/vector." }, { "code": null, "e": 3223, "s": 3196, "text": "sort(startIndex, endIndex)" }, { "code": null, "e": 3263, "s": 3223, "text": "Program to sort elements of the array −" }, { "code": null, "e": 3274, "s": 3263, "text": " Live Demo" }, { "code": null, "e": 3732, "s": 3274, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n int array[] = {65, 7,12, 90, 31, 113 };\n int l = sizeof(array) / sizeof(array[0]);\n cout<<\"The elments of the array are : \";\n for(int i = 0; i<l; i++)\n cout<<array[i]<<\"\\t\";\n cout<<endl;\n cout<<\"\\nSorting elements of the array...\\n\\n\";\n sort(array, array+l);\n cout<<\"The sorted array is : \";\n for(int i = 0; i<l; i++)\n cout<<array[i]<<\"\\t\";\n cout<<endl;\n return 0;\n}" }, { "code": null, "e": 3854, "s": 3732, "text": "The elments of the array are : 65 7 12 90 31 113\nSorting elements of the array...\nThe sorted array is : 7 12 31 65 90 113" }, { "code": null, "e": 3891, "s": 3854, "text": "Program to sort elements of vector −" }, { "code": null, "e": 3902, "s": 3891, "text": " Live Demo" }, { "code": null, "e": 4344, "s": 3902, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n vector<int> vec = {65, 7,12, 90, 31, 113 };\n cout<<\"The elments of the vector are : \";\n for(int i = 0; i<vec.size(); i++)\n cout<<vec[i]<<\"\\t\";\n cout<<endl;\n cout<<\"\\nSorting elements of the vector...\\n\\n\";\n sort(vec.begin(), vec.end());\n cout<<\"The sorted vector is : \";\n for(int i = 0; i<vec.size(); i++)\n cout<<vec[i]<<\"\\t\";\n cout<<endl;\n return 0;\n}" }, { "code": null, "e": 4469, "s": 4344, "text": "The elments of the vector are : 65 7 12 90 31 113\nSorting elements of the vector...\nThe sorted vector is : 7 12 31 65 90 113" } ]
Python | Pandas DatetimeIndex.to_series() - GeeksforGeeks
29 Dec, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas DatetimeIndex.to_series() function create a Series with both index and values equal to the index keys useful with map for returning an indexer based on an index. Syntax: DatetimeIndex.to_series(keep_tz=False, index=None, name=None) Parameters :keep_tz : return the data keeping the timezoneindex : index of resulting Series. If None, defaults to original indexname : name of resulting Series. If None, defaults to name of original index Return : Series Example #1: Use DatetimeIndex.to_series() function to create a series object from the given DatetimeIndex object. Also set the value of index for the series. # importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'S' represents secondly frequency didx = pd.DatetimeIndex(start ='2018-11-15 09:45:10', freq ='S', periods = 5) # Print the DatetimeIndexprint(didx) Output : Now we want to construct a series out of the DatetimeIndex object. # construct the seriesdidx.to_series(index =['A', 'B', 'C', 'D', 'E']) Output :As we can see in the output, the function has returned a series object constructed from the didx DatetimeIndex object. Example #2: Use DatetimeIndex.to_series() function to create a series object from the given DatetimeIndex object. Also set the value of index for the series. # importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'M' represents monthly frequency didx = pd.DatetimeIndex(start ='2015-03-02', freq ='M', periods = 5) # Print the DatetimeIndexprint(didx) Output : Now we want to construct a series out of the DatetimeIndex object. # construct the seriesdidx.to_series(index =['First', 'Second', 'Third', 'Fourth', 'Fifth']) Output :As we can see in the output, the function has returned a series object constructed from the didx DatetimeIndex object. Python pandas-datetimeIndex Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Reading and Writing to text files in Python sum() function in Python *args and **kwargs in Python
[ { "code": null, "e": 24984, "s": 24956, "text": "\n29 Dec, 2018" }, { "code": null, "e": 25198, "s": 24984, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 25367, "s": 25198, "text": "Pandas DatetimeIndex.to_series() function create a Series with both index and values equal to the index keys useful with map for returning an indexer based on an index." }, { "code": null, "e": 25437, "s": 25367, "text": "Syntax: DatetimeIndex.to_series(keep_tz=False, index=None, name=None)" }, { "code": null, "e": 25642, "s": 25437, "text": "Parameters :keep_tz : return the data keeping the timezoneindex : index of resulting Series. If None, defaults to original indexname : name of resulting Series. If None, defaults to name of original index" }, { "code": null, "e": 25658, "s": 25642, "text": "Return : Series" }, { "code": null, "e": 25816, "s": 25658, "text": "Example #1: Use DatetimeIndex.to_series() function to create a series object from the given DatetimeIndex object. Also set the value of index for the series." }, { "code": "# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'S' represents secondly frequency didx = pd.DatetimeIndex(start ='2018-11-15 09:45:10', freq ='S', periods = 5) # Print the DatetimeIndexprint(didx)", "e": 26044, "s": 25816, "text": null }, { "code": null, "e": 26053, "s": 26044, "text": "Output :" }, { "code": null, "e": 26120, "s": 26053, "text": "Now we want to construct a series out of the DatetimeIndex object." }, { "code": "# construct the seriesdidx.to_series(index =['A', 'B', 'C', 'D', 'E'])", "e": 26191, "s": 26120, "text": null }, { "code": null, "e": 26476, "s": 26191, "text": "Output :As we can see in the output, the function has returned a series object constructed from the didx DatetimeIndex object. Example #2: Use DatetimeIndex.to_series() function to create a series object from the given DatetimeIndex object. Also set the value of index for the series." }, { "code": "# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'M' represents monthly frequency didx = pd.DatetimeIndex(start ='2015-03-02', freq ='M', periods = 5) # Print the DatetimeIndexprint(didx)", "e": 26694, "s": 26476, "text": null }, { "code": null, "e": 26703, "s": 26694, "text": "Output :" }, { "code": null, "e": 26770, "s": 26703, "text": "Now we want to construct a series out of the DatetimeIndex object." }, { "code": "# construct the seriesdidx.to_series(index =['First', 'Second', 'Third', 'Fourth', 'Fifth'])", "e": 26863, "s": 26770, "text": null }, { "code": null, "e": 26990, "s": 26863, "text": "Output :As we can see in the output, the function has returned a series object constructed from the didx DatetimeIndex object." }, { "code": null, "e": 27018, "s": 26990, "text": "Python pandas-datetimeIndex" }, { "code": null, "e": 27032, "s": 27018, "text": "Python-pandas" }, { "code": null, "e": 27039, "s": 27032, "text": "Python" }, { "code": null, "e": 27137, "s": 27039, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27155, "s": 27137, "text": "Python Dictionary" }, { "code": null, "e": 27177, "s": 27155, "text": "Enumerate() in Python" }, { "code": null, "e": 27209, "s": 27177, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27239, "s": 27209, "text": "Iterate over a list in Python" }, { "code": null, "e": 27281, "s": 27239, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27307, "s": 27281, "text": "Python String | replace()" }, { "code": null, "e": 27344, "s": 27307, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27388, "s": 27344, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27413, "s": 27388, "text": "sum() function in Python" } ]
Python | sympy.collect() method - GeeksforGeeks
18 Jun, 2019 With the help of sympy.collect() method, we are able to collect the mathematical expressions having same power. Syntax : sympy.collect()Return : Return mathematical expression having same powers. Example #1 :In this example, we can see that by using sympy.collect() method, all the same powers of variables are collected together as a same mathematical expression. # import sympyfrom sympy import * x, y, z = symbols('x y z')gfg_exp = x * y + x - 3 + 2 * x**2 - z * x**2 + x**3 # Using sympy.collect() methodgfg_exp = collect(gfg_exp, x) print(gfg_exp) Output : x**3 + x**2*(2 – z) + x*(y + 1) – 3 Example #2 : # import sympyfrom sympy import * x, y, z = symbols('x y z')gfg_exp = x * x + x - 3 + 2 * z**2 - y * x**2 + x**3 # Using sympy.collect() methodgfg_exp = collect(gfg_exp, x) print(gfg_exp) Output : x**3 + x**2*(1 – y) + x + 2*z**2 – 3 SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists *args and **kwargs in Python How To Convert Python Dictionary To JSON? sum() function in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 25010, "s": 24982, "text": "\n18 Jun, 2019" }, { "code": null, "e": 25122, "s": 25010, "text": "With the help of sympy.collect() method, we are able to collect the mathematical expressions having same power." }, { "code": null, "e": 25206, "s": 25122, "text": "Syntax : sympy.collect()Return : Return mathematical expression having same powers." }, { "code": null, "e": 25375, "s": 25206, "text": "Example #1 :In this example, we can see that by using sympy.collect() method, all the same powers of variables are collected together as a same mathematical expression." }, { "code": "# import sympyfrom sympy import * x, y, z = symbols('x y z')gfg_exp = x * y + x - 3 + 2 * x**2 - z * x**2 + x**3 # Using sympy.collect() methodgfg_exp = collect(gfg_exp, x) print(gfg_exp)", "e": 25565, "s": 25375, "text": null }, { "code": null, "e": 25574, "s": 25565, "text": "Output :" }, { "code": null, "e": 25610, "s": 25574, "text": "x**3 + x**2*(2 – z) + x*(y + 1) – 3" }, { "code": null, "e": 25623, "s": 25610, "text": "Example #2 :" }, { "code": "# import sympyfrom sympy import * x, y, z = symbols('x y z')gfg_exp = x * x + x - 3 + 2 * z**2 - y * x**2 + x**3 # Using sympy.collect() methodgfg_exp = collect(gfg_exp, x) print(gfg_exp)", "e": 25813, "s": 25623, "text": null }, { "code": null, "e": 25822, "s": 25813, "text": "Output :" }, { "code": null, "e": 25859, "s": 25822, "text": "x**3 + x**2*(1 – y) + x + 2*z**2 – 3" }, { "code": null, "e": 25865, "s": 25859, "text": "SymPy" }, { "code": null, "e": 25872, "s": 25865, "text": "Python" }, { "code": null, "e": 25970, "s": 25872, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25988, "s": 25970, "text": "Python Dictionary" }, { "code": null, "e": 26010, "s": 25988, "text": "Enumerate() in Python" }, { "code": null, "e": 26042, "s": 26010, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26084, "s": 26042, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26110, "s": 26084, "text": "Python String | replace()" }, { "code": null, "e": 26147, "s": 26110, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26176, "s": 26147, "text": "*args and **kwargs in Python" }, { "code": null, "e": 26218, "s": 26176, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26243, "s": 26218, "text": "sum() function in Python" } ]
Unique Binary Search Trees II in C++
Suppose we have an integer n, we have to generate all structurally unique binary search trees that store values from 1 to n. So if the input is 3, then the trees will be − To solve this, we will follow these steps − Define one recursive function called generate(), this will take low and high define one tree node called temp. if low > high, then insert null into the temp, and return temp for i in range low to highleft_subtree := generate(low, i – 1)right_subtree := generate(i + 1, high)current := ifor j in range 0 to size of the left_subtreefor k in range 0 to size of the right_subtreecurr_node := make one tree node with value currentleft of the curr_node := left_subtree[j]right of the curr_node := right_subtree[k]insert curr_node into the temp left_subtree := generate(low, i – 1) right_subtree := generate(i + 1, high) current := i for j in range 0 to size of the left_subtreefor k in range 0 to size of the right_subtreecurr_node := make one tree node with value currentleft of the curr_node := left_subtree[j]right of the curr_node := right_subtree[k]insert curr_node into the temp for k in range 0 to size of the right_subtreecurr_node := make one tree node with value currentleft of the curr_node := left_subtree[j]right of the curr_node := right_subtree[k]insert curr_node into the temp curr_node := make one tree node with value current left of the curr_node := left_subtree[j] right of the curr_node := right_subtree[k] insert curr_node into the temp return temp. Initially call the generate() function with values 1 and n to generate all trees. Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class TreeNode{ public: int val; TreeNode *left, *right; TreeNode(int data){ val = data; left = right = NULL; } }; void insert(TreeNode **root, int val){ queue<TreeNode*> q; q.push(*root); while(q.size()){ TreeNode *temp = q.front(); q.pop(); if(!temp->left){ if(val != NULL) temp->left = new TreeNode(val); else temp->left = new TreeNode(0); return; } else{ q.push(temp->left); } if(!temp->right){ if(val != NULL) temp->right = new TreeNode(val); else temp->right = new TreeNode(0); return; } else{ q.push(temp->right); } } } TreeNode *make_tree(vector<int> v){ TreeNode *root = new TreeNode(v[0]); for(int i = 1; i<v.size(); i++){ insert(&root, v[i]); } return root; } void tree_level_trav(TreeNode*root){ if (root == NULL) return; cout << "["; queue<TreeNode *> q; TreeNode *curr; q.push(root); q.push(NULL); while (q.size() > 1) { curr = q.front(); q.pop(); if (curr == NULL){ q.push(NULL); } else { if(curr->left) q.push(curr->left); if(curr->right) q.push(curr->right); if(curr == NULL || curr->val == 0){ cout << "null" << ", "; } else{ cout << curr->val << ", "; } } } cout << "]"<<endl; } class Solution { public: vector<TreeNode*> generate(int low, int high) { vector <TreeNode*> temp; if(low > high){ temp.push_back(NULL); return temp; } for(int i = low;i<=high;i++){ vector <TreeNode*> leftSubtree = generate(low,i-1); vector <TreeNode*> rightSubtree = generate(i+1,high); int current = i; for(int j = 0;j<leftSubtree.size();j++){ for(int k =0;k<rightSubtree.size();k++){ TreeNode* currentNode = new TreeNode(current); currentNode->left = leftSubtree[j]; currentNode->right = rightSubtree[k]; temp.push_back(currentNode); } } } return temp; } vector<TreeNode*> generateTrees(int n) { if(!n){ vector <TreeNode*> r; return r; } return generate(1,n) ; } }; main(){ Solution ob; vector<TreeNode*> v = ob.generateTrees(3); for(int i = 0; i<v.size(); i++) tree_level_trav(v[i]); } 3 [1, 2, 3, ] [1, 3, 2, ] [2, 1, 3, ] [3, 1, 2, ] [3, 2, 1, ]
[ { "code": null, "e": 1234, "s": 1062, "text": "Suppose we have an integer n, we have to generate all structurally unique binary search trees that store values from 1 to n. So if the input is 3, then the trees will be −" }, { "code": null, "e": 1278, "s": 1234, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1355, "s": 1278, "text": "Define one recursive function called generate(), this will take low and high" }, { "code": null, "e": 1389, "s": 1355, "text": "define one tree node called temp." }, { "code": null, "e": 1452, "s": 1389, "text": "if low > high, then insert null into the temp, and return temp" }, { "code": null, "e": 1816, "s": 1452, "text": "for i in range low to highleft_subtree := generate(low, i – 1)right_subtree := generate(i + 1, high)current := ifor j in range 0 to size of the left_subtreefor k in range 0 to size of the right_subtreecurr_node := make one tree node with value currentleft of the curr_node := left_subtree[j]right of the curr_node := right_subtree[k]insert curr_node into the temp" }, { "code": null, "e": 1853, "s": 1816, "text": "left_subtree := generate(low, i – 1)" }, { "code": null, "e": 1892, "s": 1853, "text": "right_subtree := generate(i + 1, high)" }, { "code": null, "e": 1905, "s": 1892, "text": "current := i" }, { "code": null, "e": 2157, "s": 1905, "text": "for j in range 0 to size of the left_subtreefor k in range 0 to size of the right_subtreecurr_node := make one tree node with value currentleft of the curr_node := left_subtree[j]right of the curr_node := right_subtree[k]insert curr_node into the temp" }, { "code": null, "e": 2365, "s": 2157, "text": "for k in range 0 to size of the right_subtreecurr_node := make one tree node with value currentleft of the curr_node := left_subtree[j]right of the curr_node := right_subtree[k]insert curr_node into the temp" }, { "code": null, "e": 2416, "s": 2365, "text": "curr_node := make one tree node with value current" }, { "code": null, "e": 2457, "s": 2416, "text": "left of the curr_node := left_subtree[j]" }, { "code": null, "e": 2500, "s": 2457, "text": "right of the curr_node := right_subtree[k]" }, { "code": null, "e": 2531, "s": 2500, "text": "insert curr_node into the temp" }, { "code": null, "e": 2544, "s": 2531, "text": "return temp." }, { "code": null, "e": 2626, "s": 2544, "text": "Initially call the generate() function with values 1 and n to generate all trees." }, { "code": null, "e": 2698, "s": 2626, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 2709, "s": 2698, "text": " Live Demo" }, { "code": null, "e": 5320, "s": 2709, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass TreeNode{\n public:\n int val;\n TreeNode *left, *right;\n TreeNode(int data){\n val = data;\n left = right = NULL;\n }\n};\nvoid insert(TreeNode **root, int val){\n queue<TreeNode*> q;\n q.push(*root);\n while(q.size()){\n TreeNode *temp = q.front();\n q.pop();\n if(!temp->left){\n if(val != NULL)\n temp->left = new TreeNode(val);\n else\n temp->left = new TreeNode(0);\n return;\n }\n else{\n q.push(temp->left);\n }\n if(!temp->right){\n if(val != NULL)\n temp->right = new TreeNode(val);\n else\n temp->right = new TreeNode(0);\n return;\n }\n else{\n q.push(temp->right);\n }\n }\n}\nTreeNode *make_tree(vector<int> v){\n TreeNode *root = new TreeNode(v[0]);\n for(int i = 1; i<v.size(); i++){\n insert(&root, v[i]);\n }\n return root;\n}\nvoid tree_level_trav(TreeNode*root){\n if (root == NULL) return;\n cout << \"[\";\n queue<TreeNode *> q;\n TreeNode *curr;\n q.push(root);\n q.push(NULL);\n while (q.size() > 1) {\n curr = q.front();\n q.pop();\n if (curr == NULL){\n q.push(NULL);\n }\n else {\n if(curr->left)\n q.push(curr->left);\n if(curr->right)\n q.push(curr->right);\n if(curr == NULL || curr->val == 0){\n cout << \"null\" << \", \";\n }\n else{\n cout << curr->val << \", \";\n }\n }\n }\n cout << \"]\"<<endl;\n}\nclass Solution {\npublic:\n vector<TreeNode*> generate(int low, int high) {\n vector <TreeNode*> temp;\n if(low > high){\n temp.push_back(NULL);\n return temp;\n }\n for(int i = low;i<=high;i++){\n vector <TreeNode*> leftSubtree = generate(low,i-1);\n vector <TreeNode*> rightSubtree = generate(i+1,high);\n int current = i;\n for(int j = 0;j<leftSubtree.size();j++){\n for(int k =0;k<rightSubtree.size();k++){\n TreeNode* currentNode = new TreeNode(current);\n currentNode->left = leftSubtree[j];\n currentNode->right = rightSubtree[k];\n temp.push_back(currentNode);\n }\n }\n }\n return temp;\n }\n vector<TreeNode*> generateTrees(int n) {\n if(!n){\n vector <TreeNode*> r;\n return r;\n }\n return generate(1,n) ;\n }\n};\nmain(){\n Solution ob;\n vector<TreeNode*> v = ob.generateTrees(3);\n for(int i = 0; i<v.size(); i++)\n tree_level_trav(v[i]);\n}" }, { "code": null, "e": 5322, "s": 5320, "text": "3" }, { "code": null, "e": 5382, "s": 5322, "text": "[1, 2, 3, ]\n[1, 3, 2, ]\n[2, 1, 3, ]\n[3, 1, 2, ]\n[3, 2, 1, ]" } ]
Microsoft Expression Web - Quick Guide
Microsoft Expression Web is a full-featured professional tool for designing, developing, and publishing feature-rich websites that conform to web standards. You can use Expression Web to create web pages and sites that let you transfer files between your computer and your hosting account. Expression Web can design and develop web pages using HTML5, CSS 3, ASP.NET, PHP, JavaScript, XML+XSLT and XHTML. Expression Web 4 requires .NET Framework 4.0 and Silverlight 4.0 to install and run. Microsoft Expression Web − History Microsoft released the first Community Technology Preview (CTP) version of Expression Web on May 14, 2006. Microsoft Expression Web 4 was released on June 7, 2010. It added the option of HTML add-ins and access to a web-based functionality for testing pages on browsers that cannot be installed on the user's system, such as Mac OS X or Linux browsers. It added the option of HTML add-ins and access to a web-based functionality for testing pages on browsers that cannot be installed on the user's system, such as Mac OS X or Linux browsers. It also provides an SEO Checker using which you can analyze already created websites against the best practices for getting the highest possible search engine rankings. It also provides an SEO Checker using which you can analyze already created websites against the best practices for getting the highest possible search engine rankings. Expression Web Service Packs Expression Web 4 Service Pack 1 was released in March 2011 and added support for IntelliSense for HTML5 and CSS. Expression Web 4 Service Pack 2 was released in July 2011. It fixed a number of issues and introduced new features such as − jQuery IntelliSense support a panel for managing snippets Interactive Snapshot Panel comment/uncomment functionality in Code View, and workspace and toolbar customization. In December 2012, Microsoft announced that Expression Studio will no longer be a standalone product. Expression Blend is being integrated into Visual Studio, while Expression Web and Expression Design will now be free products. To create a website using Microsoft Expression Web, your computer should meet the following requirements − You should have at least Windows XP with Service Pack 3 or the latest operating systems. You should have a PC with 1 GHz or faster processor. Your PC should have 1 GB of RAM or more. Your PC should have 2 GB or more of available hard disk space. You should have .NET Framework 4.0 and Silverlight 4.0. Your PC should support Microsoft DirectX® 9.0 graphics. You should have DVD compatible drive. You should have 1024 × 768 or higher resolution monitor with 24-bit color. Some product features require Firefox 3.0 or later, Internet Explorer 8. So you should have the same version. Actual requirements and product functionality may vary based on your system configuration and operating system. Microsoft provides a free version of Microsoft Expression Web which can be downloaded from https://www.microsoft.com/en-pk/download/details.aspx?id=36179 Step 1 − Before you can install Expression Web, you will need to have .NET Framework 4.0 installed. Step 2 − Once downloading is complete, run the installer. The following dialog will be displayed. Step 3 − Click the Accept button. Step 4 − Select the Yes radio button and then click Next. Step 5 − You can choose other location as well for installation. Select the location and click the Install button. The installation process starts. Once the installation is complete, you will see the following dialog. Step 6 − Click Finish to continue. In the previous chapter, we have installed Microsoft Expression Web and now we are ready to start working on it. In this chapter, we will learn how to create a new website from scratch. To create a new website, let’s open Microsoft Expression Web. Next, you need to follow the steps given below. Step 1 − Select Site → New Site... menu option. Step 2 − It will open the following dialog from which you can create or import different types of website. Step 3 − For simplicity let’s select General → One Page Site. Specify the location or you can browse to the location where you want the new website to be created. Specify the location or you can browse to the location where you want the new website to be created. Type in the name of your web in the name field and click OK. Type in the name of your web in the name field and click OK. Step 4 − The new web will be created with one page named default.htm. Let’s rename it to index.html with a right-click on the file and clicking on the Rename option. Step 5 − The default doctype used in Expression Web is − <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> You can see it by just switching to the code view. You can change the doctype from Tools → Page Editor Options → Authoring. Step 6 − Now, let’s add <h1> tag inside the body tag and some text as shown in the following code. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <meta content = "text/html; charset = utf-8" http-equiv = "Content-Type" /> </head> <body> <h1> This my first Web page </h1> </body> </html> Step 7 − To see our web in a browser, let’s go to the File menu and select the Preview in Browser → Any browser, let’s say, Internet Explorer. It will open our web in Internet Explorer. As we have already created our website, now we will need to create our Home Page. In the previous chapter, we have created a one-page website, and our Home Page was created at that time automatically by Expression Web. So, if you have created a blank website, then you will need to create a Home Page for your site. Microsoft Expression Web can create the following types of pages − HTML ASPX ASP PHP CSS Master Page Dynamic Web Template JavaScript XML Text File In this chapter, we will create an HTML page and its corresponding style sheet. To create a blank page, you can simply go to File menu and select New → Page... menu option. From the new dialog, you can create different types of blank pages such as HTML page, ASPX page, CSS page, etc. and click OK. As you can see here, the default code is already added by Microsoft Expression Web. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <meta content = "text/html; charset = utf-8" http-equiv = "Content-Type" /> <title>Untitled 1</title> </head> <body> <h1> This is a blank web page </h1> </body> </html> As you can see, your newly created page has the file name Untitled_1.html or Untitled_1.htm. You will need to save the page by pressing Ctrl + S and specify the name. As our website already contains an index.html page, we don’t need another one. However, if you have created an Empty website, then name this page index.html. To see your web in a browser, let’s go to the File menu and select the Preview in Browser → Any browser, let’s say Internet Explorer. Let’s take you through the step-by-step process of creating a CSS page. Step 1 − To create a CSS page, go to the File menu and select New → Page... menu option. Step 2 − Select General → CSS and click OK. Step 3 − Save the page and type a name for the style-sheet. Step 4 − Click the Save button. Step 5 − Now, let’s go to the index.html page. Step 6 − In the Manage Styles Panel, click Attach Style Sheet. Step 7 − Browse to your style-sheet and select the Current page from “Attach to” and Link from “Attach as” and click OK. Step 8 − Now, you will see that a new line is added automatically in the index.html page. <link href = "sample.css" rel = "stylesheet" type = "text/css" /> Step 9 − The body element defines the document's body. To style the <body> tag, we need to create a new style. First, select the body tag in Design View and then click on the New Style... in Apply Styles panel or Manage Styles panel, which will open the New Style dialog. Here, you can define the different options for your style. The first step is to select the body from the Selector dropdown list and then select the Existing style sheet from “Define in” dropdown list. Step 10 − From the URL, select the sample.css file. On the left side, there is a Category list like font, background, etc. and currently the Font is highlighted. Set the Font related information as per your requirements as shown in the above screenshot and click Ok. Step 11 − Now you can see in the design view that the background color and the font has changed to what we have selected. Now, if you open the sample.css file, you will see that all the information is automatically stored in the CSS file. Let’s preview our web page in a browser. You will observe that the style is applied from the CSS file. In this chapter, we will be covering the basic layout of your webpages. Before creating our webpage layout, we need to think about our content and then design how we want to present that content, as it is the content that will be visible on our website. It is up to us how we present our content so that our viewers find our site and then stay to check it out. The layout will probably include the company logo or banner at the top, the navigation menu, a content area that may include multiple columns, and footer at the bottom of the page. Previously, developers used tables to achieve this look. Tables created group of boxes that were used to create rows and columns. Now, web designers use <div>s to form the boxes and CSS to place those boxes on the page. Following are some of the features of <div> tag. The <div> tag defines a division or a section in an HTML document and makes it easy to manage, style, and manipulate those divisions or sections. The <div> tag defines a division or a section in an HTML document and makes it easy to manage, style, and manipulate those divisions or sections. It is used to group block elements to format them with CSS. It is used to group block elements to format them with CSS. Browsers usually place a line break before and after the div element. Browsers usually place a line break before and after the div element. The <div> tag is a block-level element. The <div> tag is a block-level element. The <div> tag can contain almost any other element. The <div> tag can contain almost any other element. The <div> tag cannot be inside a <p> tag. The <div> tag cannot be inside a <p> tag. Let’s take a look at a simple example in which we will be using <div> </div> tags to create the various boxes and style rules. Step 1 − Open Expression Web and then the index.html page that we created in the previous chapter. Step 2 − As seen in the above screenshot, the Code View is highlighted by default. You can work in Code View or Design View, but you can also see the Split View which will open both Code View and Design View. So let’s select the Split View option. Step 3 − The body element defines the document's body. To style the <body> tag, we need to create a new style. First select the body tag in Design View and then click the New Style... in Apply Styles panel, which will open the New Style dialog. Here, you can define the different options for your style. Step 4 − The first step is to select the body from the Selector dropdown list and then select the Existing style sheet from “Define in” the dropdown list. From the URL, select the CSS file we have created in the previous chapter. On the left side, there is a Category list such as Font, Background, etc. and the current Font is highlighted. Set the Font-related information as per your requirements as shown in the above screenshot. Step 5 − Select the Background color you want. You can also select the image for your background by using the browser button. Once you are done with the Background, define your Borders if you want. Step 6 − Let’s select the double line option for the border and choose the width and color also from the dropdown lists. Once you are done with the style, then click Ok. Step 7 − Now you can see in the design view that the background color is changed to what we have selected. If you open the sample.css file, you will see that all the information is automatically stored in the CSS file. Step 8 − Go to the index.html page again and drag the <div> from the 'Toolbox' panel and drop it on your open page. Step 9 − Above the code view, you will see <body> and <div> tags, click the <div> tag and then in Apply Styles panel click on the New Style.... which will open the New Style dialog. Type “#container” in the Selector field. The hash mark # is an ID selector. From the “Define in” dropdown list, select the Existing style sheet and check the “Apply new style to document selection” option. Go to the Background category. Step 10 − Select the background color, let’s select white color and then go to the Box category. Step 11 − Define padding and margin and then go to the Position category Step 12 − Set the width to 90%. However, don’t specify the height as here we want that the container should expand when we enter the content. Click the OK button. Similarly, let’s add styles for Header, top navigation, left navigation, main content, and footer. Following is the code in sample.css style-sheet after adding all the above-mentioned styles. body { font-family: Calibri; font-size: medium; font-weight: normal; font-style: normal; font-variant: normal; text-transform: none; color: #0000FF; background-color: #CCFFFF; background-image: none; border: medium double #FF0000; } #container { background-color: #FFFFFF; padding: 8px; margin: 8px; width: 90%; } #header { background-color: #54B431; background-repeat: no-repeat; background-position: right center; height: 170px; } #top-nav { height: 50px; border-top: solid medium #006600; border-bottom: solid medium #006600; background-color: #FFFFFF; } #left-nav { margin: 20px 0px 10px 0px; width: 180px; float: left; border: thin dashed #006600; } #main-content { margin: 20px 10px 10px 200px; background-color: #CCFFCC; } #footer { border-top: 2px solid #006600; clear: both; padding: 10px 0px; text-align: center; } Following is the code in index.html file after adding all the <div> tags. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <meta content = "text/html; charset = utf-8" http-equiv = "Content-Type" /> <style type = "text/css"></style> <link href = "sample.css" rel = "stylesheet" type = "text/css" /> </head> <body> <div id = "container"> <div id = "header"></div> <div id = "top-nav"></div> <div id = "left-nav"></div> <div id = "main-content"></div> <div id = "footer"></div> </div> </body> </html> Your page layout in the design view will look as shown in the following screenshot. In this chapter, we will learn another way of designing the layout of a page. In the last chapter, we have used style sheet to apply the styles to header, footer, etc. but you can also specify the styles in HTML page itself without using an additional style-sheet. This is not the recommended way to design a layout, however just for understanding purpose, we will cover this technique here. Try to follow the steps given below. Step 1 − Let’s add an HTML page and call it layoutdemo.html Step 2 − Now add the <div> tag from the Toolbox. Step 3 − In the Apply Styles panel, click on the New Style... Step 4 − When you select the Current page option from “Define in” dropdown then the style will be saved in the same HTML page. Set the Font for your page and then go to the Background category. Step 5 − Set the color for your Background. You can also set the Border, Box, and Position categories and then click OK. You can see that the style is added in the same HTML file. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <meta content = "text/html; charset = utf-8" http-equiv = "Content-Type" /> <title>Untitled 1</title> <style type = "text/css"> #container { font-family: Arial, Helvetica, sans-serif; font-size: medium; font-weight: normal; font-style: normal; font-variant: normal; text-transform: capitalize; color: #800000; background-color: #C0C0C0; padding: 8px; margin: 8px; width: 90%; } </style> </head> <body> <div id = "container"></div> </body> </html> Similarly, you can add other styles like header, footer, main content, etc. as shown above. In this chapter, we will learn how to add horizontal navigation or menu items to the website. Step 1 − To create menu items or horizontal navigation, let’s add the following code in <div id = “top-nav”> in the index.html file, which contains the list of menu items. <div id = "top-nav"> <ul> <li></li> <li></li> <li></li> <li></li> </ul> </div> Step 2 − It is a simple bulleted list for the top menu. To create a hyperlink, go to the design view or code view. Step 3 − Select the item that you want to use as the hyperlink and press Ctrl + K. Step 4 − Click on the ScreenTip... button. Step 5 − Enter the text you want as the screen tip and click OK. Step 6 − In the Text to display field, enter Home and select the index.html file and then click OK. Step 7 − Similarly, add hyperlinks for other menu items, as shown in the following code. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <meta content = "text/html; charset=utf-8" http-equiv = "Content-Type" /> <style type = "text/css"></style> <link href = "sample.css" rel="stylesheet" type = "text/css" /> </head> <body> <div id = "container"> <div id = "header"></div> <div id = "top-nav"> <ul> <li><a href = "index.html" title = "Site Home Page">Home</a></li> <li><a href = "index.html" title = "Menu Item 1.">Menu Item 1</a></li> <li><a href = "index.html" title = "Menu Item 2.">Menu Item 2</a></li> <li><a href = "index.html" title = "Menu Item 3.">Menu Item 3</a></li> </ul> </div> <div id = "left-nav"> </div> <div id = "main-content"> </div> <div id = "footer"> </div> </div> </body> </html> Step 8 − To set the style for top navigation, go to the Manage Styles panel. Step 9 − Right-click on “#top-nav” and select Modify Style. Select the 'Border' Category and change the width to thin. Step 10 − Select the Box category and uncheck padding ‘Same for all’ and enter 10 in the top and bottom fields. Step 11 − Go to the Position category. Step 12 − Remove the 50 from the height field and click OK. From the Apply Styles panel, click New Style... Step 13 − Enter #top-nav ul in the Selector field and select the Existing style sheet from the “Define in” dropdown. In the Block category, select center from the test-align field and go to the List category. Step 14 − Select none from the list-style-type field and click OK. Step 15 − Again, from the Apply Styles panel, click New Style... Enter #top-nav ul li in the Selector field. Then select the Existing style-sheet from the “Define in” dropdown and go to the Layout category. Step 16 − Select inline from the display field and click OK. Step 17 − Go to Apply Styles panel, click New Style... Enter #top-nav ul li a in the Selector field and select the Existing style sheet from the “Define in” dropdown and select white as the font color. Step 18 − Go to the Background category. Step 19 − Select green as the background color and go to the Box category. Step 20 − Set the padding values and click OK. Step 21 − Now let’s go to the Apply Styles panel again and click New Style. Enter #topnav ul li a:hover in the Selector field and select the Existing style sheet from the “Define in” dropdown and select black as the font color. Step 22 − Now go to the Background category. Step 23 − Select the background color for your menu option when the mouse is hovering on the menu item and go to the Border category. Step 24 − Select the border style, width, and color, and click OK. To check how it is looks, go to the File menu and select Preview in Browser. When you hover the mouse on any menu item, it will change the background and font color. In this chapter, we will learn how to add vertical navigation or menu items to the website. Let’s go step by step. Step 1 − To create menu items or vertical navigation, let’s add the following code in <div id = “left-nav”> in the index.html file which contains the list of menu items. <div id = "left-nav"> <p>Site Navigation</p> <ul> <li></li> <li></li> <li></li> <li></li> </ul> </div> Step 2 − It is a simple bulleted list for your top menu. To create a hyperlink, go to the design view or code view. Step 3 − Select the item that you want to use as the hyperlink and press Ctrl + K. Step 4 − Click the ScreenTip... button. Enter the text you want as the screentip and click OK. Step 5 − In the Text to display field, enter Home and select the index.html file and then click OK. At this stage, our index.html page looks as follows − Step 6 − Add more hyperlinks for other menu items, as shown in the following code. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <meta content = "text/html; charset = utf-8" http-equiv = "Content-Type" /> <style type = "text/css"></style> <link href = "sample.css" rel = "stylesheet" type = "text/css" /> </head> <body> <div id = "container"> <div id = "header"></div> <div id = "top-nav"> <ul> <li><a href = "index.html" title = "Site Home Page">Home</a></li> <li><a href = "index.html" title = "Menu Item 1.">Menu Item 1</a></li> <li><a href = "index.html" title = "Menu Item 2.">Menu Item 2</a></li> <li><a href = "index.html" title = "Menu Item 3.">Menu Item 3</a></li> </ul> </div> <div id = "left-nav"> <p>Site Navigation</p> <ul> <li><a href = "index.html" title = "Site Home Page">Home</a></li> <li><a href = "index.html" title = "Navigation Item 1.">Navigation Item 1</a></li> <li><a href = "index.html" title = "Navigation Item 2.">Navigation Item 2</a></li> <li><a href = "index.html" title = "Navigation Item 3.">Navigation Item 3</a></li> </ul> </div> <div id = "main-content"></div> <div id = "footer"></div> </div> </body> </html> Step 7 − To set the style for top navigation, go to the Manage Styles panel. Right-click on #left-nav and select Modify Style... Step 8 − Enter the value 0.9 in font-size field and select em from the dropdown list next to the font-size and go to the Box category. Step 9 − Check the padding ‘Same for all’ and enter 5 in the top field and click Ok. From the Apply Styles panel, click New Style... Step 10 − Enter #left-nav ul in the Selector field. Select the Existing style-sheet from the “Define in” dropdown and in the List category, select none from the list-style-type field and click OK. Step 11 − Again, from the Apply Styles panel, click New Style. Uncheck the padding ‘Same for all’. Enter 0.2 in the bottom field and click OK. Step 12 − Enter #left-nav ul li in the Selector field and select the Existing style sheet from the “Define in” dropdown and go to the Box category. Step 13 − Go to Apply Styles panel and click New Style. Step 14 − Enter #left-nav ul li a in the Selector field and select the Existing style sheet from the “Define in” dropdown and select white as the font color. Step 15 − Go to the Background category. Select the color as the background color Step 16 − Go to the Box category and set the padding values. Step 17 − Go to the Layout category. Select block from the display dropdown and click OK. Step 18 − Now let’s go to Apply Styles panel again and click New Style. Enter #left-nav ul li a:hover in the Selector field and select the Existing style sheet from the “Define in” dropdown. Select black as the font color. Step 19 − Now go to the Background category. Select the background color for your menu option when the mouse is hovering on the menu item and click OK. Step 20 − To check how it is looks, go to the File menu and select Preview in your browser. When you hover the mouse on any menu item, it will change its background and font color. In this chapter, we will learn how to make sure that both our HTML and CSS code validates. Microsoft Expression Web provides several ways to check your webpages for code errors and the code that is incompatible with a particular HTML and CSS schema. The status bar and Code view alert you to code errors and incompatibility in a single page, while the Compatibility task pane lists all code errors and incompatibility in one or more pages, or an entire website. The status bar and Code view alert you to code errors and incompatibility in a single page, while the Compatibility task pane lists all code errors and incompatibility in one or more pages, or an entire website. Expression Web identifies incompatible code by using a document schema that is based on the DocType declaration in a page. Expression Web identifies incompatible code by using a document schema that is based on the DocType declaration in a page. If the page doesn't contain a DocType declaration or the DocType isn't recognized, Expression Web uses a secondary schema. If the page doesn't contain a DocType declaration or the DocType isn't recognized, Expression Web uses a secondary schema. When you create a site and work on its pages, you should develop a habit of validating the pages. Microsoft Expression Web has various tools which can be very helpful while validating your webpages. There are two very helpful options in Expression web, so let’s go to the Tools menu and select the Page Editor Option. The General tab offers two options − Highlight Invalid HTML − This option when checked, it will display an invalid HTML in a specific color scheme and the default in red text on a yellow background. Highlight Invalid HTML − This option when checked, it will display an invalid HTML in a specific color scheme and the default in red text on a yellow background. Highlight Incompatible HTML − This option when checked, it will display a wavy underline beneath the code that isn't compatible with HTML standards. Highlight Incompatible HTML − This option when checked, it will display a wavy underline beneath the code that isn't compatible with HTML standards. When the current, open web page contains a code error, then you get to see a Code Error Detected icon (highlighted in the following screenshot). Let’s assume you forgot the symbol “>” in a </div> tag − <div id = "footer"></div> In this case, the status bar at the bottom of the program window displays the Code Error Detected icon. When you select “Go To Error” from the dropdown menu, it will take you to the line where the error exists and you can fix the syntax easily. When the page contains a code that's incompatible with the specified DocType, then the status bar displays an HTML Incompatibility Detected icon. Let’s assume you have used “hre” for a hyperlink instead of “href”, which is an error. <li><a href = "index.html" title = "Site Home Page">Home</a></li> The status bar displays the HTML Incompatibility Detected icon as shown in the following screenshot. When you select the “Go To Error” from the dropdown menu, it will take you to the line where the error exists and you can fix the syntax easily. A compatibility report checks the pages and CSS files for code errors and the code that's incompatible with the DocType and CSS schema you specify. You can generate a report that checks only particular files or an entire website. Step 1 − To generate a compatibility report, go to the tools menu and click the Compatibility Reports...option. Step 2 − The Compatibility Checker dialog provides different options to check only particular files in your site, either open those files or select them in either the Folder List task pane or the Website view. Select the options as per the requirement and click the Check button. Step 3 − The Compatibility task pane opens and the status of the generation of the report appears at the bottom of the task pane. On double-click on any row, it will take you to the location where the error exists. A Dynamic Web Template is a HTML-based master copy of a web page that you can create to contain settings, formatting, and page elements such as text, graphics, page layout, styles, and regions of a webpage that can be modified. When you attach a Dynamic Web Template to the pages in a website, that template defines the layout for those pages. You can use any number of Dynamic Web Templates in a website, and you can attach a Dynamic Web Template to as many pages as you like. By using Dynamic Web Templates, you can create HTML pages that share the same layout. In addition to providing a shared layout, you can make some regions in a template available for editing while preventing changes to other regions in that template. This means that you can allow others to add and edit content, yet still preserve the layout of the pages and the template itself. The most important concept of website design is to maintain a consistent look and feel for your site and with Dynamic Web Template you can achieve it. Dynamic Web Template provides − Basic pages such as a Sitemap, Contact, About, and Search pages. A visitor should be able to reach your home page from any page on the site. Basic pages such as a Sitemap, Contact, About, and Search pages. A visitor should be able to reach your home page from any page on the site. Consistent navigation throughout your site. Consistent navigation throughout your site. Consistent look throughout the site. Consistent look throughout the site. To create a Dynamic Web Template (DWT), you start with an empty HTML page and save it as a *.dwt file. Let’s go step by step and learn more about it. Step 1 − Open the index.html file and select File → Save As... menu option, which will open the Save As dialog. Select the Dynamic Web Template (*.dwt) from the Save as type dropdown and change the file name from the index to the master.dwt and click the Save button. Step 2 − Now, you will see a new file master.dwt is created in the Folder list. Let’s create a new HTML file and call it index_2.html. Let’s open the master.dwt file and in the Design View or the Code View, right-click inside <div> tags of the main content. Step 3 − From the menu, select the Manage Editable Regions... which will open the Editable Regions dialog. Step 4 − In the Region name, type a name for the editable region and then click Add. Repeat to add additional editable regions if you want. Step 5 − Once you have added all editable regions, then click Close. Now go to the index_2.html file and select it in the Folder list as well. Step 6 − Go to the Format menu and select Dynamic Web Template → Attach Dynamic Web Template... which will open the Attach Dynamic Web Template dialog. Step 7 − Select the Dynamic Web Template which here is the master.dwt file and click the Open button. You will receive a warning message. Click Yes. Step 8 − You can see that the same template is applied to the index_2.html file. Similarly, you can add the same template to as many HTML pages as you want to the website. Step 9 − On this page, you can edit only the main-content section. If you move the mouse to the other section, you will see that it is not editable and the mouse curser also changes to the red cross circle. Step 10 − To see how it looks, go to the File menu and select Preview in your browser. In this chapter, we will learn how to add a search option or a search box to the website. If it is a large site, then you will need to have a search box in the site so that the user can find any data easily. There are many free ones available such as Windows Live, Google, etc. The following steps show you how to add a Windows Live Search box to your web page, and then set the search form to search the entire Web or only your website. Step 1 − Create a new HTML page and call it SearchPage. Step 2 − Go to the Format menu and select Dynamic Web Template → Attach Dynamic Web Template...option. Select the master.dwt file and click the Open button. Step 3 − Let’s add the following code inside the editable region. <form method = "get" action = "http://search.live.com/results.aspx"> <input type = "hidden" name = "cp" value = "1252"/> <input type = "hidden" name = "FORM" value = "FREESS"/> <table style = "background-color: #ffffff;"> <tr> <td> <a href = "http://search.live.com/"> <img src = "http://search.live.com/s/affillogoLive.gif" style = "border:0px;" alt = "Live Search"/> </a> </td> <td> <input type = "text" name = "q" size = "30" /> <input type = "submit" value = "Search Site"/> <input type = "hidden" name = "q1" value = "site:http://www.microsoft.com/expression"/> </td> </tr> </table> </form> Step 4 − Save the page. Go to the File menu and select Preview in Browser. Step 5 − You will see the Windows Live Search in your webpage. Let’s enter something in the search and click the Search Site button Step 6 − As you can see that it will search on the web. If you want to restrict the search to only your website, then you have to specify your site domain in the following name instead of https://www.microsoft.com/expression <input type = "hidden" name = "q1" value = "site:http://www.microsoft.com/expression"/> Step 7 − Similarly, you can add the Google search option by adding the following code in the editable region. <form method = "get" action = "http://www.google.com/search"> <div style = "border: 1px solid black; padding: 4px; width: 20em; margin: 0px auto 0px auto"> <table border = "0" cellpadding = "0"> <tr> <td class = "center"> <input type = "text" name = "q" size = "25" maxlength = "255" value = "" /> <input type = "submit" value = "Google Search" /> </td> </tr> <tr> <td align = "center" style = "font-size: 75%"> <input type = "checkbox" name = "sitesearch" value = " http://www.microsoft.com/expression" checked = "checked" /> Only search this website<br /> </td> </tr> </table> </div> </form> Step 8 − Save your HTML page and you will see a search box, search button, checkbox, and checkbox label. Step 9 − To restrict users to search only your website, select the checkbox and go to the Tag Properties panel and set the Value property to the URL of your website, such as https://www.microsoft.com/expression. Step 10 − Save your page and preview it in the browser. Now you will see the Google Search option in your webpage. Images are used heavily in webpages to make them look interesting and provide a better user experience. In this chapter, we will learn how to add images to the website. As usual, let’s go step by step and learn the process in detail. Step 1 − To start adding images, let’s create a new one-page site and change the name of default.html file to index.html. Step 2 − Now we need to include images to the website so that we can use those images in the webpage. Let’s create a new folder. In the folder list, right-click on the website name. Step 3 − Currently, there are no images in this folder. To add images in this folder, simply select and drag images from your hard drive and drop them over the images folder. You will see that the images are added to the website images folder, as shown in the following screenshot. Step 4 − Now these images are included in your website but none of these are used in a webpage. A simple way to add an image to in the webpage is to drag the image from the images folder and drop in the code view where you want to add the image in the webpage. Suppose we want to add an image below the heading. When your drop the image and release the mouse button, it will display the following dialog box. Here you can specify the alternate text and long description. Then click OK and save the webpage. Now you can see that <img> tag is added with the alternate name and source of the image. Step 5 − Follow the same process and add the second image along with its alternate name and source. Now the index.html file will appear as follows − <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <meta content = "text/html; charset = utf-8" http-equiv = "Content-Type" /> </head> <body> <h1> Working with images </h1> <img alt = "Beautiful Birds" src = "images/birds.jpg" /> <img alt = "Other Birds" src = "images/birds2.jpg" /> </body> </html> Step 6 − The Picture Properties dialog box gives you access to the most commonly used picture attributes. When you double-click an image, it will display the Picture Properties box. In Expression Web, Picture Properties dialog has two tabs, General and Appearance. Following are the options available on the General tab. Picture − It contains the folder/file name of the graphic image. Picture − It contains the folder/file name of the graphic image. Alternate Text − Type the text you want to be displayed for pictures when the graphic is downloading, when it can't be found, or when a site visitor moves the pointer over it. This text will also be used by a screen reader if your viewer is using one. Alternate Text − Type the text you want to be displayed for pictures when the graphic is downloading, when it can't be found, or when a site visitor moves the pointer over it. This text will also be used by a screen reader if your viewer is using one. Long Description − There are times a few words may not be enough to describe your image. Charts and graphs are examples. Click Browse to select a file that contains a longer description of the picture. Long Description − There are times a few words may not be enough to describe your image. Charts and graphs are examples. Click Browse to select a file that contains a longer description of the picture. Location − If you want to link your image to a webpage or larger image, you insert the hyperlink here. Location − If you want to link your image to a webpage or larger image, you insert the hyperlink here. Target Frame − If the current page is a frames page, this option indicates which frame the link should be displayed in OR you can choose to have the image or page open in a new window. Target Frame − If the current page is a frames page, this option indicates which frame the link should be displayed in OR you can choose to have the image or page open in a new window. Following options are available on the Appearance tab. Wrapping Style − Specify how the picture floats in the page, such as None, Left, or Right. Wrapping Style − Specify how the picture floats in the page, such as None, Left, or Right. Layout − In this section, you can set the alignment, border thickness, horizontal and vertical margins. Layout − In this section, you can set the alignment, border thickness, horizontal and vertical margins. Size − Expression Web automatically sets the width and height properties for the image based on the actual dimensions of the picture. Rather than resizing your image by changing these dimensions, resize the image using your graphic editor. Size − Expression Web automatically sets the width and height properties for the image based on the actual dimensions of the picture. Rather than resizing your image by changing these dimensions, resize the image using your graphic editor. Step 7 − Now, let’s preview the webpage in the browser; it will display the following output. In this chapter, we will learn how to use hyperlinks in your website. One of the things that makes the web so expansive is the capability of webpages to link to other webpages. Hyperlinks or links are found within nearly all web pages. Hyperlinks also allow users to click and go to a different page, a place within a page, an image or another location on the Internet entirely. Following are some of the important features of hyperlink − Expression Web's hyperlink tools and options make it very easy to work with hyperlinks. Expression Web's hyperlink tools and options make it very easy to work with hyperlinks. Expression Web hyperlink views and reports also make it very easy to find and fix broken and incorrect links. Expression Web hyperlink views and reports also make it very easy to find and fix broken and incorrect links. A hyperlink can be a word, a group of words, or an image that when clicked will take you to a new document or a place within the current document. A hyperlink can be a word, a group of words, or an image that when clicked will take you to a new document or a place within the current document. In HTML, <a> tag which is known as anchor tag is used to create a link to another document. An anchor can point to another html page, an image, a text document, or a pdf file among others. Here is the basic code of an anchor <a> tag. <a href = "url">Text to be displayed as link<a> In <a> tag, “href” attribute is used to address the link to the document, and the words between the open and close of the anchor tag will be displayed as a hyperlink. In <a> tag, “href” attribute is used to address the link to the document, and the words between the open and close of the anchor tag will be displayed as a hyperlink. When you move the cursor over a link in a webpage, the arrow will turn into a little hand. When you move the cursor over a link in a webpage, the arrow will turn into a little hand. A URL is an address that specifies a protocol, web server, and file path. A URL is an address that specifies a protocol, web server, and file path. There are two types of URLs, absolute and relative. An absolute URL contains a full address while a relative URL is missing one or more parts of the address. However, the web browser obtains the missing information from the page that contains the URL. There are two types of URLs, absolute and relative. An absolute URL contains a full address while a relative URL is missing one or more parts of the address. However, the web browser obtains the missing information from the page that contains the URL. Let’s take a look at a simple example in which we will be using both absolute and relative URLs. Step 1 − First, open the index.html page and add the following lines in the main content section. <div id = "main-content"> <p> Absolute URL Example: </p> <p> Google </p> <p> Youtube </p> <p> Relative URL Example: </p> <p> Home Page 2 </p> </div> Following is the complete implementation of index.html page. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <meta content = "text/html; charset = utf-8" http-equiv = "Content-Type" /> <style type = "text/css"> #left-nav ul li a:hover { color: #000000; background-color: #116611; } #left-nav ul li a:hover { color: #000000; background-color: #66FF99; } </style> <link href = "sample.css" rel = "stylesheet" type = "text/css" /> </head> <body> <div id = "container"> <div id = "header"> </div> <div id = "top-nav"> <ul> <li><a href = "index.html" title = "Site Home Page">Home</a></li> <li><a href = "index.html" title = "Menu Item 1.">Menu Item 1</a></li> <li><a href = "index.html" title = "Menu Item 2.">Menu Item 2</a></li> <li><a href = "index.html" title = "Menu Item 3.">Menu Item 3</a></li> </ul> </div> <div id = "left-nav"> <p>Site Navigation</p> <ul> <li><a href = "index.html" title = "Site Home Page">Home</a></li> <li><a href = "index.html" title = "Navigation Item 1.">Navigation Item 1</a></li> <li><a href = "index.html" title = "Navigation Item 2.">Navigation Item 2</a></li> <li><a href = "index.html" title = "Navigation Item 3.">Navigation Item 3</a></li> </ul> </div> <div id = "main-content"> <p> Absolute URL Example: </p> <p> Google </p> <p> Youtube </p> <p> Relative URL Example: </p> <p> Home Page 2 </p> </div> <div id = "footer"> </div> </div> </body> </html> Step 2 − Let’s save the webpage and you will see the text in the main content section. Step 3 − In the Design View, right-click on Google and then select Hyperlink... from the menu which will open the Insert Hyperlink dialog. Step 4 − In the Address field, specify the URL for Google home page and click OK. Similarly, right-click on YouTube in the design view and select Hyperlink... Step 5 − In the Address field, specify the URL for YouTube home page and click Ok. Now for relative right-click on the “Home Page 2” and select Hyperlink... from the menu which will open the Insert Hyperlink dialog. Step 6 − For relative path, select the index_2.html in the address field and Expression Web will get the remaining path from the index.html file, because both these files are in the same directory. Click OK. As can be seen, these words are now underlined which means that hyperlinks are created. Step 7 − The default font color is blue and the default font color for Hyperlinks is also blue. To change the default color of the hyperlink, select any of the hyperlink and go the Format menu and select Background... menu option. You will now see the following dialog. Step 8 − Let’s change the Hyperlink color to Green. In the following screenshot, you will see that the Hyperlink color has changed to Green. Step 9 − Let us now preview this web page in a browser. If you click the Google link, it will direct you to the Google homepage. Step 10 − Similarly, if you go back to the Home page and click the YouTube link, it will direct you to the YouTube home page. Let’s go back to the home page. Click the Home Page 2 link and you will see that it opens the index_2.hmtl file. In this chapter, we will learn how to add videos to the website and which formats are supported in Expression Web. With the help of videos, you can easily attract the attention of potential customers to your company's products or services. Microsoft Expression Web is a web design tool that simplifies the process of adding promotional, marketing, or training videos to webpages. You can easily insert your videos in Microsoft Expression's Design view. By default, Expression Web supports video encoding formats like Silverlight, Adobe Flash, WMV, ASF, MWA, AVI, WVX and MPEG. Let us now take an example to understand the process of adding a video in a step-by-step manner. Step 1 − Add a new HTML file and call it videodemo.html. Step 2 − Click the mouse at the location within the webpage where the video is to be inserted. Let’s say we want to add a video below the heading. Step 3 − Go to the Insert menu → Media which will open the submenu containing the list of video player formats that Expressions supports by default. Let’s select Windows Media Player. Step 4 − Locate the video you want to use. Select the video file's name and click the Insert button to insert it into the webpage. Save the file by pressing Ctrl + S and you will see the Save Embedded Files dialog box. Step 5 − Click OK and you will see that the media file is added to the website folder. Following is the code in the videodemo.html page. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <meta content = "text/html; charset = utf-8" http-equiv = "Content-Type" /> <title>Untitled 1</title> </head> <body> <h1> Video Demo</h1> <p> <object id = "media1" height = "200" type = "video/x-ms-wmv" width = "200"> <param name = "filename" value = "logo.wmv" /> </object> </p> </body> </html> Step 6 − Let us now preview the webpage in a browser. You will see that the video is playing. Expression Web has many tools for working with static HTML pages, but it also has tools for creating more dynamic pages. Dynamic pages often retrieve data or content from a source of data. In this chapter, we will learn how to create a SQL DataSource to be used in dynamic pages. Let’s take a look at a simple example in which we create a dropdown list and fill the list by retrieving data from the database using SQL DataSource. Step 1 − Start by creating a new empty website. Let’s call it SQLDataSource. Click OK. Step 2 − You will see that expression web has created a folder for us. However, since we chose to create an empty project, so we don't have any files yet. Expression Web doesn't have to be used just to create static HTML sites; we can create dynamic sites using pages and controls with much ease. Step 3 − Expression web also allows us to create a lot of dynamic content without necessarily having to be a developer. So let’s add an ASPX file from the File → New Page menu option. Select ASPX in the middle model and click OK. Step 4 − Here we will be creating a control in our form that needs to access data from a database to create a dynamic website. In this particular case, we will create a SQL DataSource which will retrieve data from the database. Step 5 − Go to the Toolbox and drag the DropDownList and drop it inside the <form> tag in Code View or you can also drop it in the form section in Design View. You will see that the code is added by Expression Web. Here, we want to connect some data from our database and store that in our dropdown list. So, the first thing we need is the database. Step 6 − Create a new Folder in your Project folder by going to the New → Folder menu option. Step 7 − Call this folder App_Data. Step 8 − We need to import a database in our project by using the File → Import → File... menu option. Step 9 − It will open the Import dialog, as shown below. Click on the Add File... button which will open the open file dialog box. Step 10 − Browse to the database (*.mdf file) which you want to include in the website and click Open. Step 11 − Open the MyTestDatabase.mdf. It will display the following dialog. Click OK. Step 12 − Now you can see that the database file is added in the App_Data folder. When you have a control like a dropdown list and Expression Web allows you to bind the data to it, then you will see a little arrow at the top right corner in the design view. Step 13 − This is the current context menu that can allow us to do a very specific task for that particular control and one of those is to choose a data source. So let’s click on Choose Data Source... and that will open the data source configuration wizard. Step 14 − Currently, we don’t have a data source. Let’s select the New data source option from the menu. Here, we will import an SQL database. Let’s select the database and click OK. Step 15 − Now, we need to specify the connection string. Let’s click the New Connection button. Step 16 − Select the Microsoft SQL Server Database File and click OK. Step 17 − Click the Browse button to locate the database file. Step 18 − Select the database file and click the Open button or double-click the database file. Step 19 − To test the connection, click the Test Connection button. It will display the following screen. Click the OK button. Step 20 − Now, we will configure the data source. Click Next on the following screen. Check the checkbox and click Next again. Step 21 − Here you will see all the tables from your database. Let’s select the Student table. Step 22 − And you will see the all the columns in the list box. Select ID and LastName. At the bottom, you can see that it is actually creating a query. You can also you use the Where or ORDER BY clauses. Once you are done with the query, click Next. Step 23 − Click the Test Query button. It will display the query result as shown below. Step 24 − In the following dialog box, the data source is selected by default. The “Select a data field to display in the DropDownList” is the field that is actually going to be displayed. Let’s select LastName and select the ID from the “Select a data field for the value of the DropDownList” and click Ok. As you can see in the following screenshot, DataSource is added in design view. Following is the complete code in ASPX file, which is created by Expression Web. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <%@ Page Language = "C#" %> <html dir = "ltr" xmlns = "http://www.w3.org/1999/xhtml"> <head runat = "server"> <meta content = "text/html; charset = utf-8" http-equiv = "Content-Type" /> <title>Untitled 1</title> </head> <body> <form id = "form1" runat = "server"> <asp:DropDownList id = "listID" runat = "server" DataSourceID = "SqlDataSource1" DataTextField = "LastName" DataValueField = "ID"> </asp:DropDownList> <asp:SqlDataSource ID = "SqlDataSource1" runat = "server" ConnectionString = "<%$ ConnectionStrings:MyTestDatabaseConnectionString %>" SelectCommand = "SELECT [ID], [LastName] FROM [Student]"> </asp:SqlDataSource> </form> </body> </html> Step 25 − Let’s save the webpage by pressing Ctrl + S. Call this page SQLDatasource.aspx and click Save. Step 26 − Let’s preview this page in a browser. You will see a dropdown list which contains the last name of the students from the Student table. In this chapter, we will learn how to create a webpage from a Microsoft Word document using Expression Web. Instead of creating pages from scratch, you can also use Microsoft Word for web content and then bring that content to your HTML page. Let's take a look at how you can get optimal results while using the content from Microsoft Word. Create a new HTML page and call it worddemo.html. Apply the Dynamic Web Template (*.dwt) to this HTML page. Here is a sample Word document with some styles applied and a table. First, copy this entire document to the clipboard and then switch over to Expression Web. Paste the document into a main-content section of the webpage. Notice that when the content is pasted into Expression Web, we get an icon. This is referred to as the paste options button. By clicking on it, we can choose different ways in which the content is pasted into Expression Web. The default setting Match Destination Formatting means that Expression Web will use any formatting that is already applied in the current webpage. For example, the document header in this document was styled using the H1 style in Microsoft Word. When pasted into the page, Expression Web will apply the formatting to the Heading one style in Expression Web. If you select the Keep Source Formatting option, then Expression Web will still apply the H1 style to the text. However, it will create a new CSS class called Style one in this case that reformats the text to look like it did in Word. If we select Remove Formatting, the page looks very similar to the way it did before, but if you look at the tables formatting, you'll see that it's just regular text now. The styles supplied in Expression Web are still in effect, but any styles that were specific to the Word document are now gone. The keep HTML only option applies only when you're copying HTML code. The last option on the paste options menu is Keep Text only and this is the option you want to choose if you really want just the text from Word. When you select this option, it will open the following Paste Text dialog. From here, we can choose exactly how we want to format the text. The first option removes all formatting line breaks, paragraphs, etc. and replaces it with just one big block of text. You can see that we have lost the table in the document as well as all formatting. You can play with options on the Paste Text dialog box. Let’s select the option Match Destination Formatting. On previewing this webpage in a browser, it will look like the following screenshot. The GridView control is used to display the values of a data source in a table. Each column represents a field, while each row represents a record. In this chapter, we will learn a very simple process to display data from a database on a webpage in a GridView. Step 1 − Let’s create a new ASPX page in SQLDataSource project and call it gridview.aspx Step 2 − In the Toolbox, you will see the ASP.NET Controls. Drag the GridView control and drop it over the form section. You can see that the GridView context menu is open. Now select the <New data source...> from the Choose Data Source dropdown list. It will display the Data Source Configuration Wizard. Step 3 − Select the Database as we will get the data from SQL database and specify the data source ID. Click OK. Step 4 − Select the existing connection string, which we have created in SQL DataSource chapter, as we will be using the same database in this chapter. Click Next. Step 5 − For the purpose of understanding, let’s select the Student table and click the * checkbox which will retrieve all the columns from the student table. Click Next. Step 6 − In the following wizard, you can test the query, so let’s click the Test Query button. Upon clicking Next, it will display the following screen − The Design View of gridview.aspx looks as follows − Step 7 − Let us preview the webpage in a browser. It will appear as follows − This is a simple table without any formatting. Step 8 − You can format the GridView from the GridView Context menu. Click the Auto Format... link. In the Auto Format dialog box, there are many predefined schemes. Select a scheme as per your requirement and click OK. Let’s preview the webpage in a browser again. It will look like the following screenshot. In this chapter, we will learn about ASP.NET master pages. When we create a master page, we can lay it out, apply styles, and add ASP.NET controls in the same way as in other pages in Microsoft Expression Web. The layout and content we create in a master page are applied to the pages attached to the master page. It is a similar concept to Dynamic Web Template. Dynamic Web Templates enable you to apply a common look and feel to all the pages in your website. As Dynamic Web Templates are applied in the pages to which they are attached at design time, applying changes to all the pages in a site can cause a delay while the HTML is updated in all the pages. If the server is running ASP.NET, ASP.NET Master Pages allow for similar functionality by defining the editable areas in the template. However, the application of the template to the custom content in the pages is done dynamically at runtime. Let’s take a look at a simple example in which we will create a master page using CSS template and use this master page to create other pages. Step 1 − Open the index.html page in which we have defined different sections using CSS style-sheet. Step 2 − From the File menu, go to New → Page and you will see the New page dialog. Step 3 − From the left pane, select ASP.NET and from the middle list, select Master Page and click the OK button. Step 4 − The above screen will produce a pop-up named Untitled1.master. Save this page and name it default.master. Step 5 − We want to build our design into the master page that will be shared throughout our site. So let’s copy the code of the content that you would like to have on each page from the index.html code and paste the code to the default.master page. Step 6 − Now we have a layout that we would like to use on every page of the site. However, if we were to start building the content pages now, we wouldn't be able to actually enter any content into this layout. Hence, we need to create ASPX content pages from the master page. To do this, we have to add the content region as well so that we can add content to the specified pages. In the design view, right-click where you want the content on your pages. Let’s say we want to add content in the main-content section and then click the Manage Microsoft ASP.NET Content Regions... Step 7 − In the Manage Content Regions wizard, enter the Region Name and click Close. Step 8 − As can be seen in the following screenshot, the Content PlaceHolder is added in the main-content section. Now we have to add ASPX web page. Step 9 − Go to the File menu and select New → Create from Master Page... Step 10 − Browse to the default.master page and click OK. Step 11 − Now, a new ASPX page is created and all the layout styles are applied from the master page. Add some text in the main section. Step 12 − Save this page and call it mypage.aspx and then preview it in a browser. In this chapter, we will learn how to add data table in your webpage. Let’s create a new HTML page, but here we want to apply the Dynamic Web Template as well to our HTML page. Step 1 − Let’s go to the File menu and select New → Create from Dynamic Web Template... It will open the following dialog box as shown in the following screenshot. Step 2 − Select the master.dwt file and then click the Open button. Step 3 − Save the web page and call it datatable.html. Step 4 − In Design View, go to the main-content section and remove the text. Step 5 − Next, go to the Table → Insert Table... menu option which will open the Insert Table dialog box. Select the number of rows and columns. You can also set different layout options like alignment, padding, border’s size and color, and Background color, etc. Once you are done, click OK. Step 6 − The Design View of datatable.html will now appear as follows − Now, if you look at the Code View of the page, you will see the following code is added by Expression Web. <table class = "auto-style2" style = "width: 100%"> <tr> <td> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td> </td> </tr> </table> Step 7 − On the Manage Styles task panel, right-click “.auto-style2”. Click the Choose rename class "auto-style2". Step 8 − In the Rename Class dialog, enter mytable in the New name field. Make sure Rename class references in this page is ticked and then click OK. Now, take a look at your web page in Design View. It will appear as follows − Step 9 − To format this table and apply some style to it, go to the Manage Styles task panel and click New Style... Step 10 − In the New Style dialog box, set the border settings and then click Ok. There is another option to format your data table. In the Design View, right-click on the table and select Modify → Table AutoFormat... In this dialog box, you will see the different formats and other settings. Let’s select the Professional format and click OK. Step 11 − Now, the Design View of your web page looks as follows − Let’s add some data in the design view. Step 12 − Save your webpage and preview it in a browser. It will look like the following screenshot. In this chapter, we will learn how to publish a website. Microsoft Expression Web is a complete website development tool. You can use Expression Web to create webpages and sites that let you transfer files between your computer and your hosting account. Step 1 − Let’s take a look at the site which we want to publish. In the latest Expression Web version, new publishing features are added such as − The ability to exclude complete folders from publishing rather than just files. The ability to easily Publish Current Page. Step 2 − If you want any specific file or folder not to be published on the site, then rightclick on that folder or file and exclude it from publishing. Let’s say we want to exclude the index_2.html file. As shown in the above screenshot, click the Exclude from Publishing button. Similarly, you can exclude other files as well. Step 3 − Now that you have finished designing the site, you will need to publish it for the world to see. Expression Web supports several different publishing scenarios. To publish the site, first we need to make sure that we have saved all the pages. A warning will be received if we have not, once the publishing process starts. Now, let’s go to the Tools menu. Select the Recalculate Hyperlinks...option. Click Yes on the following screen. Step 4 − Go to the Site menu and click the Publishing menu option. Step 5 − If this is the first time the site is published, we will receive the message Add a publishing destination, as shown in the following screenshot. Step 6 − Click the message and the following Connection Settings dialog box will appear. Enter all the required information in the Connection Settings dialog and then click the Add button. It will display the following dialog. Click Yes. Step 7 − If the Publishing Setting is already set, we will receive the message Connect to current publishing destination. Click the message or use the Connect To button on the Site View tab. Step 8 − Once the publishing process starts, the files can be seen being transferred. When complete, we will get a message that the file has finished uploading. The next time we publish a site, this process will compare the server site with what is on the computer. If there are files on the remote server that we have deleted from the web on the computer, a message box may pop up asking if we want to delete them. If we are sure they are no longer needed, then click OK. In this chapter, we will learn how to copy the site to a local computer using Expression Web. Unlike Windows Explorer, there is no Recycle Bin in Expression Web. If we inadvertently delete the website or pages within the site, we are going to be in a Restore situation. Step 1 − To take a backup of the website, let’s open the site in Expression Web. Step 2 − Go to the Tools menu and click the Recalculate Hyperlinks... option. Click Yes, as shown in the following screenshot. Step 3 − Next, go to the Site menu and click on the Publishing menu option. Step 4 − If this is the first time we have published this site, we will receive a message Add a publishing destination, as shown in the following screenshot. Step 5 − Click the message and the Connection Settings dialog box will appear. In the Name field, enter the site name. Choose File System from the Connection Type dropdown menu and then browse to the location where you want to back up your website. Next, click the Add button. Step 6 − If the folder does not currently exist, we will be prompted to create it. Click 'Yes' and the web will be created. Step 7 − Once connected, click the 'View' dropdown and select All Files. Step 8 − Select all the files on the left side. Step 9 − Click the right arrow (→) button. Once the publishing process starts, the files will be seen as being transferred. When complete, a message will pop up suggesting that the files have been uploaded. In this chapter, we will learn how to install Add-ins in Expression Web. An Expression Web Add-in, is an external software package that provides additional or enhanced functionality within Expression Web. Add-ins can be downloaded from the following location https://msdn.microsoft.com/en-us/expression/jj873995. For instance, let’s download AddFeed add-in. Step 1 − Let’s open Expression Web and go to the Tools menu. Click the Add-Ins...menu option. Step 2 − If this is the first time an Add-in is being installed, then there will be an empty list in the Manage Add-ins dialog box. Let’s click the Install button. Step 3 − Select the AddFeeds.xadd file and click the Open button. Step 4 − Once installed, it will show you the following screen. It will ask if we want to enable the add-in. The screen will give all the information on the particular add-in being installed. Click Yes. Step 5 − Depending on the add-ins installed, they will be available at a number of locations. Step 6 − Next, go to Insert menu. You will see the Twitter or RSS Feed option which is now added after installing the add-in. You can follow the same steps to install more add-ins as per requirements. 16 Lectures 11.5 hours SHIVPRASAD KOIRALA 33 Lectures 3 hours Abhishek And Pukhraj 33 Lectures 5.5 hours Abhishek And Pukhraj 40 Lectures 6.5 hours Syed Raza 15 Lectures 2 hours Harshit Srivastava, Pranjal Srivastava 18 Lectures 1.5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2486, "s": 2196, "text": "Microsoft Expression Web is a full-featured professional tool for designing, developing, and publishing feature-rich websites that conform to web standards. You can use Expression Web to create web pages and sites that let you transfer files between your computer and your hosting account." }, { "code": null, "e": 2600, "s": 2486, "text": "Expression Web can design and develop web pages using HTML5, CSS 3, ASP.NET, PHP, JavaScript, XML+XSLT and XHTML." }, { "code": null, "e": 2685, "s": 2600, "text": "Expression Web 4 requires .NET Framework 4.0 and Silverlight 4.0 to install and run." }, { "code": null, "e": 2827, "s": 2685, "text": "Microsoft Expression Web − History Microsoft released the first Community Technology Preview (CTP) version of Expression Web on May 14, 2006." }, { "code": null, "e": 2884, "s": 2827, "text": "Microsoft Expression Web 4 was released on June 7, 2010." }, { "code": null, "e": 3073, "s": 2884, "text": "It added the option of HTML add-ins and access to a web-based functionality for testing pages on browsers that cannot be installed on the user's system, such as Mac OS X or Linux browsers." }, { "code": null, "e": 3262, "s": 3073, "text": "It added the option of HTML add-ins and access to a web-based functionality for testing pages on browsers that cannot be installed on the user's system, such as Mac OS X or Linux browsers." }, { "code": null, "e": 3431, "s": 3262, "text": "It also provides an SEO Checker using which you can analyze already created websites against the best practices for getting the highest possible search engine rankings." }, { "code": null, "e": 3600, "s": 3431, "text": "It also provides an SEO Checker using which you can analyze already created websites against the best practices for getting the highest possible search engine rankings." }, { "code": null, "e": 3742, "s": 3600, "text": "Expression Web Service Packs Expression Web 4 Service Pack 1 was released in March 2011 and added support for IntelliSense for HTML5 and CSS." }, { "code": null, "e": 3867, "s": 3742, "text": "Expression Web 4 Service Pack 2 was released in July 2011. It fixed a number of issues and introduced new features such as −" }, { "code": null, "e": 3895, "s": 3867, "text": "jQuery IntelliSense support" }, { "code": null, "e": 3925, "s": 3895, "text": "a panel for managing snippets" }, { "code": null, "e": 3952, "s": 3925, "text": "Interactive Snapshot Panel" }, { "code": null, "e": 4002, "s": 3952, "text": "comment/uncomment functionality in Code View, and" }, { "code": null, "e": 4039, "s": 4002, "text": "workspace and toolbar customization." }, { "code": null, "e": 4267, "s": 4039, "text": "In December 2012, Microsoft announced that Expression Studio will no longer be a standalone product. Expression Blend is being integrated into Visual Studio, while Expression Web and Expression Design will now be free products." }, { "code": null, "e": 4374, "s": 4267, "text": "To create a website using Microsoft Expression Web, your computer should meet the following requirements −" }, { "code": null, "e": 4463, "s": 4374, "text": "You should have at least Windows XP with Service Pack 3 or the latest operating systems." }, { "code": null, "e": 4516, "s": 4463, "text": "You should have a PC with 1 GHz or faster processor." }, { "code": null, "e": 4557, "s": 4516, "text": "Your PC should have 1 GB of RAM or more." }, { "code": null, "e": 4620, "s": 4557, "text": "Your PC should have 2 GB or more of available hard disk space." }, { "code": null, "e": 4676, "s": 4620, "text": "You should have .NET Framework 4.0 and Silverlight 4.0." }, { "code": null, "e": 4732, "s": 4676, "text": "Your PC should support Microsoft DirectX® 9.0 graphics." }, { "code": null, "e": 4770, "s": 4732, "text": "You should have DVD compatible drive." }, { "code": null, "e": 4845, "s": 4770, "text": "You should have 1024 × 768 or higher resolution monitor with 24-bit color." }, { "code": null, "e": 4955, "s": 4845, "text": "Some product features require Firefox 3.0 or later, Internet Explorer 8. So you should have the same version." }, { "code": null, "e": 5067, "s": 4955, "text": "Actual requirements and product functionality may vary based on your system configuration and operating system." }, { "code": null, "e": 5221, "s": 5067, "text": "Microsoft provides a free version of Microsoft Expression Web which can be downloaded from https://www.microsoft.com/en-pk/download/details.aspx?id=36179" }, { "code": null, "e": 5321, "s": 5221, "text": "Step 1 − Before you can install Expression Web, you will need to have .NET Framework 4.0 installed." }, { "code": null, "e": 5419, "s": 5321, "text": "Step 2 − Once downloading is complete, run the installer. The following dialog will be displayed." }, { "code": null, "e": 5453, "s": 5419, "text": "Step 3 − Click the Accept button." }, { "code": null, "e": 5511, "s": 5453, "text": "Step 4 − Select the Yes radio button and then click Next." }, { "code": null, "e": 5626, "s": 5511, "text": "Step 5 − You can choose other location as well for installation. Select the location and click the Install button." }, { "code": null, "e": 5659, "s": 5626, "text": "The installation process starts." }, { "code": null, "e": 5729, "s": 5659, "text": "Once the installation is complete, you will see the following dialog." }, { "code": null, "e": 5764, "s": 5729, "text": "Step 6 − Click Finish to continue." }, { "code": null, "e": 5950, "s": 5764, "text": "In the previous chapter, we have installed Microsoft Expression Web and now we are ready to start working on it. In this chapter, we will learn how to create a new website from scratch." }, { "code": null, "e": 6012, "s": 5950, "text": "To create a new website, let’s open Microsoft Expression Web." }, { "code": null, "e": 6060, "s": 6012, "text": "Next, you need to follow the steps given below." }, { "code": null, "e": 6108, "s": 6060, "text": "Step 1 − Select Site → New Site... menu option." }, { "code": null, "e": 6215, "s": 6108, "text": "Step 2 − It will open the following dialog from which you can create or import different types of website." }, { "code": null, "e": 6277, "s": 6215, "text": "Step 3 − For simplicity let’s select General → One Page Site." }, { "code": null, "e": 6378, "s": 6277, "text": "Specify the location or you can browse to the location where you want the new website to be created." }, { "code": null, "e": 6479, "s": 6378, "text": "Specify the location or you can browse to the location where you want the new website to be created." }, { "code": null, "e": 6540, "s": 6479, "text": "Type in the name of your web in the name field and click OK." }, { "code": null, "e": 6601, "s": 6540, "text": "Type in the name of your web in the name field and click OK." }, { "code": null, "e": 6767, "s": 6601, "text": "Step 4 − The new web will be created with one page named default.htm. Let’s rename it to index.html with a right-click on the file and clicking on the Rename option." }, { "code": null, "e": 6824, "s": 6767, "text": "Step 5 − The default doctype used in Expression Web is −" }, { "code": null, "e": 6998, "s": 6824, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> \n<html xmlns = \"http://www.w3.org/1999/xhtml\"> " }, { "code": null, "e": 7049, "s": 6998, "text": "You can see it by just switching to the code view." }, { "code": null, "e": 7122, "s": 7049, "text": "You can change the doctype from Tools → Page Editor Options → Authoring." }, { "code": null, "e": 7221, "s": 7122, "text": "Step 6 − Now, let’s add <h1> tag inside the body tag and some text as shown in the following code." }, { "code": null, "e": 7595, "s": 7221, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> \n<html xmlns = \"http://www.w3.org/1999/xhtml\"> \n <head> \n <meta content = \"text/html; charset = utf-8\" http-equiv = \"Content-Type\" /> \n </head> \n \n <body> \n <h1> \n This my first Web page \n </h1> \n </body> \n</html> " }, { "code": null, "e": 7738, "s": 7595, "text": "Step 7 − To see our web in a browser, let’s go to the File menu and select the Preview in Browser → Any browser, let’s say, Internet Explorer." }, { "code": null, "e": 7781, "s": 7738, "text": "It will open our web in Internet Explorer." }, { "code": null, "e": 8097, "s": 7781, "text": "As we have already created our website, now we will need to create our Home Page. In the previous chapter, we have created a one-page website, and our Home Page was created at that time automatically by Expression Web. So, if you have created a blank website, then you will need to create a Home Page for your site." }, { "code": null, "e": 8164, "s": 8097, "text": "Microsoft Expression Web can create the following types of pages −" }, { "code": null, "e": 8169, "s": 8164, "text": "HTML" }, { "code": null, "e": 8174, "s": 8169, "text": "ASPX" }, { "code": null, "e": 8178, "s": 8174, "text": "ASP" }, { "code": null, "e": 8182, "s": 8178, "text": "PHP" }, { "code": null, "e": 8186, "s": 8182, "text": "CSS" }, { "code": null, "e": 8198, "s": 8186, "text": "Master Page" }, { "code": null, "e": 8219, "s": 8198, "text": "Dynamic Web Template" }, { "code": null, "e": 8230, "s": 8219, "text": "JavaScript" }, { "code": null, "e": 8234, "s": 8230, "text": "XML" }, { "code": null, "e": 8244, "s": 8234, "text": "Text File" }, { "code": null, "e": 8324, "s": 8244, "text": "In this chapter, we will create an HTML page and its corresponding style sheet." }, { "code": null, "e": 8417, "s": 8324, "text": "To create a blank page, you can simply go to File menu and select New → Page... menu option." }, { "code": null, "e": 8543, "s": 8417, "text": "From the new dialog, you can create different types of blank pages such as HTML page, ASPX page, CSS page, etc. and click OK." }, { "code": null, "e": 8627, "s": 8543, "text": "As you can see here, the default code is already added by Microsoft Expression Web." }, { "code": null, "e": 9035, "s": 8627, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> \n<html xmlns = \"http://www.w3.org/1999/xhtml\"> \n <head> \n <meta content = \"text/html; charset = utf-8\" http-equiv = \"Content-Type\" /> \n <title>Untitled 1</title> \n </head> \n\n <body> \n <h1> \n This is a blank web page \n </h1> \n </body> \n</html> " }, { "code": null, "e": 9203, "s": 9035, "text": "As you can see, your newly created page has the file name Untitled_1.html or Untitled_1.htm. You will need to save the page by pressing Ctrl + S and specify the name." }, { "code": null, "e": 9361, "s": 9203, "text": "As our website already contains an index.html page, we don’t need another one. However, if you have created an Empty website, then name this page index.html." }, { "code": null, "e": 9495, "s": 9361, "text": "To see your web in a browser, let’s go to the File menu and select the Preview in Browser → Any browser, let’s say Internet Explorer." }, { "code": null, "e": 9567, "s": 9495, "text": "Let’s take you through the step-by-step process of creating a CSS page." }, { "code": null, "e": 9656, "s": 9567, "text": "Step 1 − To create a CSS page, go to the File menu and select New → Page... menu option." }, { "code": null, "e": 9700, "s": 9656, "text": "Step 2 − Select General → CSS and click OK." }, { "code": null, "e": 9760, "s": 9700, "text": "Step 3 − Save the page and type a name for the style-sheet." }, { "code": null, "e": 9792, "s": 9760, "text": "Step 4 − Click the Save button." }, { "code": null, "e": 9839, "s": 9792, "text": "Step 5 − Now, let’s go to the index.html page." }, { "code": null, "e": 9902, "s": 9839, "text": "Step 6 − In the Manage Styles Panel, click Attach Style Sheet." }, { "code": null, "e": 10023, "s": 9902, "text": "Step 7 − Browse to your style-sheet and select the Current page from “Attach to” and Link from “Attach as” and click OK." }, { "code": null, "e": 10113, "s": 10023, "text": "Step 8 − Now, you will see that a new line is added automatically in the index.html page." }, { "code": null, "e": 10180, "s": 10113, "text": "<link href = \"sample.css\" rel = \"stylesheet\" type = \"text/css\" /> " }, { "code": null, "e": 10452, "s": 10180, "text": "Step 9 − The body element defines the document's body. To style the <body> tag, we need to create a new style. First, select the body tag in Design View and then click on the New Style... in Apply Styles panel or Manage Styles panel, which will open the New Style dialog." }, { "code": null, "e": 10653, "s": 10452, "text": "Here, you can define the different options for your style. The first step is to select the body from the Selector dropdown list and then select the Existing style sheet from “Define in” dropdown list." }, { "code": null, "e": 10920, "s": 10653, "text": "Step 10 − From the URL, select the sample.css file. On the left side, there is a Category list like font, background, etc. and currently the Font is highlighted. Set the Font related information as per your requirements as shown in the above screenshot and click Ok." }, { "code": null, "e": 11159, "s": 10920, "text": "Step 11 − Now you can see in the design view that the background color and the font has changed to what we have selected. Now, if you open the sample.css file, you will see that all the information is automatically stored in the CSS file." }, { "code": null, "e": 11262, "s": 11159, "text": "Let’s preview our web page in a browser. You will observe that the style is applied from the CSS file." }, { "code": null, "e": 11516, "s": 11262, "text": "In this chapter, we will be covering the basic layout of your webpages. Before creating our webpage layout, we need to think about our content and then design how we want to present that content, as it is the content that will be visible on our website." }, { "code": null, "e": 11804, "s": 11516, "text": "It is up to us how we present our content so that our viewers find our site and then stay to check it out. The layout will probably include the company logo or banner at the top, the navigation menu, a content area that may include multiple columns, and footer at the bottom of the page." }, { "code": null, "e": 12024, "s": 11804, "text": "Previously, developers used tables to achieve this look. Tables created group of boxes that were used to create rows and columns. Now, web designers use <div>s to form the boxes and CSS to place those boxes on the page." }, { "code": null, "e": 12073, "s": 12024, "text": "Following are some of the features of <div> tag." }, { "code": null, "e": 12219, "s": 12073, "text": "The <div> tag defines a division or a section in an HTML document and makes it easy to manage, style, and manipulate those divisions or sections." }, { "code": null, "e": 12365, "s": 12219, "text": "The <div> tag defines a division or a section in an HTML document and makes it easy to manage, style, and manipulate those divisions or sections." }, { "code": null, "e": 12425, "s": 12365, "text": "It is used to group block elements to format them with CSS." }, { "code": null, "e": 12485, "s": 12425, "text": "It is used to group block elements to format them with CSS." }, { "code": null, "e": 12555, "s": 12485, "text": "Browsers usually place a line break before and after the div element." }, { "code": null, "e": 12625, "s": 12555, "text": "Browsers usually place a line break before and after the div element." }, { "code": null, "e": 12665, "s": 12625, "text": "The <div> tag is a block-level element." }, { "code": null, "e": 12705, "s": 12665, "text": "The <div> tag is a block-level element." }, { "code": null, "e": 12757, "s": 12705, "text": "The <div> tag can contain almost any other element." }, { "code": null, "e": 12809, "s": 12757, "text": "The <div> tag can contain almost any other element." }, { "code": null, "e": 12851, "s": 12809, "text": "The <div> tag cannot be inside a <p> tag." }, { "code": null, "e": 12893, "s": 12851, "text": "The <div> tag cannot be inside a <p> tag." }, { "code": null, "e": 13020, "s": 12893, "text": "Let’s take a look at a simple example in which we will be using <div> </div> tags to create the various boxes and style rules." }, { "code": null, "e": 13119, "s": 13020, "text": "Step 1 − Open Expression Web and then the index.html page that we created in the previous chapter." }, { "code": null, "e": 13367, "s": 13119, "text": "Step 2 − As seen in the above screenshot, the Code View is highlighted by default. You can work in Code View or Design View, but you can also see the Split View which will open both Code View and Design View. So let’s select the Split View option." }, { "code": null, "e": 13671, "s": 13367, "text": "Step 3 − The body element defines the document's body. To style the <body> tag, we need to create a new style. First select the body tag in Design View and then click the New Style... in Apply Styles panel, which will open the New Style dialog. Here, you can define the different options for your style." }, { "code": null, "e": 13901, "s": 13671, "text": "Step 4 − The first step is to select the body from the Selector dropdown list and then select the Existing style sheet from “Define in” the dropdown list. From the URL, select the CSS file we have created in the previous chapter." }, { "code": null, "e": 14104, "s": 13901, "text": "On the left side, there is a Category list such as Font, Background, etc. and the current Font is highlighted. Set the Font-related information as per your requirements as shown in the above screenshot." }, { "code": null, "e": 14302, "s": 14104, "text": "Step 5 − Select the Background color you want. You can also select the image for your background by using the browser button. Once you are done with the Background, define your Borders if you want." }, { "code": null, "e": 14472, "s": 14302, "text": "Step 6 − Let’s select the double line option for the border and choose the width and color also from the dropdown lists. Once you are done with the style, then click Ok." }, { "code": null, "e": 14691, "s": 14472, "text": "Step 7 − Now you can see in the design view that the background color is changed to what we have selected. If you open the sample.css file, you will see that all the information is automatically stored in the CSS file." }, { "code": null, "e": 14807, "s": 14691, "text": "Step 8 − Go to the index.html page again and drag the <div> from the 'Toolbox' panel and drop it on your open page." }, { "code": null, "e": 14989, "s": 14807, "text": "Step 9 − Above the code view, you will see <body> and <div> tags, click the <div> tag and then in Apply Styles panel click on the New Style.... which will open the New Style dialog." }, { "code": null, "e": 15226, "s": 14989, "text": "Type “#container” in the Selector field. The hash mark # is an ID selector. From the “Define in” dropdown list, select the Existing style sheet and check the “Apply new style to document selection” option. Go to the Background category." }, { "code": null, "e": 15323, "s": 15226, "text": "Step 10 − Select the background color, let’s select white color and then go to the Box category." }, { "code": null, "e": 15396, "s": 15323, "text": "Step 11 − Define padding and margin and then go to the Position category" }, { "code": null, "e": 15559, "s": 15396, "text": "Step 12 − Set the width to 90%. However, don’t specify the height as here we want that the container should expand when we enter the content. Click the OK button." }, { "code": null, "e": 15658, "s": 15559, "text": "Similarly, let’s add styles for Header, top navigation, left navigation, main content, and footer." }, { "code": null, "e": 15751, "s": 15658, "text": "Following is the code in sample.css style-sheet after adding all the above-mentioned styles." }, { "code": null, "e": 16749, "s": 15751, "text": "body { \n font-family: Calibri; \n font-size: medium; \n font-weight: normal; \n font-style: normal; \n font-variant: normal; \n text-transform: none; \n color: #0000FF; \n background-color: #CCFFFF; \n background-image: none; \n border: medium double #FF0000; \n} \n\n#container { \n background-color: #FFFFFF; \n padding: 8px; \n margin: 8px; \n width: 90%; \n} \n\n#header { \n background-color: #54B431; \n background-repeat: no-repeat; \n background-position: right center; \n height: 170px; \n} \n\n#top-nav { \n height: 50px; \n border-top: solid medium #006600; \n border-bottom: solid medium #006600; \n background-color: #FFFFFF; \n} \n\n#left-nav { \n margin: 20px 0px 10px 0px; \n width: 180px; \n float: left; \n border: thin dashed #006600; \n} \n\n#main-content { \n margin: 20px 10px 10px 200px; \n background-color: #CCFFCC; \n} \n\n#footer { \n border-top: 2px solid #006600; \n clear: both; \n padding: 10px 0px; \n text-align: center; \n } " }, { "code": null, "e": 16823, "s": 16749, "text": "Following is the code in index.html file after adding all the <div> tags." }, { "code": null, "e": 17485, "s": 16823, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> \n<html xmlns = \"http://www.w3.org/1999/xhtml\"> \n <head> \n <meta content = \"text/html; charset = utf-8\" http-equiv = \"Content-Type\" /> \n <style type = \"text/css\"></style> \n <link href = \"sample.css\" rel = \"stylesheet\" type = \"text/css\" /> \n </head> \n\n <body> \n <div id = \"container\"> \n <div id = \"header\"></div> \n <div id = \"top-nav\"></div> \n <div id = \"left-nav\"></div> \n <div id = \"main-content\"></div> \n <div id = \"footer\"></div> \n </div> \n </body> \n</html> " }, { "code": null, "e": 17569, "s": 17485, "text": "Your page layout in the design view will look as shown in the following screenshot." }, { "code": null, "e": 17834, "s": 17569, "text": "In this chapter, we will learn another way of designing the layout of a page. In the last chapter, we have used style sheet to apply the styles to header, footer, etc. but you can also specify the styles in HTML page itself without using an additional style-sheet." }, { "code": null, "e": 17998, "s": 17834, "text": "This is not the recommended way to design a layout, however just for understanding purpose, we will cover this technique here. Try to follow the steps given below." }, { "code": null, "e": 18058, "s": 17998, "text": "Step 1 − Let’s add an HTML page and call it layoutdemo.html" }, { "code": null, "e": 18107, "s": 18058, "text": "Step 2 − Now add the <div> tag from the Toolbox." }, { "code": null, "e": 18169, "s": 18107, "text": "Step 3 − In the Apply Styles panel, click on the New Style..." }, { "code": null, "e": 18363, "s": 18169, "text": "Step 4 − When you select the Current page option from “Define in” dropdown then the style will be saved in the same HTML page. Set the Font for your page and then go to the Background category." }, { "code": null, "e": 18484, "s": 18363, "text": "Step 5 − Set the color for your Background. You can also set the Border, Box, and Position categories and then click OK." }, { "code": null, "e": 18543, "s": 18484, "text": "You can see that the style is added in the same HTML file." }, { "code": null, "e": 19388, "s": 18543, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> \n<html xmlns = \"http://www.w3.org/1999/xhtml\"> \n <head> \n <meta content = \"text/html; charset = utf-8\" http-equiv = \"Content-Type\" /> \n <title>Untitled 1</title> \n <style type = \"text/css\">\n #container { \n font-family: Arial, Helvetica, sans-serif; \n font-size: medium; \n font-weight: normal; \n font-style: normal; \n font-variant: normal; \n text-transform: capitalize; \n color: #800000; \n background-color: #C0C0C0; \n padding: 8px; \n margin: 8px; \n width: 90%; \n } \n </style> \n </head> \n\n <body> \n <div id = \"container\"></div> \n </body> \n</html> " }, { "code": null, "e": 19480, "s": 19388, "text": "Similarly, you can add other styles like header, footer, main content, etc. as shown above." }, { "code": null, "e": 19574, "s": 19480, "text": "In this chapter, we will learn how to add horizontal navigation or menu items to the website." }, { "code": null, "e": 19746, "s": 19574, "text": "Step 1 − To create menu items or horizontal navigation, let’s add the following code in <div id = “top-nav”> in the index.html file, which contains the list of menu items." }, { "code": null, "e": 19862, "s": 19746, "text": "<div id = \"top-nav\"> \n <ul> \n <li></li> \n <li></li> \n <li></li> \n <li></li> \n </ul> \n</div>" }, { "code": null, "e": 19977, "s": 19862, "text": "Step 2 − It is a simple bulleted list for the top menu. To create a hyperlink, go to the design view or code view." }, { "code": null, "e": 20060, "s": 19977, "text": "Step 3 − Select the item that you want to use as the hyperlink and press Ctrl + K." }, { "code": null, "e": 20103, "s": 20060, "text": "Step 4 − Click on the ScreenTip... button." }, { "code": null, "e": 20168, "s": 20103, "text": "Step 5 − Enter the text you want as the screen tip and click OK." }, { "code": null, "e": 20268, "s": 20168, "text": "Step 6 − In the Text to display field, enter Home and select the index.html file and then click OK." }, { "code": null, "e": 20357, "s": 20268, "text": "Step 7 − Similarly, add hyperlinks for other menu items, as shown in the following code." }, { "code": null, "e": 21410, "s": 20357, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> \n<html xmlns = \"http://www.w3.org/1999/xhtml\"> \n <head> \n <meta content = \"text/html; charset=utf-8\" http-equiv = \"Content-Type\" /> \n <style type = \"text/css\"></style> \n <link href = \"sample.css\" rel=\"stylesheet\" type = \"text/css\" /> \n </head> \n\n <body> \n <div id = \"container\"> \n <div id = \"header\"></div> \n <div id = \"top-nav\"> \n <ul> \n <li><a href = \"index.html\" title = \"Site Home Page\">Home</a></li> \n <li><a href = \"index.html\" title = \"Menu Item 1.\">Menu Item 1</a></li> \n <li><a href = \"index.html\" title = \"Menu Item 2.\">Menu Item 2</a></li> \n <li><a href = \"index.html\" title = \"Menu Item 3.\">Menu Item 3</a></li> \n </ul> \n </div> \n <div id = \"left-nav\"> </div> \n <div id = \"main-content\"> </div> \n <div id = \"footer\"> </div> \n </div> \n </body> \n</html>" }, { "code": null, "e": 21487, "s": 21410, "text": "Step 8 − To set the style for top navigation, go to the Manage Styles panel." }, { "code": null, "e": 21606, "s": 21487, "text": "Step 9 − Right-click on “#top-nav” and select Modify Style. Select the 'Border' Category and change the width to thin." }, { "code": null, "e": 21718, "s": 21606, "text": "Step 10 − Select the Box category and uncheck padding ‘Same for all’ and enter 10 in the top and bottom fields." }, { "code": null, "e": 21757, "s": 21718, "text": "Step 11 − Go to the Position category." }, { "code": null, "e": 21865, "s": 21757, "text": "Step 12 − Remove the 50 from the height field and click OK. From the Apply Styles panel, click New Style..." }, { "code": null, "e": 22074, "s": 21865, "text": "Step 13 − Enter #top-nav ul in the Selector field and select the Existing style sheet from the “Define in” dropdown. In the Block category, select center from the test-align field and go to the List category." }, { "code": null, "e": 22141, "s": 22074, "text": "Step 14 − Select none from the list-style-type field and click OK." }, { "code": null, "e": 22348, "s": 22141, "text": "Step 15 − Again, from the Apply Styles panel, click New Style... Enter #top-nav ul li in the Selector field. Then select the Existing style-sheet from the “Define in” dropdown and go to the Layout category." }, { "code": null, "e": 22409, "s": 22348, "text": "Step 16 − Select inline from the display field and click OK." }, { "code": null, "e": 22611, "s": 22409, "text": "Step 17 − Go to Apply Styles panel, click New Style... Enter #top-nav ul li a in the Selector field and select the Existing style sheet from the “Define in” dropdown and select white as the font color." }, { "code": null, "e": 22652, "s": 22611, "text": "Step 18 − Go to the Background category." }, { "code": null, "e": 22727, "s": 22652, "text": "Step 19 − Select green as the background color and go to the Box category." }, { "code": null, "e": 22774, "s": 22727, "text": "Step 20 − Set the padding values and click OK." }, { "code": null, "e": 23002, "s": 22774, "text": "Step 21 − Now let’s go to the Apply Styles panel again and click New Style. Enter #topnav ul li a:hover in the Selector field and select the Existing style sheet from the “Define in” dropdown and select black as the font color." }, { "code": null, "e": 23047, "s": 23002, "text": "Step 22 − Now go to the Background category." }, { "code": null, "e": 23181, "s": 23047, "text": "Step 23 − Select the background color for your menu option when the mouse is hovering on the menu item and go to the Border category." }, { "code": null, "e": 23325, "s": 23181, "text": "Step 24 − Select the border style, width, and color, and click OK. To check how it is looks, go to the File menu and select Preview in Browser." }, { "code": null, "e": 23414, "s": 23325, "text": "When you hover the mouse on any menu item, it will change the background and font color." }, { "code": null, "e": 23529, "s": 23414, "text": "In this chapter, we will learn how to add vertical navigation or menu items to the website. Let’s go step by step." }, { "code": null, "e": 23699, "s": 23529, "text": "Step 1 − To create menu items or vertical navigation, let’s add the following code in <div id = “left-nav”> in the index.html file which contains the list of menu items." }, { "code": null, "e": 23844, "s": 23699, "text": "<div id = \"left-nav\"> \n <p>Site Navigation</p> \n <ul> \n <li></li> \n <li></li> \n <li></li> \n <li></li> \n </ul> \n</div> " }, { "code": null, "e": 23960, "s": 23844, "text": "Step 2 − It is a simple bulleted list for your top menu. To create a hyperlink, go to the design view or code view." }, { "code": null, "e": 24043, "s": 23960, "text": "Step 3 − Select the item that you want to use as the hyperlink and press Ctrl + K." }, { "code": null, "e": 24138, "s": 24043, "text": "Step 4 − Click the ScreenTip... button. Enter the text you want as the screentip and click OK." }, { "code": null, "e": 24238, "s": 24138, "text": "Step 5 − In the Text to display field, enter Home and select the index.html file and then click OK." }, { "code": null, "e": 24292, "s": 24238, "text": "At this stage, our index.html page looks as follows −" }, { "code": null, "e": 24375, "s": 24292, "text": "Step 6 − Add more hyperlinks for other menu items, as shown in the following code." }, { "code": null, "e": 26002, "s": 24375, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\">\n <head>\n <meta content = \"text/html; charset = utf-8\" http-equiv = \"Content-Type\" />\n <style type = \"text/css\"></style>\n <link href = \"sample.css\" rel = \"stylesheet\" type = \"text/css\" />\n </head>\n\n <body>\n <div id = \"container\">\n <div id = \"header\"></div>\n <div id = \"top-nav\"> \n <ul> \n <li><a href = \"index.html\" title = \"Site Home Page\">Home</a></li>\n <li><a href = \"index.html\" title = \"Menu Item 1.\">Menu Item 1</a></li>\n <li><a href = \"index.html\" title = \"Menu Item 2.\">Menu Item 2</a></li>\n <li><a href = \"index.html\" title = \"Menu Item 3.\">Menu Item 3</a></li>\n </ul> \n </div> \n \n <div id = \"left-nav\"> \n <p>Site Navigation</p> \n <ul>\n <li><a href = \"index.html\" title = \"Site Home Page\">Home</a></li>\n <li><a href = \"index.html\" title = \"Navigation Item 1.\">Navigation Item 1</a></li>\n <li><a href = \"index.html\" title = \"Navigation Item 2.\">Navigation Item 2</a></li>\n <li><a href = \"index.html\" title = \"Navigation Item 3.\">Navigation Item 3</a></li>\n </ul> \n </div> \n <div id = \"main-content\"></div> \n <div id = \"footer\"></div> \n </div> \n </body> \n</html> " }, { "code": null, "e": 26131, "s": 26002, "text": "Step 7 − To set the style for top navigation, go to the Manage Styles panel. Right-click on #left-nav and select Modify Style..." }, { "code": null, "e": 26266, "s": 26131, "text": "Step 8 − Enter the value 0.9 in font-size field and select em from the dropdown list next to the font-size and go to the Box category." }, { "code": null, "e": 26399, "s": 26266, "text": "Step 9 − Check the padding ‘Same for all’ and enter 5 in the top field and click Ok. From the Apply Styles panel, click New Style..." }, { "code": null, "e": 26596, "s": 26399, "text": "Step 10 − Enter #left-nav ul in the Selector field. Select the Existing style-sheet from the “Define in” dropdown and in the List category, select none from the list-style-type field and click OK." }, { "code": null, "e": 26739, "s": 26596, "text": "Step 11 − Again, from the Apply Styles panel, click New Style. Uncheck the padding ‘Same for all’. Enter 0.2 in the bottom field and click OK." }, { "code": null, "e": 26887, "s": 26739, "text": "Step 12 − Enter #left-nav ul li in the Selector field and select the Existing style sheet from the “Define in” dropdown and go to the Box category." }, { "code": null, "e": 26943, "s": 26887, "text": "Step 13 − Go to Apply Styles panel and click New Style." }, { "code": null, "e": 27101, "s": 26943, "text": "Step 14 − Enter #left-nav ul li a in the Selector field and select the Existing style sheet from the “Define in” dropdown and select white as the font color." }, { "code": null, "e": 27183, "s": 27101, "text": "Step 15 − Go to the Background category. Select the color as the background color" }, { "code": null, "e": 27244, "s": 27183, "text": "Step 16 − Go to the Box category and set the padding values." }, { "code": null, "e": 27335, "s": 27244, "text": "Step 17 − Go to the Layout category. Select block from the display dropdown and click OK." }, { "code": null, "e": 27558, "s": 27335, "text": "Step 18 − Now let’s go to Apply Styles panel again and click New Style. Enter #left-nav ul li a:hover in the Selector field and select the Existing style sheet from the “Define in” dropdown. Select black as the font color." }, { "code": null, "e": 27710, "s": 27558, "text": "Step 19 − Now go to the Background category. Select the background color for your menu option when the mouse is hovering on the menu item and click OK." }, { "code": null, "e": 27802, "s": 27710, "text": "Step 20 − To check how it is looks, go to the File menu and select Preview in your browser." }, { "code": null, "e": 27891, "s": 27802, "text": "When you hover the mouse on any menu item, it will change its background and font color." }, { "code": null, "e": 28141, "s": 27891, "text": "In this chapter, we will learn how to make sure that both our HTML and CSS code validates. Microsoft Expression Web provides several ways to check your webpages for code errors and the code that is incompatible with a particular HTML and CSS schema." }, { "code": null, "e": 28353, "s": 28141, "text": "The status bar and Code view alert you to code errors and incompatibility in a single page, while the Compatibility task pane lists all code errors and incompatibility in one or more pages, or an entire website." }, { "code": null, "e": 28565, "s": 28353, "text": "The status bar and Code view alert you to code errors and incompatibility in a single page, while the Compatibility task pane lists all code errors and incompatibility in one or more pages, or an entire website." }, { "code": null, "e": 28688, "s": 28565, "text": "Expression Web identifies incompatible code by using a document schema that is based on the DocType declaration in a page." }, { "code": null, "e": 28811, "s": 28688, "text": "Expression Web identifies incompatible code by using a document schema that is based on the DocType declaration in a page." }, { "code": null, "e": 28934, "s": 28811, "text": "If the page doesn't contain a DocType declaration or the DocType isn't recognized, Expression Web uses a secondary schema." }, { "code": null, "e": 29057, "s": 28934, "text": "If the page doesn't contain a DocType declaration or the DocType isn't recognized, Expression Web uses a secondary schema." }, { "code": null, "e": 29375, "s": 29057, "text": "When you create a site and work on its pages, you should develop a habit of validating the pages. Microsoft Expression Web has various tools which can be very helpful while validating your webpages. There are two very helpful options in Expression web, so let’s go to the Tools menu and select the Page Editor Option." }, { "code": null, "e": 29412, "s": 29375, "text": "The General tab offers two options −" }, { "code": null, "e": 29574, "s": 29412, "text": "Highlight Invalid HTML − This option when checked, it will display an invalid HTML in a specific color scheme and the default in red text on a yellow background." }, { "code": null, "e": 29736, "s": 29574, "text": "Highlight Invalid HTML − This option when checked, it will display an invalid HTML in a specific color scheme and the default in red text on a yellow background." }, { "code": null, "e": 29885, "s": 29736, "text": "Highlight Incompatible HTML − This option when checked, it will display a wavy underline beneath the code that isn't compatible with HTML standards." }, { "code": null, "e": 30034, "s": 29885, "text": "Highlight Incompatible HTML − This option when checked, it will display a wavy underline beneath the code that isn't compatible with HTML standards." }, { "code": null, "e": 30179, "s": 30034, "text": "When the current, open web page contains a code error, then you get to see a Code Error Detected icon (highlighted in the following screenshot)." }, { "code": null, "e": 30236, "s": 30179, "text": "Let’s assume you forgot the symbol “>” in a </div> tag −" }, { "code": null, "e": 30262, "s": 30236, "text": "<div id = \"footer\"></div>" }, { "code": null, "e": 30366, "s": 30262, "text": "In this case, the status bar at the bottom of the program window displays the Code Error Detected icon." }, { "code": null, "e": 30507, "s": 30366, "text": "When you select “Go To Error” from the dropdown menu, it will take you to the line where the error exists and you can fix the syntax easily." }, { "code": null, "e": 30653, "s": 30507, "text": "When the page contains a code that's incompatible with the specified DocType, then the status bar displays an HTML Incompatibility Detected icon." }, { "code": null, "e": 30740, "s": 30653, "text": "Let’s assume you have used “hre” for a hyperlink instead of “href”, which is an error." }, { "code": null, "e": 30807, "s": 30740, "text": "<li><a href = \"index.html\" title = \"Site Home Page\">Home</a></li> " }, { "code": null, "e": 30908, "s": 30807, "text": "The status bar displays the HTML Incompatibility Detected icon as shown in the following screenshot." }, { "code": null, "e": 31053, "s": 30908, "text": "When you select the “Go To Error” from the dropdown menu, it will take you to the line where the error exists and you can fix the syntax easily." }, { "code": null, "e": 31283, "s": 31053, "text": "A compatibility report checks the pages and CSS files for code errors and the code that's incompatible with the DocType and CSS schema you specify. You can generate a report that checks only particular files or an entire website." }, { "code": null, "e": 31395, "s": 31283, "text": "Step 1 − To generate a compatibility report, go to the tools menu and click the Compatibility Reports...option." }, { "code": null, "e": 31675, "s": 31395, "text": "Step 2 − The Compatibility Checker dialog provides different options to check only particular files in your site, either open those files or select them in either the Folder List task pane or the Website view. Select the options as per the requirement and click the Check button." }, { "code": null, "e": 31890, "s": 31675, "text": "Step 3 − The Compatibility task pane opens and the status of the generation of the report appears at the bottom of the task pane. On double-click on any row, it will take you to the location where the error exists." }, { "code": null, "e": 32118, "s": 31890, "text": "A Dynamic Web Template is a HTML-based master copy of a web page that you can create to contain settings, formatting, and page elements such as text, graphics, page layout, styles, and regions of a webpage that can be modified." }, { "code": null, "e": 32368, "s": 32118, "text": "When you attach a Dynamic Web Template to the pages in a website, that template defines the layout for those pages. You can use any number of Dynamic Web Templates in a website, and you can attach a Dynamic Web Template to as many pages as you like." }, { "code": null, "e": 32618, "s": 32368, "text": "By using Dynamic Web Templates, you can create HTML pages that share the same layout. In addition to providing a shared layout, you can make some regions in a template available for editing while preventing changes to other regions in that template." }, { "code": null, "e": 32748, "s": 32618, "text": "This means that you can allow others to add and edit content, yet still preserve the layout of the pages and the template itself." }, { "code": null, "e": 32931, "s": 32748, "text": "The most important concept of website design is to maintain a consistent look and feel for your site and with Dynamic Web Template you can achieve it. Dynamic Web Template provides −" }, { "code": null, "e": 33072, "s": 32931, "text": "Basic pages such as a Sitemap, Contact, About, and Search pages. A visitor should be able to reach your home page from any page on the site." }, { "code": null, "e": 33213, "s": 33072, "text": "Basic pages such as a Sitemap, Contact, About, and Search pages. A visitor should be able to reach your home page from any page on the site." }, { "code": null, "e": 33257, "s": 33213, "text": "Consistent navigation throughout your site." }, { "code": null, "e": 33301, "s": 33257, "text": "Consistent navigation throughout your site." }, { "code": null, "e": 33338, "s": 33301, "text": "Consistent look throughout the site." }, { "code": null, "e": 33375, "s": 33338, "text": "Consistent look throughout the site." }, { "code": null, "e": 33525, "s": 33375, "text": "To create a Dynamic Web Template (DWT), you start with an empty HTML page and save it as a *.dwt file. Let’s go step by step and learn more about it." }, { "code": null, "e": 33637, "s": 33525, "text": "Step 1 − Open the index.html file and select File → Save As... menu option, which will open the Save As dialog." }, { "code": null, "e": 33793, "s": 33637, "text": "Select the Dynamic Web Template (*.dwt) from the Save as type dropdown and change the file name from the index to the master.dwt and click the Save button." }, { "code": null, "e": 34051, "s": 33793, "text": "Step 2 − Now, you will see a new file master.dwt is created in the Folder list. Let’s create a new HTML file and call it index_2.html. Let’s open the master.dwt file and in the Design View or the Code View, right-click inside <div> tags of the main content." }, { "code": null, "e": 34158, "s": 34051, "text": "Step 3 − From the menu, select the Manage Editable Regions... which will open the Editable Regions dialog." }, { "code": null, "e": 34298, "s": 34158, "text": "Step 4 − In the Region name, type a name for the editable region and then click Add. Repeat to add additional editable regions if you want." }, { "code": null, "e": 34441, "s": 34298, "text": "Step 5 − Once you have added all editable regions, then click Close. Now go to the index_2.html file and select it in the Folder list as well." }, { "code": null, "e": 34593, "s": 34441, "text": "Step 6 − Go to the Format menu and select Dynamic Web Template → Attach Dynamic Web Template... which will open the Attach Dynamic Web Template dialog." }, { "code": null, "e": 34742, "s": 34593, "text": "Step 7 − Select the Dynamic Web Template which here is the master.dwt file and click the Open button. You will receive a warning message. Click Yes." }, { "code": null, "e": 34914, "s": 34742, "text": "Step 8 − You can see that the same template is applied to the index_2.html file. Similarly, you can add the same template to as many HTML pages as you want to the website." }, { "code": null, "e": 35121, "s": 34914, "text": "Step 9 − On this page, you can edit only the main-content section. If you move the mouse to the other section, you will see that it is not editable and the mouse curser also changes to the red cross circle." }, { "code": null, "e": 35208, "s": 35121, "text": "Step 10 − To see how it looks, go to the File menu and select Preview in your browser." }, { "code": null, "e": 35486, "s": 35208, "text": "In this chapter, we will learn how to add a search option or a search box to the website. If it is a large site, then you will need to have a search box in the site so that the user can find any data easily. There are many free ones available such as Windows Live, Google, etc." }, { "code": null, "e": 35646, "s": 35486, "text": "The following steps show you how to add a Windows Live Search box to your web page, and then set the search form to search the entire Web or only your website." }, { "code": null, "e": 35702, "s": 35646, "text": "Step 1 − Create a new HTML page and call it SearchPage." }, { "code": null, "e": 35859, "s": 35702, "text": "Step 2 − Go to the Format menu and select Dynamic Web Template → Attach Dynamic Web Template...option. Select the master.dwt file and click the Open button." }, { "code": null, "e": 35925, "s": 35859, "text": "Step 3 − Let’s add the following code inside the editable region." }, { "code": null, "e": 36707, "s": 35925, "text": "<form method = \"get\" action = \"http://search.live.com/results.aspx\"> \n <input type = \"hidden\" name = \"cp\" value = \"1252\"/> \n <input type = \"hidden\" name = \"FORM\" value = \"FREESS\"/> \n <table style = \"background-color: #ffffff;\"> \n <tr> \n <td>\n <a href = \"http://search.live.com/\"> \n <img src = \"http://search.live.com/s/affillogoLive.gif\" \n style = \"border:0px;\" alt = \"Live Search\"/> \n </a> \n </td> \n <td> \n <input type = \"text\" name = \"q\" size = \"30\" /> \n <input type = \"submit\" value = \"Search Site\"/> \n <input type = \"hidden\" name = \"q1\" \n value = \"site:http://www.microsoft.com/expression\"/> \n </td> \n </tr> \n </table> \n</form>" }, { "code": null, "e": 36782, "s": 36707, "text": "Step 4 − Save the page. Go to the File menu and select Preview in Browser." }, { "code": null, "e": 36914, "s": 36782, "text": "Step 5 − You will see the Windows Live Search in your webpage. Let’s enter something in the search and click the Search Site button" }, { "code": null, "e": 37139, "s": 36914, "text": "Step 6 − As you can see that it will search on the web. If you want to restrict the search to only your website, then you have to specify your site domain in the following name instead of https://www.microsoft.com/expression" }, { "code": null, "e": 37228, "s": 37139, "text": "<input type = \"hidden\" name = \"q1\" value = \"site:http://www.microsoft.com/expression\"/> " }, { "code": null, "e": 37338, "s": 37228, "text": "Step 7 − Similarly, you can add the Google search option by adding the following code in the editable region." }, { "code": null, "e": 38133, "s": 37338, "text": "<form method = \"get\" action = \"http://www.google.com/search\"> \n <div style = \"border: 1px solid black; padding: 4px; width: 20em; margin: 0px auto 0px auto\"> \n <table border = \"0\" cellpadding = \"0\"> \n <tr> \n <td class = \"center\"> \n <input type = \"text\" name = \"q\" size = \"25\" maxlength = \"255\" value = \"\" /> \n <input type = \"submit\" value = \"Google Search\" /> \n </td> \n </tr> \n <tr> \n <td align = \"center\" style = \"font-size: 75%\"> \n <input type = \"checkbox\" name = \"sitesearch\" \n value = \" http://www.microsoft.com/expression\" checked = \"checked\" /> \n Only search this website<br /> \n </td> \n </tr> \n </table> \n </div> \n</form> " }, { "code": null, "e": 38238, "s": 38133, "text": "Step 8 − Save your HTML page and you will see a search box, search button, checkbox, and checkbox label." }, { "code": null, "e": 38450, "s": 38238, "text": "Step 9 − To restrict users to search only your website, select the checkbox and go to the Tag Properties panel and set the Value property to the URL of your website, such as https://www.microsoft.com/expression." }, { "code": null, "e": 38565, "s": 38450, "text": "Step 10 − Save your page and preview it in the browser. Now you will see the Google Search option in your webpage." }, { "code": null, "e": 38799, "s": 38565, "text": "Images are used heavily in webpages to make them look interesting and provide a better user experience. In this chapter, we will learn how to add images to the website. As usual, let’s go step by step and learn the process in detail." }, { "code": null, "e": 38921, "s": 38799, "text": "Step 1 − To start adding images, let’s create a new one-page site and change the name of default.html file to index.html." }, { "code": null, "e": 39103, "s": 38921, "text": "Step 2 − Now we need to include images to the website so that we can use those images in the webpage. Let’s create a new folder. In the folder list, right-click on the website name." }, { "code": null, "e": 39278, "s": 39103, "text": "Step 3 − Currently, there are no images in this folder. To add images in this folder, simply select and drag images from your hard drive and drop them over the images folder." }, { "code": null, "e": 39385, "s": 39278, "text": "You will see that the images are added to the website images folder, as shown in the following screenshot." }, { "code": null, "e": 39646, "s": 39385, "text": "Step 4 − Now these images are included in your website but none of these are used in a webpage. A simple way to add an image to in the webpage is to drag the image from the images folder and drop in the code view where you want to add the image in the webpage." }, { "code": null, "e": 39794, "s": 39646, "text": "Suppose we want to add an image below the heading. When your drop the image and release the mouse button, it will display the following dialog box." }, { "code": null, "e": 39981, "s": 39794, "text": "Here you can specify the alternate text and long description. Then click OK and save the webpage. Now you can see that <img> tag is added with the alternate name and source of the image." }, { "code": null, "e": 40081, "s": 39981, "text": "Step 5 − Follow the same process and add the second image along with its alternate name and source." }, { "code": null, "e": 40130, "s": 40081, "text": "Now the index.html file will appear as follows −" }, { "code": null, "e": 40612, "s": 40130, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> \n<html xmlns = \"http://www.w3.org/1999/xhtml\"> \n <head> \n <meta content = \"text/html; charset = utf-8\" http-equiv = \"Content-Type\" /> \n </head> \n \n <body> \n <h1> Working with images </h1> \n <img alt = \"Beautiful Birds\" src = \"images/birds.jpg\" /> \n <img alt = \"Other Birds\" src = \"images/birds2.jpg\" /> \n </body> \n</html> " }, { "code": null, "e": 40795, "s": 40612, "text": "Step 6 − The Picture Properties dialog box gives you access to the most commonly used picture attributes. When you double-click an image, it will display the Picture Properties box." }, { "code": null, "e": 40878, "s": 40795, "text": "In Expression Web, Picture Properties dialog has two tabs, General and Appearance." }, { "code": null, "e": 40934, "s": 40878, "text": "Following are the options available on the General tab." }, { "code": null, "e": 40999, "s": 40934, "text": "Picture − It contains the folder/file name of the graphic image." }, { "code": null, "e": 41064, "s": 40999, "text": "Picture − It contains the folder/file name of the graphic image." }, { "code": null, "e": 41316, "s": 41064, "text": "Alternate Text − Type the text you want to be displayed for pictures when the graphic is downloading, when it can't be found, or when a site visitor moves the pointer over it. This text will also be used by a screen reader if your viewer is using one." }, { "code": null, "e": 41568, "s": 41316, "text": "Alternate Text − Type the text you want to be displayed for pictures when the graphic is downloading, when it can't be found, or when a site visitor moves the pointer over it. This text will also be used by a screen reader if your viewer is using one." }, { "code": null, "e": 41770, "s": 41568, "text": "Long Description − There are times a few words may not be enough to describe your image. Charts and graphs are examples. Click Browse to select a file that contains a longer description of the picture." }, { "code": null, "e": 41972, "s": 41770, "text": "Long Description − There are times a few words may not be enough to describe your image. Charts and graphs are examples. Click Browse to select a file that contains a longer description of the picture." }, { "code": null, "e": 42075, "s": 41972, "text": "Location − If you want to link your image to a webpage or larger image, you insert the hyperlink here." }, { "code": null, "e": 42178, "s": 42075, "text": "Location − If you want to link your image to a webpage or larger image, you insert the hyperlink here." }, { "code": null, "e": 42363, "s": 42178, "text": "Target Frame − If the current page is a frames page, this option indicates which frame the link should be displayed in OR you can choose to have the image or page open in a new window." }, { "code": null, "e": 42548, "s": 42363, "text": "Target Frame − If the current page is a frames page, this option indicates which frame the link should be displayed in OR you can choose to have the image or page open in a new window." }, { "code": null, "e": 42603, "s": 42548, "text": "Following options are available on the Appearance tab." }, { "code": null, "e": 42694, "s": 42603, "text": "Wrapping Style − Specify how the picture floats in the page, such as None, Left, or Right." }, { "code": null, "e": 42785, "s": 42694, "text": "Wrapping Style − Specify how the picture floats in the page, such as None, Left, or Right." }, { "code": null, "e": 42889, "s": 42785, "text": "Layout − In this section, you can set the alignment, border thickness, horizontal and vertical margins." }, { "code": null, "e": 42993, "s": 42889, "text": "Layout − In this section, you can set the alignment, border thickness, horizontal and vertical margins." }, { "code": null, "e": 43233, "s": 42993, "text": "Size − Expression Web automatically sets the width and height properties for the image based on the actual dimensions of the picture. Rather than resizing your image by changing these dimensions, resize the image using your graphic editor." }, { "code": null, "e": 43473, "s": 43233, "text": "Size − Expression Web automatically sets the width and height properties for the image based on the actual dimensions of the picture. Rather than resizing your image by changing these dimensions, resize the image using your graphic editor." }, { "code": null, "e": 43567, "s": 43473, "text": "Step 7 − Now, let’s preview the webpage in the browser; it will display the following output." }, { "code": null, "e": 43803, "s": 43567, "text": "In this chapter, we will learn how to use hyperlinks in your website. One of the things that makes the web so expansive is the capability of webpages to link to other webpages. Hyperlinks or links are found within nearly all web pages." }, { "code": null, "e": 44006, "s": 43803, "text": "Hyperlinks also allow users to click and go to a different page, a place within a page, an image or another location on the Internet entirely. Following are some of the important features of hyperlink −" }, { "code": null, "e": 44094, "s": 44006, "text": "Expression Web's hyperlink tools and options make it very easy to work with hyperlinks." }, { "code": null, "e": 44182, "s": 44094, "text": "Expression Web's hyperlink tools and options make it very easy to work with hyperlinks." }, { "code": null, "e": 44292, "s": 44182, "text": "Expression Web hyperlink views and reports also make it very easy to find and fix broken and incorrect links." }, { "code": null, "e": 44402, "s": 44292, "text": "Expression Web hyperlink views and reports also make it very easy to find and fix broken and incorrect links." }, { "code": null, "e": 44549, "s": 44402, "text": "A hyperlink can be a word, a group of words, or an image that when clicked will take you to a new document or a place within the current document." }, { "code": null, "e": 44696, "s": 44549, "text": "A hyperlink can be a word, a group of words, or an image that when clicked will take you to a new document or a place within the current document." }, { "code": null, "e": 44931, "s": 44696, "text": "In HTML, <a> tag which is known as anchor tag is used to create a link to another document. An anchor can point to another html page, an image, a text document, or a pdf file among others. Here is the basic code of an anchor <a> tag." }, { "code": null, "e": 44979, "s": 44931, "text": "<a href = \"url\">Text to be displayed as link<a>" }, { "code": null, "e": 45146, "s": 44979, "text": "In <a> tag, “href” attribute is used to address the link to the document, and the words between the open and close of the anchor tag will be displayed as a hyperlink." }, { "code": null, "e": 45313, "s": 45146, "text": "In <a> tag, “href” attribute is used to address the link to the document, and the words between the open and close of the anchor tag will be displayed as a hyperlink." }, { "code": null, "e": 45404, "s": 45313, "text": "When you move the cursor over a link in a webpage, the arrow will turn into a little hand." }, { "code": null, "e": 45495, "s": 45404, "text": "When you move the cursor over a link in a webpage, the arrow will turn into a little hand." }, { "code": null, "e": 45569, "s": 45495, "text": "A URL is an address that specifies a protocol, web server, and file path." }, { "code": null, "e": 45643, "s": 45569, "text": "A URL is an address that specifies a protocol, web server, and file path." }, { "code": null, "e": 45895, "s": 45643, "text": "There are two types of URLs, absolute and relative. An absolute URL contains a full address while a relative URL is missing one or more parts of the address. However, the web browser obtains the missing information from the page that contains the URL." }, { "code": null, "e": 46147, "s": 45895, "text": "There are two types of URLs, absolute and relative. An absolute URL contains a full address while a relative URL is missing one or more parts of the address. However, the web browser obtains the missing information from the page that contains the URL." }, { "code": null, "e": 46244, "s": 46147, "text": "Let’s take a look at a simple example in which we will be using both absolute and relative URLs." }, { "code": null, "e": 46342, "s": 46244, "text": "Step 1 − First, open the index.html page and add the following lines in the main content section." }, { "code": null, "e": 46518, "s": 46342, "text": "<div id = \"main-content\"> \n <p> Absolute URL Example: </p> \n <p> Google </p> \n <p> Youtube </p> \n <p> Relative URL Example: </p> \n <p> Home Page 2 </p> \n</div> " }, { "code": null, "e": 46579, "s": 46518, "text": "Following is the complete implementation of index.html page." }, { "code": null, "e": 48522, "s": 46579, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> \n<html xmlns = \"http://www.w3.org/1999/xhtml\"> \n <head> \n <meta content = \"text/html; charset = utf-8\" http-equiv = \"Content-Type\" /> \n <style type = \"text/css\"> \n #left-nav ul li a:hover { \n color: #000000; background-color: #116611; \n } \n \n #left-nav ul li a:hover { \n color: #000000; background-color: #66FF99; \n } \n </style> \n <link href = \"sample.css\" rel = \"stylesheet\" type = \"text/css\" /> \n </head> \n <body> \n <div id = \"container\"> \n <div id = \"header\"> </div> \n <div id = \"top-nav\"> \n <ul> \n <li><a href = \"index.html\" title = \"Site Home Page\">Home</a></li> \n <li><a href = \"index.html\" title = \"Menu Item 1.\">Menu Item 1</a></li> \n <li><a href = \"index.html\" title = \"Menu Item 2.\">Menu Item 2</a></li> \n <li><a href = \"index.html\" title = \"Menu Item 3.\">Menu Item 3</a></li> \n </ul> \n </div> \n \n <div id = \"left-nav\"> \n <p>Site Navigation</p> \n <ul> \n <li><a href = \"index.html\" title = \"Site Home Page\">Home</a></li> \n <li><a href = \"index.html\" title = \"Navigation Item 1.\">Navigation Item 1</a></li> \n <li><a href = \"index.html\" title = \"Navigation Item 2.\">Navigation Item 2</a></li> \n <li><a href = \"index.html\" title = \"Navigation Item 3.\">Navigation Item 3</a></li> \n </ul> \n </div> \n \n <div id = \"main-content\"> \n <p> Absolute URL Example: </p> \n <p> Google </p> \n <p> Youtube </p> \n <p> Relative URL Example: </p> \n <p> Home Page 2 </p> \n </div> \n <div id = \"footer\"> </div> \n </div> \n </body> \n</html> " }, { "code": null, "e": 48609, "s": 48522, "text": "Step 2 − Let’s save the webpage and you will see the text in the main content section." }, { "code": null, "e": 48748, "s": 48609, "text": "Step 3 − In the Design View, right-click on Google and then select Hyperlink... from the menu which will open the Insert Hyperlink dialog." }, { "code": null, "e": 48907, "s": 48748, "text": "Step 4 − In the Address field, specify the URL for Google home page and click OK. Similarly, right-click on YouTube in the design view and select Hyperlink..." }, { "code": null, "e": 49123, "s": 48907, "text": "Step 5 − In the Address field, specify the URL for YouTube home page and click Ok. Now for relative right-click on the “Home Page 2” and select Hyperlink... from the menu which will open the Insert Hyperlink dialog." }, { "code": null, "e": 49331, "s": 49123, "text": "Step 6 − For relative path, select the index_2.html in the address field and Expression Web will get the remaining path from the index.html file, because both these files are in the same directory. Click OK." }, { "code": null, "e": 49419, "s": 49331, "text": "As can be seen, these words are now underlined which means that hyperlinks are created." }, { "code": null, "e": 49650, "s": 49419, "text": "Step 7 − The default font color is blue and the default font color for Hyperlinks is also blue. To change the default color of the hyperlink, select any of the hyperlink and go the Format menu and select Background... menu option." }, { "code": null, "e": 49689, "s": 49650, "text": "You will now see the following dialog." }, { "code": null, "e": 49741, "s": 49689, "text": "Step 8 − Let’s change the Hyperlink color to Green." }, { "code": null, "e": 49830, "s": 49741, "text": "In the following screenshot, you will see that the Hyperlink color has changed to Green." }, { "code": null, "e": 49886, "s": 49830, "text": "Step 9 − Let us now preview this web page in a browser." }, { "code": null, "e": 49959, "s": 49886, "text": "If you click the Google link, it will direct you to the Google homepage." }, { "code": null, "e": 50117, "s": 49959, "text": "Step 10 − Similarly, if you go back to the Home page and click the YouTube link, it will direct you to the YouTube home page. Let’s go back to the home page." }, { "code": null, "e": 50198, "s": 50117, "text": "Click the Home Page 2 link and you will see that it opens the index_2.hmtl file." }, { "code": null, "e": 50438, "s": 50198, "text": "In this chapter, we will learn how to add videos to the website and which formats are supported in Expression Web. With the help of videos, you can easily attract the attention of potential customers to your company's products or services." }, { "code": null, "e": 50651, "s": 50438, "text": "Microsoft Expression Web is a web design tool that simplifies the process of adding promotional, marketing, or training videos to webpages. You can easily insert your videos in Microsoft Expression's Design view." }, { "code": null, "e": 50775, "s": 50651, "text": "By default, Expression Web supports video encoding formats like Silverlight, Adobe Flash, WMV, ASF, MWA, AVI, WVX and MPEG." }, { "code": null, "e": 50872, "s": 50775, "text": "Let us now take an example to understand the process of adding a video in a step-by-step manner." }, { "code": null, "e": 50929, "s": 50872, "text": "Step 1 − Add a new HTML file and call it videodemo.html." }, { "code": null, "e": 51076, "s": 50929, "text": "Step 2 − Click the mouse at the location within the webpage where the video is to be inserted. Let’s say we want to add a video below the heading." }, { "code": null, "e": 51260, "s": 51076, "text": "Step 3 − Go to the Insert menu → Media which will open the submenu containing the list of video player formats that Expressions supports by default. Let’s select Windows Media Player." }, { "code": null, "e": 51479, "s": 51260, "text": "Step 4 − Locate the video you want to use. Select the video file's name and click the Insert button to insert it into the webpage. Save the file by pressing Ctrl + S and you will see the Save Embedded Files dialog box." }, { "code": null, "e": 51566, "s": 51479, "text": "Step 5 − Click OK and you will see that the media file is added to the website folder." }, { "code": null, "e": 51616, "s": 51566, "text": "Following is the code in the videodemo.html page." }, { "code": null, "e": 52184, "s": 51616, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> \n<html xmlns = \"http://www.w3.org/1999/xhtml\"> \n <head> \n <meta content = \"text/html; charset = utf-8\" http-equiv = \"Content-Type\" /> \n <title>Untitled 1</title> \n </head> \n \n <body> \n <h1> Video Demo</h1> \n <p> \n <object id = \"media1\" height = \"200\" type = \"video/x-ms-wmv\" width = \"200\"> \n <param name = \"filename\" value = \"logo.wmv\" /> \n </object> \n </p> \n </body> \n</html> " }, { "code": null, "e": 52278, "s": 52184, "text": "Step 6 − Let us now preview the webpage in a browser. You will see that the video is playing." }, { "code": null, "e": 52558, "s": 52278, "text": "Expression Web has many tools for working with static HTML pages, but it also has tools for creating more dynamic pages. Dynamic pages often retrieve data or content from a source of data. In this chapter, we will learn how to create a SQL DataSource to be used in dynamic pages." }, { "code": null, "e": 52708, "s": 52558, "text": "Let’s take a look at a simple example in which we create a dropdown list and fill the list by retrieving data from the database using SQL DataSource." }, { "code": null, "e": 52756, "s": 52708, "text": "Step 1 − Start by creating a new empty website." }, { "code": null, "e": 52795, "s": 52756, "text": "Let’s call it SQLDataSource. Click OK." }, { "code": null, "e": 52950, "s": 52795, "text": "Step 2 − You will see that expression web has created a folder for us. However, since we chose to create an empty project, so we don't have any files yet." }, { "code": null, "e": 53092, "s": 52950, "text": "Expression Web doesn't have to be used just to create static HTML sites; we can create dynamic sites using pages and controls with much ease." }, { "code": null, "e": 53322, "s": 53092, "text": "Step 3 − Expression web also allows us to create a lot of dynamic content without necessarily having to be a developer. So let’s add an ASPX file from the File → New Page menu option. Select ASPX in the middle model and click OK." }, { "code": null, "e": 53449, "s": 53322, "text": "Step 4 − Here we will be creating a control in our form that needs to access data from a database to create a dynamic website." }, { "code": null, "e": 53550, "s": 53449, "text": "In this particular case, we will create a SQL DataSource which will retrieve data from the database." }, { "code": null, "e": 53765, "s": 53550, "text": "Step 5 − Go to the Toolbox and drag the DropDownList and drop it inside the <form> tag in Code View or you can also drop it in the form section in Design View. You will see that the code is added by Expression Web." }, { "code": null, "e": 53900, "s": 53765, "text": "Here, we want to connect some data from our database and store that in our dropdown list. So, the first thing we need is the database." }, { "code": null, "e": 53994, "s": 53900, "text": "Step 6 − Create a new Folder in your Project folder by going to the New → Folder menu option." }, { "code": null, "e": 54030, "s": 53994, "text": "Step 7 − Call this folder App_Data." }, { "code": null, "e": 54133, "s": 54030, "text": "Step 8 − We need to import a database in our project by using the File → Import → File... menu option." }, { "code": null, "e": 54264, "s": 54133, "text": "Step 9 − It will open the Import dialog, as shown below. Click on the Add File... button which will open the open file dialog box." }, { "code": null, "e": 54367, "s": 54264, "text": "Step 10 − Browse to the database (*.mdf file) which you want to include in the website and click Open." }, { "code": null, "e": 54454, "s": 54367, "text": "Step 11 − Open the MyTestDatabase.mdf. It will display the following dialog. Click OK." }, { "code": null, "e": 54712, "s": 54454, "text": "Step 12 − Now you can see that the database file is added in the App_Data folder. When you have a control like a dropdown list and Expression Web allows you to bind the data to it, then you will see a little arrow at the top right corner in the design view." }, { "code": null, "e": 54970, "s": 54712, "text": "Step 13 − This is the current context menu that can allow us to do a very specific task for that particular control and one of those is to choose a data source. So let’s click on Choose Data Source... and that will open the data source configuration wizard." }, { "code": null, "e": 55075, "s": 54970, "text": "Step 14 − Currently, we don’t have a data source. Let’s select the New data source option from the menu." }, { "code": null, "e": 55153, "s": 55075, "text": "Here, we will import an SQL database. Let’s select the database and click OK." }, { "code": null, "e": 55249, "s": 55153, "text": "Step 15 − Now, we need to specify the connection string. Let’s click the New Connection button." }, { "code": null, "e": 55319, "s": 55249, "text": "Step 16 − Select the Microsoft SQL Server Database File and click OK." }, { "code": null, "e": 55382, "s": 55319, "text": "Step 17 − Click the Browse button to locate the database file." }, { "code": null, "e": 55478, "s": 55382, "text": "Step 18 − Select the database file and click the Open button or double-click the database file." }, { "code": null, "e": 55546, "s": 55478, "text": "Step 19 − To test the connection, click the Test Connection button." }, { "code": null, "e": 55605, "s": 55546, "text": "It will display the following screen. Click the OK button." }, { "code": null, "e": 55691, "s": 55605, "text": "Step 20 − Now, we will configure the data source. Click Next on the following screen." }, { "code": null, "e": 55732, "s": 55691, "text": "Check the checkbox and click Next again." }, { "code": null, "e": 55827, "s": 55732, "text": "Step 21 − Here you will see all the tables from your database. Let’s select the Student table." }, { "code": null, "e": 56078, "s": 55827, "text": "Step 22 − And you will see the all the columns in the list box. Select ID and LastName. At the bottom, you can see that it is actually creating a query. You can also you use the Where or ORDER BY clauses. Once you are done with the query, click Next." }, { "code": null, "e": 56166, "s": 56078, "text": "Step 23 − Click the Test Query button. It will display the query result as shown below." }, { "code": null, "e": 56474, "s": 56166, "text": "Step 24 − In the following dialog box, the data source is selected by default. The “Select a data field to display in the DropDownList” is the field that is actually going to be displayed. Let’s select LastName and select the ID from the “Select a data field for the value of the DropDownList” and click Ok." }, { "code": null, "e": 56554, "s": 56474, "text": "As you can see in the following screenshot, DataSource is added in design view." }, { "code": null, "e": 56635, "s": 56554, "text": "Following is the complete code in ASPX file, which is created by Expression Web." }, { "code": null, "e": 57554, "s": 56635, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> \n<%@ Page Language = \"C#\" %> \n<html dir = \"ltr\" xmlns = \"http://www.w3.org/1999/xhtml\"> \n <head runat = \"server\"> \n <meta content = \"text/html; charset = utf-8\" http-equiv = \"Content-Type\" /> \n <title>Untitled 1</title> \n </head> \n\n <body> \n <form id = \"form1\" runat = \"server\"> \n <asp:DropDownList id = \"listID\" runat = \"server\" DataSourceID = \"SqlDataSource1\" \n DataTextField = \"LastName\" DataValueField = \"ID\"> \n </asp:DropDownList> \n\n <asp:SqlDataSource ID = \"SqlDataSource1\" runat = \"server\" \n ConnectionString = \"<%$ ConnectionStrings:MyTestDatabaseConnectionString %>\" \n SelectCommand = \"SELECT [ID], [LastName] FROM [Student]\"> \n </asp:SqlDataSource> \n </form> \n </body> \n</html>" }, { "code": null, "e": 57609, "s": 57554, "text": "Step 25 − Let’s save the webpage by pressing Ctrl + S." }, { "code": null, "e": 57659, "s": 57609, "text": "Call this page SQLDatasource.aspx and click Save." }, { "code": null, "e": 57805, "s": 57659, "text": "Step 26 − Let’s preview this page in a browser. You will see a dropdown list which contains the last name of the students from the Student table." }, { "code": null, "e": 58048, "s": 57805, "text": "In this chapter, we will learn how to create a webpage from a Microsoft Word document using Expression Web. Instead of creating pages from scratch, you can also use Microsoft Word for web content and then bring that content to your HTML page." }, { "code": null, "e": 58146, "s": 58048, "text": "Let's take a look at how you can get optimal results while using the content from Microsoft Word." }, { "code": null, "e": 58254, "s": 58146, "text": "Create a new HTML page and call it worddemo.html. Apply the Dynamic Web Template (*.dwt) to this HTML page." }, { "code": null, "e": 58476, "s": 58254, "text": "Here is a sample Word document with some styles applied and a table. First, copy this entire document to the clipboard and then switch over to Expression Web. Paste the document into a main-content section of the webpage." }, { "code": null, "e": 58701, "s": 58476, "text": "Notice that when the content is pasted into Expression Web, we get an icon. This is referred to as the paste options button. By clicking on it, we can choose different ways in which the content is pasted into Expression Web." }, { "code": null, "e": 58848, "s": 58701, "text": "The default setting Match Destination Formatting means that Expression Web will use any formatting that is already applied in the current webpage." }, { "code": null, "e": 59059, "s": 58848, "text": "For example, the document header in this document was styled using the H1 style in Microsoft Word. When pasted into the page, Expression Web will apply the formatting to the Heading one style in Expression Web." }, { "code": null, "e": 59294, "s": 59059, "text": "If you select the Keep Source Formatting option, then Expression Web will still apply the H1 style to the text. However, it will create a new CSS class called Style one in this case that reformats the text to look like it did in Word." }, { "code": null, "e": 59466, "s": 59294, "text": "If we select Remove Formatting, the page looks very similar to the way it did before, but if you look at the tables formatting, you'll see that it's just regular text now." }, { "code": null, "e": 59594, "s": 59466, "text": "The styles supplied in Expression Web are still in effect, but any styles that were specific to the Word document are now gone." }, { "code": null, "e": 59885, "s": 59594, "text": "The keep HTML only option applies only when you're copying HTML code. The last option on the paste options menu is Keep Text only and this is the option you want to choose if you really want just the text from Word. When you select this option, it will open the following Paste Text dialog." }, { "code": null, "e": 60069, "s": 59885, "text": "From here, we can choose exactly how we want to format the text. The first option removes all formatting line breaks, paragraphs, etc. and replaces it with just one big block of text." }, { "code": null, "e": 60262, "s": 60069, "text": "You can see that we have lost the table in the document as well as all formatting. You can play with options on the Paste Text dialog box. Let’s select the option Match Destination Formatting." }, { "code": null, "e": 60347, "s": 60262, "text": "On previewing this webpage in a browser, it will look like the following screenshot." }, { "code": null, "e": 60608, "s": 60347, "text": "The GridView control is used to display the values of a data source in a table. Each column represents a field, while each row represents a record. In this chapter, we will learn a very simple process to display data from a database on a webpage in a GridView." }, { "code": null, "e": 60697, "s": 60608, "text": "Step 1 − Let’s create a new ASPX page in SQLDataSource project and call it gridview.aspx" }, { "code": null, "e": 60818, "s": 60697, "text": "Step 2 − In the Toolbox, you will see the ASP.NET Controls. Drag the GridView control and drop it over the form section." }, { "code": null, "e": 61003, "s": 60818, "text": "You can see that the GridView context menu is open. Now select the <New data source...> from the Choose Data Source dropdown list. It will display the Data Source Configuration Wizard." }, { "code": null, "e": 61116, "s": 61003, "text": "Step 3 − Select the Database as we will get the data from SQL database and specify the data source ID. Click OK." }, { "code": null, "e": 61280, "s": 61116, "text": "Step 4 − Select the existing connection string, which we have created in SQL DataSource chapter, as we will be using the same database in this chapter. Click Next." }, { "code": null, "e": 61451, "s": 61280, "text": "Step 5 − For the purpose of understanding, let’s select the Student table and click the * checkbox which will retrieve all the columns from the student table. Click Next." }, { "code": null, "e": 61547, "s": 61451, "text": "Step 6 − In the following wizard, you can test the query, so let’s click the Test Query button." }, { "code": null, "e": 61606, "s": 61547, "text": "Upon clicking Next, it will display the following screen −" }, { "code": null, "e": 61658, "s": 61606, "text": "The Design View of gridview.aspx looks as follows −" }, { "code": null, "e": 61736, "s": 61658, "text": "Step 7 − Let us preview the webpage in a browser. It will appear as follows −" }, { "code": null, "e": 61783, "s": 61736, "text": "This is a simple table without any formatting." }, { "code": null, "e": 61852, "s": 61783, "text": "Step 8 − You can format the GridView from the GridView Context menu." }, { "code": null, "e": 62003, "s": 61852, "text": "Click the Auto Format... link. In the Auto Format dialog box, there are many predefined schemes. Select a scheme as per your requirement and click OK." }, { "code": null, "e": 62093, "s": 62003, "text": "Let’s preview the webpage in a browser again. It will look like the following screenshot." }, { "code": null, "e": 62456, "s": 62093, "text": "In this chapter, we will learn about ASP.NET master pages. When we create a master page, we can lay it out, apply styles, and add ASP.NET controls in the same way as in other pages in Microsoft Expression Web. The layout and content we create in a master page are applied to the pages attached to the master page. It is a similar concept to Dynamic Web Template." }, { "code": null, "e": 62754, "s": 62456, "text": "Dynamic Web Templates enable you to apply a common look and feel to all the pages in your website. As Dynamic Web Templates are applied in the pages to which they are attached at design time, applying changes to all the pages in a site can cause a delay while the HTML is updated in all the pages." }, { "code": null, "e": 62997, "s": 62754, "text": "If the server is running ASP.NET, ASP.NET Master Pages allow for similar functionality by defining the editable areas in the template. However, the application of the template to the custom content in the pages is done dynamically at runtime." }, { "code": null, "e": 63140, "s": 62997, "text": "Let’s take a look at a simple example in which we will create a master page using CSS template and use this master page to create other pages." }, { "code": null, "e": 63241, "s": 63140, "text": "Step 1 − Open the index.html page in which we have defined different sections using CSS style-sheet." }, { "code": null, "e": 63325, "s": 63241, "text": "Step 2 − From the File menu, go to New → Page and you will see the New page dialog." }, { "code": null, "e": 63439, "s": 63325, "text": "Step 3 − From the left pane, select ASP.NET and from the middle list, select Master Page and click the OK button." }, { "code": null, "e": 63554, "s": 63439, "text": "Step 4 − The above screen will produce a pop-up named Untitled1.master. Save this page and name it default.master." }, { "code": null, "e": 63804, "s": 63554, "text": "Step 5 − We want to build our design into the master page that will be shared throughout our site. So let’s copy the code of the content that you would like to have on each page from the index.html code and paste the code to the default.master page." }, { "code": null, "e": 64187, "s": 63804, "text": "Step 6 − Now we have a layout that we would like to use on every page of the site. However, if we were to start building the content pages now, we wouldn't be able to actually enter any content into this layout. Hence, we need to create ASPX content pages from the master page. To do this, we have to add the content region as well so that we can add content to the specified pages." }, { "code": null, "e": 64385, "s": 64187, "text": "In the design view, right-click where you want the content on your pages. Let’s say we want to add content in the main-content section and then click the Manage Microsoft ASP.NET Content Regions..." }, { "code": null, "e": 64471, "s": 64385, "text": "Step 7 − In the Manage Content Regions wizard, enter the Region Name and click Close." }, { "code": null, "e": 64620, "s": 64471, "text": "Step 8 − As can be seen in the following screenshot, the Content PlaceHolder is added in the main-content section. Now we have to add ASPX web page." }, { "code": null, "e": 64693, "s": 64620, "text": "Step 9 − Go to the File menu and select New → Create from Master Page..." }, { "code": null, "e": 64751, "s": 64693, "text": "Step 10 − Browse to the default.master page and click OK." }, { "code": null, "e": 64853, "s": 64751, "text": "Step 11 − Now, a new ASPX page is created and all the layout styles are applied from the master page." }, { "code": null, "e": 64888, "s": 64853, "text": "Add some text in the main section." }, { "code": null, "e": 64971, "s": 64888, "text": "Step 12 − Save this page and call it mypage.aspx and then preview it in a browser." }, { "code": null, "e": 65148, "s": 64971, "text": "In this chapter, we will learn how to add data table in your webpage. Let’s create a new HTML page, but here we want to apply the Dynamic Web Template as well to our HTML page." }, { "code": null, "e": 65236, "s": 65148, "text": "Step 1 − Let’s go to the File menu and select New → Create from Dynamic Web Template..." }, { "code": null, "e": 65312, "s": 65236, "text": "It will open the following dialog box as shown in the following screenshot." }, { "code": null, "e": 65380, "s": 65312, "text": "Step 2 − Select the master.dwt file and then click the Open button." }, { "code": null, "e": 65435, "s": 65380, "text": "Step 3 − Save the web page and call it datatable.html." }, { "code": null, "e": 65512, "s": 65435, "text": "Step 4 − In Design View, go to the main-content section and remove the text." }, { "code": null, "e": 65618, "s": 65512, "text": "Step 5 − Next, go to the Table → Insert Table... menu option which will open the Insert Table dialog box." }, { "code": null, "e": 65805, "s": 65618, "text": "Select the number of rows and columns. You can also set different layout options like alignment, padding, border’s size and color, and Background color, etc. Once you are done, click OK." }, { "code": null, "e": 65877, "s": 65805, "text": "Step 6 − The Design View of datatable.html will now appear as follows −" }, { "code": null, "e": 65984, "s": 65877, "text": "Now, if you look at the Code View of the page, you will see the following code is added by Expression Web." }, { "code": null, "e": 66621, "s": 65984, "text": "<table class = \"auto-style2\" style = \"width: 100%\"> \n <tr> \n <td> </td> \n <td> </td> \n <td> </td> \n <td> </td> \n </tr> \n \n <tr> \n <td> </td> \n <td> </td> \n <td> </td> \n <td> </td> \n </tr> \n \n <tr> \n <td> </td> \n <td> </td> \n <td> </td> \n <td> </td> \n </tr> \n \n <tr> \n <td> </td> \n <td> </td> \n <td> </td> \n <td> </td> \n </tr> \n \n <tr> \n <td> </td> \n <td> </td> \n <td> </td> \n <td> </td> \n </tr> \n \n <tr> \n <td> </td> \n <td> </td> \n <td> </td> \n <td> </td> \n </tr> \n</table> " }, { "code": null, "e": 66736, "s": 66621, "text": "Step 7 − On the Manage Styles task panel, right-click “.auto-style2”. Click the Choose rename class \"auto-style2\"." }, { "code": null, "e": 66886, "s": 66736, "text": "Step 8 − In the Rename Class dialog, enter mytable in the New name field. Make sure Rename class references in this page is ticked and then click OK." }, { "code": null, "e": 66964, "s": 66886, "text": "Now, take a look at your web page in Design View. It will appear as follows −" }, { "code": null, "e": 67080, "s": 66964, "text": "Step 9 − To format this table and apply some style to it, go to the Manage Styles task panel and click New Style..." }, { "code": null, "e": 67298, "s": 67080, "text": "Step 10 − In the New Style dialog box, set the border settings and then click Ok. There is another option to format your data table. In the Design View, right-click on the table and select Modify → Table AutoFormat..." }, { "code": null, "e": 67424, "s": 67298, "text": "In this dialog box, you will see the different formats and other settings. Let’s select the Professional format and click OK." }, { "code": null, "e": 67491, "s": 67424, "text": "Step 11 − Now, the Design View of your web page looks as follows −" }, { "code": null, "e": 67531, "s": 67491, "text": "Let’s add some data in the design view." }, { "code": null, "e": 67632, "s": 67531, "text": "Step 12 − Save your webpage and preview it in a browser. It will look like the following screenshot." }, { "code": null, "e": 67886, "s": 67632, "text": "In this chapter, we will learn how to publish a website. Microsoft Expression Web is a complete website development tool. You can use Expression Web to create webpages and sites that let you transfer files between your computer and your hosting account." }, { "code": null, "e": 67951, "s": 67886, "text": "Step 1 − Let’s take a look at the site which we want to publish." }, { "code": null, "e": 68033, "s": 67951, "text": "In the latest Expression Web version, new publishing features are added such as −" }, { "code": null, "e": 68113, "s": 68033, "text": "The ability to exclude complete folders from publishing rather than just files." }, { "code": null, "e": 68157, "s": 68113, "text": "The ability to easily Publish Current Page." }, { "code": null, "e": 68362, "s": 68157, "text": "Step 2 − If you want any specific file or folder not to be published on the site, then rightclick on that folder or file and exclude it from publishing. Let’s say we want to exclude the index_2.html file." }, { "code": null, "e": 68486, "s": 68362, "text": "As shown in the above screenshot, click the Exclude from Publishing button. Similarly, you can exclude other files as well." }, { "code": null, "e": 68656, "s": 68486, "text": "Step 3 − Now that you have finished designing the site, you will need to publish it for the world to see. Expression Web supports several different publishing scenarios." }, { "code": null, "e": 68817, "s": 68656, "text": "To publish the site, first we need to make sure that we have saved all the pages. A warning will be received if we have not, once the publishing process starts." }, { "code": null, "e": 68850, "s": 68817, "text": "Now, let’s go to the Tools menu." }, { "code": null, "e": 68929, "s": 68850, "text": "Select the Recalculate Hyperlinks...option. Click Yes on the following screen." }, { "code": null, "e": 68996, "s": 68929, "text": "Step 4 − Go to the Site menu and click the Publishing menu option." }, { "code": null, "e": 69150, "s": 68996, "text": "Step 5 − If this is the first time the site is published, we will receive the message Add a publishing destination, as shown in the following screenshot." }, { "code": null, "e": 69339, "s": 69150, "text": "Step 6 − Click the message and the following Connection Settings dialog box will appear. Enter all the required information in the Connection Settings dialog and then click the Add button." }, { "code": null, "e": 69388, "s": 69339, "text": "It will display the following dialog. Click Yes." }, { "code": null, "e": 69579, "s": 69388, "text": "Step 7 − If the Publishing Setting is already set, we will receive the message Connect to current publishing destination. Click the message or use the Connect To button on the Site View tab." }, { "code": null, "e": 69740, "s": 69579, "text": "Step 8 − Once the publishing process starts, the files can be seen being transferred. When complete, we will get a message that the file has finished uploading." }, { "code": null, "e": 70052, "s": 69740, "text": "The next time we publish a site, this process will compare the server site with what is on the computer. If there are files on the remote server that we have deleted from the web on the computer, a message box may pop up asking if we want to delete them. If we are sure they are no longer needed, then click OK." }, { "code": null, "e": 70322, "s": 70052, "text": "In this chapter, we will learn how to copy the site to a local computer using Expression Web. Unlike Windows Explorer, there is no Recycle Bin in Expression Web. If we inadvertently delete the website or pages within the site, we are going to be in a Restore situation." }, { "code": null, "e": 70403, "s": 70322, "text": "Step 1 − To take a backup of the website, let’s open the site in Expression Web." }, { "code": null, "e": 70481, "s": 70403, "text": "Step 2 − Go to the Tools menu and click the Recalculate Hyperlinks... option." }, { "code": null, "e": 70530, "s": 70481, "text": "Click Yes, as shown in the following screenshot." }, { "code": null, "e": 70606, "s": 70530, "text": "Step 3 − Next, go to the Site menu and click on the Publishing menu option." }, { "code": null, "e": 70764, "s": 70606, "text": "Step 4 − If this is the first time we have published this site, we will receive a message Add a publishing destination, as shown in the following screenshot." }, { "code": null, "e": 70843, "s": 70764, "text": "Step 5 − Click the message and the Connection Settings dialog box will appear." }, { "code": null, "e": 71041, "s": 70843, "text": "In the Name field, enter the site name. Choose File System from the Connection Type dropdown menu and then browse to the location where you want to back up your website. Next, click the Add button." }, { "code": null, "e": 71165, "s": 71041, "text": "Step 6 − If the folder does not currently exist, we will be prompted to create it. Click 'Yes' and the web will be created." }, { "code": null, "e": 71238, "s": 71165, "text": "Step 7 − Once connected, click the 'View' dropdown and select All Files." }, { "code": null, "e": 71286, "s": 71238, "text": "Step 8 − Select all the files on the left side." }, { "code": null, "e": 71329, "s": 71286, "text": "Step 9 − Click the right arrow (→) button." }, { "code": null, "e": 71493, "s": 71329, "text": "Once the publishing process starts, the files will be seen as being transferred. When complete, a message will pop up suggesting that the files have been uploaded." }, { "code": null, "e": 71698, "s": 71493, "text": "In this chapter, we will learn how to install Add-ins in Expression Web. An Expression Web Add-in, is an external software package that provides additional or enhanced functionality within Expression Web." }, { "code": null, "e": 71851, "s": 71698, "text": "Add-ins can be downloaded from the following location https://msdn.microsoft.com/en-us/expression/jj873995. For instance, let’s download AddFeed add-in." }, { "code": null, "e": 71945, "s": 71851, "text": "Step 1 − Let’s open Expression Web and go to the Tools menu. Click the Add-Ins...menu option." }, { "code": null, "e": 72109, "s": 71945, "text": "Step 2 − If this is the first time an Add-in is being installed, then there will be an empty list in the Manage Add-ins dialog box. Let’s click the Install button." }, { "code": null, "e": 72175, "s": 72109, "text": "Step 3 − Select the AddFeeds.xadd file and click the Open button." }, { "code": null, "e": 72378, "s": 72175, "text": "Step 4 − Once installed, it will show you the following screen. It will ask if we want to enable the add-in. The screen will give all the information on the particular add-in being installed. Click Yes." }, { "code": null, "e": 72472, "s": 72378, "text": "Step 5 − Depending on the add-ins installed, they will be available at a number of locations." }, { "code": null, "e": 72598, "s": 72472, "text": "Step 6 − Next, go to Insert menu. You will see the Twitter or RSS Feed option which is now added after installing the add-in." }, { "code": null, "e": 72673, "s": 72598, "text": "You can follow the same steps to install more add-ins as per requirements." }, { "code": null, "e": 72709, "s": 72673, "text": "\n 16 Lectures \n 11.5 hours \n" }, { "code": null, "e": 72729, "s": 72709, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 72762, "s": 72729, "text": "\n 33 Lectures \n 3 hours \n" }, { "code": null, "e": 72784, "s": 72762, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 72819, "s": 72784, "text": "\n 33 Lectures \n 5.5 hours \n" }, { "code": null, "e": 72841, "s": 72819, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 72876, "s": 72841, "text": "\n 40 Lectures \n 6.5 hours \n" }, { "code": null, "e": 72887, "s": 72876, "text": " Syed Raza" }, { "code": null, "e": 72920, "s": 72887, "text": "\n 15 Lectures \n 2 hours \n" }, { "code": null, "e": 72960, "s": 72920, "text": " Harshit Srivastava, Pranjal Srivastava" }, { "code": null, "e": 72995, "s": 72960, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 73035, "s": 72995, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 73042, "s": 73035, "text": " Print" }, { "code": null, "e": 73053, "s": 73042, "text": " Add Notes" } ]
PHP - Web Concepts
This session demonstrates how PHP can provide dynamic content according to browser type, randomly generated numbers or User Input. It also demonstrated how the client browser can be redirected. PHP creates some useful environment variables that can be seen in the phpinfo.php page that was used to setup the PHP environment. One of the environment variables set by PHP is HTTP_USER_AGENT which identifies the user's browser and operating system. PHP provides a function getenv() to access the value of all the environment variables. The information contained in the HTTP_USER_AGENT environment variable can be used to create dynamic content appropriate to the browser. Following example demonstrates how you can identify a client browser and operating system. NOTE − The function preg_match()is discussed in PHP Regular expression session. <html> <body> <?php function getBrowser() { $u_agent = $_SERVER['HTTP_USER_AGENT']; $bname = 'Unknown'; $platform = 'Unknown'; $version = ""; //First get the platform? if (preg_match('/linux/i', $u_agent)) { $platform = 'linux'; }elseif (preg_match('/macintosh|mac os x/i', $u_agent)) { $platform = 'mac'; }elseif (preg_match('/windows|win32/i', $u_agent)) { $platform = 'windows'; } // Next get the name of the useragent yes seperately and for good reason if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)) { $bname = 'Internet Explorer'; $ub = "MSIE"; } elseif(preg_match('/Firefox/i',$u_agent)) { $bname = 'Mozilla Firefox'; $ub = "Firefox"; } elseif(preg_match('/Chrome/i',$u_agent)) { $bname = 'Google Chrome'; $ub = "Chrome"; }elseif(preg_match('/Safari/i',$u_agent)) { $bname = 'Apple Safari'; $ub = "Safari"; }elseif(preg_match('/Opera/i',$u_agent)) { $bname = 'Opera'; $ub = "Opera"; }elseif(preg_match('/Netscape/i',$u_agent)) { $bname = 'Netscape'; $ub = "Netscape"; } // finally get the correct version number $known = array('Version', $ub, 'other'); $pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#'; if (!preg_match_all($pattern, $u_agent, $matches)) { // we have no matching number just continue } // see how many we have $i = count($matches['browser']); if ($i != 1) { //we will have two since we are not using 'other' argument yet //see if version is before or after the name if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){ $version= $matches['version'][0]; }else { $version= $matches['version'][1]; } }else { $version= $matches['version'][0]; } // check if we have a number if ($version == null || $version == "") {$version = "?";} return array( 'userAgent' => $u_agent, 'name' => $bname, 'version' => $version, 'platform' => $platform, 'pattern' => $pattern ); } // now try it $ua = getBrowser(); $yourbrowser = "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent']; print_r($yourbrowser); ?> </body> </html> This is producing following result on my machine. This result may be different for your computer depending on what you are using. It will produce the following result − Your browser: Google Chrome 54.0.2840.99 on windows reports: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36 The PHP rand() function is used to generate a random number.i This function can generate numbers with-in a given range. The random number generator should be seeded to prevent a regular pattern of numbers being generated. This is achieved using the srand() function that specifies the seed number as its argument. Following example demonstrates how you can display different image each time out of four images − <html> <body> <?php srand( microtime() * 1000000 ); $num = rand( 1, 4 ); switch( $num ) { case 1: $image_file = "/php/images/logo.png"; break; case 2: $image_file = "/php/images/php.jpg"; break; case 3: $image_file = "/php/images/logo.png"; break; case 4: $image_file = "/php/images/php.jpg"; break; } echo "Random Image : <img src=$image_file />"; ?> </body> </html> It will produce the following result − The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts. Try out following example by putting the source code in test.php script. <?php if( $_POST["name"] || $_POST["age"] ) { if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) { die ("invalid name and name should be alpha"); } echo "Welcome ". $_POST['name']. "<br />"; echo "You are ". $_POST['age']. " years old."; exit(); } ?> <html> <body> <form action = "<?php $_PHP_SELF ?>" method = "POST"> Name: <input type = "text" name = "name" /> Age: <input type = "text" name = "age" /> <input type = "submit" /> </form> </body> </html> It will produce the following result − The PHP default variable $_PHP_SELF is used for the PHP script name and when you click "submit" button then same PHP script will be called and will produce following result − The PHP default variable $_PHP_SELF is used for the PHP script name and when you click "submit" button then same PHP script will be called and will produce following result − The method = "POST" is used to post user data to the server script. There are two methods of posting data to the server script which are discussed in PHP GET & POST chapter. The method = "POST" is used to post user data to the server script. There are two methods of posting data to the server script which are discussed in PHP GET & POST chapter. The PHP header() function supplies raw HTTP headers to the browser and can be used to redirect it to another location. The redirection script should be at the very top of the page to prevent any other part of the page from loading. The target is specified by the Location: header as the argument to the header() function. After calling this function the exit() function can be used to halt parsing of rest of the code. Following example demonstrates how you can redirect a browser request to another web page. Try out this example by putting the source code in test.php script. <?php if( $_POST["location"] ) { $location = $_POST["location"]; header( "Location:$location" ); exit(); } ?> <html> <body> <p>Choose a site to visit :</p> <form action = "<?php $_SERVER['PHP_SELF'] ?>" method ="POST"> <select name = "location">. <option value = "http://www.tutorialspoint.com"> Tutorialspoint.com </option> <option value = "http://www.google.com"> Google Search Page </option> </select> <input type = "submit" /> </form> </body> </html> It will produce the following result − 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": 2951, "s": 2757, "text": "This session demonstrates how PHP can provide dynamic content according to browser type, randomly generated numbers or User Input. It also demonstrated how the client browser can be redirected." }, { "code": null, "e": 3082, "s": 2951, "text": "PHP creates some useful environment variables that can be seen in the phpinfo.php page that was used to setup the PHP environment." }, { "code": null, "e": 3203, "s": 3082, "text": "One of the environment variables set by PHP is HTTP_USER_AGENT which identifies the user's browser and operating system." }, { "code": null, "e": 3426, "s": 3203, "text": "PHP provides a function getenv() to access the value of all the environment variables. The information contained in the HTTP_USER_AGENT environment variable can be used to create dynamic content appropriate to the browser." }, { "code": null, "e": 3517, "s": 3426, "text": "Following example demonstrates how you can identify a client browser and operating system." }, { "code": null, "e": 3597, "s": 3517, "text": "NOTE − The function preg_match()is discussed in PHP Regular expression session." }, { "code": null, "e": 6701, "s": 3597, "text": "<html>\n <body>\n \n <?php\n function getBrowser() { \n $u_agent = $_SERVER['HTTP_USER_AGENT']; \n $bname = 'Unknown';\n $platform = 'Unknown';\n $version = \"\";\n \n //First get the platform?\n if (preg_match('/linux/i', $u_agent)) {\n $platform = 'linux';\n }elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {\n $platform = 'mac';\n }elseif (preg_match('/windows|win32/i', $u_agent)) {\n $platform = 'windows';\n }\n \n // Next get the name of the useragent yes seperately and for good reason\n if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)) {\n $bname = 'Internet Explorer';\n $ub = \"MSIE\";\n } elseif(preg_match('/Firefox/i',$u_agent)) {\n $bname = 'Mozilla Firefox';\n $ub = \"Firefox\";\n } elseif(preg_match('/Chrome/i',$u_agent)) {\n $bname = 'Google Chrome';\n $ub = \"Chrome\";\n }elseif(preg_match('/Safari/i',$u_agent)) {\n $bname = 'Apple Safari';\n $ub = \"Safari\";\n }elseif(preg_match('/Opera/i',$u_agent)) {\n $bname = 'Opera';\n $ub = \"Opera\";\n }elseif(preg_match('/Netscape/i',$u_agent)) {\n $bname = 'Netscape';\n $ub = \"Netscape\";\n }\n \n // finally get the correct version number\n $known = array('Version', $ub, 'other');\n $pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';\n \n if (!preg_match_all($pattern, $u_agent, $matches)) {\n // we have no matching number just continue\n }\n \n // see how many we have\n $i = count($matches['browser']);\n \n if ($i != 1) {\n //we will have two since we are not using 'other' argument yet\n \n //see if version is before or after the name\n if (strripos($u_agent,\"Version\") < strripos($u_agent,$ub)){\n $version= $matches['version'][0];\n }else {\n $version= $matches['version'][1];\n }\n }else {\n $version= $matches['version'][0];\n }\n \n // check if we have a number\n if ($version == null || $version == \"\") {$version = \"?\";}\n return array(\n 'userAgent' => $u_agent,\n 'name' => $bname,\n 'version' => $version,\n 'platform' => $platform,\n 'pattern' => $pattern\n );\n }\n \n // now try it\n $ua = getBrowser();\n $yourbrowser = \"Your browser: \" . $ua['name'] . \" \" . $ua['version'] .\n \" on \" .$ua['platform'] . \" reports: <br >\" . $ua['userAgent'];\n \n print_r($yourbrowser);\n ?>\n \n </body>\n</html>" }, { "code": null, "e": 6831, "s": 6701, "text": "This is producing following result on my machine. This result may be different for your computer depending on what you are using." }, { "code": null, "e": 6870, "s": 6831, "text": "It will produce the following result −" }, { "code": null, "e": 7051, "s": 6870, "text": "Your browser: Google Chrome 54.0.2840.99 on windows reports: \nMozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \n Chrome/54.0.2840.99 Safari/537.36\n" }, { "code": null, "e": 7365, "s": 7051, "text": "The PHP rand() function is used to generate a random number.i This function can generate numbers with-in a given range. The random number generator should be seeded to prevent a regular pattern of numbers being generated. This is achieved using the srand() function that specifies the seed number as its argument." }, { "code": null, "e": 7463, "s": 7365, "text": "Following example demonstrates how you can display different image each time out of four images −" }, { "code": null, "e": 8062, "s": 7463, "text": "<html>\n <body>\n \n <?php\n srand( microtime() * 1000000 );\n $num = rand( 1, 4 );\n \n switch( $num ) {\n case 1: $image_file = \"/php/images/logo.png\";\n break;\n \n case 2: $image_file = \"/php/images/php.jpg\";\n break;\n \n case 3: $image_file = \"/php/images/logo.png\";\n break;\n \n case 4: $image_file = \"/php/images/php.jpg\";\n break;\n }\n echo \"Random Image : <img src=$image_file />\";\n ?>\n \n </body>\n</html>" }, { "code": null, "e": 8101, "s": 8062, "text": "It will produce the following result −" }, { "code": null, "e": 8267, "s": 8101, "text": "The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts." }, { "code": null, "e": 8340, "s": 8267, "text": "Try out following example by putting the source code in test.php script." }, { "code": null, "e": 8908, "s": 8340, "text": "<?php\n if( $_POST[\"name\"] || $_POST[\"age\"] ) {\n if (preg_match(\"/[^A-Za-z'-]/\",$_POST['name'] )) {\n die (\"invalid name and name should be alpha\");\n }\n \n echo \"Welcome \". $_POST['name']. \"<br />\";\n echo \"You are \". $_POST['age']. \" years old.\";\n \n exit();\n }\n?>\n<html>\n <body>\n \n <form action = \"<?php $_PHP_SELF ?>\" method = \"POST\">\n Name: <input type = \"text\" name = \"name\" />\n Age: <input type = \"text\" name = \"age\" />\n <input type = \"submit\" />\n </form>\n \n </body>\n</html>" }, { "code": null, "e": 8947, "s": 8908, "text": "It will produce the following result −" }, { "code": null, "e": 9122, "s": 8947, "text": "The PHP default variable $_PHP_SELF is used for the PHP script name and when you click \"submit\" button then same PHP script will be called and will produce following result −" }, { "code": null, "e": 9297, "s": 9122, "text": "The PHP default variable $_PHP_SELF is used for the PHP script name and when you click \"submit\" button then same PHP script will be called and will produce following result −" }, { "code": null, "e": 9471, "s": 9297, "text": "The method = \"POST\" is used to post user data to the server script. There are two methods of posting data to the server script which are discussed in PHP GET & POST chapter." }, { "code": null, "e": 9645, "s": 9471, "text": "The method = \"POST\" is used to post user data to the server script. There are two methods of posting data to the server script which are discussed in PHP GET & POST chapter." }, { "code": null, "e": 9877, "s": 9645, "text": "The PHP header() function supplies raw HTTP headers to the browser and can be used to redirect it to another location. The redirection script should be at the very top of the page to prevent any other part of the page from loading." }, { "code": null, "e": 10065, "s": 9877, "text": "The target is specified by the Location: header as the argument to the header() function. After calling this function the exit() function can be used to halt parsing of rest of the code." }, { "code": null, "e": 10224, "s": 10065, "text": "Following example demonstrates how you can redirect a browser request to another web page. Try out this example by putting the source code in test.php script." }, { "code": null, "e": 10887, "s": 10224, "text": "<?php\n if( $_POST[\"location\"] ) {\n $location = $_POST[\"location\"];\n header( \"Location:$location\" );\n \n exit();\n }\n?>\n<html>\n <body>\n \n <p>Choose a site to visit :</p>\n \n <form action = \"<?php $_SERVER['PHP_SELF'] ?>\" method =\"POST\">\n <select name = \"location\">.\n \n <option value = \"http://www.tutorialspoint.com\">\n Tutorialspoint.com\n </option>\n \n <option value = \"http://www.google.com\">\n Google Search Page\n </option>\n \n </select>\n <input type = \"submit\" />\n </form>\n \n </body>\n</html>" }, { "code": null, "e": 10926, "s": 10887, "text": "It will produce the following result −" }, { "code": null, "e": 10959, "s": 10926, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 10975, "s": 10959, "text": " Malhar Lathkar" }, { "code": null, "e": 11008, "s": 10975, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 11019, "s": 11008, "text": " Syed Raza" }, { "code": null, "e": 11054, "s": 11019, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 11071, "s": 11054, "text": " Frahaan Hussain" }, { "code": null, "e": 11104, "s": 11071, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 11119, "s": 11104, "text": " Nivedita Jain" }, { "code": null, "e": 11154, "s": 11119, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 11166, "s": 11154, "text": " Azaz Patel" }, { "code": null, "e": 11201, "s": 11166, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 11229, "s": 11201, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 11236, "s": 11229, "text": " Print" }, { "code": null, "e": 11247, "s": 11236, "text": " Add Notes" } ]
DataTables pagingType Option - GeeksforGeeks
13 Jul, 2021 DataTables is a jQuery plugin that can be used for adding interactive and advanced controls to HTML tables for the webpage. This also allows the data in the table to be searched, sorted, and filtered according to the needs of the user. The DataTable also exposes a powerful API that can be further used to modify how the data is displayed. The pagingType option is used to specify the type of controls that will be displayed below the DataTable for pagination. It accepts a string value that can be specified by using 6 built-in types of available controls. These are specified by the following values. simple: In this type of control, only the ‘Previous’ and ‘Next’ buttons are displayed. simple_numbers: In this type of control, the ‘Previous’ and ‘Next’ buttons are displayed along with the page numbers. full: In this type of control, only the ‘First’, ‘Previous’, ‘Next’ and ‘Last’ buttons are displayed. full_numbers: In this type of control, the ‘First’, ‘Previous’, ‘Next’, and ‘Last’ buttons are displayed along with the page numbers. numbers: In this type of control, only the page numbers are displayed. first_last_numbers: In this type of control, the ‘First’ and ‘Last’ buttons are displayed along with the page numbers. Other types can be added using DataTable plugins. Syntax: { pagingType: value } Parameters: This option has a single value as mentioned above and described below. value: This is a string value that specifies the type of controls that will be displayed. The example below illustrates the use of this option. We will see all the different paging types that are built-in to DataTables. Example 1: In this type of control, the buttons are displayed along with the page numbers. HTML <html><head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script> </head> <body> <h2 style="color:green;"> GeeksForGeeks </h2> <h3>DataTables pagingType Option</h3> <!-- HTML table with random data --> <h4>pagingType: numbers</h4> <table id="table_numbers" class="display nowrap" style="width: 100%;"> </table> <script> // Define the columns and content // of the DataTable let columnData = [ { title: "Day" }, { title: "Name" }, { title: "Age" } ]; let tableData = [ ["2", "Ivor", "30"], ["3", "Vance", "32"], ["5", "Octavius", "43"], ["0", "Abel", "35"], ["3", "Cecilia", "32"], ["4", "Sebastian", "36"], ["5", "Uriah", "41"], ["6", "Abigail", "15"], ["10", "Sam", "68"], ["33", "Richard", "25"] ] // Initialize the DataTable $(document).ready(function () { $('#table_numbers').DataTable({ data: tableData, columns: columnData, pageLength: 4, // Specify the paging type to be used // in the DataTable pagingType: "numbers" }); }); </script></body></html> Output: Example 2: In this type of control, only the ‘Previous’ and ‘Next’ buttons are displayed. HTML <html><head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script> </head> <body> <h2 style="color:green;"> GeeksForGeeks </h2> <h3>DataTables pagingType Option</h3> <!-- HTML table with random data --> <h4>pagingType: simple</h4> <table id="table_simple" class="display nowrap" style="width: 100%;"> </table> <script> // Define the columns and content // of the DataTable let columnData = [ { title: "Day" }, { title: "Name" }, { title: "Age" } ]; let tableData = [ ["2", "Ivor", "30"], ["3", "Vance", "32"], ["5", "Octavius", "43"], ["0", "Abel", "35"], ["3", "Cecilia", "32"], ["4", "Sebastian", "36"], ["5", "Uriah", "41"], ["6", "Abigail", "15"], ["10", "Sam", "68"], ["33", "Richard", "25"] ] // Initialize the DataTable $(document).ready(function () { $('#table_simple').DataTable({ data: tableData, columns: columnData, pageLength: 4, // Specify the paging type to be used // in the DataTable pagingType: "simple" }); }); </script></body></html> Output: Example 3:In this type of control, the ‘Previous’ and ‘Next’ buttons are displayed along with the page numbers HTML <html><head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script> </head> <body> <h2 style="color:green;"> GeeksForGeeks </h2> <h3>DataTables pagingType Option</h3> <!-- HTML table with random data --> <h4>pagingType: simple_numbers</h4> <table id="table_simple_numbers" class="display nowrap" style="width: 100%;"> </table> <script> // Define the columns and content // of the DataTable let columnData = [ { title: "Day" }, { title: "Name" }, { title: "Age" } ]; let tableData = [ ["2", "Ivor", "30"], ["3", "Vance", "32"], ["5", "Octavius", "43"], ["0", "Abel", "35"], ["3", "Cecilia", "32"], ["4", "Sebastian", "36"], ["5", "Uriah", "41"], ["6", "Abigail", "15"], ["10", "Sam", "68"], ["33", "Richard", "25"] ] // Initialize the DataTable $(document).ready(function () { $('#table_simple_numbers').DataTable({ data: tableData, columns: columnData, pageLength: 4, // Specify the paging type to be used // in the DataTable pagingType: "simple_numbers" }); }); </script></body></html> Output: Example 4: In this type of control, only the ‘First’, ‘Previous’, ‘Next’, and ‘Last’ buttons are displayed. HTML <html><head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script> </head> <body> <h2 style="color:green;"> GeeksForGeeks </h2> <h3>DataTables pagingType Option</h3> <!-- HTML table with random data --> <h4>pagingType: full</h4> <table id="table_full" class="display nowrap" style="width: 100%;"> </table> <script> // Define the columns and content // of the DataTable let columnData = [ { title: "Day" }, { title: "Name" }, { title: "Age" } ]; let tableData = [ ["2", "Ivor", "30"], ["3", "Vance", "32"], ["5", "Octavius", "43"], ["0", "Abel", "35"], ["3", "Cecilia", "32"], ["4", "Sebastian", "36"], ["5", "Uriah", "41"], ["6", "Abigail", "15"], ["10", "Sam", "68"], ["33", "Richard", "25"] ] // Initialize the DataTable $(document).ready(function () { $('#table_full').DataTable({ data: tableData, columns: columnData, pageLength: 4, // Specify the paging type to be used // in the DataTable pagingType: "full" }); }); </script></body></html> Output: Example 5: In this type of control, the ‘First’, ‘Previous’, ‘Next’, and ‘Last’ buttons are displayed along with the page numbers. HTML <html><head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script> </head> <body> <h2 style="color:green;"> GeeksForGeeks </h2> <h3>DataTables pagingType Option</h3> <!-- HTML table with random data --> <h4>pagingType: full_numbers</h4> <table id="table_full_numbers" class="display nowrap" style="width: 100%;"> </table> <script> // Define the columns and content // of the DataTable let columnData = [ { title: "Day" }, { title: "Name" }, { title: "Age" } ]; let tableData = [ ["2", "Ivor", "30"], ["3", "Vance", "32"], ["5", "Octavius", "43"], ["0", "Abel", "35"], ["3", "Cecilia", "32"], ["4", "Sebastian", "36"], ["5", "Uriah", "41"], ["6", "Abigail", "15"], ["10", "Sam", "68"], ["33", "Richard", "25"] ] // Initialize the DataTable $(document).ready(function () { $('#table_full_numbers').DataTable({ data: tableData, columns: columnData, pageLength: 4, // Specify the paging type to be used // in the DataTable pagingType: "full_numbers" }); }); </script></body></html> Output: Example 6: In this type of control, the ‘First’ and ‘Last’ buttons are displayed along with the page numbers. HTML <html><head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script> </head> <body> <h2 style="color:green;"> GeeksForGeeks </h2> <h3>DataTables pagingType Option</h3> <!-- HTML table with random data --> <h4>pagingType: first_last_numbers</h4> <table id="table_first_last_numbers" class="display nowrap" style="width: 100%;"> </table> <script> // Define the columns and content // of the DataTable let columnData = [ { title: "Day" }, { title: "Name" }, { title: "Age" } ]; let tableData = [ ["2", "Ivor", "30"], ["3", "Vance", "32"], ["5", "Octavius", "43"], ["0", "Abel", "35"], ["3", "Cecilia", "32"], ["4", "Sebastian", "36"], ["5", "Uriah", "41"], ["6", "Abigail", "15"], ["10", "Sam", "68"], ["33", "Richard", "25"] ] // Initialize the DataTable $(document).ready(function () { $('#table_first_last_numbers').DataTable({ data: tableData, columns: columnData, pageLength: 4, // Specify the paging type to be used // in the DataTable pagingType: "first_last_numbers" }); }); </script></body></html> Output: Reference Link: https://datatables.net/reference/option/pagingType jQuery-DataTables JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method How to get the value in an input text box using jQuery ? jQuery | parent() & parents() with Examples Difference Between JavaScript and jQuery Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 25755, "s": 25727, "text": "\n13 Jul, 2021" }, { "code": null, "e": 26095, "s": 25755, "text": "DataTables is a jQuery plugin that can be used for adding interactive and advanced controls to HTML tables for the webpage. This also allows the data in the table to be searched, sorted, and filtered according to the needs of the user. The DataTable also exposes a powerful API that can be further used to modify how the data is displayed." }, { "code": null, "e": 26358, "s": 26095, "text": "The pagingType option is used to specify the type of controls that will be displayed below the DataTable for pagination. It accepts a string value that can be specified by using 6 built-in types of available controls. These are specified by the following values." }, { "code": null, "e": 26445, "s": 26358, "text": "simple: In this type of control, only the ‘Previous’ and ‘Next’ buttons are displayed." }, { "code": null, "e": 26563, "s": 26445, "text": "simple_numbers: In this type of control, the ‘Previous’ and ‘Next’ buttons are displayed along with the page numbers." }, { "code": null, "e": 26665, "s": 26563, "text": "full: In this type of control, only the ‘First’, ‘Previous’, ‘Next’ and ‘Last’ buttons are displayed." }, { "code": null, "e": 26799, "s": 26665, "text": "full_numbers: In this type of control, the ‘First’, ‘Previous’, ‘Next’, and ‘Last’ buttons are displayed along with the page numbers." }, { "code": null, "e": 26870, "s": 26799, "text": "numbers: In this type of control, only the page numbers are displayed." }, { "code": null, "e": 26989, "s": 26870, "text": "first_last_numbers: In this type of control, the ‘First’ and ‘Last’ buttons are displayed along with the page numbers." }, { "code": null, "e": 27039, "s": 26989, "text": "Other types can be added using DataTable plugins." }, { "code": null, "e": 27047, "s": 27039, "text": "Syntax:" }, { "code": null, "e": 27069, "s": 27047, "text": "{ pagingType: value }" }, { "code": null, "e": 27154, "s": 27071, "text": "Parameters: This option has a single value as mentioned above and described below." }, { "code": null, "e": 27244, "s": 27154, "text": "value: This is a string value that specifies the type of controls that will be displayed." }, { "code": null, "e": 27374, "s": 27244, "text": "The example below illustrates the use of this option. We will see all the different paging types that are built-in to DataTables." }, { "code": null, "e": 27465, "s": 27374, "text": "Example 1: In this type of control, the buttons are displayed along with the page numbers." }, { "code": null, "e": 27470, "s": 27465, "text": "HTML" }, { "code": "<html><head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src=\"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script> </head> <body> <h2 style=\"color:green;\"> GeeksForGeeks </h2> <h3>DataTables pagingType Option</h3> <!-- HTML table with random data --> <h4>pagingType: numbers</h4> <table id=\"table_numbers\" class=\"display nowrap\" style=\"width: 100%;\"> </table> <script> // Define the columns and content // of the DataTable let columnData = [ { title: \"Day\" }, { title: \"Name\" }, { title: \"Age\" } ]; let tableData = [ [\"2\", \"Ivor\", \"30\"], [\"3\", \"Vance\", \"32\"], [\"5\", \"Octavius\", \"43\"], [\"0\", \"Abel\", \"35\"], [\"3\", \"Cecilia\", \"32\"], [\"4\", \"Sebastian\", \"36\"], [\"5\", \"Uriah\", \"41\"], [\"6\", \"Abigail\", \"15\"], [\"10\", \"Sam\", \"68\"], [\"33\", \"Richard\", \"25\"] ] // Initialize the DataTable $(document).ready(function () { $('#table_numbers').DataTable({ data: tableData, columns: columnData, pageLength: 4, // Specify the paging type to be used // in the DataTable pagingType: \"numbers\" }); }); </script></body></html>", "e": 28936, "s": 27470, "text": null }, { "code": null, "e": 28944, "s": 28936, "text": "Output:" }, { "code": null, "e": 29035, "s": 28944, "text": "Example 2: In this type of control, only the ‘Previous’ and ‘Next’ buttons are displayed." }, { "code": null, "e": 29040, "s": 29035, "text": "HTML" }, { "code": "<html><head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src=\"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script> </head> <body> <h2 style=\"color:green;\"> GeeksForGeeks </h2> <h3>DataTables pagingType Option</h3> <!-- HTML table with random data --> <h4>pagingType: simple</h4> <table id=\"table_simple\" class=\"display nowrap\" style=\"width: 100%;\"> </table> <script> // Define the columns and content // of the DataTable let columnData = [ { title: \"Day\" }, { title: \"Name\" }, { title: \"Age\" } ]; let tableData = [ [\"2\", \"Ivor\", \"30\"], [\"3\", \"Vance\", \"32\"], [\"5\", \"Octavius\", \"43\"], [\"0\", \"Abel\", \"35\"], [\"3\", \"Cecilia\", \"32\"], [\"4\", \"Sebastian\", \"36\"], [\"5\", \"Uriah\", \"41\"], [\"6\", \"Abigail\", \"15\"], [\"10\", \"Sam\", \"68\"], [\"33\", \"Richard\", \"25\"] ] // Initialize the DataTable $(document).ready(function () { $('#table_simple').DataTable({ data: tableData, columns: columnData, pageLength: 4, // Specify the paging type to be used // in the DataTable pagingType: \"simple\" }); }); </script></body></html>", "e": 30506, "s": 29040, "text": null }, { "code": null, "e": 30514, "s": 30506, "text": "Output:" }, { "code": null, "e": 30625, "s": 30514, "text": "Example 3:In this type of control, the ‘Previous’ and ‘Next’ buttons are displayed along with the page numbers" }, { "code": null, "e": 30630, "s": 30625, "text": "HTML" }, { "code": "<html><head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src=\"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script> </head> <body> <h2 style=\"color:green;\"> GeeksForGeeks </h2> <h3>DataTables pagingType Option</h3> <!-- HTML table with random data --> <h4>pagingType: simple_numbers</h4> <table id=\"table_simple_numbers\" class=\"display nowrap\" style=\"width: 100%;\"> </table> <script> // Define the columns and content // of the DataTable let columnData = [ { title: \"Day\" }, { title: \"Name\" }, { title: \"Age\" } ]; let tableData = [ [\"2\", \"Ivor\", \"30\"], [\"3\", \"Vance\", \"32\"], [\"5\", \"Octavius\", \"43\"], [\"0\", \"Abel\", \"35\"], [\"3\", \"Cecilia\", \"32\"], [\"4\", \"Sebastian\", \"36\"], [\"5\", \"Uriah\", \"41\"], [\"6\", \"Abigail\", \"15\"], [\"10\", \"Sam\", \"68\"], [\"33\", \"Richard\", \"25\"] ] // Initialize the DataTable $(document).ready(function () { $('#table_simple_numbers').DataTable({ data: tableData, columns: columnData, pageLength: 4, // Specify the paging type to be used // in the DataTable pagingType: \"simple_numbers\" }); }); </script></body></html>", "e": 32126, "s": 30630, "text": null }, { "code": null, "e": 32134, "s": 32126, "text": "Output:" }, { "code": null, "e": 32242, "s": 32134, "text": "Example 4: In this type of control, only the ‘First’, ‘Previous’, ‘Next’, and ‘Last’ buttons are displayed." }, { "code": null, "e": 32247, "s": 32242, "text": "HTML" }, { "code": "<html><head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src=\"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script> </head> <body> <h2 style=\"color:green;\"> GeeksForGeeks </h2> <h3>DataTables pagingType Option</h3> <!-- HTML table with random data --> <h4>pagingType: full</h4> <table id=\"table_full\" class=\"display nowrap\" style=\"width: 100%;\"> </table> <script> // Define the columns and content // of the DataTable let columnData = [ { title: \"Day\" }, { title: \"Name\" }, { title: \"Age\" } ]; let tableData = [ [\"2\", \"Ivor\", \"30\"], [\"3\", \"Vance\", \"32\"], [\"5\", \"Octavius\", \"43\"], [\"0\", \"Abel\", \"35\"], [\"3\", \"Cecilia\", \"32\"], [\"4\", \"Sebastian\", \"36\"], [\"5\", \"Uriah\", \"41\"], [\"6\", \"Abigail\", \"15\"], [\"10\", \"Sam\", \"68\"], [\"33\", \"Richard\", \"25\"] ] // Initialize the DataTable $(document).ready(function () { $('#table_full').DataTable({ data: tableData, columns: columnData, pageLength: 4, // Specify the paging type to be used // in the DataTable pagingType: \"full\" }); }); </script></body></html>", "e": 33703, "s": 32247, "text": null }, { "code": null, "e": 33711, "s": 33703, "text": "Output:" }, { "code": null, "e": 33842, "s": 33711, "text": "Example 5: In this type of control, the ‘First’, ‘Previous’, ‘Next’, and ‘Last’ buttons are displayed along with the page numbers." }, { "code": null, "e": 33847, "s": 33842, "text": "HTML" }, { "code": "<html><head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src=\"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script> </head> <body> <h2 style=\"color:green;\"> GeeksForGeeks </h2> <h3>DataTables pagingType Option</h3> <!-- HTML table with random data --> <h4>pagingType: full_numbers</h4> <table id=\"table_full_numbers\" class=\"display nowrap\" style=\"width: 100%;\"> </table> <script> // Define the columns and content // of the DataTable let columnData = [ { title: \"Day\" }, { title: \"Name\" }, { title: \"Age\" } ]; let tableData = [ [\"2\", \"Ivor\", \"30\"], [\"3\", \"Vance\", \"32\"], [\"5\", \"Octavius\", \"43\"], [\"0\", \"Abel\", \"35\"], [\"3\", \"Cecilia\", \"32\"], [\"4\", \"Sebastian\", \"36\"], [\"5\", \"Uriah\", \"41\"], [\"6\", \"Abigail\", \"15\"], [\"10\", \"Sam\", \"68\"], [\"33\", \"Richard\", \"25\"] ] // Initialize the DataTable $(document).ready(function () { $('#table_full_numbers').DataTable({ data: tableData, columns: columnData, pageLength: 4, // Specify the paging type to be used // in the DataTable pagingType: \"full_numbers\" }); }); </script></body></html>", "e": 35332, "s": 33847, "text": null }, { "code": null, "e": 35340, "s": 35332, "text": "Output:" }, { "code": null, "e": 35450, "s": 35340, "text": "Example 6: In this type of control, the ‘First’ and ‘Last’ buttons are displayed along with the page numbers." }, { "code": null, "e": 35455, "s": 35450, "text": "HTML" }, { "code": "<html><head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src=\"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script> </head> <body> <h2 style=\"color:green;\"> GeeksForGeeks </h2> <h3>DataTables pagingType Option</h3> <!-- HTML table with random data --> <h4>pagingType: first_last_numbers</h4> <table id=\"table_first_last_numbers\" class=\"display nowrap\" style=\"width: 100%;\"> </table> <script> // Define the columns and content // of the DataTable let columnData = [ { title: \"Day\" }, { title: \"Name\" }, { title: \"Age\" } ]; let tableData = [ [\"2\", \"Ivor\", \"30\"], [\"3\", \"Vance\", \"32\"], [\"5\", \"Octavius\", \"43\"], [\"0\", \"Abel\", \"35\"], [\"3\", \"Cecilia\", \"32\"], [\"4\", \"Sebastian\", \"36\"], [\"5\", \"Uriah\", \"41\"], [\"6\", \"Abigail\", \"15\"], [\"10\", \"Sam\", \"68\"], [\"33\", \"Richard\", \"25\"] ] // Initialize the DataTable $(document).ready(function () { $('#table_first_last_numbers').DataTable({ data: tableData, columns: columnData, pageLength: 4, // Specify the paging type to be used // in the DataTable pagingType: \"first_last_numbers\" }); }); </script></body></html>", "e": 36964, "s": 35455, "text": null }, { "code": null, "e": 36972, "s": 36964, "text": "Output:" }, { "code": null, "e": 37039, "s": 36972, "text": "Reference Link: https://datatables.net/reference/option/pagingType" }, { "code": null, "e": 37057, "s": 37039, "text": "jQuery-DataTables" }, { "code": null, "e": 37064, "s": 37057, "text": "JQuery" }, { "code": null, "e": 37081, "s": 37064, "text": "Web Technologies" }, { "code": null, "e": 37179, "s": 37081, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37252, "s": 37179, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 37275, "s": 37252, "text": "jQuery | ajax() Method" }, { "code": null, "e": 37332, "s": 37275, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 37376, "s": 37332, "text": "jQuery | parent() & parents() with Examples" }, { "code": null, "e": 37417, "s": 37376, "text": "Difference Between JavaScript and jQuery" }, { "code": null, "e": 37459, "s": 37417, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 37492, "s": 37459, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 37535, "s": 37492, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 37597, "s": 37535, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Maximum of Absolute Value Expression in C++
Suppose we have two arrays of integers with equal lengths, we have to find the maximum value of: |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|. Where the maximum value is taken over all 0 <= i, j < arr1.length. So if the given two arrays are [1,2,3,4] and [-1,4,5,6], the output will be 13. To solve this, we will follow these steps − Define a method called getVal, that will take array v Define a method called getVal, that will take array v maxVal := -inf, minVal := inf maxVal := -inf, minVal := inf for i in range 0 to size of vminVal := min of v[i] and minValmaxVal := max of v[i] and maxVal for i in range 0 to size of v minVal := min of v[i] and minVal minVal := min of v[i] and minVal maxVal := max of v[i] and maxVal maxVal := max of v[i] and maxVal return maxVal – minVal return maxVal – minVal From the main method, do the following From the main method, do the following make an array ret of size 4 make an array ret of size 4 n := size of arr1 n := size of arr1 for i in range 0 to n – 1insert arr1[i] – arr2[i] + i into ret[0]insert arr1[i] + arr2[i] + i into ret[1]insert arr1[i] – arr2[i] - i into ret[2]insert arr1[i] + arr2[i] - i into ret[3] for i in range 0 to n – 1 insert arr1[i] – arr2[i] + i into ret[0] insert arr1[i] – arr2[i] + i into ret[0] insert arr1[i] + arr2[i] + i into ret[1] insert arr1[i] + arr2[i] + i into ret[1] insert arr1[i] – arr2[i] - i into ret[2] insert arr1[i] – arr2[i] - i into ret[2] insert arr1[i] + arr2[i] - i into ret[3] insert arr1[i] + arr2[i] - i into ret[3] ans := -inf ans := -inf for i in range 0 to 3ans := max of ans and getVal(ret[i]) for i in range 0 to 3 ans := max of ans and getVal(ret[i]) ans := max of ans and getVal(ret[i]) return ans return ans Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int getVal(vector <int>& v){ int maxVal = INT_MIN; int minVal = INT_MAX; for(int i = 0; i < v.size(); i++){ minVal = min(v[i], minVal); maxVal = max(v[i], maxVal); } return maxVal - minVal; } int maxAbsValExpr(vector<int>& arr1, vector<int>& arr2) { vector <int> ret[4]; int n = arr1.size(); for(int i = 0; i < n; i++){ ret[0].push_back(arr1[i] - arr2[i] + i); ret[1].push_back(arr1[i] + arr2[i] + i); ret[2].push_back(arr1[i] - arr2[i] - i); ret[3].push_back(arr1[i] + arr2[i] - i); } int ans = INT_MIN; for(int i = 0; i < 4; i++){ ans = max(ans, getVal(ret[i])); } return ans; } }; main(){ vector<int> v1 = {1,2,3,4}, v2 = {-1, 4, 5, 6}; Solution ob; cout << (ob.maxAbsValExpr(v1, v2)); } [1,2,3,4] [-1,4,5,6] 13
[ { "code": null, "e": 1359, "s": 1062, "text": "Suppose we have two arrays of integers with equal lengths, we have to find the maximum value of: |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|. Where the maximum value is taken over all 0 <= i, j < arr1.length. So if the given two arrays are [1,2,3,4] and [-1,4,5,6], the output will be 13." }, { "code": null, "e": 1403, "s": 1359, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1457, "s": 1403, "text": "Define a method called getVal, that will take array v" }, { "code": null, "e": 1511, "s": 1457, "text": "Define a method called getVal, that will take array v" }, { "code": null, "e": 1541, "s": 1511, "text": "maxVal := -inf, minVal := inf" }, { "code": null, "e": 1571, "s": 1541, "text": "maxVal := -inf, minVal := inf" }, { "code": null, "e": 1665, "s": 1571, "text": "for i in range 0 to size of vminVal := min of v[i] and minValmaxVal := max of v[i] and maxVal" }, { "code": null, "e": 1695, "s": 1665, "text": "for i in range 0 to size of v" }, { "code": null, "e": 1728, "s": 1695, "text": "minVal := min of v[i] and minVal" }, { "code": null, "e": 1761, "s": 1728, "text": "minVal := min of v[i] and minVal" }, { "code": null, "e": 1794, "s": 1761, "text": "maxVal := max of v[i] and maxVal" }, { "code": null, "e": 1827, "s": 1794, "text": "maxVal := max of v[i] and maxVal" }, { "code": null, "e": 1850, "s": 1827, "text": "return maxVal – minVal" }, { "code": null, "e": 1873, "s": 1850, "text": "return maxVal – minVal" }, { "code": null, "e": 1912, "s": 1873, "text": "From the main method, do the following" }, { "code": null, "e": 1951, "s": 1912, "text": "From the main method, do the following" }, { "code": null, "e": 1979, "s": 1951, "text": "make an array ret of size 4" }, { "code": null, "e": 2007, "s": 1979, "text": "make an array ret of size 4" }, { "code": null, "e": 2025, "s": 2007, "text": "n := size of arr1" }, { "code": null, "e": 2043, "s": 2025, "text": "n := size of arr1" }, { "code": null, "e": 2229, "s": 2043, "text": "for i in range 0 to n – 1insert arr1[i] – arr2[i] + i into ret[0]insert arr1[i] + arr2[i] + i into ret[1]insert arr1[i] – arr2[i] - i into ret[2]insert arr1[i] + arr2[i] - i into ret[3]" }, { "code": null, "e": 2255, "s": 2229, "text": "for i in range 0 to n – 1" }, { "code": null, "e": 2296, "s": 2255, "text": "insert arr1[i] – arr2[i] + i into ret[0]" }, { "code": null, "e": 2337, "s": 2296, "text": "insert arr1[i] – arr2[i] + i into ret[0]" }, { "code": null, "e": 2378, "s": 2337, "text": "insert arr1[i] + arr2[i] + i into ret[1]" }, { "code": null, "e": 2419, "s": 2378, "text": "insert arr1[i] + arr2[i] + i into ret[1]" }, { "code": null, "e": 2460, "s": 2419, "text": "insert arr1[i] – arr2[i] - i into ret[2]" }, { "code": null, "e": 2501, "s": 2460, "text": "insert arr1[i] – arr2[i] - i into ret[2]" }, { "code": null, "e": 2542, "s": 2501, "text": "insert arr1[i] + arr2[i] - i into ret[3]" }, { "code": null, "e": 2583, "s": 2542, "text": "insert arr1[i] + arr2[i] - i into ret[3]" }, { "code": null, "e": 2595, "s": 2583, "text": "ans := -inf" }, { "code": null, "e": 2607, "s": 2595, "text": "ans := -inf" }, { "code": null, "e": 2665, "s": 2607, "text": "for i in range 0 to 3ans := max of ans and getVal(ret[i])" }, { "code": null, "e": 2687, "s": 2665, "text": "for i in range 0 to 3" }, { "code": null, "e": 2724, "s": 2687, "text": "ans := max of ans and getVal(ret[i])" }, { "code": null, "e": 2761, "s": 2724, "text": "ans := max of ans and getVal(ret[i])" }, { "code": null, "e": 2772, "s": 2761, "text": "return ans" }, { "code": null, "e": 2783, "s": 2772, "text": "return ans" }, { "code": null, "e": 2853, "s": 2783, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2864, "s": 2853, "text": " Live Demo" }, { "code": null, "e": 3791, "s": 2864, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int getVal(vector <int>& v){\n int maxVal = INT_MIN;\n int minVal = INT_MAX;\n for(int i = 0; i < v.size(); i++){\n minVal = min(v[i], minVal);\n maxVal = max(v[i], maxVal);\n }\n return maxVal - minVal;\n }\n int maxAbsValExpr(vector<int>& arr1, vector<int>& arr2) {\n vector <int> ret[4];\n int n = arr1.size();\n for(int i = 0; i < n; i++){\n ret[0].push_back(arr1[i] - arr2[i] + i);\n ret[1].push_back(arr1[i] + arr2[i] + i);\n ret[2].push_back(arr1[i] - arr2[i] - i);\n ret[3].push_back(arr1[i] + arr2[i] - i);\n }\n int ans = INT_MIN;\n for(int i = 0; i < 4; i++){\n ans = max(ans, getVal(ret[i]));\n }\n return ans;\n }\n};\nmain(){\n vector<int> v1 = {1,2,3,4}, v2 = {-1, 4, 5, 6};\n Solution ob;\n cout << (ob.maxAbsValExpr(v1, v2));\n}" }, { "code": null, "e": 3812, "s": 3791, "text": "[1,2,3,4]\n[-1,4,5,6]" }, { "code": null, "e": 3815, "s": 3812, "text": "13" } ]
Program to find out the number of special numbers in a given range in Python
Suppose we are given a range of integer numbers and are asked to find out the special numbers in the range. A special number is a number that is a positive integer having only 1 digit in its decimal representation. A number that has more than 1 digit in its decimal representation can also be special if the number is divisible by the count of digits in its decimal representation and the quotient value is itself a special number. We return the count of special numbers in the given range (left_limit, right_limit). So, if the input is like left_limit = 5, right_limit = 30, then the output will be 13. The special numbers in this range are: 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 24, and 28. To solve this, we will follow these steps − if right_limit < 10, thenreturn right_limit - left_limit + 1 return right_limit - left_limit + 1 len_right := size of string representation of (right_limit) number_list := [0,1,2,3,4,5,6,7,8,9,10,12,14,16,18] for j in range 2 to len_right + 1, dofor each k in number_list, dotemp1 := k * jif size of string representation of temp1 is same as j, theninsert temp1 at the end of number_listotherwise when len(str(temp1)) > j, thencome out from the loopif number_list[size of number_list - 1] >= right_limit, thencome out from the loop for each k in number_list, dotemp1 := k * jif size of string representation of temp1 is same as j, theninsert temp1 at the end of number_listotherwise when len(str(temp1)) > j, thencome out from the loopif number_list[size of number_list - 1] >= right_limit, thencome out from the loop temp1 := k * j if size of string representation of temp1 is same as j, theninsert temp1 at the end of number_list insert temp1 at the end of number_list otherwise when len(str(temp1)) > j, thencome out from the loop come out from the loop if number_list[size of number_list - 1] >= right_limit, thencome out from the loop come out from the loop delete duplicate values from number_list and sort count := 0 for each temp2 in number_list, doif temp2 >= left_limit and temp2 <= right_limit, thencount := count + 1 if temp2 >= left_limit and temp2 <= right_limit, thencount := count + 1 count := count + 1 return count Let us see the following implementation to get better understanding − def strange(left_limit, right_limit): if right_limit < 10: return right_limit - left_limit + 1 len_right = len(str(right_limit)) number_list = [0,1,2,3,4,5,6,7,8,9,10,12,14,16,18] for j in range(2, len_right + 1): for k in number_list: temp1 = k*j if len(str(temp1)) == j: number_list.append(temp1) elif len(str(temp1)) > j: break if number_list[len(number_list)-1] >= right_limit: break number_list = list(set(number_list)) count = 0 for temp2 in number_list: if temp2 >= left_limit and temp2 <= right_limit: count = count + 1 return count print(strange(5, 30)) 5, 30 13
[ { "code": null, "e": 1704, "s": 1187, "text": "Suppose we are given a range of integer numbers and are asked to find out the special numbers in the range. A special number is a number that is a positive integer having only 1 digit in its decimal representation. A number that has more than 1 digit in its decimal representation can also be special if the number is divisible by the count of digits in its decimal representation and the quotient value is itself a special number. We return the count of special numbers in the given range (left_limit, right_limit)." }, { "code": null, "e": 1791, "s": 1704, "text": "So, if the input is like left_limit = 5, right_limit = 30, then the output will be 13." }, { "code": null, "e": 1881, "s": 1791, "text": "The special numbers in this range are: 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 24, and 28." }, { "code": null, "e": 1925, "s": 1881, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1986, "s": 1925, "text": "if right_limit < 10, thenreturn right_limit - left_limit + 1" }, { "code": null, "e": 2022, "s": 1986, "text": "return right_limit - left_limit + 1" }, { "code": null, "e": 2082, "s": 2022, "text": "len_right := size of string representation of (right_limit)" }, { "code": null, "e": 2134, "s": 2082, "text": "number_list := [0,1,2,3,4,5,6,7,8,9,10,12,14,16,18]" }, { "code": null, "e": 2457, "s": 2134, "text": "for j in range 2 to len_right + 1, dofor each k in number_list, dotemp1 := k * jif size of string representation of temp1 is same as j, theninsert temp1 at the end of number_listotherwise when len(str(temp1)) > j, thencome out from the loopif number_list[size of number_list - 1] >= right_limit, thencome out from the loop" }, { "code": null, "e": 2743, "s": 2457, "text": "for each k in number_list, dotemp1 := k * jif size of string representation of temp1 is same as j, theninsert temp1 at the end of number_listotherwise when len(str(temp1)) > j, thencome out from the loopif number_list[size of number_list - 1] >= right_limit, thencome out from the loop" }, { "code": null, "e": 2758, "s": 2743, "text": "temp1 := k * j" }, { "code": null, "e": 2857, "s": 2758, "text": "if size of string representation of temp1 is same as j, theninsert temp1 at the end of number_list" }, { "code": null, "e": 2896, "s": 2857, "text": "insert temp1 at the end of number_list" }, { "code": null, "e": 2959, "s": 2896, "text": "otherwise when len(str(temp1)) > j, thencome out from the loop" }, { "code": null, "e": 2982, "s": 2959, "text": "come out from the loop" }, { "code": null, "e": 3065, "s": 2982, "text": "if number_list[size of number_list - 1] >= right_limit, thencome out from the loop" }, { "code": null, "e": 3088, "s": 3065, "text": "come out from the loop" }, { "code": null, "e": 3138, "s": 3088, "text": "delete duplicate values from number_list and sort" }, { "code": null, "e": 3149, "s": 3138, "text": "count := 0" }, { "code": null, "e": 3254, "s": 3149, "text": "for each temp2 in number_list, doif temp2 >= left_limit and temp2 <= right_limit, thencount := count + 1" }, { "code": null, "e": 3326, "s": 3254, "text": "if temp2 >= left_limit and temp2 <= right_limit, thencount := count + 1" }, { "code": null, "e": 3345, "s": 3326, "text": "count := count + 1" }, { "code": null, "e": 3358, "s": 3345, "text": "return count" }, { "code": null, "e": 3428, "s": 3358, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 4000, "s": 3428, "text": "def strange(left_limit, right_limit):\n if right_limit < 10:\n return right_limit - left_limit + 1\nlen_right = len(str(right_limit))\nnumber_list = [0,1,2,3,4,5,6,7,8,9,10,12,14,16,18]\nfor j in range(2, len_right + 1):\nfor k in number_list:\ntemp1 = k*j\nif len(str(temp1)) == j:\nnumber_list.append(temp1)\nelif len(str(temp1)) > j:\nbreak\nif number_list[len(number_list)-1] >= right_limit:\nbreak\nnumber_list = list(set(number_list))\ncount = 0\nfor temp2 in number_list:\nif temp2 >= left_limit and temp2 <= right_limit:\ncount = count + 1\nreturn count\nprint(strange(5, 30))" }, { "code": null, "e": 4006, "s": 4000, "text": "5, 30" }, { "code": null, "e": 4009, "s": 4006, "text": "13" } ]
HTML | <img> align Attribute
17 Feb, 2022 The <img> align attribute is used to set the alignment of an image. It is an inline element. It is used to specify the alignment of the image according to surrounding elements. It is not supported by HTML 5. HTML 5 uses CSS property instead of this attribute. Syntax: <img align="left|right|middle|top|bottom"> Attribute Values: left: It sets the alignment of the image to the left. right: It sets the alignment of the image to the right. middle: It sets the alignment of the image to the middle. top: It sets the alignment of the image to the top. bottom: It sets the alignment of the image to the bottom. Example: html <!DOCTYPE html><html> <head> <title> HTML img align Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML img align Attribute</h2> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png" alt="GeeksforGeeks logo" align="right"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png" alt="GeeksforGeeks logo" align="left"></body> </html> Output: Supported Browsers: The browser supported by HTML <img> align Attribute are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTML is the foundation of web pages, is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. chhabradhanvi HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) DOM (Document Object Model) How to make elements float to center? How to Insert Form Data into Database using PHP ? How to Show Images on Click using HTML ? Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Feb, 2022" }, { "code": null, "e": 312, "s": 52, "text": "The <img> align attribute is used to set the alignment of an image. It is an inline element. It is used to specify the alignment of the image according to surrounding elements. It is not supported by HTML 5. HTML 5 uses CSS property instead of this attribute." }, { "code": null, "e": 321, "s": 312, "text": "Syntax: " }, { "code": null, "e": 364, "s": 321, "text": "<img align=\"left|right|middle|top|bottom\">" }, { "code": null, "e": 383, "s": 364, "text": "Attribute Values: " }, { "code": null, "e": 437, "s": 383, "text": "left: It sets the alignment of the image to the left." }, { "code": null, "e": 493, "s": 437, "text": "right: It sets the alignment of the image to the right." }, { "code": null, "e": 551, "s": 493, "text": "middle: It sets the alignment of the image to the middle." }, { "code": null, "e": 603, "s": 551, "text": "top: It sets the alignment of the image to the top." }, { "code": null, "e": 661, "s": 603, "text": "bottom: It sets the alignment of the image to the bottom." }, { "code": null, "e": 671, "s": 661, "text": "Example: " }, { "code": null, "e": 676, "s": 671, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML img align Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML img align Attribute</h2> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png\" alt=\"GeeksforGeeks logo\" align=\"right\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png\" alt=\"GeeksforGeeks logo\" align=\"left\"></body> </html>", "e": 1141, "s": 676, "text": null }, { "code": null, "e": 1151, "s": 1141, "text": "Output: " }, { "code": null, "e": 1242, "s": 1151, "text": "Supported Browsers: The browser supported by HTML <img> align Attribute are listed below: " }, { "code": null, "e": 1256, "s": 1242, "text": "Google Chrome" }, { "code": null, "e": 1274, "s": 1256, "text": "Internet Explorer" }, { "code": null, "e": 1282, "s": 1274, "text": "Firefox" }, { "code": null, "e": 1289, "s": 1282, "text": "Safari" }, { "code": null, "e": 1296, "s": 1289, "text": "Opera " }, { "code": null, "e": 1492, "s": 1296, "text": "HTML is the foundation of web pages, is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 1506, "s": 1492, "text": "chhabradhanvi" }, { "code": null, "e": 1522, "s": 1506, "text": "HTML-Attributes" }, { "code": null, "e": 1527, "s": 1522, "text": "HTML" }, { "code": null, "e": 1544, "s": 1527, "text": "Web Technologies" }, { "code": null, "e": 1549, "s": 1544, "text": "HTML" }, { "code": null, "e": 1647, "s": 1549, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1684, "s": 1647, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 1712, "s": 1684, "text": "DOM (Document Object Model)" }, { "code": null, "e": 1750, "s": 1712, "text": "How to make elements float to center?" }, { "code": null, "e": 1800, "s": 1750, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 1841, "s": 1800, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 1874, "s": 1841, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1935, "s": 1874, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1978, "s": 1935, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2050, "s": 1978, "text": "Differences between Functional Components and Class Components in React" } ]
Exporting a Pandas DataFrame to an Excel file
02 Sep, 2020 Let us see how to export a Pandas DataFrame to an Excel file. Algorithm: Create the DataFrame.Determine the name of the Excel file.Call to_excel() function with the file name to export the DataFrame. Create the DataFrame. Determine the name of the Excel file. Call to_excel() function with the file name to export the DataFrame. Example 1: Python3 # importing the moduleimport pandas as pd # creating the DataFramemarks_data = pd.DataFrame({'ID': {0: 23, 1: 43, 2: 12, 3: 13, 4: 67, 5: 89, 6: 90, 7: 56, 8: 34}, 'Name': {0: 'Ram', 1: 'Deep', 2: 'Yash', 3: 'Aman', 4: 'Arjun', 5: 'Aditya', 6: 'Divya', 7: 'Chalsea', 8: 'Akash' }, 'Marks': {0: 89, 1: 97, 2: 45, 3: 78, 4: 56, 5: 76, 6: 100, 7: 87, 8: 81}, 'Grade': {0: 'B', 1: 'A', 2: 'F', 3: 'C', 4: 'E', 5: 'C', 6: 'A', 7: 'B', 8: 'B'}}) # determining the name of the filefile_name = 'MarksData.xlsx' # saving the excelmarks_data.to_excel(file_name)print('DataFrame is written to Excel File successfully.') Output: DataFrame is written to Excel File successfully. The Excel file is: Example 2: We can also first use the ExcelWriter() method to save it. Python3 # importing the moduleimport pandas as pd # creating the DataFramecars_data = pd.DataFrame({'Cars': ['BMW', 'Audi', 'Bugatti', 'Porsche', 'Volkswagen'], 'MaxSpeed': [220, 230, 240, 210, 190], 'Color': ['Black', 'Red', 'Blue', 'Violet', 'White']}) # writing to Exceldatatoexcel = pd.ExcelWriter('CarsData1.xlsx') # write DataFrame to excelcars_data.to_excel(datatoexcel) # save the exceldatatoexcel.save()print('DataFrame is written to Excel File successfully.') Output: DataFrame is written to Excel File successfully. Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Sep, 2020" }, { "code": null, "e": 91, "s": 28, "text": "Let us see how to export a Pandas DataFrame to an Excel file. " }, { "code": null, "e": 102, "s": 91, "text": "Algorithm:" }, { "code": null, "e": 229, "s": 102, "text": "Create the DataFrame.Determine the name of the Excel file.Call to_excel() function with the file name to export the DataFrame." }, { "code": null, "e": 251, "s": 229, "text": "Create the DataFrame." }, { "code": null, "e": 289, "s": 251, "text": "Determine the name of the Excel file." }, { "code": null, "e": 358, "s": 289, "text": "Call to_excel() function with the file name to export the DataFrame." }, { "code": null, "e": 369, "s": 358, "text": "Example 1:" }, { "code": null, "e": 377, "s": 369, "text": "Python3" }, { "code": "# importing the moduleimport pandas as pd # creating the DataFramemarks_data = pd.DataFrame({'ID': {0: 23, 1: 43, 2: 12, 3: 13, 4: 67, 5: 89, 6: 90, 7: 56, 8: 34}, 'Name': {0: 'Ram', 1: 'Deep', 2: 'Yash', 3: 'Aman', 4: 'Arjun', 5: 'Aditya', 6: 'Divya', 7: 'Chalsea', 8: 'Akash' }, 'Marks': {0: 89, 1: 97, 2: 45, 3: 78, 4: 56, 5: 76, 6: 100, 7: 87, 8: 81}, 'Grade': {0: 'B', 1: 'A', 2: 'F', 3: 'C', 4: 'E', 5: 'C', 6: 'A', 7: 'B', 8: 'B'}}) # determining the name of the filefile_name = 'MarksData.xlsx' # saving the excelmarks_data.to_excel(file_name)print('DataFrame is written to Excel File successfully.')", "e": 1404, "s": 377, "text": null }, { "code": null, "e": 1412, "s": 1404, "text": "Output:" }, { "code": null, "e": 1461, "s": 1412, "text": "DataFrame is written to Excel File successfully." }, { "code": null, "e": 1480, "s": 1461, "text": "The Excel file is:" }, { "code": null, "e": 1550, "s": 1480, "text": "Example 2: We can also first use the ExcelWriter() method to save it." }, { "code": null, "e": 1558, "s": 1550, "text": "Python3" }, { "code": "# importing the moduleimport pandas as pd # creating the DataFramecars_data = pd.DataFrame({'Cars': ['BMW', 'Audi', 'Bugatti', 'Porsche', 'Volkswagen'], 'MaxSpeed': [220, 230, 240, 210, 190], 'Color': ['Black', 'Red', 'Blue', 'Violet', 'White']}) # writing to Exceldatatoexcel = pd.ExcelWriter('CarsData1.xlsx') # write DataFrame to excelcars_data.to_excel(datatoexcel) # save the exceldatatoexcel.save()print('DataFrame is written to Excel File successfully.')", "e": 2145, "s": 1558, "text": null }, { "code": null, "e": 2153, "s": 2145, "text": "Output:" }, { "code": null, "e": 2202, "s": 2153, "text": "DataFrame is written to Excel File successfully." }, { "code": null, "e": 2226, "s": 2202, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2240, "s": 2226, "text": "Python-pandas" }, { "code": null, "e": 2247, "s": 2240, "text": "Python" }, { "code": null, "e": 2345, "s": 2247, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2377, "s": 2345, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2404, "s": 2377, "text": "Python Classes and Objects" }, { "code": null, "e": 2425, "s": 2404, "text": "Python OOPs Concepts" }, { "code": null, "e": 2448, "s": 2425, "text": "Introduction To PYTHON" }, { "code": null, "e": 2504, "s": 2448, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2535, "s": 2504, "text": "Python | os.path.join() method" }, { "code": null, "e": 2577, "s": 2535, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2619, "s": 2577, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2658, "s": 2619, "text": "Python | Get unique values from a list" } ]
Minimize number of boxes by putting small box inside bigger one
25 Apr, 2022 Given an array size[] of box sizes, our task is to find the number of boxes left at the end, after putting the smaller-sized box into a bigger one. Note: Only one small box can fit inside one box.Examples: Input: size[] = {1, 2, 3} Output: 1 Explanation: Here, box of size 1 can fit inside box of size 2 and the box of size 2 can fit inside box of size 3. So at last we have only one box of size 3. Input: size[] = {1, 2, 2, 3, 7, 4, 2, 1} Output: 3 Explanation: Put the box of size 1, 2, 3, 4 and 7 together and for the second box put 1 and 2 together. At last 2 is left which will not fit inside anyone. So we have 3 boxes left. Approach: The idea is to follow the steps given below: Sort the given array size[] in increasing order and check if the current box size is greater than the next box size. If yes then decrease the initial box number. Otherwise, if the current box size is equal to next box size, then check if the current box can fit inside next to next box size. If yes then move the current box pointing variable, else move next pointing variable further. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to minimize the// number of the box by putting small// box inside the bigger one #include <bits/stdc++.h>using namespace std; // Function to minimize the countvoid minBox(int arr[], int n){ // Initial number of box int box = n; // Sort array of box size // in increasing order sort(arr, arr + n); int curr_box = 0, next_box = 1; while (curr_box < n && next_box < n) { // check is current box size // is smaller than next box size if (arr[curr_box] < arr[next_box]) { // Decrement box count // Increment current box count // Increment next box count box--; curr_box++; next_box++; } // Check if both box // have same size else if (arr[curr_box] == arr[next_box]) next_box++; } // Print the result cout << box << endl;} // Driver codeint main(){ int size[] = { 1, 2, 3 }; int n = sizeof(size) / sizeof(size[0]); minBox(size, n); return 0;} // Java implementation to minimize the// number of the box by putting small// box inside the bigger oneimport java.util.Arrays; class GFG{ // Function to minimize the countpublic static void minBox(int arr[], int n){ // Initial number of box int box = n; // Sort array of box size // in increasing order Arrays.sort(arr); int curr_box = 0, next_box = 1; while (curr_box < n && next_box < n) { // Check is current box size // is smaller than next box size if (arr[curr_box] < arr[next_box]) { // Decrement box count // Increment current box count // Increment next box count box--; curr_box++; next_box++; } // Check if both box // have same size else if (arr[curr_box] == arr[next_box]) next_box++; } // Print the result System.out.println(box);} // Driver codepublic static void main(String args[]){ int []size = { 1, 2, 3 }; int n = size.length; minBox(size, n);}} // This code is contributed by SoumikMondal # Python3 implementation to minimize the# number of the box by putting small# box inside the bigger one # Function to minimize the countdef minBox(arr, n): # Initial number of box box = n # Sort array of box size # in increasing order arr.sort() curr_box, next_box = 0, 1 while (curr_box < n and next_box < n): # Check is current box size # is smaller than next box size if (arr[curr_box] < arr[next_box]): # Decrement box count # Increment current box count # Increment next box count box = box - 1 curr_box = curr_box + 1 next_box = next_box + 1 # Check if both box # have same size elif (arr[curr_box] == arr[next_box]): next_box = next_box + 1 # Print the result print(box) # Driver codesize = [ 1, 2, 3 ]n = len(size) minBox(size, n) # This code is contributed by divyeshrabadiya07 // C# implementation to minimize the// number of the box by putting small// box inside the bigger oneusing System; class GFG{ // Function to minimize the countpublic static void minBox(int []arr, int n){ // Initial number of box int box = n; // Sort array of box size // in increasing order Array.Sort(arr); int curr_box = 0, next_box = 1; while (curr_box < n && next_box < n) { // Check is current box size // is smaller than next box size if (arr[curr_box] < arr[next_box]) { // Decrement box count // Increment current box count // Increment next box count box--; curr_box++; next_box++; } // Check if both box // have same size else if (arr[curr_box] == arr[next_box]) next_box++; } // Print the result Console.WriteLine(box);} // Driver codepublic static void Main(String []args){ int []size = { 1, 2, 3 }; int n = size.Length; minBox(size, n);}} // This code is contributed by Amit Katiyar <script> // javascript implementation to minimize the// number of the box by putting small// box inside the bigger one // Function to minimize the countfunction minBox(arr, n){ // Initial number of box var box = n; // Sort array of box size // in increasing order arr.sort(); var curr_box = 0, next_box = 1; while (curr_box < n && next_box < n) { // Check is current box size // is smaller than next box size if (arr[curr_box] < arr[next_box]) { // Decrement box count // Increment current box count // Increment next box count box--; curr_box++; next_box++; } // Check if both box // have same size else if (arr[curr_box] == arr[next_box]) next_box++; } // Print the result document.write(box);} // Driver code var size = [ 1, 2, 3 ]; var n = size.length; minBox(size, n); </script> 1 Time Complexity: O(N*logN) as Arrays.sort() method is used.Auxiliary Space: O(1) Approach: The key observation in the problem is that the minimum number of boxes is same as the maximum frequency of any element in the array. Because the rest of the elements are adjusted into one another. Below is the illustration with the help of steps: Create a Hash-map to store the frequency of the elements. Finally, after maintaining the frequency return the maximum frequency of the element. Below is the implementation of the above approach: C++ Java Python3 Javascript // C++ implementation of the// above approach#include<bits/stdc++.h>using namespace std; // Function to count the boxes// at the endint countBoxes(vector<int>A) { // Default value if // array is empty int count = -1; int n = A.size(); // Map to store frequencies unordered_map<int,int>Map; // Loop to iterate over the // elements of the array for (int i=0; i<n; i++) { int key = A[i]; Map[key]++; int val = Map[key]; // Condition to get the maximum // value of the key if (val > count) count = val; } return count;} // Driver Codeint main(){ vector<int>a = {8, 15, 1, 10, 5, 1}; // Function Call int minBoxes = countBoxes(a); cout<<minBoxes<<endl;} // This code is contributed by shinjanpatra. // Java implementation of the// above approach import java.util.*; public class Boxes { // Function to count the boxes // at the end int countBoxes(int[] A) { // Default value if // array is empty int count = -1; int n = A.length; // Map to store frequencies Map<Integer, Integer> map = new HashMap<>(); // Loop to iterate over the // elements of the array for (int i=0; i<n; i++) { int key = A[i]; map.put(key, map.getOrDefault(key, 0) + 1); int val = map.get(key); // Condition to get the maximum // value of the key if (val > count) count = val; } return count; } // Driver Code public static void main( String[] args) { int[] a = {8, 15, 1, 10, 5, 1}; Boxes obj = new Boxes(); // Function Call int minBoxes = obj.countBoxes(a); System.out.println(minBoxes); }} # Python implementation of the# above approach # Function to count the boxes# at the enddef countBoxes(A): # Default value if # array is empty count = -1 n = len(A) # Map to store frequencies map = {} # Loop to iterate over the # elements of the array for i in range(n): key = A[i] if(key in map): map[key] = map[key]+1 else: map[key] = 1 val = map[key] # Condition to get the maximum # value of the key if (val > count): count = val return count # Driver Codea = [8, 15, 1, 10, 5, 1] # Function CallminBoxes = countBoxes(a)print(minBoxes) # This code is contributed by shinjanpatra. <script> // JavaScript implementation of the// above approach // Function to count the boxes// at the endfunction countBoxes(A) { // Default value if // array is empty let count = -1; let n = A.length; // Map to store frequencies let map = new Map(); // Loop to iterate over the // elements of the array for (let i=0; i<n; i++) { let key = A[i]; if(map.has(key)){ map.set(key,map.get(key)+1); } else map.set(key,1); let val = map.get(key); // Condition to get the maximum // value of the key if (val > count) count = val; } return count; } // Driver Code let a = [8, 15, 1, 10, 5, 1]; // Function Calllet minBoxes = countBoxes(a);document.write(minBoxes,"</br>"); // This code is contributed by shinjanpatra.</script> 2 Time Complexity: O(N)Auxiliary Space: O(N) SoumikMondal amit143katiyar divyeshrabadiya07 hrksom01 bunnyram19 shinjanpatra Arrays Competitive Programming Greedy Sorting Arrays Greedy Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Apr, 2022" }, { "code": null, "e": 261, "s": 54, "text": "Given an array size[] of box sizes, our task is to find the number of boxes left at the end, after putting the smaller-sized box into a bigger one. Note: Only one small box can fit inside one box.Examples: " }, { "code": null, "e": 454, "s": 261, "text": "Input: size[] = {1, 2, 3} Output: 1 Explanation: Here, box of size 1 can fit inside box of size 2 and the box of size 2 can fit inside box of size 3. So at last we have only one box of size 3." }, { "code": null, "e": 687, "s": 454, "text": "Input: size[] = {1, 2, 2, 3, 7, 4, 2, 1} Output: 3 Explanation: Put the box of size 1, 2, 3, 4 and 7 together and for the second box put 1 and 2 together. At last 2 is left which will not fit inside anyone. So we have 3 boxes left. " }, { "code": null, "e": 742, "s": 687, "text": "Approach: The idea is to follow the steps given below:" }, { "code": null, "e": 904, "s": 742, "text": "Sort the given array size[] in increasing order and check if the current box size is greater than the next box size. If yes then decrease the initial box number." }, { "code": null, "e": 1128, "s": 904, "text": "Otherwise, if the current box size is equal to next box size, then check if the current box can fit inside next to next box size. If yes then move the current box pointing variable, else move next pointing variable further." }, { "code": null, "e": 1180, "s": 1128, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1184, "s": 1180, "text": "C++" }, { "code": null, "e": 1189, "s": 1184, "text": "Java" }, { "code": null, "e": 1197, "s": 1189, "text": "Python3" }, { "code": null, "e": 1200, "s": 1197, "text": "C#" }, { "code": null, "e": 1211, "s": 1200, "text": "Javascript" }, { "code": "// C++ implementation to minimize the// number of the box by putting small// box inside the bigger one #include <bits/stdc++.h>using namespace std; // Function to minimize the countvoid minBox(int arr[], int n){ // Initial number of box int box = n; // Sort array of box size // in increasing order sort(arr, arr + n); int curr_box = 0, next_box = 1; while (curr_box < n && next_box < n) { // check is current box size // is smaller than next box size if (arr[curr_box] < arr[next_box]) { // Decrement box count // Increment current box count // Increment next box count box--; curr_box++; next_box++; } // Check if both box // have same size else if (arr[curr_box] == arr[next_box]) next_box++; } // Print the result cout << box << endl;} // Driver codeint main(){ int size[] = { 1, 2, 3 }; int n = sizeof(size) / sizeof(size[0]); minBox(size, n); return 0;}", "e": 2245, "s": 1211, "text": null }, { "code": "// Java implementation to minimize the// number of the box by putting small// box inside the bigger oneimport java.util.Arrays; class GFG{ // Function to minimize the countpublic static void minBox(int arr[], int n){ // Initial number of box int box = n; // Sort array of box size // in increasing order Arrays.sort(arr); int curr_box = 0, next_box = 1; while (curr_box < n && next_box < n) { // Check is current box size // is smaller than next box size if (arr[curr_box] < arr[next_box]) { // Decrement box count // Increment current box count // Increment next box count box--; curr_box++; next_box++; } // Check if both box // have same size else if (arr[curr_box] == arr[next_box]) next_box++; } // Print the result System.out.println(box);} // Driver codepublic static void main(String args[]){ int []size = { 1, 2, 3 }; int n = size.length; minBox(size, n);}} // This code is contributed by SoumikMondal", "e": 3387, "s": 2245, "text": null }, { "code": "# Python3 implementation to minimize the# number of the box by putting small# box inside the bigger one # Function to minimize the countdef minBox(arr, n): # Initial number of box box = n # Sort array of box size # in increasing order arr.sort() curr_box, next_box = 0, 1 while (curr_box < n and next_box < n): # Check is current box size # is smaller than next box size if (arr[curr_box] < arr[next_box]): # Decrement box count # Increment current box count # Increment next box count box = box - 1 curr_box = curr_box + 1 next_box = next_box + 1 # Check if both box # have same size elif (arr[curr_box] == arr[next_box]): next_box = next_box + 1 # Print the result print(box) # Driver codesize = [ 1, 2, 3 ]n = len(size) minBox(size, n) # This code is contributed by divyeshrabadiya07", "e": 4331, "s": 3387, "text": null }, { "code": "// C# implementation to minimize the// number of the box by putting small// box inside the bigger oneusing System; class GFG{ // Function to minimize the countpublic static void minBox(int []arr, int n){ // Initial number of box int box = n; // Sort array of box size // in increasing order Array.Sort(arr); int curr_box = 0, next_box = 1; while (curr_box < n && next_box < n) { // Check is current box size // is smaller than next box size if (arr[curr_box] < arr[next_box]) { // Decrement box count // Increment current box count // Increment next box count box--; curr_box++; next_box++; } // Check if both box // have same size else if (arr[curr_box] == arr[next_box]) next_box++; } // Print the result Console.WriteLine(box);} // Driver codepublic static void Main(String []args){ int []size = { 1, 2, 3 }; int n = size.Length; minBox(size, n);}} // This code is contributed by Amit Katiyar", "e": 5458, "s": 4331, "text": null }, { "code": "<script> // javascript implementation to minimize the// number of the box by putting small// box inside the bigger one // Function to minimize the countfunction minBox(arr, n){ // Initial number of box var box = n; // Sort array of box size // in increasing order arr.sort(); var curr_box = 0, next_box = 1; while (curr_box < n && next_box < n) { // Check is current box size // is smaller than next box size if (arr[curr_box] < arr[next_box]) { // Decrement box count // Increment current box count // Increment next box count box--; curr_box++; next_box++; } // Check if both box // have same size else if (arr[curr_box] == arr[next_box]) next_box++; } // Print the result document.write(box);} // Driver code var size = [ 1, 2, 3 ]; var n = size.length; minBox(size, n); </script>", "e": 6490, "s": 5458, "text": null }, { "code": null, "e": 6492, "s": 6490, "text": "1" }, { "code": null, "e": 6573, "s": 6492, "text": "Time Complexity: O(N*logN) as Arrays.sort() method is used.Auxiliary Space: O(1)" }, { "code": null, "e": 6831, "s": 6573, "text": "Approach: The key observation in the problem is that the minimum number of boxes is same as the maximum frequency of any element in the array. Because the rest of the elements are adjusted into one another. Below is the illustration with the help of steps:" }, { "code": null, "e": 6889, "s": 6831, "text": "Create a Hash-map to store the frequency of the elements." }, { "code": null, "e": 6975, "s": 6889, "text": "Finally, after maintaining the frequency return the maximum frequency of the element." }, { "code": null, "e": 7026, "s": 6975, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 7030, "s": 7026, "text": "C++" }, { "code": null, "e": 7035, "s": 7030, "text": "Java" }, { "code": null, "e": 7043, "s": 7035, "text": "Python3" }, { "code": null, "e": 7054, "s": 7043, "text": "Javascript" }, { "code": "// C++ implementation of the// above approach#include<bits/stdc++.h>using namespace std; // Function to count the boxes// at the endint countBoxes(vector<int>A) { // Default value if // array is empty int count = -1; int n = A.size(); // Map to store frequencies unordered_map<int,int>Map; // Loop to iterate over the // elements of the array for (int i=0; i<n; i++) { int key = A[i]; Map[key]++; int val = Map[key]; // Condition to get the maximum // value of the key if (val > count) count = val; } return count;} // Driver Codeint main(){ vector<int>a = {8, 15, 1, 10, 5, 1}; // Function Call int minBoxes = countBoxes(a); cout<<minBoxes<<endl;} // This code is contributed by shinjanpatra.", "e": 7896, "s": 7054, "text": null }, { "code": "// Java implementation of the// above approach import java.util.*; public class Boxes { // Function to count the boxes // at the end int countBoxes(int[] A) { // Default value if // array is empty int count = -1; int n = A.length; // Map to store frequencies Map<Integer, Integer> map = new HashMap<>(); // Loop to iterate over the // elements of the array for (int i=0; i<n; i++) { int key = A[i]; map.put(key, map.getOrDefault(key, 0) + 1); int val = map.get(key); // Condition to get the maximum // value of the key if (val > count) count = val; } return count; } // Driver Code public static void main( String[] args) { int[] a = {8, 15, 1, 10, 5, 1}; Boxes obj = new Boxes(); // Function Call int minBoxes = obj.countBoxes(a); System.out.println(minBoxes); }}", "e": 8952, "s": 7896, "text": null }, { "code": "# Python implementation of the# above approach # Function to count the boxes# at the enddef countBoxes(A): # Default value if # array is empty count = -1 n = len(A) # Map to store frequencies map = {} # Loop to iterate over the # elements of the array for i in range(n): key = A[i] if(key in map): map[key] = map[key]+1 else: map[key] = 1 val = map[key] # Condition to get the maximum # value of the key if (val > count): count = val return count # Driver Codea = [8, 15, 1, 10, 5, 1] # Function CallminBoxes = countBoxes(a)print(minBoxes) # This code is contributed by shinjanpatra.", "e": 9668, "s": 8952, "text": null }, { "code": "<script> // JavaScript implementation of the// above approach // Function to count the boxes// at the endfunction countBoxes(A) { // Default value if // array is empty let count = -1; let n = A.length; // Map to store frequencies let map = new Map(); // Loop to iterate over the // elements of the array for (let i=0; i<n; i++) { let key = A[i]; if(map.has(key)){ map.set(key,map.get(key)+1); } else map.set(key,1); let val = map.get(key); // Condition to get the maximum // value of the key if (val > count) count = val; } return count; } // Driver Code let a = [8, 15, 1, 10, 5, 1]; // Function Calllet minBoxes = countBoxes(a);document.write(minBoxes,\"</br>\"); // This code is contributed by shinjanpatra.</script>", "e": 10601, "s": 9668, "text": null }, { "code": null, "e": 10603, "s": 10601, "text": "2" }, { "code": null, "e": 10646, "s": 10603, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 10659, "s": 10646, "text": "SoumikMondal" }, { "code": null, "e": 10674, "s": 10659, "text": "amit143katiyar" }, { "code": null, "e": 10692, "s": 10674, "text": "divyeshrabadiya07" }, { "code": null, "e": 10701, "s": 10692, "text": "hrksom01" }, { "code": null, "e": 10712, "s": 10701, "text": "bunnyram19" }, { "code": null, "e": 10725, "s": 10712, "text": "shinjanpatra" }, { "code": null, "e": 10732, "s": 10725, "text": "Arrays" }, { "code": null, "e": 10756, "s": 10732, "text": "Competitive Programming" }, { "code": null, "e": 10763, "s": 10756, "text": "Greedy" }, { "code": null, "e": 10771, "s": 10763, "text": "Sorting" }, { "code": null, "e": 10778, "s": 10771, "text": "Arrays" }, { "code": null, "e": 10785, "s": 10778, "text": "Greedy" }, { "code": null, "e": 10793, "s": 10785, "text": "Sorting" } ]
Image Filtering Using Convolution in OpenCV
16 Oct, 2021 Prerequisites: Basics of OpenCV, Basics of Convolution In this article, filtering of images using convolution in OpenCV (Open Source Computer Vision) is discussed. In order to use the OpenCV library in Python, the following libraries should be installed as a prerequisite: Numpy library Matplotlib library OpenCV library To install the following libraries, run the following commands in the command prompt: pip install opencv-python pip install numpy pip install matplotlib The fundamental and the most basic operation in image processing is convolution. This can be achieved by using Kernels. Kernel is a matrix that is generally smaller than the image and the center of the kernel matrix coincides with the pixels. In a 2D Convolution, the kernel matrix is a 2-dimensional, Square, A x B matrix, where both A and B are odd integers The position of the output image is obtained by multiplying each value of the matrix with the corresponding value of the image matrix and then summing them up. Based on these operations performed, various effects like blurring and sharpening of the images can be performed. Identity Kernel is the simplest and the most basic kernel operation that could be performed. The output image produced is exactly like the image that is given as the input. It does change the input image. It is a square matrix with the center element equal to 1. All the other elements of the matrix are 0. The code given below demonstrates the operation of Identity Kernel: Image used : Python3 # Importing OpenCV and Numpy Librariesimport cv2import numpy as np # Reads image from the disk using cv2.imread() function img = cv2.imread('geeksforgeeks.png') # Apply identity kernel# In an Identity Kernel matrix the value of the middle element is 1# The values of all the other elements are 0id_kernel = np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) # Filtered image is obtained using the variable flt_img# cv2.fliter2D() is the function used# src is the source of image(here, img)# ddepth is destination depth. -1 will mean output image will have same depth as input image# kernel is used for specifying the kernel operation (here, id_kernel)flt_img = cv2.filter2D(src=img, ddepth=-1, kernel=id_kernel) # Display the filtered image using cv2.imshow() function# Here, output image is same as input image since we are using identity kernelcv2.imshow('Identity', flt_img) # cv2.waitkey(delay) function holds the screen till any key is pressed by the user# It pauses the screen for delay milliseconds if the delay is a positive value# It pauses the screen for a key event infinitely if the delay is 0 or negativecv2.waitKey(0) # cv2.destroyAllWindows() function deletes all the GUI windows from memorycv2.destroyAllWindows() Output : Blurring is defined as averaging the values of the pixel within a neighborhood. This averaging effect makes the sharp edges smooth or blur. The blurring effect is also said to have ‘Low pass filter’ effect because it allows only low frequencies (low rate of change of pixels) to enter through it. Steps involved in Blurring an Image : Choose the size of the kernel over a pixel (p). Larger the size of the kernel, the greater the smoothening effect. This is because, large kernels produce large averaging values with respect to the neighboring pixels and thus, results in a high amount of smoothening. Multiply each value of the kernel with the corresponding value of the image matrix. Add the results of multiplications and compute the average and obtain the Resultant. Lastly, replace the value of pixel (p) with the results obtained. This is obtained by uniformly averaging the values in the neighborhood. It is a straightforward blur. It is represented as follows: The values should be summed up to 1. This is why we divide the matrix by 9. This is called Normalization. Following below is the code to demonstrate the Box Blurring Effect : Python3 # Importing the OpenCV, Numpy and Mat librariesimport cv2import numpy as npimport matplotlib.pyplot as plt # Reading the image from the disk using cv2.imread() function# Showing the original image using matplotlib library function plt.imshow()img = cv2.imread('geeksforgeeks.png')plt.imshow(img)plt.show() # Kernel for box blur filter# It is a unity matrix which is divided by 9 box_blur_ker = np.array([[0.1111111, 0.1111111, 0.1111111], [0.1111111, 0.1111111, 0.1111111], [0.1111111, 0.1111111, 0.1111111]]) # Applying Box Blur effect# Using the cv2.filter2D() function# src is the source of image(here, img)# ddepth is destination depth. -1 will mean output image will have same depth as input image# kernel is used for specifying the kernel operation (here, box_blur_ker)Box_blur = cv2.filter2D(src=img, ddepth=-1, kernel=box_blur_ker) # Showing the box blur image using matplotlib library function plt.imshow()plt.imshow(Box_blur)plt.show() Output : This filter can be obtained by finding the weighted average of the pixel. The weights of the pixels are calculated on the basis of distance from the center of the kernel. Pixels nearer to the center of the kernel influence more on the weighted average. The Gaussian filter requires 2 specifications – standard deviation in the X-axis and standard deviation in the Y-axis, represented as sigmaX and sigmaY respectively. If they are both set to 0, the kernel size is taken for calculating the standard deviation. The code given below demonstrates Gaussian Blur Filter: Python3 # Importing the OpenCV, Numpy and Matplotlib librariesimport cv2import numpy as npimport matplotlib.pyplot as plt # Reading the image from the disk using cv2.imread() function# Showing the original image using matplotlib library function plt.imshow()img = cv2.imread('geeksforgeeks.png')plt.imshow(img)plt.show() # Applying Gaussian Blur Filter using cv2.GaussianBlur() function# src is the source of image(here, img)# ksize is the size of kernel in the form A x B (here 3 x 3)# sigmaX is standard deviation of X axis# sigmaY is the standard deviation of Y axis# Since sigmaX and sigmaY is 0, the standard deviation the size of kernelgaussian_blur = cv2.GaussianBlur(src=img, ksize=(3,3),sigmaX=0, sigmaY=0) # Showing the Gaussian blur image using matplotlib library function plt.imshow()plt.imshow(gaussian_blur)plt.show() Output : The Median Blur filtering effect is obtained when every pixel value is replaced with the median value of the image pixels in the neighborhood. The code given below demonstrates Median Blur: Python3 # Importing the OpenCV, Numpy and Matplotlib librariesimport cv2import numpy as npimport matplotlib.pyplot as plt # Reading the image from the disk using cv2.imread() function# Showing the original image using matplotlib library function plt.imshow()img = cv2.imread('geeksforgeeks.png')plt.imshow(img)plt.show() # Applying median Blur Filter using cv2.medianBlur() function# src is the source of image(here, img)# ksize is the size of kernel. Should have a positive odd valuemedian_blur = cv2.medianBlur(src=img, ksize=9) # Showing the Median blur image using matplotlib library function plt.imshow()plt.imshow(median_blur)plt.show() Output : Image sharpening helps in enhancing the edges and making them crisp. This filter helps in sharpening the edges and making the image look prominent. The features in the image look distinctive on using this filter. We use a custom 2D kernel in order to apply this filtering technique. The following kernel can be used for sharpening the image: The Code given below demonstrates the usage of sharpening filter: Python3 # Importing the OpenCV, Numpy and Matplotlib librariesimport cv2import numpy as npimport matplotlib.pyplot as plt # Reading the image from the disk using cv2.imread() function# Showing the original image using matplotlib library function plt.imshow()img = cv2.imread('geeksforgeeks.png')plt.imshow(img)plt.show() # Apply kernel for sharpeningsharp_kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]]) # Sharpeneded image is obtained using the variable sharp_img# cv2.fliter2D() is the function used# src is the source of image(here, img)# ddepth is destination depth. -1 will mean output image will have same depth as input image# kernel is used for specifying the kernel operation (here, sharp_kernel)sharp_img = cv2.filter2D(src=img, ddepth=-1, kernel=sharp_kernel) # Showing the sharpened image using matplotlib library function plt.imshow()plt.imshow(sharp_img)plt.show() Output : Forming a 3D design that pops out of the surface is called Emboss. It replaces the pixel with a shadow or a highlight. The following kernel matrix can be used to apply to emboss filter: The following code demonstrates the application of the embossing filter: Python3 # Importing the OpenCV, Numpy and Matplotlib librariesimport cv2import numpy as npimport matplotlib.pyplot as plt # Reading the image from the disk using cv2.imread() function# Showing the original image using matplotlib library function plt.imshow()img = cv2.imread('geeksforgeeks.png')plt.imshow(img)plt.show() # Apply kernel for embossingemboss_kernel = np.array([[-1, 0, 0], [0, 0, 0], [0, 0, 1]]) # Embossed image is obtained using the variable emboss_img# cv2.fliter2D() is the function used# src is the source of image(here, img)# ddepth is destination depth. -1 will mean output image will have same depth as input image# kernel is used for specifying the kernel operation (here, emboss_kernel)emboss_img = cv2.filter2D(src=img, ddepth=-1, kernel=emboss_kernel) # Showing the embossed image using matplotlib library function plt.imshow()plt.imshow(emboss_img)plt.show() Output : Picked Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Oct, 2021" }, { "code": null, "e": 83, "s": 28, "text": "Prerequisites: Basics of OpenCV, Basics of Convolution" }, { "code": null, "e": 301, "s": 83, "text": "In this article, filtering of images using convolution in OpenCV (Open Source Computer Vision) is discussed. In order to use the OpenCV library in Python, the following libraries should be installed as a prerequisite:" }, { "code": null, "e": 315, "s": 301, "text": "Numpy library" }, { "code": null, "e": 334, "s": 315, "text": "Matplotlib library" }, { "code": null, "e": 349, "s": 334, "text": "OpenCV library" }, { "code": null, "e": 435, "s": 349, "text": "To install the following libraries, run the following commands in the command prompt:" }, { "code": null, "e": 505, "s": 435, "text": " pip install opencv-python\n pip install numpy\n pip install matplotlib" }, { "code": null, "e": 750, "s": 505, "text": "The fundamental and the most basic operation in image processing is convolution. This can be achieved by using Kernels. Kernel is a matrix that is generally smaller than the image and the center of the kernel matrix coincides with the pixels. " }, { "code": null, "e": 869, "s": 750, "text": "In a 2D Convolution, the kernel matrix is a 2-dimensional, Square, A x B matrix, where both A and B are odd integers " }, { "code": null, "e": 1143, "s": 869, "text": "The position of the output image is obtained by multiplying each value of the matrix with the corresponding value of the image matrix and then summing them up. Based on these operations performed, various effects like blurring and sharpening of the images can be performed." }, { "code": null, "e": 1518, "s": 1143, "text": "Identity Kernel is the simplest and the most basic kernel operation that could be performed. The output image produced is exactly like the image that is given as the input. It does change the input image. It is a square matrix with the center element equal to 1. All the other elements of the matrix are 0. The code given below demonstrates the operation of Identity Kernel:" }, { "code": null, "e": 1532, "s": 1518, "text": "Image used : " }, { "code": null, "e": 1540, "s": 1532, "text": "Python3" }, { "code": "# Importing OpenCV and Numpy Librariesimport cv2import numpy as np # Reads image from the disk using cv2.imread() function img = cv2.imread('geeksforgeeks.png') # Apply identity kernel# In an Identity Kernel matrix the value of the middle element is 1# The values of all the other elements are 0id_kernel = np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) # Filtered image is obtained using the variable flt_img# cv2.fliter2D() is the function used# src is the source of image(here, img)# ddepth is destination depth. -1 will mean output image will have same depth as input image# kernel is used for specifying the kernel operation (here, id_kernel)flt_img = cv2.filter2D(src=img, ddepth=-1, kernel=id_kernel) # Display the filtered image using cv2.imshow() function# Here, output image is same as input image since we are using identity kernelcv2.imshow('Identity', flt_img) # cv2.waitkey(delay) function holds the screen till any key is pressed by the user# It pauses the screen for delay milliseconds if the delay is a positive value# It pauses the screen for a key event infinitely if the delay is 0 or negativecv2.waitKey(0) # cv2.destroyAllWindows() function deletes all the GUI windows from memorycv2.destroyAllWindows()", "e": 2807, "s": 1540, "text": null }, { "code": null, "e": 2817, "s": 2807, "text": "Output : " }, { "code": null, "e": 3115, "s": 2817, "text": "Blurring is defined as averaging the values of the pixel within a neighborhood. This averaging effect makes the sharp edges smooth or blur. The blurring effect is also said to have ‘Low pass filter’ effect because it allows only low frequencies (low rate of change of pixels) to enter through it. " }, { "code": null, "e": 3153, "s": 3115, "text": "Steps involved in Blurring an Image :" }, { "code": null, "e": 3420, "s": 3153, "text": "Choose the size of the kernel over a pixel (p). Larger the size of the kernel, the greater the smoothening effect. This is because, large kernels produce large averaging values with respect to the neighboring pixels and thus, results in a high amount of smoothening." }, { "code": null, "e": 3504, "s": 3420, "text": "Multiply each value of the kernel with the corresponding value of the image matrix." }, { "code": null, "e": 3589, "s": 3504, "text": "Add the results of multiplications and compute the average and obtain the Resultant." }, { "code": null, "e": 3655, "s": 3589, "text": "Lastly, replace the value of pixel (p) with the results obtained." }, { "code": null, "e": 3787, "s": 3655, "text": "This is obtained by uniformly averaging the values in the neighborhood. It is a straightforward blur. It is represented as follows:" }, { "code": null, "e": 3962, "s": 3787, "text": "The values should be summed up to 1. This is why we divide the matrix by 9. This is called Normalization. Following below is the code to demonstrate the Box Blurring Effect :" }, { "code": null, "e": 3970, "s": 3962, "text": "Python3" }, { "code": "# Importing the OpenCV, Numpy and Mat librariesimport cv2import numpy as npimport matplotlib.pyplot as plt # Reading the image from the disk using cv2.imread() function# Showing the original image using matplotlib library function plt.imshow()img = cv2.imread('geeksforgeeks.png')plt.imshow(img)plt.show() # Kernel for box blur filter# It is a unity matrix which is divided by 9 box_blur_ker = np.array([[0.1111111, 0.1111111, 0.1111111], [0.1111111, 0.1111111, 0.1111111], [0.1111111, 0.1111111, 0.1111111]]) # Applying Box Blur effect# Using the cv2.filter2D() function# src is the source of image(here, img)# ddepth is destination depth. -1 will mean output image will have same depth as input image# kernel is used for specifying the kernel operation (here, box_blur_ker)Box_blur = cv2.filter2D(src=img, ddepth=-1, kernel=box_blur_ker) # Showing the box blur image using matplotlib library function plt.imshow()plt.imshow(Box_blur)plt.show()", "e": 4958, "s": 3970, "text": null }, { "code": null, "e": 4968, "s": 4958, "text": "Output : " }, { "code": null, "e": 5221, "s": 4968, "text": "This filter can be obtained by finding the weighted average of the pixel. The weights of the pixels are calculated on the basis of distance from the center of the kernel. Pixels nearer to the center of the kernel influence more on the weighted average." }, { "code": null, "e": 5479, "s": 5221, "text": "The Gaussian filter requires 2 specifications – standard deviation in the X-axis and standard deviation in the Y-axis, represented as sigmaX and sigmaY respectively. If they are both set to 0, the kernel size is taken for calculating the standard deviation." }, { "code": null, "e": 5535, "s": 5479, "text": "The code given below demonstrates Gaussian Blur Filter:" }, { "code": null, "e": 5543, "s": 5535, "text": "Python3" }, { "code": "# Importing the OpenCV, Numpy and Matplotlib librariesimport cv2import numpy as npimport matplotlib.pyplot as plt # Reading the image from the disk using cv2.imread() function# Showing the original image using matplotlib library function plt.imshow()img = cv2.imread('geeksforgeeks.png')plt.imshow(img)plt.show() # Applying Gaussian Blur Filter using cv2.GaussianBlur() function# src is the source of image(here, img)# ksize is the size of kernel in the form A x B (here 3 x 3)# sigmaX is standard deviation of X axis# sigmaY is the standard deviation of Y axis# Since sigmaX and sigmaY is 0, the standard deviation the size of kernelgaussian_blur = cv2.GaussianBlur(src=img, ksize=(3,3),sigmaX=0, sigmaY=0) # Showing the Gaussian blur image using matplotlib library function plt.imshow()plt.imshow(gaussian_blur)plt.show()", "e": 6370, "s": 5543, "text": null }, { "code": null, "e": 6379, "s": 6370, "text": "Output :" }, { "code": null, "e": 6523, "s": 6379, "text": "The Median Blur filtering effect is obtained when every pixel value is replaced with the median value of the image pixels in the neighborhood. " }, { "code": null, "e": 6570, "s": 6523, "text": "The code given below demonstrates Median Blur:" }, { "code": null, "e": 6578, "s": 6570, "text": "Python3" }, { "code": "# Importing the OpenCV, Numpy and Matplotlib librariesimport cv2import numpy as npimport matplotlib.pyplot as plt # Reading the image from the disk using cv2.imread() function# Showing the original image using matplotlib library function plt.imshow()img = cv2.imread('geeksforgeeks.png')plt.imshow(img)plt.show() # Applying median Blur Filter using cv2.medianBlur() function# src is the source of image(here, img)# ksize is the size of kernel. Should have a positive odd valuemedian_blur = cv2.medianBlur(src=img, ksize=9) # Showing the Median blur image using matplotlib library function plt.imshow()plt.imshow(median_blur)plt.show()", "e": 7216, "s": 6578, "text": null }, { "code": null, "e": 7226, "s": 7216, "text": "Output : " }, { "code": null, "e": 7439, "s": 7226, "text": "Image sharpening helps in enhancing the edges and making them crisp. This filter helps in sharpening the edges and making the image look prominent. The features in the image look distinctive on using this filter." }, { "code": null, "e": 7568, "s": 7439, "text": "We use a custom 2D kernel in order to apply this filtering technique. The following kernel can be used for sharpening the image:" }, { "code": null, "e": 7634, "s": 7568, "text": "The Code given below demonstrates the usage of sharpening filter:" }, { "code": null, "e": 7642, "s": 7634, "text": "Python3" }, { "code": "# Importing the OpenCV, Numpy and Matplotlib librariesimport cv2import numpy as npimport matplotlib.pyplot as plt # Reading the image from the disk using cv2.imread() function# Showing the original image using matplotlib library function plt.imshow()img = cv2.imread('geeksforgeeks.png')plt.imshow(img)plt.show() # Apply kernel for sharpeningsharp_kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]]) # Sharpeneded image is obtained using the variable sharp_img# cv2.fliter2D() is the function used# src is the source of image(here, img)# ddepth is destination depth. -1 will mean output image will have same depth as input image# kernel is used for specifying the kernel operation (here, sharp_kernel)sharp_img = cv2.filter2D(src=img, ddepth=-1, kernel=sharp_kernel) # Showing the sharpened image using matplotlib library function plt.imshow()plt.imshow(sharp_img)plt.show()", "e": 8564, "s": 7642, "text": null }, { "code": null, "e": 8574, "s": 8564, "text": "Output : " }, { "code": null, "e": 8694, "s": 8574, "text": "Forming a 3D design that pops out of the surface is called Emboss. It replaces the pixel with a shadow or a highlight. " }, { "code": null, "e": 8761, "s": 8694, "text": "The following kernel matrix can be used to apply to emboss filter:" }, { "code": null, "e": 8834, "s": 8761, "text": "The following code demonstrates the application of the embossing filter:" }, { "code": null, "e": 8842, "s": 8834, "text": "Python3" }, { "code": "# Importing the OpenCV, Numpy and Matplotlib librariesimport cv2import numpy as npimport matplotlib.pyplot as plt # Reading the image from the disk using cv2.imread() function# Showing the original image using matplotlib library function plt.imshow()img = cv2.imread('geeksforgeeks.png')plt.imshow(img)plt.show() # Apply kernel for embossingemboss_kernel = np.array([[-1, 0, 0], [0, 0, 0], [0, 0, 1]]) # Embossed image is obtained using the variable emboss_img# cv2.fliter2D() is the function used# src is the source of image(here, img)# ddepth is destination depth. -1 will mean output image will have same depth as input image# kernel is used for specifying the kernel operation (here, emboss_kernel)emboss_img = cv2.filter2D(src=img, ddepth=-1, kernel=emboss_kernel) # Showing the embossed image using matplotlib library function plt.imshow()plt.imshow(emboss_img)plt.show()", "e": 9762, "s": 8842, "text": null }, { "code": null, "e": 9772, "s": 9762, "text": "Output : " }, { "code": null, "e": 9779, "s": 9772, "text": "Picked" }, { "code": null, "e": 9786, "s": 9779, "text": "Python" }, { "code": null, "e": 9884, "s": 9786, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9916, "s": 9884, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 9943, "s": 9916, "text": "Python Classes and Objects" }, { "code": null, "e": 9964, "s": 9943, "text": "Python OOPs Concepts" }, { "code": null, "e": 9987, "s": 9964, "text": "Introduction To PYTHON" }, { "code": null, "e": 10043, "s": 9987, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 10074, "s": 10043, "text": "Python | os.path.join() method" }, { "code": null, "e": 10116, "s": 10074, "text": "Check if element exists in list in Python" }, { "code": null, "e": 10158, "s": 10116, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 10197, "s": 10158, "text": "Python | Get unique values from a list" } ]
How to see cache statistics in Linux?
31 Jan, 2019 Cache is a very important part of the computer hardware to give superfast response time. Cache PerformanceWhen the processor needs to read or write a location in main memory, it first checks for a corresponding entry in the cache. If the processor finds that the memory location is in the cache, a cache hit has occurred and data is read from cacheIf the processor does not find the memory location in the cache, a cache miss has occurred. For a cache miss, the cache allocates a new entry and copies in data from main memory, then the request is fulfilled from the contents of the cache. The performance of cache memory is frequently measured in terms of a quantity called Hit ratio. Hit ratio = hit / (hit + miss) = no. of hits/total accesses To monitor the performance of your cache, linux provides some excellent library: Cachestat. Cachestat is not directly available, it is deprecated by linux.Cachestat uses the perf tools, which is a part of linux-tools library. To install perf-tools, open terminal and run: sudo apt-get install linux-tools-common linux-tools-generic Then, to install cachestat, run: wget https://raw.githubusercontent.com/brendangregg/perf-tools/master/fs/cachestat To make it executable, run: chmod +x cachestat Finally run it: sudo ./cachestat If you get a lot of misses, you should probably run diagnostics. This article is contributed by Suprotik Dey. 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. linux-command Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Jan, 2019" }, { "code": null, "e": 117, "s": 28, "text": "Cache is a very important part of the computer hardware to give superfast response time." }, { "code": null, "e": 259, "s": 117, "text": "Cache PerformanceWhen the processor needs to read or write a location in main memory, it first checks for a corresponding entry in the cache." }, { "code": null, "e": 617, "s": 259, "text": "If the processor finds that the memory location is in the cache, a cache hit has occurred and data is read from cacheIf the processor does not find the memory location in the cache, a cache miss has occurred. For a cache miss, the cache allocates a new entry and copies in data from main memory, then the request is fulfilled from the contents of the cache." }, { "code": null, "e": 713, "s": 617, "text": "The performance of cache memory is frequently measured in terms of a quantity called Hit ratio." }, { "code": null, "e": 774, "s": 713, "text": "Hit ratio = hit / (hit + miss) = no. of hits/total accesses" }, { "code": null, "e": 866, "s": 774, "text": "To monitor the performance of your cache, linux provides some excellent library: Cachestat." }, { "code": null, "e": 1000, "s": 866, "text": "Cachestat is not directly available, it is deprecated by linux.Cachestat uses the perf tools, which is a part of linux-tools library." }, { "code": null, "e": 1046, "s": 1000, "text": "To install perf-tools, open terminal and run:" }, { "code": null, "e": 1106, "s": 1046, "text": "sudo apt-get install linux-tools-common linux-tools-generic" }, { "code": null, "e": 1139, "s": 1106, "text": "Then, to install cachestat, run:" }, { "code": null, "e": 1222, "s": 1139, "text": "wget https://raw.githubusercontent.com/brendangregg/perf-tools/master/fs/cachestat" }, { "code": null, "e": 1250, "s": 1222, "text": "To make it executable, run:" }, { "code": null, "e": 1269, "s": 1250, "text": "chmod +x cachestat" }, { "code": null, "e": 1285, "s": 1269, "text": "Finally run it:" }, { "code": null, "e": 1302, "s": 1285, "text": "sudo ./cachestat" }, { "code": null, "e": 1367, "s": 1302, "text": "If you get a lot of misses, you should probably run diagnostics." }, { "code": null, "e": 1667, "s": 1367, "text": "This article is contributed by Suprotik Dey. 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": 1792, "s": 1667, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1806, "s": 1792, "text": "linux-command" }, { "code": null, "e": 1817, "s": 1806, "text": "Linux-Unix" } ]
jQuery | filter() with Examples
13 Feb, 2019 The jQuery is a very powerful tool which helps us to incorporate a variety of DOM traversal methods to select elements in a document randomly or in sequential order. Most of the DOM traversal methods do not modify the elements whereas they filter them out upon the given conditions.The filter() method is used to filter out all the elements that do not match the selected criteria and those matches will be returned.Syntax: $(selector).filter(criteria, function(index)) Parameters:criteria : It specifies a selector expression, a jQuery object or one or more elements to be returned from a group of selected elements.function(index) : It specifies a function to run for each element in the set. If the function returns true, the element is kept. Otherwise, it is removed.index : The index position of the element in the set.NOTE : To specify more than one criteria, use a comma. <html> <head> <title>GEEKS FOR GEEKS ARTICLE</title> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("li").filter(".first, .last").css("color", "red") .css("backgroundColor", "yellow"); }); </script></head> <body> <ul> <li class="first">GeeksForGeeks</li> <li class="first">GeeksForGeeks</li> <li class="middle">GeeksForGeeks</li> <li class="last">GeeksForGeeks</li> <li class="last">GeeksForGeeks</li> </ul></body> </html> Output:Code #2:This code will select the elements matching with the criteria checked by the function. Here, the function checks for two elements in a list and returns true or false. <html> <head> <title>GEEKS FOR GEEKS ARTICLE</title> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("ul").filter(function() { return $("li", this).length == 2; }).css("color", "red").css("fontSize", "20"); }); </script></head> <body> A list with two elements: <ul> <li>option1</li> <li>option2</li> </ul> A list with one element: <ul> <li>option1</li> </ul> A list with two elements: <ul> <li>option1</li> <li>option2</li> </ul> A list with three elements: <ul> <li>option1</li> </ul> <ul> <li>option2</li> </ul> <ul> <li>option3</li> </ul></body> </html> Output: jQuery-Traversing JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Difference Between PUT and PATCH Request JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to add options to a select element using jQuery? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Feb, 2019" }, { "code": null, "e": 452, "s": 28, "text": "The jQuery is a very powerful tool which helps us to incorporate a variety of DOM traversal methods to select elements in a document randomly or in sequential order. Most of the DOM traversal methods do not modify the elements whereas they filter them out upon the given conditions.The filter() method is used to filter out all the elements that do not match the selected criteria and those matches will be returned.Syntax:" }, { "code": null, "e": 498, "s": 452, "text": "$(selector).filter(criteria, function(index))" }, { "code": null, "e": 907, "s": 498, "text": "Parameters:criteria : It specifies a selector expression, a jQuery object or one or more elements to be returned from a group of selected elements.function(index) : It specifies a function to run for each element in the set. If the function returns true, the element is kept. Otherwise, it is removed.index : The index position of the element in the set.NOTE : To specify more than one criteria, use a comma." }, { "code": "<html> <head> <title>GEEKS FOR GEEKS ARTICLE</title> <script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js\"></script> <script type=\"text/javascript\"> $(document).ready(function() { $(\"li\").filter(\".first, .last\").css(\"color\", \"red\") .css(\"backgroundColor\", \"yellow\"); }); </script></head> <body> <ul> <li class=\"first\">GeeksForGeeks</li> <li class=\"first\">GeeksForGeeks</li> <li class=\"middle\">GeeksForGeeks</li> <li class=\"last\">GeeksForGeeks</li> <li class=\"last\">GeeksForGeeks</li> </ul></body> </html>", "e": 1550, "s": 907, "text": null }, { "code": null, "e": 1732, "s": 1550, "text": "Output:Code #2:This code will select the elements matching with the criteria checked by the function. Here, the function checks for two elements in a list and returns true or false." }, { "code": "<html> <head> <title>GEEKS FOR GEEKS ARTICLE</title> <script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js\"></script> <script type=\"text/javascript\"> $(document).ready(function() { $(\"ul\").filter(function() { return $(\"li\", this).length == 2; }).css(\"color\", \"red\").css(\"fontSize\", \"20\"); }); </script></head> <body> A list with two elements: <ul> <li>option1</li> <li>option2</li> </ul> A list with one element: <ul> <li>option1</li> </ul> A list with two elements: <ul> <li>option1</li> <li>option2</li> </ul> A list with three elements: <ul> <li>option1</li> </ul> <ul> <li>option2</li> </ul> <ul> <li>option3</li> </ul></body> </html>", "e": 2582, "s": 1732, "text": null }, { "code": null, "e": 2590, "s": 2582, "text": "Output:" }, { "code": null, "e": 2608, "s": 2590, "text": "jQuery-Traversing" }, { "code": null, "e": 2619, "s": 2608, "text": "JavaScript" }, { "code": null, "e": 2626, "s": 2619, "text": "JQuery" }, { "code": null, "e": 2724, "s": 2626, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2785, "s": 2724, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2857, "s": 2785, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2897, "s": 2857, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2950, "s": 2897, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2991, "s": 2950, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3037, "s": 2991, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 3066, "s": 3037, "text": "Form validation using jQuery" }, { "code": null, "e": 3129, "s": 3066, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 3182, "s": 3129, "text": "How to add options to a select element using jQuery?" } ]
PHP | mysqli_fetch_array() Function
23 Apr, 2020 The mysqli_fetch_array() function is used to fetch rows from the database and store them as an array. The array can be fetched as an associative array, as a numeric array or both. Associative arrays are the arrays where the indexes are the names of the individual columns of the table. On the other hand, numeric arrays are arrays where indexes are numbers, with 0 representing the first column and n-1 representing the last column of an n-column table. Syntax: mysqli_fetch_array ("database_name", "mode") Parameters: This function accepts two parameters as mentioned above and described below: database_name: It is the database on which operations are being performed. It is a mandatory parameter. mode: It can have three values – MYSQLI_ASSOC, MYSQLI_NUM, and MYSQLI_BOTH. MYSQLI_ASSOC makes the function behave like mysqli_fetch_assoc() function, fetching an associative array, MYSQLI_NUM makes the function behave like mysqli_fetch_row() function, fetching a numeric array while MYSQLI_BOTH stores the data fetched in an array that can be accessed using both column indexes as well as column names. Program: <?php $conn = mysqli_connect( "localhost", "root", "", "Persons"); // Check connection if (mysqli_connect_errno()) { echo "Database connection failed."; } $sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname";$result -> $mysqli -> query($sql); // Numeric array$row = mysqli_fetch_array($conn, MYSQLI_NUM);printf ("%s (%s)\n", $row[0], $row[1]); printf("\n"); // Associative array$row = mysqli_fetch_array($conn, MYSQLI_ASSOC);printf ("%s (%s)\n", $row["Firstname"], $row["Lastname"]); mysqli_close($conn);?> For the above table, the output will be:Output: A B C D E F G H A B C D E F G H PHP-function PHP-MySQL PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? PHP in_array() Function How to delete an array element based on key in PHP? How to Insert Form Data into Database using PHP ? How to convert array to 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": "\n23 Apr, 2020" }, { "code": null, "e": 208, "s": 28, "text": "The mysqli_fetch_array() function is used to fetch rows from the database and store them as an array. The array can be fetched as an associative array, as a numeric array or both." }, { "code": null, "e": 482, "s": 208, "text": "Associative arrays are the arrays where the indexes are the names of the individual columns of the table. On the other hand, numeric arrays are arrays where indexes are numbers, with 0 representing the first column and n-1 representing the last column of an n-column table." }, { "code": null, "e": 490, "s": 482, "text": "Syntax:" }, { "code": null, "e": 536, "s": 490, "text": "mysqli_fetch_array (\"database_name\", \"mode\")\n" }, { "code": null, "e": 625, "s": 536, "text": "Parameters: This function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 729, "s": 625, "text": "database_name: It is the database on which operations are being performed. It is a mandatory parameter." }, { "code": null, "e": 1133, "s": 729, "text": "mode: It can have three values – MYSQLI_ASSOC, MYSQLI_NUM, and MYSQLI_BOTH. MYSQLI_ASSOC makes the function behave like mysqli_fetch_assoc() function, fetching an associative array, MYSQLI_NUM makes the function behave like mysqli_fetch_row() function, fetching a numeric array while MYSQLI_BOTH stores the data fetched in an array that can be accessed using both column indexes as well as column names." }, { "code": null, "e": 1142, "s": 1133, "text": "Program:" }, { "code": "<?php $conn = mysqli_connect( \"localhost\", \"root\", \"\", \"Persons\"); // Check connection if (mysqli_connect_errno()) { echo \"Database connection failed.\"; } $sql = \"SELECT Lastname, Age FROM Persons ORDER BY Lastname\";$result -> $mysqli -> query($sql); // Numeric array$row = mysqli_fetch_array($conn, MYSQLI_NUM);printf (\"%s (%s)\\n\", $row[0], $row[1]); printf(\"\\n\"); // Associative array$row = mysqli_fetch_array($conn, MYSQLI_ASSOC);printf (\"%s (%s)\\n\", $row[\"Firstname\"], $row[\"Lastname\"]); mysqli_close($conn);?>", "e": 1679, "s": 1142, "text": null }, { "code": null, "e": 1727, "s": 1679, "text": "For the above table, the output will be:Output:" }, { "code": null, "e": 1785, "s": 1727, "text": "A B\nC D\nE F\nG H\n\nA B\nC D\nE F\nG H\n" }, { "code": null, "e": 1798, "s": 1785, "text": "PHP-function" }, { "code": null, "e": 1808, "s": 1798, "text": "PHP-MySQL" }, { "code": null, "e": 1812, "s": 1808, "text": "PHP" }, { "code": null, "e": 1829, "s": 1812, "text": "Web Technologies" }, { "code": null, "e": 1833, "s": 1829, "text": "PHP" }, { "code": null, "e": 1931, "s": 1833, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1976, "s": 1931, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 2000, "s": 1976, "text": "PHP in_array() Function" }, { "code": null, "e": 2052, "s": 2000, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 2102, "s": 2052, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 2142, "s": 2102, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2175, "s": 2142, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2237, "s": 2175, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2298, "s": 2237, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2348, "s": 2298, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
CSS | Transitions
09 Aug, 2019 Transitions in CSS allows us to control the way in which transition takes place between the two states of the element. For example, when on hovering your mouse over a button, you can change the background color of the element with help of CSS selector and pseudo-class. We can change any other or combination of properties, though. Transition allows us to determine how the change in color takes place. We can use the transitions to animate the changes, and make the changes visually appealing to the user and hence, giving better user experience and interactivity. In this article, we will show you how to animate the transition between the CSS properties. There are four CSS properties which you should use, all or in part (at least two, transition-property and transition-duration, is must), to animate the transition. All these properties must be placed along with other CSS properties of the initial state of the element: transition-property: This property allows you to select the CSS properties which you want to animate during transition(change).Syntax:transition-property: none | all | property | property1, property2, ..., propertyN; Values:none is used to specify that no property should be selected.all is used to specify all the properties to be selected, though not all properties are animate-able, only the properties which are animate-able will be influenced.We can specify a single property or a set of comma separated properties property1, property2, ..., propertyN.transition-duration: This property allows you to determine how long it will take to complete the transition from one CSS property to the other.Syntax:transition-duration: time; Here, time can be in seconds(s) or milliseconds(ms), you should use ‘s’ or ‘ms’ after the number (without quotes).transition-timing-function: This property allows you to determine the speed of change and the manner of change, during the transition. Like, the change should be fast at the beginning and slow at the end, etc.Syntax:transition-timing-function: ease|ease-in|ease-out|ease-in-out|linear| step-start|step-end; Note, there are other values which this transition-timing-function can take, only the most frequent and simple are mentioned here.transition-delay: This property allows you to determine the amount of time to wait before the transition actually starts to take place.Syntax:transition-delay: time; Here, again, time can be in seconds(s) or milliseconds(ms), and you should use ‘s’ or ‘ms’ after the number (without quotes). transition-property: This property allows you to select the CSS properties which you want to animate during transition(change).Syntax:transition-property: none | all | property | property1, property2, ..., propertyN; Values:none is used to specify that no property should be selected.all is used to specify all the properties to be selected, though not all properties are animate-able, only the properties which are animate-able will be influenced.We can specify a single property or a set of comma separated properties property1, property2, ..., propertyN. Syntax: transition-property: none | all | property | property1, property2, ..., propertyN; Values: none is used to specify that no property should be selected. all is used to specify all the properties to be selected, though not all properties are animate-able, only the properties which are animate-able will be influenced. We can specify a single property or a set of comma separated properties property1, property2, ..., propertyN. transition-duration: This property allows you to determine how long it will take to complete the transition from one CSS property to the other.Syntax:transition-duration: time; Here, time can be in seconds(s) or milliseconds(ms), you should use ‘s’ or ‘ms’ after the number (without quotes). Syntax: transition-duration: time; Here, time can be in seconds(s) or milliseconds(ms), you should use ‘s’ or ‘ms’ after the number (without quotes). transition-timing-function: This property allows you to determine the speed of change and the manner of change, during the transition. Like, the change should be fast at the beginning and slow at the end, etc.Syntax:transition-timing-function: ease|ease-in|ease-out|ease-in-out|linear| step-start|step-end; Note, there are other values which this transition-timing-function can take, only the most frequent and simple are mentioned here. Syntax: transition-timing-function: ease|ease-in|ease-out|ease-in-out|linear| step-start|step-end; Note, there are other values which this transition-timing-function can take, only the most frequent and simple are mentioned here. transition-delay: This property allows you to determine the amount of time to wait before the transition actually starts to take place.Syntax:transition-delay: time; Here, again, time can be in seconds(s) or milliseconds(ms), and you should use ‘s’ or ‘ms’ after the number (without quotes). Syntax: transition-delay: time; Here, again, time can be in seconds(s) or milliseconds(ms), and you should use ‘s’ or ‘ms’ after the number (without quotes). The Shorthand Property You can combine all the four transition properties mentioned above, into one single shorthand property, according to the syntax given below. This saves us from writing long codes and prevents from getting messy. Note the ordering of property, it has significance. Syntax: transition: (property name) | (duration) | (timing function) | (delay); The value is taken by are same as mentioned above. This property must be placed with other CSS properties, if any, of the initial state. You should use at least, property name and duration to get any animate-able effect. Also, the ordering of the values matters. The first value is of the property name, second for the duration and so on, as listed above. So, if only one number is mentioned, it will be taken up as duration, and not as a delay. Example: Changing property without using transitions. <!DOCTYPE html><html> <head> <title>CSS Transition</title> <style> h1{ color: green; text-align: center; } div.one{ height: 150px; width: 150px; border: 1px dashed black; margin: 0 auto; background: #FFEBEE; } div.one:hover{ height: 300px; width: 300px; background: #BBDEFB; } </style> </head> <body> <h1>GeeksForGeeks</h1> <div class="one"> </div> </body></html> Output: Example: Changing property using transitions. <!DOCTYPE html><html> <head> <title>CSS Transition</title> <style> h1{ color: green; text-align: center; } div.one{ height: 150px; width: 150px; border: 1px dashed black; margin: 0 auto; background: #FFEBEE; transition: height 2s, width 2s, background 2s; } div.one:hover{ height: 300px; width: 300px; background: #BBDEFB; } </style> </head> <body> <h1>GeeksForGeeks</h1> <div class="one"> </div> </body> </html> Output: Supported browsers: The browsers supported by Transition are listed below: Google Chrome Internet Explorer Firefox Opera Safari CSS-Properties Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form 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": "\n09 Aug, 2019" }, { "code": null, "e": 686, "s": 28, "text": "Transitions in CSS allows us to control the way in which transition takes place between the two states of the element. For example, when on hovering your mouse over a button, you can change the background color of the element with help of CSS selector and pseudo-class. We can change any other or combination of properties, though. Transition allows us to determine how the change in color takes place. We can use the transitions to animate the changes, and make the changes visually appealing to the user and hence, giving better user experience and interactivity. In this article, we will show you how to animate the transition between the CSS properties." }, { "code": null, "e": 955, "s": 686, "text": "There are four CSS properties which you should use, all or in part (at least two, transition-property and transition-duration, is must), to animate the transition. All these properties must be placed along with other CSS properties of the initial state of the element:" }, { "code": null, "e": 2532, "s": 955, "text": "transition-property: This property allows you to select the CSS properties which you want to animate during transition(change).Syntax:transition-property: none | all | property | property1,\nproperty2, ..., propertyN;\nValues:none is used to specify that no property should be selected.all is used to specify all the properties to be selected, though not all properties are animate-able, only the properties which are animate-able will be influenced.We can specify a single property or a set of comma separated properties property1, property2, ..., propertyN.transition-duration: This property allows you to determine how long it will take to complete the transition from one CSS property to the other.Syntax:transition-duration: time;\nHere, time can be in seconds(s) or milliseconds(ms), you should use ‘s’ or ‘ms’ after the number (without quotes).transition-timing-function: This property allows you to determine the speed of change and the manner of change, during the transition. Like, the change should be fast at the beginning and slow at the end, etc.Syntax:transition-timing-function: ease|ease-in|ease-out|ease-in-out|linear|\nstep-start|step-end;\nNote, there are other values which this transition-timing-function can take, only the most frequent and simple are mentioned here.transition-delay: This property allows you to determine the amount of time to wait before the transition actually starts to take place.Syntax:transition-delay: time;\nHere, again, time can be in seconds(s) or milliseconds(ms), and you should use ‘s’ or ‘ms’ after the number (without quotes)." }, { "code": null, "e": 3090, "s": 2532, "text": "transition-property: This property allows you to select the CSS properties which you want to animate during transition(change).Syntax:transition-property: none | all | property | property1,\nproperty2, ..., propertyN;\nValues:none is used to specify that no property should be selected.all is used to specify all the properties to be selected, though not all properties are animate-able, only the properties which are animate-able will be influenced.We can specify a single property or a set of comma separated properties property1, property2, ..., propertyN." }, { "code": null, "e": 3098, "s": 3090, "text": "Syntax:" }, { "code": null, "e": 3182, "s": 3098, "text": "transition-property: none | all | property | property1,\nproperty2, ..., propertyN;\n" }, { "code": null, "e": 3190, "s": 3182, "text": "Values:" }, { "code": null, "e": 3251, "s": 3190, "text": "none is used to specify that no property should be selected." }, { "code": null, "e": 3416, "s": 3251, "text": "all is used to specify all the properties to be selected, though not all properties are animate-able, only the properties which are animate-able will be influenced." }, { "code": null, "e": 3526, "s": 3416, "text": "We can specify a single property or a set of comma separated properties property1, property2, ..., propertyN." }, { "code": null, "e": 3818, "s": 3526, "text": "transition-duration: This property allows you to determine how long it will take to complete the transition from one CSS property to the other.Syntax:transition-duration: time;\nHere, time can be in seconds(s) or milliseconds(ms), you should use ‘s’ or ‘ms’ after the number (without quotes)." }, { "code": null, "e": 3826, "s": 3818, "text": "Syntax:" }, { "code": null, "e": 3854, "s": 3826, "text": "transition-duration: time;\n" }, { "code": null, "e": 3969, "s": 3854, "text": "Here, time can be in seconds(s) or milliseconds(ms), you should use ‘s’ or ‘ms’ after the number (without quotes)." }, { "code": null, "e": 4407, "s": 3969, "text": "transition-timing-function: This property allows you to determine the speed of change and the manner of change, during the transition. Like, the change should be fast at the beginning and slow at the end, etc.Syntax:transition-timing-function: ease|ease-in|ease-out|ease-in-out|linear|\nstep-start|step-end;\nNote, there are other values which this transition-timing-function can take, only the most frequent and simple are mentioned here." }, { "code": null, "e": 4415, "s": 4407, "text": "Syntax:" }, { "code": null, "e": 4507, "s": 4415, "text": "transition-timing-function: ease|ease-in|ease-out|ease-in-out|linear|\nstep-start|step-end;\n" }, { "code": null, "e": 4638, "s": 4507, "text": "Note, there are other values which this transition-timing-function can take, only the most frequent and simple are mentioned here." }, { "code": null, "e": 4930, "s": 4638, "text": "transition-delay: This property allows you to determine the amount of time to wait before the transition actually starts to take place.Syntax:transition-delay: time;\nHere, again, time can be in seconds(s) or milliseconds(ms), and you should use ‘s’ or ‘ms’ after the number (without quotes)." }, { "code": null, "e": 4938, "s": 4930, "text": "Syntax:" }, { "code": null, "e": 4963, "s": 4938, "text": "transition-delay: time;\n" }, { "code": null, "e": 5089, "s": 4963, "text": "Here, again, time can be in seconds(s) or milliseconds(ms), and you should use ‘s’ or ‘ms’ after the number (without quotes)." }, { "code": null, "e": 5376, "s": 5089, "text": "The Shorthand Property You can combine all the four transition properties mentioned above, into one single shorthand property, according to the syntax given below. This saves us from writing long codes and prevents from getting messy. Note the ordering of property, it has significance." }, { "code": null, "e": 5384, "s": 5376, "text": "Syntax:" }, { "code": null, "e": 5457, "s": 5384, "text": "transition: (property name) | (duration) | (timing function) | (delay);\n" }, { "code": null, "e": 5903, "s": 5457, "text": "The value is taken by are same as mentioned above. This property must be placed with other CSS properties, if any, of the initial state. You should use at least, property name and duration to get any animate-able effect. Also, the ordering of the values matters. The first value is of the property name, second for the duration and so on, as listed above. So, if only one number is mentioned, it will be taken up as duration, and not as a delay." }, { "code": null, "e": 5957, "s": 5903, "text": "Example: Changing property without using transitions." }, { "code": "<!DOCTYPE html><html> <head> <title>CSS Transition</title> <style> h1{ color: green; text-align: center; } div.one{ height: 150px; width: 150px; border: 1px dashed black; margin: 0 auto; background: #FFEBEE; } div.one:hover{ height: 300px; width: 300px; background: #BBDEFB; } </style> </head> <body> <h1>GeeksForGeeks</h1> <div class=\"one\"> </div> </body></html>", "e": 6466, "s": 5957, "text": null }, { "code": null, "e": 6474, "s": 6466, "text": "Output:" }, { "code": null, "e": 6520, "s": 6474, "text": "Example: Changing property using transitions." }, { "code": "<!DOCTYPE html><html> <head> <title>CSS Transition</title> <style> h1{ color: green; text-align: center; } div.one{ height: 150px; width: 150px; border: 1px dashed black; margin: 0 auto; background: #FFEBEE; transition: height 2s, width 2s, background 2s; } div.one:hover{ height: 300px; width: 300px; background: #BBDEFB; } </style> </head> <body> <h1>GeeksForGeeks</h1> <div class=\"one\"> </div> </body> </html>", "e": 7075, "s": 6520, "text": null }, { "code": null, "e": 7083, "s": 7075, "text": "Output:" }, { "code": null, "e": 7158, "s": 7083, "text": "Supported browsers: The browsers supported by Transition are listed below:" }, { "code": null, "e": 7172, "s": 7158, "text": "Google Chrome" }, { "code": null, "e": 7190, "s": 7172, "text": "Internet Explorer" }, { "code": null, "e": 7198, "s": 7190, "text": "Firefox" }, { "code": null, "e": 7204, "s": 7198, "text": "Opera" }, { "code": null, "e": 7211, "s": 7204, "text": "Safari" }, { "code": null, "e": 7226, "s": 7211, "text": "CSS-Properties" }, { "code": null, "e": 7233, "s": 7226, "text": "Picked" }, { "code": null, "e": 7237, "s": 7233, "text": "CSS" }, { "code": null, "e": 7254, "s": 7237, "text": "Web Technologies" }, { "code": null, "e": 7352, "s": 7254, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7400, "s": 7352, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 7462, "s": 7400, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 7512, "s": 7462, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 7570, "s": 7512, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 7620, "s": 7570, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 7653, "s": 7620, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 7715, "s": 7653, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 7776, "s": 7715, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7826, "s": 7776, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Scala Iterator map() method with example - GeeksforGeeks
13 Aug, 2019 The map() method belongs to the concrete value member of the class Abstract Iterator. It is utilized to build a new iterator by applying a function to each of the elements of the stated iterator. Method Definition: def map[B](f: (A) => B): Iterator[B] where, B is the element type of the returned iterator and f is the function to be applied on each element of the iterator.Return Type:It returns a new iterator from the stated iterator after applying the function to each element of the given iterator.Example #1: // Scala program of map()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating an Iterator val iter = Iterator(3, 6, 15, 19, 21) // Applying map method val iter1 = iter.map(x=>{x*3}) // Applying next method val result = iter1.next() // Again applying next method val result1 = iter1.next() // Displays output println(result) println(result1) }} 9 18 Here, the function is applied to all the elements of the stated iterator and we can see here for the first two elements, where three is multiplied to each of them, similarly it is multiplied to all the elements of the stated iterator resulting into a new iterator.Example #2: // Scala program of map()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating an Iterator val iter = Iterator(3, 6, 15, 19, 21) // Applying map method val iter1 = iter.map(y=>{y/3}) // Applying next method val result= iter1.next() // Again applying next method val result1= iter1.next() // Displays output println(result) println(result1) }} 1 2 Here, first two elements will be divided by three and will get the result into a new iterator. Scala Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inheritance in Scala Hello World in Scala Scala | Option How to install Scala on Windows? Scala | Case Class and Case Object Scala Map get() method with example Scala | Decision Making (if, if-else, Nested if-else, if-else if) Scala List map() method with example Scala List exists() method with example
[ { "code": null, "e": 24006, "s": 23978, "text": "\n13 Aug, 2019" }, { "code": null, "e": 24202, "s": 24006, "text": "The map() method belongs to the concrete value member of the class Abstract Iterator. It is utilized to build a new iterator by applying a function to each of the elements of the stated iterator." }, { "code": null, "e": 24221, "s": 24202, "text": "Method Definition:" }, { "code": null, "e": 24259, "s": 24221, "text": "def map[B](f: (A) => B): Iterator[B]\n" }, { "code": null, "e": 24522, "s": 24259, "text": "where, B is the element type of the returned iterator and f is the function to be applied on each element of the iterator.Return Type:It returns a new iterator from the stated iterator after applying the function to each element of the given iterator.Example #1:" }, { "code": "// Scala program of map()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating an Iterator val iter = Iterator(3, 6, 15, 19, 21) // Applying map method val iter1 = iter.map(x=>{x*3}) // Applying next method val result = iter1.next() // Again applying next method val result1 = iter1.next() // Displays output println(result) println(result1) }}", "e": 25061, "s": 24522, "text": null }, { "code": null, "e": 25067, "s": 25061, "text": "9\n18\n" }, { "code": null, "e": 25343, "s": 25067, "text": "Here, the function is applied to all the elements of the stated iterator and we can see here for the first two elements, where three is multiplied to each of them, similarly it is multiplied to all the elements of the stated iterator resulting into a new iterator.Example #2:" }, { "code": "// Scala program of map()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating an Iterator val iter = Iterator(3, 6, 15, 19, 21) // Applying map method val iter1 = iter.map(y=>{y/3}) // Applying next method val result= iter1.next() // Again applying next method val result1= iter1.next() // Displays output println(result) println(result1) }}", "e": 25880, "s": 25343, "text": null }, { "code": null, "e": 25885, "s": 25880, "text": "1\n2\n" }, { "code": null, "e": 25980, "s": 25885, "text": "Here, first two elements will be divided by three and will get the result into a new iterator." }, { "code": null, "e": 25986, "s": 25980, "text": "Scala" }, { "code": null, "e": 25999, "s": 25986, "text": "Scala-Method" }, { "code": null, "e": 26005, "s": 25999, "text": "Scala" }, { "code": null, "e": 26103, "s": 26005, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26112, "s": 26103, "text": "Comments" }, { "code": null, "e": 26125, "s": 26112, "text": "Old Comments" }, { "code": null, "e": 26146, "s": 26125, "text": "Inheritance in Scala" }, { "code": null, "e": 26167, "s": 26146, "text": "Hello World in Scala" }, { "code": null, "e": 26182, "s": 26167, "text": "Scala | Option" }, { "code": null, "e": 26215, "s": 26182, "text": "How to install Scala on Windows?" }, { "code": null, "e": 26250, "s": 26215, "text": "Scala | Case Class and Case Object" }, { "code": null, "e": 26286, "s": 26250, "text": "Scala Map get() method with example" }, { "code": null, "e": 26352, "s": 26286, "text": "Scala | Decision Making (if, if-else, Nested if-else, if-else if)" }, { "code": null, "e": 26389, "s": 26352, "text": "Scala List map() method with example" } ]
How to create boxplot for a list object in base R?
A list object can contain multiple elements of data, also the size of the data may vary. If a list object has numerical vectors then the boxplot for each of the elements can be created simply by using boxplot function. For example, if we have a list object called LIST that contains five numerical vectors then the boxplot for each of the vectors can be created by using the command boxplot(LIST) Live Demo List<-list(x1=rnorm(50),x2=rnorm(50,5,2.25),x3=rpois(20,5),x4=rexp(50,2.24)) List $x1 [1] 0.47673123 -0.13988530 -0.03454116 -1.07172674 -0.07038959 0.84246745 [7] -0.24880770 -0.16358068 0.58943824 -0.02419312 1.23205397 0.41819088 [13] -0.18096917 -0.66329446 0.59654575 -0.38813742 0.11389223 0.34736194 [19] -1.02731203 -1.00254775 -0.12265414 -0.26374874 0.70882415 0.94992258 [25] 0.94381547 -0.96601086 0.64740016 1.11793512 1.17730331 1.71042415 [31] -0.41691694 -0.96920255 0.41512216 1.26071518 -0.14539137 -1.16879555 [37] 1.38377334 3.45037406 1.35805370 0.47444658 -0.49433200 -0.36656357 [43] -0.21815763 -0.74840666 0.26719190 1.20493116 1.60986589 -0.60518029 [49] -0.41968672 -0.32073967 $x2 [1] 5.8796314 5.7298751 5.3845408 3.1797638 4.7799172 6.9741100 7.9921069 [8] 9.5581477 2.2260415 1.0497262 4.2621598 3.3089075 4.8928650 7.3186556 [15] 4.9003319 5.3323320 6.5852322 2.6108129 5.5484016 3.1658888 5.5651849 [22] 3.9454364 1.2637536 3.1110510 0.5324844 5.9578925 8.1218069 2.9446954 [29] 8.5903533 5.5571433 0.5557869 5.0468930 3.9626768 3.4359655 2.1267040 [36] 5.3730887 3.4845970 6.1972562 2.9490418 4.0302330 7.4539694 6.6024379 [43] 6.4314803 3.6497954 3.3413132 6.1229056 3.5588145 6.1242543 3.5965840 [50] 8.6095519 $x3 [1] 2 0 8 5 2 3 6 4 5 11 6 6 7 3 6 3 4 12 6 5 $x4 [1] 0.585750982 0.370122795 1.987015464 0.024077675 0.032587786 0.997293306 [7] 0.130429262 0.422050875 0.348886654 0.106149101 1.439493919 0.105526681 [13] 0.609840540 0.196605252 0.671462334 0.196896603 0.265777491 0.987109188 [19] 0.177649340 0.310512653 0.169546605 0.356390141 1.055593510 0.401508889 [25] 0.785761516 0.430135796 0.274123388 0.823727150 0.613929177 0.264846348 [31] 0.904656444 0.089555490 0.110510149 0.461548606 0.017619161 1.007491679 [37] 0.329095102 0.338861211 0.004771366 0.861360820 0.059209099 1.097892124 [43] 0.071317813 0.372330993 0.168262454 0.562485840 0.465475293 0.287788140 [49] 1.282085210 1.655309706 boxplot(List)
[ { "code": null, "e": 1459, "s": 1062, "text": "A list object can contain multiple elements of data, also the size of the data may vary. If a list object has numerical vectors then the boxplot for each of the elements can be created simply by using boxplot function. For example, if we have a list object called LIST that contains five numerical vectors then the boxplot for each of the vectors can be created by using the command boxplot(LIST)" }, { "code": null, "e": 1470, "s": 1459, "text": " Live Demo" }, { "code": null, "e": 1552, "s": 1470, "text": "List<-list(x1=rnorm(50),x2=rnorm(50,5,2.25),x3=rpois(20,5),x4=rexp(50,2.24))\nList" }, { "code": null, "e": 3444, "s": 1552, "text": "$x1\n[1] 0.47673123 -0.13988530 -0.03454116 -1.07172674 -0.07038959 0.84246745\n[7] -0.24880770 -0.16358068 0.58943824 -0.02419312 1.23205397 0.41819088\n[13] -0.18096917 -0.66329446 0.59654575 -0.38813742 0.11389223 0.34736194\n[19] -1.02731203 -1.00254775 -0.12265414 -0.26374874 0.70882415 0.94992258\n[25] 0.94381547 -0.96601086 0.64740016 1.11793512 1.17730331 1.71042415\n[31] -0.41691694 -0.96920255 0.41512216 1.26071518 -0.14539137 -1.16879555\n[37] 1.38377334 3.45037406 1.35805370 0.47444658 -0.49433200 -0.36656357\n[43] -0.21815763 -0.74840666 0.26719190 1.20493116 1.60986589 -0.60518029\n[49] -0.41968672 -0.32073967\n$x2\n[1] 5.8796314 5.7298751 5.3845408 3.1797638 4.7799172 6.9741100 7.9921069\n[8] 9.5581477 2.2260415 1.0497262 4.2621598 3.3089075 4.8928650 7.3186556\n[15] 4.9003319 5.3323320 6.5852322 2.6108129 5.5484016 3.1658888 5.5651849\n[22] 3.9454364 1.2637536 3.1110510 0.5324844 5.9578925 8.1218069 2.9446954\n[29] 8.5903533 5.5571433 0.5557869 5.0468930 3.9626768 3.4359655 2.1267040\n[36] 5.3730887 3.4845970 6.1972562 2.9490418 4.0302330 7.4539694 6.6024379\n[43] 6.4314803 3.6497954 3.3413132 6.1229056 3.5588145 6.1242543 3.5965840\n[50] 8.6095519\n$x3\n[1] 2 0 8 5 2 3 6 4 5 11 6 6 7 3 6 3 4 12 6 5\n$x4\n[1] 0.585750982 0.370122795 1.987015464 0.024077675 0.032587786 0.997293306\n[7] 0.130429262 0.422050875 0.348886654 0.106149101 1.439493919 0.105526681\n[13] 0.609840540 0.196605252 0.671462334 0.196896603 0.265777491 0.987109188\n[19] 0.177649340 0.310512653 0.169546605 0.356390141 1.055593510 0.401508889\n[25] 0.785761516 0.430135796 0.274123388 0.823727150 0.613929177 0.264846348\n[31] 0.904656444 0.089555490 0.110510149 0.461548606 0.017619161 1.007491679\n[37] 0.329095102 0.338861211 0.004771366 0.861360820 0.059209099 1.097892124\n[43] 0.071317813 0.372330993 0.168262454 0.562485840 0.465475293 0.287788140\n[49] 1.282085210 1.655309706" }, { "code": null, "e": 3458, "s": 3444, "text": "boxplot(List)" } ]
Binary Search | Practice | GeeksforGeeks
Given a sorted array of size N and an integer K, find the position at which K is present in the array using binary search. Example 1: Input: N = 5 arr[] = {1 2 3 4 5} K = 4 Output: 3 Explanation: 4 appears at index 3. Example 2: Input: N = 5 arr[] = {11 22 33 44 55} K = 445 Output: -1 Explanation: 445 is not present. Your Task: You dont need to read input or print anything. Complete the function binarysearch() which takes arr[], N and K as input parameters and returns the index of K in the array. If K is not present in the array, return -1. Expected Time Complexity: O(LogN) Expected Auxiliary Space: O(LogN) if solving recursively and O(1) otherwise. Constraints: 1 <= N <= 104 1 <= arr[i] <= 104 0 aggshubham12339 This comment was deleted. 0 aggshubham12339 This comment was deleted. +2 abhishekniraj8022 days ago in C++ solution class Solution{public: int binarysearch(int arr[], int n, int k){ // code here int low = 0, high = n-1; while(low<=high) { int mid = low + (high-low)/2; if(arr[mid]==k) return mid; else if(arr[mid]>k) high = mid - 1; else low = mid + 1; } return -1; }}; 0 koulikmaity3 days ago int binarysearch(int arr[], int n, int k){ int s = 0; int e = n-1; int mid = s + (e - s) / 2; while(s <= e) { if(arr[mid] == k) return mid; if(arr[mid] <= k) { s = mid + 1 ; } if(arr[mid] > k) { e = mid - 1; } mid = s + (e - s) / 2; } return -1; } 0 sidvas584 days ago Why does this show time limit exceeded? class Solution{public: int binarysearch(int arr[], int n, int k){ // code here int l=0,h=n-1; int mid=l+(h-l)/2; while(l<=h) { if(arr[mid]==k) return mid; else if(arr[mid]<k) l=mid+1; else h=mid-1; } return -1; }}; 0 aggshubham12339 This comment was deleted. 0 priyansh708905 days ago int binarysearch(int arr[], int n, int k){ // code here int start = 0; int end = n-1; int mid = start + (end-start)/2; while(start<=end) { // if we find key if(arr[mid] == k) { return mid; } // if key is Less than mid else if(arr[mid] > k) { end = mid - 1; } // if key is greater than mid else { start = mid +1; } // find new mid mid = start + (end-start)/2; } return -1; } -1 ashok1si18ec0175 days ago class Solution { int binarysearch(int arr[], int n, int k){ // code here int count=-1; for(int i=0;i<n;i++) { if(arr[i]==k) { count=i; } } return count; }} 0 mukuldhurkunde5 days ago Python3 for i in range(len(arr)): if arr[i] == k: return i return -1 0 pallemadhuyadhav29296 days ago B We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 361, "s": 238, "text": "Given a sorted array of size N and an integer K, find the position at which K is present in the array using binary search." }, { "code": null, "e": 373, "s": 361, "text": "\nExample 1:" }, { "code": null, "e": 458, "s": 373, "text": "Input:\nN = 5\narr[] = {1 2 3 4 5} \nK = 4\nOutput: 3\nExplanation: 4 appears at index 3." }, { "code": null, "e": 470, "s": 458, "text": "\nExample 2:" }, { "code": null, "e": 561, "s": 470, "text": "Input:\nN = 5\narr[] = {11 22 33 44 55} \nK = 445\nOutput: -1\nExplanation: 445 is not present." }, { "code": null, "e": 792, "s": 561, "text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function binarysearch() which takes arr[], N and K as input parameters and returns the index of K in the array. If K is not present in the array, return -1." }, { "code": null, "e": 904, "s": 792, "text": "\nExpected Time Complexity: O(LogN)\nExpected Auxiliary Space: O(LogN) if solving recursively and O(1) otherwise." }, { "code": null, "e": 951, "s": 904, "text": "\nConstraints:\n1 <= N <= 104\n1 <= arr[i] <= 104" }, { "code": null, "e": 953, "s": 951, "text": "0" }, { "code": null, "e": 969, "s": 953, "text": "aggshubham12339" }, { "code": null, "e": 995, "s": 969, "text": "This comment was deleted." }, { "code": null, "e": 997, "s": 995, "text": "0" }, { "code": null, "e": 1013, "s": 997, "text": "aggshubham12339" }, { "code": null, "e": 1039, "s": 1013, "text": "This comment was deleted." }, { "code": null, "e": 1042, "s": 1039, "text": "+2" }, { "code": null, "e": 1069, "s": 1042, "text": "abhishekniraj8022 days ago" }, { "code": null, "e": 1085, "s": 1069, "text": "in C++ solution" }, { "code": null, "e": 1456, "s": 1085, "text": "class Solution{public: int binarysearch(int arr[], int n, int k){ // code here int low = 0, high = n-1; while(low<=high) { int mid = low + (high-low)/2; if(arr[mid]==k) return mid; else if(arr[mid]>k) high = mid - 1; else low = mid + 1; } return -1; }};" }, { "code": null, "e": 1458, "s": 1456, "text": "0" }, { "code": null, "e": 1480, "s": 1458, "text": "koulikmaity3 days ago" }, { "code": null, "e": 1909, "s": 1480, "text": "int binarysearch(int arr[], int n, int k){ int s = 0; int e = n-1; int mid = s + (e - s) / 2; while(s <= e) { if(arr[mid] == k) return mid; if(arr[mid] <= k) { s = mid + 1 ; } if(arr[mid] > k) { e = mid - 1; } mid = s + (e - s) / 2; } return -1; }" }, { "code": null, "e": 1911, "s": 1909, "text": "0" }, { "code": null, "e": 1930, "s": 1911, "text": "sidvas584 days ago" }, { "code": null, "e": 1970, "s": 1930, "text": "Why does this show time limit exceeded?" }, { "code": null, "e": 2293, "s": 1972, "text": "class Solution{public: int binarysearch(int arr[], int n, int k){ // code here int l=0,h=n-1; int mid=l+(h-l)/2; while(l<=h) { if(arr[mid]==k) return mid; else if(arr[mid]<k) l=mid+1; else h=mid-1; } return -1; }};" }, { "code": null, "e": 2295, "s": 2293, "text": "0" }, { "code": null, "e": 2311, "s": 2295, "text": "aggshubham12339" }, { "code": null, "e": 2337, "s": 2311, "text": "This comment was deleted." }, { "code": null, "e": 2339, "s": 2337, "text": "0" }, { "code": null, "e": 2363, "s": 2339, "text": "priyansh708905 days ago" }, { "code": null, "e": 3023, "s": 2363, "text": " int binarysearch(int arr[], int n, int k){ // code here int start = 0; int end = n-1; int mid = start + (end-start)/2; while(start<=end) { // if we find key if(arr[mid] == k) { return mid; } // if key is Less than mid else if(arr[mid] > k) { end = mid - 1; } // if key is greater than mid else { start = mid +1; } // find new mid mid = start + (end-start)/2; } return -1; }" }, { "code": null, "e": 3026, "s": 3023, "text": "-1" }, { "code": null, "e": 3052, "s": 3026, "text": "ashok1si18ec0175 days ago" }, { "code": null, "e": 3292, "s": 3052, "text": "class Solution { int binarysearch(int arr[], int n, int k){ // code here int count=-1; for(int i=0;i<n;i++) { if(arr[i]==k) { count=i; } } return count; }}" }, { "code": null, "e": 3294, "s": 3292, "text": "0" }, { "code": null, "e": 3319, "s": 3294, "text": "mukuldhurkunde5 days ago" }, { "code": null, "e": 3327, "s": 3319, "text": "Python3" }, { "code": null, "e": 3394, "s": 3327, "text": "for i in range(len(arr)):\n\tif arr[i] == k:\n\t return i\n return -1" }, { "code": null, "e": 3396, "s": 3394, "text": "0" }, { "code": null, "e": 3427, "s": 3396, "text": "pallemadhuyadhav29296 days ago" }, { "code": null, "e": 3429, "s": 3427, "text": "B" }, { "code": null, "e": 3575, "s": 3429, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 3611, "s": 3575, "text": " Login to access your submissions. " }, { "code": null, "e": 3621, "s": 3611, "text": "\nProblem\n" }, { "code": null, "e": 3631, "s": 3621, "text": "\nContest\n" }, { "code": null, "e": 3694, "s": 3631, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3842, "s": 3694, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 4050, "s": 3842, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 4156, "s": 4050, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Bank Customer Churn with Tidymodels — Part 2 Decision Threshold Analysis | by Murray Gillin | Towards Data Science
Welcome back for Part 2 of our exploration of the Bank Customer Churn problem now examining decision threshold analysis. In Part 1 we developed a candidate workflow that achieved strong results across a variety of classification metrics, and discussed the impacts of different up- and downsampling techniques to manage the 4:1 class imbalance in the bank customer churn dataset (taken from https://www.kaggle.com/shivan118/churn-modeling-dataset (License CC0: Public Domain)). Part 1 is available here, and I recommend reading prior to better understand context and model development. This article will focus on explaining the consequences of model output to a non-technical audience. We will complete decision threshold analysis and generate a cost function and present two scenarios — the threshold that either best differentiates between classes OR has the lowest cost. We will use the probably package from tidymodels to complete this analysis. Our aim is to identify and present a costed decision threshold analysis to our stakeholders weighing the cost of customer churn and intervention strategies. Load Packages library(tidymodels) #ML Metapackagelibrary(probably) #Threshold Analysislibrary(forcats) #Working with factorslibrary(patchwork) #ggplot gridstidymodels_prefer()options(yardstick.event_first = FALSE)class_metric <- metric_set(accuracy, f_meas, j_index, kap, precision, sensitivity, specificity, mcc) Finalize and Fit Model Picking up from where we left off in Part 1, we’ll identify the best performing workflow and finalise the model. best_result <- wf_sample_exp %>% extract_workflow_set_result("UPSAMPLE_Boosted_Trees") %>% select_best(metric = 'j_index')xgb_fit <- wf_sample_exp %>% extract_workflow("UPSAMPLE_Boosted_Trees") %>% finalize_workflow(best_result) %>% fit(training(cust_split)) workflowsets::extract_workflow_set_result takes a named workflow to generate a tibble of all trialled hyperparameter combinations and will select the best based on the the metric called in select_best(). workflows::extract_workflow() again takes a named workflow and then updates the hyperparameters based on what is stored in best_result. The resulting workflow is then fit to the training data. Threshold Analysis xgb_fit %>% predict(new_data = testing(cust_split), type = 'prob') %>% bind_cols(testing(cust_split)) %>% ggplot(aes(x=.pred_1, fill = Exited, color = Exited)) + geom_histogram(bins = 40, alpha = 0.5) + theme_minimal() + scale_fill_viridis_d(aesthetics = c('color', 'fill'), end = 0.8) + labs(title = 'Distribution of Prediction Probabilities by Exited Status', x = 'Probability Prediction', y = 'Count') By predicting probabilities, we can visualise the respective distribution of churn status. At the default threshold of 0.5, predictions greater then are predicted as churning and vice versa. Threshold analysis identifies an optimal threshold given desired metrics. The probably package enables us to carry out such analysis. probably::threshold_perf() takes the Truth, Estimate and sequentially varies the threshold and calculates sensitivity, specificity and J-Index for each threshold. #Generate Probability Prediction Datasetxgb_pred <- xgb_fit %>% predict(new_data = testing(cust_split), type = 'prob') %>% bind_cols(testing(cust_split)) %>% select(Exited, .pred_0, .pred_1)#Generate Sequential Threshold Tibblethreshold_data <- xgb_pred %>% threshold_perf(truth = Exited, Estimate = .pred_1, thresholds = seq(0.1, 1, by = 0.01))#Identify Threshold for Maximum J-Indexmax_j_index <- threshold_data %>% filter(.metric == 'j_index') %>% filter(.estimate == max(.estimate)) %>% select(.threshold) %>% as_vector()#Visualise Threshold Analysisthreshold_data %>% filter(.metric != 'distance') %>% ggplot(aes(x=.threshold, y=.estimate, color = .metric)) + geom_line(size = 2) + geom_vline(xintercept = max_j_index, lty = 5, alpha = .6) + theme_minimal() + scale_colour_viridis_d(end = 0.8) + labs(x='Threshold', y='Estimate', title = 'Balancing Performance by Varying Threshold', subtitle = 'Verticle Line = Max J-Index', color = 'Metric') Our analysis indicates that the threshold with the highest J-index is 0.47. To extend this analysis we can hypothetically tune the threshold to any available metric as below. I couldn’t get this to work using a yardstick::metric_set() and probably::threshold_perf() and include pr_auc and roc_auc, so had to use a purrr-fect tricks. #Threshold Analysis by Several Classification Metricslist(pred_df = list(pred_df = xgb_pred), threshold = list(threshold = seq(0.03, 0.99, by = 0.01))) %>% cross_df() %>% mutate(pred_data = map2(pred_df, threshold, ~mutate(.x, .prob_class = as_factor(if_else(.pred_1 < .y , 0, 1)))), pred_data = map2(pred_data, threshold, ~mutate(.x, .prob_metric = if_else(.pred_1 < .y , 0, 1))), pred_metric = map(pred_data, ~class_metric(.x, truth = Exited, estimate = .prob_class)), roc_auc = map(pred_data, ~roc_auc(.x, truth = Exited, estimate = .prob_metric)), pr_auc = map(pred_data, ~pr_auc(.x, truth = Exited, estimate = .prob_metric)), pred_metric = pmap(list(pred_metric, roc_auc, pr_auc),~bind_rows(..1,..2,..3))) %>% select(pred_metric, threshold) %>% unnest(pred_metric) %>% ggplot(aes(x=threshold, y=.estimate, color = .metric)) + geom_line(size = 1) + scale_color_viridis_d() + theme_minimal() + theme(axis.text.x = element_text(angle = 45)) + facet_wrap(~.metric, nrow = 2) + labs(title = 'Impact of Decision Threshold on Classification Metrics', x= 'Threshold', y = 'Estimate', color = 'Metric') The above aside, we have all we need from the output of probably::threshold_perf(). Sensitivity and Specificity enable us to calculate the FPR and FNR for a particular threshold, and hence a cost function. Cost Function Here we enter a hypothetical situation not captured within the original dataset. In order to calculate the Total Cost of FN and FP as below we need an approximation for Customer Lifetime Value (CLV) and a cost of intervention. Now let’s suppose the cost of intervention is $99 or the value of an annual fee for a standard account, if we suspect a customer is churning, customer service will honour a years discount for an annual fee. For annualised CLV we take the sum of account fees and credit card fees. We assume that each product has a $99 annual fee except credit cards which have a $149 fee. So as below we calculate an approximate CLV per customer and then take the median value as CLV. That so happens to be $149. N.B. I know this is a very basic view on what constitutes CLV, and no doubt a real life scenario would calculate the amount of interest a customer has paid on credit or loans amongst other avenues of bank customer revenue. train %>% mutate(CreditCardFees = HasCrCard*149, AccountFees = (NumOfProducts - HasCrCard)*99, CLV = CreditCardFees + AccountFees) %>% ggplot(aes(CLV)) + geom_histogram() + theme_minimal() + labs(title = 'Distribution of Annual CLV', x='CLV', y = 'Count') In applying this logic to our threshold_data tibble, we can visualise these functions. threshold_data %>% filter(.metric %in% c('sens', 'spec')) %>% pivot_wider(id_cols = .threshold, values_from = .estimate, names_from = .metric) %>% mutate(Cost_FN = ((1-sens) * 510 * 149), Cost_FP = ((1-spec) * 1991 * 99), Total_Cost = Cost_FN + Cost_FP) %>% select(.threshold, Cost_FN, Cost_FP, Total_Cost) %>% pivot_longer(2:4, names_to = 'Cost_Function', values_to = 'Cost') %>% ggplot(aes(x = .threshold, y = Cost, color = Cost_Function)) + geom_line(size = 1.5) + theme_minimal() + scale_colour_viridis_d(end = 0.8) + labs(title = 'Threshold Cost Function', x = 'Threshold') Scenario Analysis — Minimising Cost or Maximising Differentiation As we have established cost functions, we can then identify a decision threshold that minimises these costs. As noted in the introduction, we can think of two scenarios, as we’ve identified above, the threshold that optimises the J-index or the threshold that minimises cost. This is demonstrated below. threshold_data %>% filter(.metric %in% c('sens', 'spec')) %>% pivot_wider(id_cols = .threshold, values_from = .estimate, names_from = .metric) %>% mutate(Cost = ((1-sens) * 510 * 149) + ((1-spec) * 1991 * 99), j_index = (sens+spec)-1) %>% ggplot(aes(y=Cost, x = .threshold)) + geom_line() + geom_point(aes(size = j_index, color = j_index)) + geom_vline(xintercept = 0.47, lty = 2) + annotate(x = 0.36, y=100000, geom = 'text', label = 'Best Class Differentiation\nJ-Index = 0.56,\nCost = $57,629,\nThreshold = 0.47') + geom_vline(xintercept = 0.69, lty = 2) + annotate(x = 0.81, y = 100000, geom = 'text', label = 'Lowest Cost Model\nJ-Index = 0.48,\nCost = $48,329,\nThreshold = 0.69') + theme_minimal() + scale_colour_viridis_c() + labs(title = 'Decision Threshold Attrition Cost Function', subtitle = 'Where Cost(FN) = $149 & Cost(FP) = $99', x = 'Classification Threshold', size = 'J-Index', color = 'J-Index') Interestingly, given our cost assumptions, the lowest cost threshold is 0.69, unsurprisingly increasing specificity (TPR) at the cost of sensitivity (TNR). We visualise confusion matrices as below. t1 <- xgb_pred %>% mutate(.pred = make_two_class_pred(.pred_0, levels(Exited), threshold = 0.5)) %>% conf_mat(estimate = .pred, Exited) %>% autoplot(type = 'heatmap') + scale_fill_gradient2() + labs(title = 'Default Decision Threshold = 0.50')t2 <- xgb_pred %>% mutate(.pred = make_two_class_pred(.pred_0, levels(Exited), threshold = 0.47)) %>% conf_mat(estimate = .pred, Exited) %>% autoplot(type = 'heatmap') + scale_fill_gradient2() + labs(title = 'With Adjusted Decision Threshold = 0.47')t3 <- xgb_pred %>% mutate(.pred = make_two_class_pred(.pred_0, levels(Exited), threshold = 0.69)) %>% conf_mat(estimate = .pred, Exited) %>% autoplot(type = 'heatmap') + scale_fill_gradient2() + labs(title ='With Adjusted Decision Threshold = 0.69')t2 / t1 / t3 + plot_annotation(title = 'Confusion Matrices for UPSAMPLE_Boosted_Trees') Concluding Remarks We’ve completed a decision threshold analysis using the probably package, and a constructed a hypothetical scenario analysis. Given our assumptions, the lowest cost model reduces model performance. This is the trade off the business needs to consider, productionalise an effective model that can differentiate classes moderately well or go with the lower cost one despite the need for more interventions with greater false positive predictions. Thank you for reading this article, and I hope you enjoyed it. I write these to teach myself something, and I hope you’ve learnt something too. If you’re not a Medium member — use my referral link below and get regular updates on new publications from myself and other fantastic Medium authors.
[ { "code": null, "e": 286, "s": 165, "text": "Welcome back for Part 2 of our exploration of the Bank Customer Churn problem now examining decision threshold analysis." }, { "code": null, "e": 642, "s": 286, "text": "In Part 1 we developed a candidate workflow that achieved strong results across a variety of classification metrics, and discussed the impacts of different up- and downsampling techniques to manage the 4:1 class imbalance in the bank customer churn dataset (taken from https://www.kaggle.com/shivan118/churn-modeling-dataset (License CC0: Public Domain))." }, { "code": null, "e": 750, "s": 642, "text": "Part 1 is available here, and I recommend reading prior to better understand context and model development." }, { "code": null, "e": 1271, "s": 750, "text": "This article will focus on explaining the consequences of model output to a non-technical audience. We will complete decision threshold analysis and generate a cost function and present two scenarios — the threshold that either best differentiates between classes OR has the lowest cost. We will use the probably package from tidymodels to complete this analysis. Our aim is to identify and present a costed decision threshold analysis to our stakeholders weighing the cost of customer churn and intervention strategies." }, { "code": null, "e": 1285, "s": 1271, "text": "Load Packages" }, { "code": null, "e": 1585, "s": 1285, "text": "library(tidymodels) #ML Metapackagelibrary(probably) #Threshold Analysislibrary(forcats) #Working with factorslibrary(patchwork) #ggplot gridstidymodels_prefer()options(yardstick.event_first = FALSE)class_metric <- metric_set(accuracy, f_meas, j_index, kap, precision, sensitivity, specificity, mcc)" }, { "code": null, "e": 1608, "s": 1585, "text": "Finalize and Fit Model" }, { "code": null, "e": 1721, "s": 1608, "text": "Picking up from where we left off in Part 1, we’ll identify the best performing workflow and finalise the model." }, { "code": null, "e": 1989, "s": 1721, "text": "best_result <- wf_sample_exp %>% extract_workflow_set_result(\"UPSAMPLE_Boosted_Trees\") %>% select_best(metric = 'j_index')xgb_fit <- wf_sample_exp %>% extract_workflow(\"UPSAMPLE_Boosted_Trees\") %>% finalize_workflow(best_result) %>% fit(training(cust_split))" }, { "code": null, "e": 2386, "s": 1989, "text": "workflowsets::extract_workflow_set_result takes a named workflow to generate a tibble of all trialled hyperparameter combinations and will select the best based on the the metric called in select_best(). workflows::extract_workflow() again takes a named workflow and then updates the hyperparameters based on what is stored in best_result. The resulting workflow is then fit to the training data." }, { "code": null, "e": 2405, "s": 2386, "text": "Threshold Analysis" }, { "code": null, "e": 2828, "s": 2405, "text": "xgb_fit %>% predict(new_data = testing(cust_split), type = 'prob') %>% bind_cols(testing(cust_split)) %>% ggplot(aes(x=.pred_1, fill = Exited, color = Exited)) + geom_histogram(bins = 40, alpha = 0.5) + theme_minimal() + scale_fill_viridis_d(aesthetics = c('color', 'fill'), end = 0.8) + labs(title = 'Distribution of Prediction Probabilities by Exited Status', x = 'Probability Prediction', y = 'Count')" }, { "code": null, "e": 3316, "s": 2828, "text": "By predicting probabilities, we can visualise the respective distribution of churn status. At the default threshold of 0.5, predictions greater then are predicted as churning and vice versa. Threshold analysis identifies an optimal threshold given desired metrics. The probably package enables us to carry out such analysis. probably::threshold_perf() takes the Truth, Estimate and sequentially varies the threshold and calculates sensitivity, specificity and J-Index for each threshold." }, { "code": null, "e": 4325, "s": 3316, "text": "#Generate Probability Prediction Datasetxgb_pred <- xgb_fit %>% predict(new_data = testing(cust_split), type = 'prob') %>% bind_cols(testing(cust_split)) %>% select(Exited, .pred_0, .pred_1)#Generate Sequential Threshold Tibblethreshold_data <- xgb_pred %>% threshold_perf(truth = Exited, Estimate = .pred_1, thresholds = seq(0.1, 1, by = 0.01))#Identify Threshold for Maximum J-Indexmax_j_index <- threshold_data %>% filter(.metric == 'j_index') %>% filter(.estimate == max(.estimate)) %>% select(.threshold) %>% as_vector()#Visualise Threshold Analysisthreshold_data %>% filter(.metric != 'distance') %>% ggplot(aes(x=.threshold, y=.estimate, color = .metric)) + geom_line(size = 2) + geom_vline(xintercept = max_j_index, lty = 5, alpha = .6) + theme_minimal() + scale_colour_viridis_d(end = 0.8) + labs(x='Threshold', y='Estimate', title = 'Balancing Performance by Varying Threshold', subtitle = 'Verticle Line = Max J-Index', color = 'Metric')" }, { "code": null, "e": 4401, "s": 4325, "text": "Our analysis indicates that the threshold with the highest J-index is 0.47." }, { "code": null, "e": 4658, "s": 4401, "text": "To extend this analysis we can hypothetically tune the threshold to any available metric as below. I couldn’t get this to work using a yardstick::metric_set() and probably::threshold_perf() and include pr_auc and roc_auc, so had to use a purrr-fect tricks." }, { "code": null, "e": 5958, "s": 4658, "text": "#Threshold Analysis by Several Classification Metricslist(pred_df = list(pred_df = xgb_pred), threshold = list(threshold = seq(0.03, 0.99, by = 0.01))) %>% cross_df() %>% mutate(pred_data = map2(pred_df, threshold, ~mutate(.x, .prob_class = as_factor(if_else(.pred_1 < .y , 0, 1)))), pred_data = map2(pred_data, threshold, ~mutate(.x, .prob_metric = if_else(.pred_1 < .y , 0, 1))), pred_metric = map(pred_data, ~class_metric(.x, truth = Exited, estimate = .prob_class)), roc_auc = map(pred_data, ~roc_auc(.x, truth = Exited, estimate = .prob_metric)), pr_auc = map(pred_data, ~pr_auc(.x, truth = Exited, estimate = .prob_metric)), pred_metric = pmap(list(pred_metric, roc_auc, pr_auc),~bind_rows(..1,..2,..3))) %>% select(pred_metric, threshold) %>% unnest(pred_metric) %>% ggplot(aes(x=threshold, y=.estimate, color = .metric)) + geom_line(size = 1) + scale_color_viridis_d() + theme_minimal() + theme(axis.text.x = element_text(angle = 45)) + facet_wrap(~.metric, nrow = 2) + labs(title = 'Impact of Decision Threshold on Classification Metrics', x= 'Threshold', y = 'Estimate', color = 'Metric')" }, { "code": null, "e": 6164, "s": 5958, "text": "The above aside, we have all we need from the output of probably::threshold_perf(). Sensitivity and Specificity enable us to calculate the FPR and FNR for a particular threshold, and hence a cost function." }, { "code": null, "e": 6178, "s": 6164, "text": "Cost Function" }, { "code": null, "e": 6612, "s": 6178, "text": "Here we enter a hypothetical situation not captured within the original dataset. In order to calculate the Total Cost of FN and FP as below we need an approximation for Customer Lifetime Value (CLV) and a cost of intervention. Now let’s suppose the cost of intervention is $99 or the value of an annual fee for a standard account, if we suspect a customer is churning, customer service will honour a years discount for an annual fee." }, { "code": null, "e": 6901, "s": 6612, "text": "For annualised CLV we take the sum of account fees and credit card fees. We assume that each product has a $99 annual fee except credit cards which have a $149 fee. So as below we calculate an approximate CLV per customer and then take the median value as CLV. That so happens to be $149." }, { "code": null, "e": 7124, "s": 6901, "text": "N.B. I know this is a very basic view on what constitutes CLV, and no doubt a real life scenario would calculate the amount of interest a customer has paid on credit or loans amongst other avenues of bank customer revenue." }, { "code": null, "e": 7406, "s": 7124, "text": "train %>% mutate(CreditCardFees = HasCrCard*149, AccountFees = (NumOfProducts - HasCrCard)*99, CLV = CreditCardFees + AccountFees) %>% ggplot(aes(CLV)) + geom_histogram() + theme_minimal() + labs(title = 'Distribution of Annual CLV', x='CLV', y = 'Count')" }, { "code": null, "e": 7493, "s": 7406, "text": "In applying this logic to our threshold_data tibble, we can visualise these functions." }, { "code": null, "e": 8111, "s": 7493, "text": "threshold_data %>% filter(.metric %in% c('sens', 'spec')) %>% pivot_wider(id_cols = .threshold, values_from = .estimate, names_from = .metric) %>% mutate(Cost_FN = ((1-sens) * 510 * 149), Cost_FP = ((1-spec) * 1991 * 99), Total_Cost = Cost_FN + Cost_FP) %>% select(.threshold, Cost_FN, Cost_FP, Total_Cost) %>% pivot_longer(2:4, names_to = 'Cost_Function', values_to = 'Cost') %>% ggplot(aes(x = .threshold, y = Cost, color = Cost_Function)) + geom_line(size = 1.5) + theme_minimal() + scale_colour_viridis_d(end = 0.8) + labs(title = 'Threshold Cost Function', x = 'Threshold')" }, { "code": null, "e": 8177, "s": 8111, "text": "Scenario Analysis — Minimising Cost or Maximising Differentiation" }, { "code": null, "e": 8481, "s": 8177, "text": "As we have established cost functions, we can then identify a decision threshold that minimises these costs. As noted in the introduction, we can think of two scenarios, as we’ve identified above, the threshold that optimises the J-index or the threshold that minimises cost. This is demonstrated below." }, { "code": null, "e": 9460, "s": 8481, "text": "threshold_data %>% filter(.metric %in% c('sens', 'spec')) %>% pivot_wider(id_cols = .threshold, values_from = .estimate, names_from = .metric) %>% mutate(Cost = ((1-sens) * 510 * 149) + ((1-spec) * 1991 * 99), j_index = (sens+spec)-1) %>% ggplot(aes(y=Cost, x = .threshold)) + geom_line() + geom_point(aes(size = j_index, color = j_index)) + geom_vline(xintercept = 0.47, lty = 2) + annotate(x = 0.36, y=100000, geom = 'text', label = 'Best Class Differentiation\\nJ-Index = 0.56,\\nCost = $57,629,\\nThreshold = 0.47') + geom_vline(xintercept = 0.69, lty = 2) + annotate(x = 0.81, y = 100000, geom = 'text', label = 'Lowest Cost Model\\nJ-Index = 0.48,\\nCost = $48,329,\\nThreshold = 0.69') + theme_minimal() + scale_colour_viridis_c() + labs(title = 'Decision Threshold Attrition Cost Function', subtitle = 'Where Cost(FN) = $149 & Cost(FP) = $99', x = 'Classification Threshold', size = 'J-Index', color = 'J-Index')" }, { "code": null, "e": 9658, "s": 9460, "text": "Interestingly, given our cost assumptions, the lowest cost threshold is 0.69, unsurprisingly increasing specificity (TPR) at the cost of sensitivity (TNR). We visualise confusion matrices as below." }, { "code": null, "e": 10513, "s": 9658, "text": "t1 <- xgb_pred %>% mutate(.pred = make_two_class_pred(.pred_0, levels(Exited), threshold = 0.5)) %>% conf_mat(estimate = .pred, Exited) %>% autoplot(type = 'heatmap') + scale_fill_gradient2() + labs(title = 'Default Decision Threshold = 0.50')t2 <- xgb_pred %>% mutate(.pred = make_two_class_pred(.pred_0, levels(Exited), threshold = 0.47)) %>% conf_mat(estimate = .pred, Exited) %>% autoplot(type = 'heatmap') + scale_fill_gradient2() + labs(title = 'With Adjusted Decision Threshold = 0.47')t3 <- xgb_pred %>% mutate(.pred = make_two_class_pred(.pred_0, levels(Exited), threshold = 0.69)) %>% conf_mat(estimate = .pred, Exited) %>% autoplot(type = 'heatmap') + scale_fill_gradient2() + labs(title ='With Adjusted Decision Threshold = 0.69')t2 / t1 / t3 + plot_annotation(title = 'Confusion Matrices for UPSAMPLE_Boosted_Trees')" }, { "code": null, "e": 10532, "s": 10513, "text": "Concluding Remarks" }, { "code": null, "e": 10977, "s": 10532, "text": "We’ve completed a decision threshold analysis using the probably package, and a constructed a hypothetical scenario analysis. Given our assumptions, the lowest cost model reduces model performance. This is the trade off the business needs to consider, productionalise an effective model that can differentiate classes moderately well or go with the lower cost one despite the need for more interventions with greater false positive predictions." } ]
Arduino - Strings
Strings are used to store text. They can be used to display text on an LCD or in the Arduino IDE Serial Monitor window. Strings are also useful for storing the user input. For example, the characters that a user types on a keypad connected to the Arduino. There are two types of strings in Arduino programming − Arrays of characters, which are the same as the strings used in C programming. The Arduino String, which lets us use a string object in a sketch. In this chapter, we will learn Strings, objects and the use of strings in Arduino sketches. By the end of the chapter, you will learn which type of string to use in a sketch. The first type of string that we will learn is the string that is a series of characters of the type char. In the previous chapter, we learned what an array is; a consecutive series of the same type of variable stored in memory. A string is an array of char variables. A string is a special array that has one extra element at the end of the string, which always has the value of 0 (zero). This is known as a "null terminated string". This example will show how to make a string and print it to the serial monitor window. Example void setup() { char my_str[6]; // an array big enough for a 5 character string Serial.begin(9600); my_str[0] = 'H'; // the string consists of 5 characters my_str[1] = 'e'; my_str[2] = 'l'; my_str[3] = 'l'; my_str[4] = 'o'; my_str[5] = 0; // 6th array element is a null terminator Serial.println(my_str); } void loop() { } The following example shows what a string is made up of; a character array with printable characters and 0 as the last element of the array to show that this is where the string ends. The string can be printed out to the Arduino IDE Serial Monitor window by using Serial.println() and passing the name of the string. This same example can be written in a more convenient way as shown below − Example void setup() { char my_str[] = "Hello"; Serial.begin(9600); Serial.println(my_str); } void loop() { } In this sketch, the compiler calculates the size of the string array and also automatically null terminates the string with a zero. An array that is six elements long and consists of five characters followed by a zero is created exactly the same way as in the previous sketch. We can alter a string array within a sketch as shown in the following sketch. void setup() { char like[] = "I like coffee and cake"; // create a string Serial.begin(9600); // (1) print the string Serial.println(like); // (2) delete part of the string like[13] = 0; Serial.println(like); // (3) substitute a word into the string like[13] = ' '; // replace the null terminator with a space like[18] = 't'; // insert the new word like[19] = 'e'; like[20] = 'a'; like[21] = 0; // terminate the string Serial.println(like); } void loop() { } I like coffee and cake I like coffee I like coffee and tea The sketch works in the following way. In the sketch given above, a new string is created and then printed for display in the Serial Monitor window. The string is shortened by replacing the 14th character in the string with a null terminating zero (2). This is element number 13 in the string array counting from 0. When the string is printed, all the characters are printed up to the new null terminating zero. The other characters do not disappear; they still exist in the memory and the string array is still the same size. The only difference is that any function that works with strings will only see the string up to the first null terminator. Finally, the sketch replaces the word "cake" with "tea" (3). It first has to replace the null terminator at like[13] with a space so that the string is restored to the originally created format. New characters overwrite "cak" of the word "cake" with the word "tea". This is done by overwriting individual characters. The 'e' of "cake" is replaced with a new null terminating character. The result is that the string is actually terminated with two null characters, the original one at the end of the string and the new one that replaces the 'e' in "cake". This makes no difference when the new string is printed because the function that prints the string stops printing the string characters when it encounters the first null terminator. The previous sketch manipulated the string in a manual way by accessing individual characters in the string. To make it easier to manipulate string arrays, you can write your own functions to do so, or use some of the string functions from the C language library. String() The String class, part of the core as of version 0019, allows you to use and manipulate strings of text in more complex ways than character arrays do. You can concatenate Strings, append to them, search for and replace substrings, and more. It takes more memory than a simple character array, but it is also more useful. For reference, character arrays are referred to as strings with a small ‘s’, and instances of the String class are referred to as Strings with a capital S. Note that constant strings, specified in "double quotes" are treated as char arrays, not instances of the String class charAt() Access a particular character of the String. compareTo() Compares two Strings, testing whether one comes before or after the other, or whether they are equal. The strings are compared character by character, using the ASCII values of the characters. That means, for example, 'a' comes before 'b' but after 'A'. Numbers come before letters. concat() Appends the parameter to a String. c_str() Converts the contents of a string as a C-style, null-terminated string. Note that this gives direct access to the internal String buffer and should be used with care. In particular, you should never modify the string through the pointer returned. When you modify the String object, or when it is destroyed, any pointer previously returned by c_str() becomes invalid and should not be used any longer. endsWith() Tests whether or not a String ends with the characters of another String. equals() Compares two strings for equality. The comparison is case-sensitive, meaning the String "hello" is not equal to the String "HELLO". equalsIgnoreCase() Compares two strings for equality. The comparison is not case-sensitive, meaning the String("hello") is equal to the String("HELLO"). getBytes() Copies the string's characters to the supplied buffer. indexOf() Locates a character or String within another String. By default, it searches from the beginning of the String, but can also start from a given index, allowing to locate all instances of the character or String. lastIndexOf() Locates a character or String within another String. By default, it searches from the end of the String, but can also work backwards from a given index, allowing to locate all instances of the character or String. length() Returns the length of the String, in characters. (Note that this does not include a trailing null character.) remove() Modify in place, a string removing chars from the provided index to the end of the string or from the provided index to index plus count. replace() The String replace() function allows you to replace all instances of a given character with another character. You can also use replace to replace substrings of a string with a different substring. reserve() The String reserve() function allows you to allocate a buffer in memory for manipulating strings. setCharAt() Sets a character of the String. Has no effect on indices outside the existing length of the String. startsWith() Tests whether or not a String starts with the characters of another String. toCharArray() Copies the string's characters to the supplied buffer. substring() Get a substring of a String. The starting index is inclusive (the corresponding character is included in the substring), but the optional ending index is exclusive (the corresponding character is not included in the substring). If the ending index is omitted, the substring continues to the end of the String. toInt() Converts a valid String to an integer. The input string should start with an integer number. If the string contains non-integer numbers, the function will stop performing the conversion. toFloat() Converts a valid String to a float. The input string should start with a digit. If the string contains non-digit characters, the function will stop performing the conversion. For example, the strings "123.45", "123", and "123fish" are converted to 123.45, 123.00, and 123.00 respectively. Note that "123.456" is approximated with 123.46. Note too that floats have only 6-7 decimal digits of precision and that longer strings might be truncated. toLowerCase() Get a lower-case version of a String. As of 1.0, toLowerCase() modifies the string in place rather than returning a new. toUpperCase() Get an upper-case version of a String. As of 1.0, toUpperCase() modifies the string in place rather than returning a new one. trim() Get a version of the String with any leading and trailing whitespace removed. As of 1.0, trim() modifies the string in place rather than returning a new one. The next sketch uses some C string functions. void setup() { char str[] = "This is my string"; // create a string char out_str[40]; // output from string functions placed here int num; // general purpose integer Serial.begin(9600); // (1) print the string Serial.println(str); // (2) get the length of the string (excludes null terminator) num = strlen(str); Serial.print("String length is: "); Serial.println(num); // (3) get the length of the array (includes null terminator) num = sizeof(str); // sizeof() is not a C string function Serial.print("Size of the array: "); Serial.println(num); // (4) copy a string strcpy(out_str, str); Serial.println(out_str); // (5) add a string to the end of a string (append) strcat(out_str, " sketch."); Serial.println(out_str); num = strlen(out_str); Serial.print("String length is: "); Serial.println(num); num = sizeof(out_str); Serial.print("Size of the array out_str[]: "); Serial.println(num); } void loop() { } This is my string String length is: 17 Size of the array: 18 This is my string This is my string sketch. String length is: 25 Size of the array out_str[]: 40 The sketch works in the following way. The newly created string is printed to the Serial Monitor window as done in previous sketches. The strlen() function is used to get the length of the string. The length of the string is for the printable characters only and does not include the null terminator. The string contains 17 characters, so we see 17 printed in the Serial Monitor window. The operator sizeof() is used to get the length of the array that contains the string. The length includes the null terminator, so the length is one more than the length of the string. sizeof() looks like a function, but technically is an operator. It is not a part of the C string library, but was used in the sketch to show the difference between the size of the array and the size of the string (or string length). The strcpy() function is used to copy the str[] string to the out_num[] array. The strcpy() function copies the second string passed to it into the first string. A copy of the string now exists in the out_num[] array, but only takes up 18 elements of the array, so we still have 22 free char elements in the array. These free elements are found after the string in memory. The string was copied to the array so that we would have some extra space in the array to use in the next part of the sketch, which is adding a string to the end of a string. The sketch joins one string to another, which is known as concatenation. This is done using the strcat() function. The strcat() function puts the second string passed to it onto the end of the first string passed to it. After concatenation, the length of the string is printed to show the new string length. The length of the array is then printed to show that we have a 25-character long string in a 40 element long array. Remember that the 25-character long string actually takes up 26 characters of the array because of the null terminating zero. When working with strings and arrays, it is very important to work within the bounds of strings or arrays. In the example sketch, an array was created, which was 40 characters long, in order to allocate the memory that could be used to manipulate strings. If the array was made too small and we tried to copy a string that is bigger than the array to it, the string would be copied over the end of the array. The memory beyond the end of the array could contain other important data used in the sketch, which would then be overwritten by our string. If the memory beyond the end of the string is overrun, it could crash the sketch or cause unexpected behavior. 65 Lectures 6.5 hours Amit Rana 43 Lectures 3 hours Amit Rana 20 Lectures 2 hours Ashraf Said 19 Lectures 1.5 hours Ashraf Said 11 Lectures 47 mins Ashraf Said 9 Lectures 41 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 3126, "s": 2870, "text": "Strings are used to store text. They can be used to display text on an LCD or in the Arduino IDE Serial Monitor window. Strings are also useful for storing the user input. For example, the characters that a user types on a keypad connected to the Arduino." }, { "code": null, "e": 3182, "s": 3126, "text": "There are two types of strings in Arduino programming −" }, { "code": null, "e": 3261, "s": 3182, "text": "Arrays of characters, which are the same as the strings used in C programming." }, { "code": null, "e": 3328, "s": 3261, "text": "The Arduino String, which lets us use a string object in a sketch." }, { "code": null, "e": 3503, "s": 3328, "text": "In this chapter, we will learn Strings, objects and the use of strings in Arduino sketches. By the end of the chapter, you will learn which type of string to use in a sketch." }, { "code": null, "e": 3772, "s": 3503, "text": "The first type of string that we will learn is the string that is a series of characters of the type char. In the previous chapter, we learned what an array is; a consecutive series of the same type of variable stored in memory. A string is an array of char variables." }, { "code": null, "e": 3938, "s": 3772, "text": "A string is a special array that has one extra element at the end of the string, which always has the value of 0 (zero). This is known as a \"null terminated string\"." }, { "code": null, "e": 4025, "s": 3938, "text": "This example will show how to make a string and print it to the serial monitor window." }, { "code": null, "e": 4033, "s": 4025, "text": "Example" }, { "code": null, "e": 4385, "s": 4033, "text": "void setup() {\n char my_str[6]; // an array big enough for a 5 character string\n Serial.begin(9600);\n my_str[0] = 'H'; // the string consists of 5 characters\n my_str[1] = 'e';\n my_str[2] = 'l';\n my_str[3] = 'l';\n my_str[4] = 'o';\n my_str[5] = 0; // 6th array element is a null terminator\n Serial.println(my_str);\n}\n\nvoid loop() { \n\n}" }, { "code": null, "e": 4702, "s": 4385, "text": "The following example shows what a string is made up of; a character array with printable characters and 0 as the last element of the array to show that this is where the string ends. The string can be printed out to the Arduino IDE Serial Monitor window by using Serial.println() and passing the name of the string." }, { "code": null, "e": 4777, "s": 4702, "text": "This same example can be written in a more convenient way as shown below −" }, { "code": null, "e": 4785, "s": 4777, "text": "Example" }, { "code": null, "e": 4898, "s": 4785, "text": "void setup() {\n char my_str[] = \"Hello\";\n Serial.begin(9600);\n Serial.println(my_str);\n}\n\nvoid loop() {\n\n}" }, { "code": null, "e": 5175, "s": 4898, "text": "In this sketch, the compiler calculates the size of the string array and also automatically null terminates the string with a zero. An array that is six elements long and consists of five characters followed by a zero is created exactly the same way as in the previous sketch." }, { "code": null, "e": 5253, "s": 5175, "text": "We can alter a string array within a sketch as shown in the following sketch." }, { "code": null, "e": 5756, "s": 5253, "text": "void setup() {\n char like[] = \"I like coffee and cake\"; // create a string\n Serial.begin(9600);\n // (1) print the string\n Serial.println(like);\n // (2) delete part of the string\n like[13] = 0;\n Serial.println(like);\n // (3) substitute a word into the string\n like[13] = ' '; // replace the null terminator with a space\n like[18] = 't'; // insert the new word\n like[19] = 'e';\n like[20] = 'a';\n like[21] = 0; // terminate the string\n Serial.println(like);\n}\n\nvoid loop() {\n\n}" }, { "code": null, "e": 5816, "s": 5756, "text": "I like coffee and cake\nI like coffee\nI like coffee and tea\n" }, { "code": null, "e": 5855, "s": 5816, "text": "The sketch works in the following way." }, { "code": null, "e": 5965, "s": 5855, "text": "In the sketch given above, a new string is created and then printed for display in the Serial Monitor window." }, { "code": null, "e": 6132, "s": 5965, "text": "The string is shortened by replacing the 14th character in the string with a null terminating zero (2). This is element number 13 in the string array counting from 0." }, { "code": null, "e": 6466, "s": 6132, "text": "When the string is printed, all the characters are printed up to the new null terminating zero. The other characters do not disappear; they still exist in the memory and the string array is still the same size. The only difference is that any function that works with strings will only see the string up to the first null terminator." }, { "code": null, "e": 6661, "s": 6466, "text": "Finally, the sketch replaces the word \"cake\" with \"tea\" (3). It first has to replace the null terminator at like[13] with a space so that the string is restored to the originally created format." }, { "code": null, "e": 7205, "s": 6661, "text": "New characters overwrite \"cak\" of the word \"cake\" with the word \"tea\". This is done by overwriting individual characters. The 'e' of \"cake\" is replaced with a new null terminating character. The result is that the string is actually terminated with two null characters, the original one at the end of the string and the new one that replaces the 'e' in \"cake\". This makes no difference when the new string is printed because the function that prints the string stops printing the string characters when it encounters the first null terminator." }, { "code": null, "e": 7469, "s": 7205, "text": "The previous sketch manipulated the string in a manual way by accessing individual characters in the string. To make it easier to manipulate string arrays, you can write your own functions to do so, or use some of the string functions from the C language library." }, { "code": null, "e": 7478, "s": 7469, "text": "String()" }, { "code": null, "e": 7799, "s": 7478, "text": "The String class, part of the core as of version 0019, allows you to use and manipulate strings of text in more complex ways than character arrays do. You can concatenate Strings, append to them, search for and replace substrings, and more. It takes more memory than a simple character array, but it is also more useful." }, { "code": null, "e": 8074, "s": 7799, "text": "For reference, character arrays are referred to as strings with a small ‘s’, and instances of the String class are referred to as Strings with a capital S. Note that constant strings, specified in \"double quotes\" are treated as char arrays, not instances of the String class" }, { "code": null, "e": 8083, "s": 8074, "text": "charAt()" }, { "code": null, "e": 8128, "s": 8083, "text": "Access a particular character of the String." }, { "code": null, "e": 8140, "s": 8128, "text": "compareTo()" }, { "code": null, "e": 8423, "s": 8140, "text": "Compares two Strings, testing whether one comes before or after the other, or whether they are equal. The strings are compared character by character, using the ASCII values of the characters. That means, for example, 'a' comes before 'b' but after 'A'. Numbers come before letters." }, { "code": null, "e": 8432, "s": 8423, "text": "concat()" }, { "code": null, "e": 8467, "s": 8432, "text": "Appends the parameter to a String." }, { "code": null, "e": 8475, "s": 8467, "text": "c_str()" }, { "code": null, "e": 8876, "s": 8475, "text": "Converts the contents of a string as a C-style, null-terminated string. Note that this gives direct access to the internal String buffer and should be used with care. In particular, you should never modify the string through the pointer returned. When you modify the String object, or when it is destroyed, any pointer previously returned by c_str() becomes invalid and should not be used any longer." }, { "code": null, "e": 8887, "s": 8876, "text": "endsWith()" }, { "code": null, "e": 8961, "s": 8887, "text": "Tests whether or not a String ends with the characters of another String." }, { "code": null, "e": 8970, "s": 8961, "text": "equals()" }, { "code": null, "e": 9102, "s": 8970, "text": "Compares two strings for equality. The comparison is case-sensitive, meaning the String \"hello\" is not equal to the String \"HELLO\"." }, { "code": null, "e": 9121, "s": 9102, "text": "equalsIgnoreCase()" }, { "code": null, "e": 9255, "s": 9121, "text": "Compares two strings for equality. The comparison is not case-sensitive, meaning the String(\"hello\") is equal to the String(\"HELLO\")." }, { "code": null, "e": 9266, "s": 9255, "text": "getBytes()" }, { "code": null, "e": 9321, "s": 9266, "text": "Copies the string's characters to the supplied buffer." }, { "code": null, "e": 9331, "s": 9321, "text": "indexOf()" }, { "code": null, "e": 9542, "s": 9331, "text": "Locates a character or String within another String. By default, it searches from the beginning of the String, but can also start from a given index, allowing to locate all instances of the character or String." }, { "code": null, "e": 9556, "s": 9542, "text": "lastIndexOf()" }, { "code": null, "e": 9770, "s": 9556, "text": "Locates a character or String within another String. By default, it searches from the end of the String, but can also work backwards from a given index, allowing to locate all instances of the character or String." }, { "code": null, "e": 9779, "s": 9770, "text": "length()" }, { "code": null, "e": 9889, "s": 9779, "text": "Returns the length of the String, in characters. (Note that this does not include a trailing null character.)" }, { "code": null, "e": 9898, "s": 9889, "text": "remove()" }, { "code": null, "e": 10036, "s": 9898, "text": "Modify in place, a string removing chars from the provided index to the end of the string or from the provided index to index plus count." }, { "code": null, "e": 10046, "s": 10036, "text": "replace()" }, { "code": null, "e": 10244, "s": 10046, "text": "The String replace() function allows you to replace all instances of a given character with another character. You can also use replace to replace substrings of a string with a different substring." }, { "code": null, "e": 10254, "s": 10244, "text": "reserve()" }, { "code": null, "e": 10352, "s": 10254, "text": "The String reserve() function allows you to allocate a buffer in memory for manipulating strings." }, { "code": null, "e": 10364, "s": 10352, "text": "setCharAt()" }, { "code": null, "e": 10464, "s": 10364, "text": "Sets a character of the String. Has no effect on indices outside the existing length of the String." }, { "code": null, "e": 10477, "s": 10464, "text": "startsWith()" }, { "code": null, "e": 10553, "s": 10477, "text": "Tests whether or not a String starts with the characters of another String." }, { "code": null, "e": 10567, "s": 10553, "text": "toCharArray()" }, { "code": null, "e": 10622, "s": 10567, "text": "Copies the string's characters to the supplied buffer." }, { "code": null, "e": 10634, "s": 10622, "text": "substring()" }, { "code": null, "e": 10944, "s": 10634, "text": "Get a substring of a String. The starting index is inclusive (the corresponding character is included in the substring), but the optional ending index is exclusive (the corresponding character is not included in the substring). If the ending index is omitted, the substring continues to the end of the String." }, { "code": null, "e": 10952, "s": 10944, "text": "toInt()" }, { "code": null, "e": 11139, "s": 10952, "text": "Converts a valid String to an integer. The input string should start with an integer number. If the string contains non-integer numbers, the function will stop performing the conversion." }, { "code": null, "e": 11149, "s": 11139, "text": "toFloat()" }, { "code": null, "e": 11594, "s": 11149, "text": "Converts a valid String to a float. The input string should start with a digit. If the string contains non-digit characters, the function will stop performing the conversion. For example, the strings \"123.45\", \"123\", and \"123fish\" are converted to 123.45, 123.00, and 123.00 respectively. Note that \"123.456\" is approximated with 123.46. Note too that floats have only 6-7 decimal digits of precision and that longer strings might be truncated." }, { "code": null, "e": 11608, "s": 11594, "text": "toLowerCase()" }, { "code": null, "e": 11729, "s": 11608, "text": "Get a lower-case version of a String. As of 1.0, toLowerCase() modifies the string in place rather than returning a new." }, { "code": null, "e": 11743, "s": 11729, "text": "toUpperCase()" }, { "code": null, "e": 11869, "s": 11743, "text": "Get an upper-case version of a String. As of 1.0, toUpperCase() modifies the string in place rather than returning a new one." }, { "code": null, "e": 11876, "s": 11869, "text": "trim()" }, { "code": null, "e": 12034, "s": 11876, "text": "Get a version of the String with any leading and trailing whitespace removed. As of 1.0, trim() modifies the string in place rather than returning a new one." }, { "code": null, "e": 12080, "s": 12034, "text": "The next sketch uses some C string functions." }, { "code": null, "e": 13076, "s": 12080, "text": "void setup() {\n char str[] = \"This is my string\"; // create a string\n char out_str[40]; // output from string functions placed here\n int num; // general purpose integer\n Serial.begin(9600);\n\n // (1) print the string\n Serial.println(str);\n\n // (2) get the length of the string (excludes null terminator)\n num = strlen(str);\n Serial.print(\"String length is: \");\n Serial.println(num);\n\n // (3) get the length of the array (includes null terminator)\n num = sizeof(str); // sizeof() is not a C string function\n Serial.print(\"Size of the array: \");\n Serial.println(num);\n\n // (4) copy a string\n strcpy(out_str, str);\n Serial.println(out_str);\n\n // (5) add a string to the end of a string (append)\n strcat(out_str, \" sketch.\");\n Serial.println(out_str);\n num = strlen(out_str);\n Serial.print(\"String length is: \");\n Serial.println(num);\n num = sizeof(out_str);\n Serial.print(\"Size of the array out_str[]: \");\n Serial.println(num);\n}\n\nvoid loop() {\n\n}" }, { "code": null, "e": 13235, "s": 13076, "text": "This is my string\nString length is: 17\nSize of the array: 18\nThis is my string\nThis is my string sketch.\nString length is: 25\nSize of the array out_str[]: 40\n" }, { "code": null, "e": 13274, "s": 13235, "text": "The sketch works in the following way." }, { "code": null, "e": 13369, "s": 13274, "text": "The newly created string is printed to the Serial Monitor window as done in previous sketches." }, { "code": null, "e": 13536, "s": 13369, "text": "The strlen() function is used to get the length of the string. The length of the string is for the printable characters only and does not include the null terminator." }, { "code": null, "e": 13622, "s": 13536, "text": "The string contains 17 characters, so we see 17 printed in the Serial Monitor window." }, { "code": null, "e": 13807, "s": 13622, "text": "The operator sizeof() is used to get the length of the array that contains the string. The length includes the null terminator, so the length is one more than the length of the string." }, { "code": null, "e": 14040, "s": 13807, "text": "sizeof() looks like a function, but technically is an operator. It is not a part of the C string library, but was used in the sketch to show the difference between the size of the array and the size of the string (or string length)." }, { "code": null, "e": 14413, "s": 14040, "text": "The strcpy() function is used to copy the str[] string to the out_num[] array. The strcpy() function copies the second string passed to it into the first string. A copy of the string now exists in the out_num[] array, but only takes up 18 elements of the array, so we still have 22 free char elements in the array. These free elements are found after the string in memory." }, { "code": null, "e": 14588, "s": 14413, "text": "The string was copied to the array so that we would have some extra space in the array to use in the next part of the sketch, which is adding a string to the end of a string." }, { "code": null, "e": 14808, "s": 14588, "text": "The sketch joins one string to another, which is known as concatenation. This is done using the strcat() function. The strcat() function puts the second string passed to it onto the end of the first string passed to it." }, { "code": null, "e": 15012, "s": 14808, "text": "After concatenation, the length of the string is printed to show the new string length. The length of the array is then printed to show that we have a 25-character long string in a 40 element long array." }, { "code": null, "e": 15138, "s": 15012, "text": "Remember that the 25-character long string actually takes up 26 characters of the array because of the null terminating zero." }, { "code": null, "e": 15394, "s": 15138, "text": "When working with strings and arrays, it is very important to work within the bounds of strings or arrays. In the example sketch, an array was created, which was 40 characters long, in order to allocate the memory that could be used to manipulate strings." }, { "code": null, "e": 15799, "s": 15394, "text": "If the array was made too small and we tried to copy a string that is bigger than the array to it, the string would be copied over the end of the array. The memory beyond the end of the array could contain other important data used in the sketch, which would then be overwritten by our string. If the memory beyond the end of the string is overrun, it could crash the sketch or cause unexpected behavior." }, { "code": null, "e": 15834, "s": 15799, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 15845, "s": 15834, "text": " Amit Rana" }, { "code": null, "e": 15878, "s": 15845, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 15889, "s": 15878, "text": " Amit Rana" }, { "code": null, "e": 15922, "s": 15889, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 15935, "s": 15922, "text": " Ashraf Said" }, { "code": null, "e": 15970, "s": 15935, "text": "\n 19 Lectures \n 1.5 hours \n" }, { "code": null, "e": 15983, "s": 15970, "text": " Ashraf Said" }, { "code": null, "e": 16015, "s": 15983, "text": "\n 11 Lectures \n 47 mins\n" }, { "code": null, "e": 16028, "s": 16015, "text": " Ashraf Said" }, { "code": null, "e": 16059, "s": 16028, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 16072, "s": 16059, "text": " Ashraf Said" }, { "code": null, "e": 16079, "s": 16072, "text": " Print" }, { "code": null, "e": 16090, "s": 16079, "text": " Add Notes" } ]
Detecting communities in a language co-occurrence network | by Harry Bitten | Towards Data Science
In this post, we are going to undertake community detection in the python package Igraph, to attempt to detect communities within a language co-occurrence network. This will be implemented using two popular community detection algorithms: Walktrap, and Label Propagation Global language co-occurrence networks (GLCNs) link languages that are likely to be co-spoken. Representing language co-occurrence as a network allows inference about international information sharing and knowledge transfer. This includes the diversity of information received by speakers of the language, the speed at which the information will be received, and the ability of native speakers to globally disseminate information. Let us begin with the formal foundation over which we will build up the exchange of networks. This is the thought of a basic graph which is compromised by a set of nodes (or vertices) along with a set of links (or edges) among them. A graph may be directed (whereby edges indicate a one-way relationship) or undirected (edges indicate a two-way relationship, in that each edge can be traversed in both directions). Moreover, a graph may be two-fold, in which case any connection between two hubs either exists or does not exist. On the other hand, a diagram may be weighted, in which case any connection is furnished with a specific weight or esteem, which is commonly a (positive) number. The purpose here is to display an early on and brief exchange of the formal idea of a network with regards to the hypothesis of complex networks (and informal community investigation), and to portray (for the most part by models) several of the numerous computational systems which are normally utilized for the recognition of networks in a diagram theoretic foundation. Here, we portray the idea of language co-occurrence within Global language co-occurrence networks (GLCNs) by using existing algorithms to discover community structures in graphs Walktrap, developed by Pascal Pons, is an algorithm in graph theory, used to identify communities in large networks via random walks. These random walks are then used to compute distances between nodes. Nodes are then assigned into groups with small intra and larger inter-community distances via bottom-up hierarchical clustering. It should be noted, of course, that this algorithm considers only one community per node, which in some cases can be an incorrect hypothesis. Label propagation, or LPA, proposed by U.N.Raghavan, is a near-linear community detection solution that benefits from fairly simple implementation. The algorithm works as follows: A network is characterized as a graph G(V, E), where V is the full set of nodes and E is the full set of edges.For node i(i ∈ V) , let Li denote the label of i, and N(i) denote the set of its neighborsAt the start of the process, each node is assigned a unique label e.g. Li = i.These labels then propagate throughout the network, with each node updating its label at every iteration to the one shared by most of its neighbors.This process is repeated until each node has one of the most frequent labels of its neighbors, that is, none of the nodes need to change their label. A network is characterized as a graph G(V, E), where V is the full set of nodes and E is the full set of edges. For node i(i ∈ V) , let Li denote the label of i, and N(i) denote the set of its neighbors At the start of the process, each node is assigned a unique label e.g. Li = i. These labels then propagate throughout the network, with each node updating its label at every iteration to the one shared by most of its neighbors. This process is repeated until each node has one of the most frequent labels of its neighbors, that is, none of the nodes need to change their label. 6. Finally, communities are constructed of nodes that share the same label The book translations global languages network from the Massachusetts Institute of Technology (MIT) will be used for this post. The dataset is a directed network, derived from over 2.2 million book translations published worldwide from 1979 to 2011. The translation data was obtained from UNESCO’s Index Translationum — an international index of printed book translations. In the network, nodes represent individual languages and edges indicate a translation of a book from one language to another. The frequency of the translation in the dataset — the co-occurrence frequency — can be used to weight the edges. Our chosen algorithms (Walktrap and Label Propagation) will be implemented in Python using the iGraph package with preparation for the testing being fairly simple. Firstly, required for iGraph are only SourceNode, DestinationNode, and Weight, fortunately our dataset comes with these 3 columns as default. So first of all we can load the network into the workspace using an iGraph function: Read_Ncol, as shown below: import cairocffiimport igraphg = igraph.Graph.Read_Ncol('books.txt', directed = True) We can then simply use igraph.plot(g) To get a graphical representation of the network: Community_walktrap in iGraph takes two optional parameters; weights and steps, where weights is a list containing edge weights and steps in the length of random walks to perform. The weights are automatically assigned as the third column with Read_Ncol, so to specify weights in the function, it is as simple as weights=g.es[“weight”] where ‘g’ is the graph that was read in. Generally speaking, 3, 4, or 5 steps are used in implementation. For this post, we’re going to use 4. Running community_walktrap returns a VertexDendrogram object which is initially cut at the maximum modularity. Running as_clustering() on this object returns a VertexClustering object, which describes the clustering of the vertex set of a graph. wtrap = g.community_walktrap(weights=g.es["weight"], steps = 4)clust=wtrap.as_clustering() Although this is fine, its not particularly interesting to look at! we are then able to plot this result in iGraph using plot(), with two parameters, mark_groups, and **visual_style, where mark_groups specifies whether to highlight some of the vertex groups by coloured polygons and visual_style specifying visual properties. We can simply set up a python dictionary containing keyword arguments that we wish to pass to plot(), which in this case, is marking the vertex labels. visual_style = dict()visual_style["bbox"] = (700, 600)visual_style["vertex_label"] = g.vs["name"]igraph.plot(clust,mark_groups = True,**visual_style) The output shows that 2 main communities are formed, containing 71 and 94 nodes respectively, and a third, smaller community with only 3 members. The remaining 100 nodes (37.3%) were each assigned to their own cluster (i.e. n=1), which we would not count in our definition of a community. These two main communities, however, seem to revolve around English and Russian, we can further verify this by looking back to the VertexClustering object and seeing the members of each community. Label propagation is a simpler approach requiring no parameters, however, there are a few optional arguments; weights, initial, and fixed, where weights is identical to the structure in the walktrap approach. However, initial can be a list of the initial vertex labels, and fixed is a list of Booleans for each vertex with True corresponding to vertices who’s labeling should not change during the algorithm. These last two parameters were not required with our testing, with only weights being specified in the arguments. Unlike walktrap, label propagation does not return a dendrogram object and instead directly returns a VertexClustering object which can then be plotted in an identical fashion to the walktrap approach. labelProp = g.community_label_propagation(weights=g.es["weight"])igraph.plot(labelProp,mark_groups = True,**visual_style) As found with the Walktrap algorithm, running label propagation on the weighted dataset identified two major communities of a similar size, with 70 and 102 members. There were, however, a further two minor communities, which contained 3 and 8 members respectively. Again, approximately one third of the nodes were not classified into communities due to the agglomerative nature of the approach (n=85, 31.7% of the dataset) It is important to note that the high weights and dense nature of the graph has a considerable impact on how the algorithms work in this analysis. For example, for walktrap, in an unweighted graph, a node with 3 unweighted edges to neighbors would have a 1/3 chance to traverse each edge in a random walk. However, when taking weights into account, the probability of choosing a highly weighted edge (mainly English and Russian) becomes extremely high, causing the walks to get stuck going back and forth on a single edge. The situation with label propagation differs slightly; after each iteration, node labels update to that of the one shared by most of its neighbours. As Russian and English have such high in and out-degrees, the majority of nodes have one of these two languages in their neighborhood set, meaning there is a large possibility that these nodes will update labels to match that of the two aforementioned, even more so when edge weights are considered. Although removing the weights wouldn’t have much effect on the community structure with the label propagation, it should have a large impact on the outcome of the Walktrap algorithm. We can therefore re-run the algorithm, leaving weights unspecified: wtrapnoweights = g.community_walktrap(steps = 4)clustnoweights=wtrapnoweights.as_clustering() We can already see that many more communities have been formed, and it is looking to be a much more interesting result. So let’s plot it! wtrapnoweights = g.community_walktrap(steps = 4)clustnoweights=wtrapnoweights.as_clustering()igraph.plot(clustnoweights,mark_groups = True, **visual_style) Repeating the test, this time giving all edges equal weighting yielded very different results. Ten communities were detected, with only a single node being assigned to its own cluster. There was also less of an imbalance in the size of the identified communities (mean 22.4 node members; minimum 3; maximum 54). This result is actually very interesting, even more so if you look at the VertexClustering object, and look at community 9, which shows that all the Scandinavian languages have been formed into a community, and also community 7, which has clustered many Asian languages together, such as Korean and Japanese. In this post, we have compared two agglomerative community detection algorithms using the book translations global languages network. We found that, when using the weighted network, neither approach generated many distinct communities in the dataset. Instead, generally, two major communities formed. This suggests that there are not distinct groups of languages, and instead, information sharing occurs at an international level in this network. This conclusion is supported by the fact that we identified similarities in the two major communities identified by the two approaches, in terms of their size and constituents, by qualitatively considering the language families of the community members. Suggesting that the findings were not an artefact of the method employed. By removing the edge weights, we found that this attribute of the underlying dataset was very important important in community formation. However, it is not known if the edge weights used in this work are truly representative of language co-occurrence frequencies. The edge weights were derived from data reported to UNESCO by many different international libraries. These data may be subject to reporting biases of the various locations, with different locations following different practices and having differing levels of completeness, and may they may also not be up to date. This warrants further investigation. An interesting extension would perhaps be to re-run the algorithms on the graph but without English and Russian nodes. We would expect that this would return a more interesting set of communities, that aren’t quite as affected by the large bias towards highly connected nodes and heavily weighted edges. Thanks for checking this article out! Although this isn’t normally the sort of thing I would create, I found the idea of community detection fascinating. Full information and code can be found on my Github below github.com See you the next time!
[ { "code": null, "e": 442, "s": 171, "text": "In this post, we are going to undertake community detection in the python package Igraph, to attempt to detect communities within a language co-occurrence network. This will be implemented using two popular community detection algorithms: Walktrap, and Label Propagation" }, { "code": null, "e": 873, "s": 442, "text": "Global language co-occurrence networks (GLCNs) link languages that are likely to be co-spoken. Representing language co-occurrence as a network allows inference about international information sharing and knowledge transfer. This includes the diversity of information received by speakers of the language, the speed at which the information will be received, and the ability of native speakers to globally disseminate information." }, { "code": null, "e": 2112, "s": 873, "text": "Let us begin with the formal foundation over which we will build up the exchange of networks. This is the thought of a basic graph which is compromised by a set of nodes (or vertices) along with a set of links (or edges) among them. A graph may be directed (whereby edges indicate a one-way relationship) or undirected (edges indicate a two-way relationship, in that each edge can be traversed in both directions). Moreover, a graph may be two-fold, in which case any connection between two hubs either exists or does not exist. On the other hand, a diagram may be weighted, in which case any connection is furnished with a specific weight or esteem, which is commonly a (positive) number. The purpose here is to display an early on and brief exchange of the formal idea of a network with regards to the hypothesis of complex networks (and informal community investigation), and to portray (for the most part by models) several of the numerous computational systems which are normally utilized for the recognition of networks in a diagram theoretic foundation. Here, we portray the idea of language co-occurrence within Global language co-occurrence networks (GLCNs) by using existing algorithms to discover community structures in graphs" }, { "code": null, "e": 2586, "s": 2112, "text": "Walktrap, developed by Pascal Pons, is an algorithm in graph theory, used to identify communities in large networks via random walks. These random walks are then used to compute distances between nodes. Nodes are then assigned into groups with small intra and larger inter-community distances via bottom-up hierarchical clustering. It should be noted, of course, that this algorithm considers only one community per node, which in some cases can be an incorrect hypothesis." }, { "code": null, "e": 2766, "s": 2586, "text": "Label propagation, or LPA, proposed by U.N.Raghavan, is a near-linear community detection solution that benefits from fairly simple implementation. The algorithm works as follows:" }, { "code": null, "e": 3343, "s": 2766, "text": "A network is characterized as a graph G(V, E), where V is the full set of nodes and E is the full set of edges.For node i(i ∈ V) , let Li denote the label of i, and N(i) denote the set of its neighborsAt the start of the process, each node is assigned a unique label e.g. Li = i.These labels then propagate throughout the network, with each node updating its label at every iteration to the one shared by most of its neighbors.This process is repeated until each node has one of the most frequent labels of its neighbors, that is, none of the nodes need to change their label." }, { "code": null, "e": 3455, "s": 3343, "text": "A network is characterized as a graph G(V, E), where V is the full set of nodes and E is the full set of edges." }, { "code": null, "e": 3546, "s": 3455, "text": "For node i(i ∈ V) , let Li denote the label of i, and N(i) denote the set of its neighbors" }, { "code": null, "e": 3625, "s": 3546, "text": "At the start of the process, each node is assigned a unique label e.g. Li = i." }, { "code": null, "e": 3774, "s": 3625, "text": "These labels then propagate throughout the network, with each node updating its label at every iteration to the one shared by most of its neighbors." }, { "code": null, "e": 3924, "s": 3774, "text": "This process is repeated until each node has one of the most frequent labels of its neighbors, that is, none of the nodes need to change their label." }, { "code": null, "e": 3999, "s": 3924, "text": "6. Finally, communities are constructed of nodes that share the same label" }, { "code": null, "e": 4611, "s": 3999, "text": "The book translations global languages network from the Massachusetts Institute of Technology (MIT) will be used for this post. The dataset is a directed network, derived from over 2.2 million book translations published worldwide from 1979 to 2011. The translation data was obtained from UNESCO’s Index Translationum — an international index of printed book translations. In the network, nodes represent individual languages and edges indicate a translation of a book from one language to another. The frequency of the translation in the dataset — the co-occurrence frequency — can be used to weight the edges." }, { "code": null, "e": 5029, "s": 4611, "text": "Our chosen algorithms (Walktrap and Label Propagation) will be implemented in Python using the iGraph package with preparation for the testing being fairly simple. Firstly, required for iGraph are only SourceNode, DestinationNode, and Weight, fortunately our dataset comes with these 3 columns as default. So first of all we can load the network into the workspace using an iGraph function: Read_Ncol, as shown below:" }, { "code": null, "e": 5115, "s": 5029, "text": "import cairocffiimport igraphg = igraph.Graph.Read_Ncol('books.txt', directed = True)" }, { "code": null, "e": 5138, "s": 5115, "text": "We can then simply use" }, { "code": null, "e": 5153, "s": 5138, "text": "igraph.plot(g)" }, { "code": null, "e": 5203, "s": 5153, "text": "To get a graphical representation of the network:" }, { "code": null, "e": 5515, "s": 5203, "text": "Community_walktrap in iGraph takes two optional parameters; weights and steps, where weights is a list containing edge weights and steps in the length of random walks to perform. The weights are automatically assigned as the third column with Read_Ncol, so to specify weights in the function, it is as simple as" }, { "code": null, "e": 5538, "s": 5515, "text": "weights=g.es[“weight”]" }, { "code": null, "e": 5681, "s": 5538, "text": "where ‘g’ is the graph that was read in. Generally speaking, 3, 4, or 5 steps are used in implementation. For this post, we’re going to use 4." }, { "code": null, "e": 5927, "s": 5681, "text": "Running community_walktrap returns a VertexDendrogram object which is initially cut at the maximum modularity. Running as_clustering() on this object returns a VertexClustering object, which describes the clustering of the vertex set of a graph." }, { "code": null, "e": 6018, "s": 5927, "text": "wtrap = g.community_walktrap(weights=g.es[\"weight\"], steps = 4)clust=wtrap.as_clustering()" }, { "code": null, "e": 6496, "s": 6018, "text": "Although this is fine, its not particularly interesting to look at! we are then able to plot this result in iGraph using plot(), with two parameters, mark_groups, and **visual_style, where mark_groups specifies whether to highlight some of the vertex groups by coloured polygons and visual_style specifying visual properties. We can simply set up a python dictionary containing keyword arguments that we wish to pass to plot(), which in this case, is marking the vertex labels." }, { "code": null, "e": 6646, "s": 6496, "text": "visual_style = dict()visual_style[\"bbox\"] = (700, 600)visual_style[\"vertex_label\"] = g.vs[\"name\"]igraph.plot(clust,mark_groups = True,**visual_style)" }, { "code": null, "e": 7132, "s": 6646, "text": "The output shows that 2 main communities are formed, containing 71 and 94 nodes respectively, and a third, smaller community with only 3 members. The remaining 100 nodes (37.3%) were each assigned to their own cluster (i.e. n=1), which we would not count in our definition of a community. These two main communities, however, seem to revolve around English and Russian, we can further verify this by looking back to the VertexClustering object and seeing the members of each community." }, { "code": null, "e": 7857, "s": 7132, "text": "Label propagation is a simpler approach requiring no parameters, however, there are a few optional arguments; weights, initial, and fixed, where weights is identical to the structure in the walktrap approach. However, initial can be a list of the initial vertex labels, and fixed is a list of Booleans for each vertex with True corresponding to vertices who’s labeling should not change during the algorithm. These last two parameters were not required with our testing, with only weights being specified in the arguments. Unlike walktrap, label propagation does not return a dendrogram object and instead directly returns a VertexClustering object which can then be plotted in an identical fashion to the walktrap approach." }, { "code": null, "e": 7979, "s": 7857, "text": "labelProp = g.community_label_propagation(weights=g.es[\"weight\"])igraph.plot(labelProp,mark_groups = True,**visual_style)" }, { "code": null, "e": 8402, "s": 7979, "text": "As found with the Walktrap algorithm, running label propagation on the weighted dataset identified two major communities of a similar size, with 70 and 102 members. There were, however, a further two minor communities, which contained 3 and 8 members respectively. Again, approximately one third of the nodes were not classified into communities due to the agglomerative nature of the approach (n=85, 31.7% of the dataset)" }, { "code": null, "e": 9374, "s": 8402, "text": "It is important to note that the high weights and dense nature of the graph has a considerable impact on how the algorithms work in this analysis. For example, for walktrap, in an unweighted graph, a node with 3 unweighted edges to neighbors would have a 1/3 chance to traverse each edge in a random walk. However, when taking weights into account, the probability of choosing a highly weighted edge (mainly English and Russian) becomes extremely high, causing the walks to get stuck going back and forth on a single edge. The situation with label propagation differs slightly; after each iteration, node labels update to that of the one shared by most of its neighbours. As Russian and English have such high in and out-degrees, the majority of nodes have one of these two languages in their neighborhood set, meaning there is a large possibility that these nodes will update labels to match that of the two aforementioned, even more so when edge weights are considered." }, { "code": null, "e": 9625, "s": 9374, "text": "Although removing the weights wouldn’t have much effect on the community structure with the label propagation, it should have a large impact on the outcome of the Walktrap algorithm. We can therefore re-run the algorithm, leaving weights unspecified:" }, { "code": null, "e": 9719, "s": 9625, "text": "wtrapnoweights = g.community_walktrap(steps = 4)clustnoweights=wtrapnoweights.as_clustering()" }, { "code": null, "e": 9857, "s": 9719, "text": "We can already see that many more communities have been formed, and it is looking to be a much more interesting result. So let’s plot it!" }, { "code": null, "e": 10013, "s": 9857, "text": "wtrapnoweights = g.community_walktrap(steps = 4)clustnoweights=wtrapnoweights.as_clustering()igraph.plot(clustnoweights,mark_groups = True, **visual_style)" }, { "code": null, "e": 10634, "s": 10013, "text": "Repeating the test, this time giving all edges equal weighting yielded very different results. Ten communities were detected, with only a single node being assigned to its own cluster. There was also less of an imbalance in the size of the identified communities (mean 22.4 node members; minimum 3; maximum 54). This result is actually very interesting, even more so if you look at the VertexClustering object, and look at community 9, which shows that all the Scandinavian languages have been formed into a community, and also community 7, which has clustered many Asian languages together, such as Korean and Japanese." }, { "code": null, "e": 12026, "s": 10634, "text": "In this post, we have compared two agglomerative community detection algorithms using the book translations global languages network. We found that, when using the weighted network, neither approach generated many distinct communities in the dataset. Instead, generally, two major communities formed. This suggests that there are not distinct groups of languages, and instead, information sharing occurs at an international level in this network. This conclusion is supported by the fact that we identified similarities in the two major communities identified by the two approaches, in terms of their size and constituents, by qualitatively considering the language families of the community members. Suggesting that the findings were not an artefact of the method employed. By removing the edge weights, we found that this attribute of the underlying dataset was very important important in community formation. However, it is not known if the edge weights used in this work are truly representative of language co-occurrence frequencies. The edge weights were derived from data reported to UNESCO by many different international libraries. These data may be subject to reporting biases of the various locations, with different locations following different practices and having differing levels of completeness, and may they may also not be up to date. This warrants further investigation." }, { "code": null, "e": 12330, "s": 12026, "text": "An interesting extension would perhaps be to re-run the algorithms on the graph but without English and Russian nodes. We would expect that this would return a more interesting set of communities, that aren’t quite as affected by the large bias towards highly connected nodes and heavily weighted edges." }, { "code": null, "e": 12542, "s": 12330, "text": "Thanks for checking this article out! Although this isn’t normally the sort of thing I would create, I found the idea of community detection fascinating. Full information and code can be found on my Github below" }, { "code": null, "e": 12553, "s": 12542, "text": "github.com" } ]
JavaFX - 2D Shapes Line
In general, a line is a geometrical structure which joins two points on an XY plane. In JavaFX, a line is represented by a class named Line. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create a line node in JavaFX. This class has 4 properties of the double datatype namely − startX − The x coordinate of the start point of the line. startX − The x coordinate of the start point of the line. startY − The y coordinate of the start point of the line. startY − The y coordinate of the start point of the line. endX − The x coordinate of the end point of the line. endX − The x coordinate of the end point of the line. endY − The y coordinate of the end point of the line. endY − The y coordinate of the end point of the line. To draw a line, you need to pass values to these properties, either by passing them to the constructor of this class, in the same order, at the time of instantiation, as follows − Line line = new Line(startX, startY, endX, endY); Or, by using their respective setter methods as follows − setStartX(value); setStartY(value); setEndX(value); setEndY(value); Follow the steps given below to Draw a Line in JavaFX. Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows. public class ClassName extends Application { @Override public void start(Stage primaryStage) throws Exception { } } You can create a line in JavaFX by instantiating the class named Line which belongs to a package javafx.scene.shape, instantiate this class as follows. //Creating a line object Line line = new Line(); Specify the coordinates to draw the line on an XY plane by setting the properties startX, startY, endX and endY, using their respective setter methods as shown in the following code block. line.setStartX(100.0); line.setStartY(150.0); line.setEndX(500.0); line.setEndY(150.0); Create a group object by instantiating the class named Group, which belongs to the package javafx.scene. Pass the Line (node) object, created in the previous step, as a parameter to the constructor of the Group class, in order to add it to the group as follows − Group root = new Group(line); Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class pass the Group object (root), created in the previous step. In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows. Scene scene = new Scene(group ,600, 300); You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter. Using the primaryStage object, set the title of the scene as Sample Application as follows. primaryStage.setTitle("Sample Application"); You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene Object prepared in the previous steps using this method as follows. primaryStage.setScene(scene) Display the contents of the scene using the method named show() of the Stage class as follows. primaryStage.show(); Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows. public static void main(String args[]){ launch(args); } Following is the program which generates a straight line using JavaFX. Save this code in a file with the name DrawingLine.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Line; import javafx.stage.Stage; public class DrawingLine extends Application{ @Override public void start(Stage stage) { //Creating a line object Line line = new Line(); //Setting the properties to a line line.setStartX(100.0); line.setStartY(150.0); line.setEndX(500.0); line.setEndY(150.0); //Creating a Group Group root = new Group(line); //Creating a Scene Scene scene = new Scene(root, 600, 300); //Setting title to the scene stage.setTitle("Sample application"); //Adding the scene to the stage stage.setScene(scene); //Displaying the contents of a scene stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac DrawingLine.java java DrawingLine On executing, the above program generates a JavaFX window displaying a straight line as shown below. 33 Lectures 7.5 hours Syed Raza 64 Lectures 12.5 hours Emenwa Global, Ejike IfeanyiChukwu 20 Lectures 4 hours Emenwa Global, Ejike IfeanyiChukwu Print Add Notes Bookmark this page
[ { "code": null, "e": 1985, "s": 1900, "text": "In general, a line is a geometrical structure which joins two points on an XY plane." }, { "code": null, "e": 2095, "s": 1985, "text": "In JavaFX, a line is represented by a class named Line. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 2162, "s": 2095, "text": "By instantiating this class, you can create a line node in JavaFX." }, { "code": null, "e": 2222, "s": 2162, "text": "This class has 4 properties of the double datatype namely −" }, { "code": null, "e": 2280, "s": 2222, "text": "startX − The x coordinate of the start point of the line." }, { "code": null, "e": 2338, "s": 2280, "text": "startX − The x coordinate of the start point of the line." }, { "code": null, "e": 2396, "s": 2338, "text": "startY − The y coordinate of the start point of the line." }, { "code": null, "e": 2454, "s": 2396, "text": "startY − The y coordinate of the start point of the line." }, { "code": null, "e": 2508, "s": 2454, "text": "endX − The x coordinate of the end point of the line." }, { "code": null, "e": 2562, "s": 2508, "text": "endX − The x coordinate of the end point of the line." }, { "code": null, "e": 2616, "s": 2562, "text": "endY − The y coordinate of the end point of the line." }, { "code": null, "e": 2670, "s": 2616, "text": "endY − The y coordinate of the end point of the line." }, { "code": null, "e": 2850, "s": 2670, "text": "To draw a line, you need to pass values to these properties, either by passing them to the constructor of this class, in the same order, at the time of instantiation, as follows −" }, { "code": null, "e": 2901, "s": 2850, "text": "Line line = new Line(startX, startY, endX, endY);\n" }, { "code": null, "e": 2959, "s": 2901, "text": "Or, by using their respective setter methods as follows −" }, { "code": null, "e": 3032, "s": 2959, "text": "setStartX(value); \nsetStartY(value); \nsetEndX(value); \nsetEndY(value); \n" }, { "code": null, "e": 3087, "s": 3032, "text": "Follow the steps given below to Draw a Line in JavaFX." }, { "code": null, "e": 3234, "s": 3087, "text": "Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows." }, { "code": null, "e": 3369, "s": 3234, "text": "public class ClassName extends Application { \n @Override \n public void start(Stage primaryStage) throws Exception {\n }\n} " }, { "code": null, "e": 3521, "s": 3369, "text": "You can create a line in JavaFX by instantiating the class named Line which belongs to a package javafx.scene.shape, instantiate this class as follows." }, { "code": null, "e": 3580, "s": 3521, "text": "//Creating a line object \nLine line = new Line();\n" }, { "code": null, "e": 3769, "s": 3580, "text": "Specify the coordinates to draw the line on an XY plane by setting the properties startX, startY, endX and endY, using their respective setter methods as shown in the following code block." }, { "code": null, "e": 3862, "s": 3769, "text": "line.setStartX(100.0); \nline.setStartY(150.0); \nline.setEndX(500.0); \nline.setEndY(150.0); \n" }, { "code": null, "e": 3967, "s": 3862, "text": "Create a group object by instantiating the class named Group, which belongs to the package javafx.scene." }, { "code": null, "e": 4125, "s": 3967, "text": "Pass the Line (node) object, created in the previous step, as a parameter to the constructor of the Group class, in order to add it to the group as follows −" }, { "code": null, "e": 4156, "s": 4125, "text": "Group root = new Group(line);\n" }, { "code": null, "e": 4327, "s": 4156, "text": "Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class pass the Group object (root), created in the previous step." }, { "code": null, "e": 4496, "s": 4327, "text": "In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows." }, { "code": null, "e": 4539, "s": 4496, "text": "Scene scene = new Scene(group ,600, 300);\n" }, { "code": null, "e": 4729, "s": 4539, "text": "You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter." }, { "code": null, "e": 4821, "s": 4729, "text": "Using the primaryStage object, set the title of the scene as Sample Application as follows." }, { "code": null, "e": 4867, "s": 4821, "text": "primaryStage.setTitle(\"Sample Application\");\n" }, { "code": null, "e": 5043, "s": 4867, "text": "You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene Object prepared in the previous steps using this method as follows." }, { "code": null, "e": 5073, "s": 5043, "text": "primaryStage.setScene(scene)\n" }, { "code": null, "e": 5168, "s": 5073, "text": "Display the contents of the scene using the method named show() of the Stage class as follows." }, { "code": null, "e": 5190, "s": 5168, "text": "primaryStage.show();\n" }, { "code": null, "e": 5317, "s": 5190, "text": "Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows." }, { "code": null, "e": 5386, "s": 5317, "text": "public static void main(String args[]){ \n launch(args); \n} " }, { "code": null, "e": 5514, "s": 5386, "text": "Following is the program which generates a straight line using JavaFX. Save this code in a file with the name DrawingLine.java." }, { "code": null, "e": 6493, "s": 5514, "text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.scene.shape.Line; \nimport javafx.stage.Stage; \n\npublic class DrawingLine extends Application{ \n @Override\n public void start(Stage stage) { \n //Creating a line object\n Line line = new Line(); \n \n //Setting the properties to a line \n line.setStartX(100.0); \n line.setStartY(150.0); \n line.setEndX(500.0); \n line.setEndY(150.0); \n \n //Creating a Group \n Group root = new Group(line); \n \n //Creating a Scene \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the scene \n stage.setTitle(\"Sample application\"); \n \n //Adding the scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of a scene \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n} " }, { "code": null, "e": 6587, "s": 6493, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 6629, "s": 6587, "text": "javac DrawingLine.java \njava DrawingLine\n" }, { "code": null, "e": 6730, "s": 6629, "text": "On executing, the above program generates a JavaFX window displaying a straight line as shown below." }, { "code": null, "e": 6765, "s": 6730, "text": "\n 33 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6776, "s": 6765, "text": " Syed Raza" }, { "code": null, "e": 6812, "s": 6776, "text": "\n 64 Lectures \n 12.5 hours \n" }, { "code": null, "e": 6848, "s": 6812, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 6881, "s": 6848, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 6917, "s": 6881, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 6924, "s": 6917, "text": " Print" }, { "code": null, "e": 6935, "s": 6924, "text": " Add Notes" } ]
Dice, Polls & Dirichlet Multinomials | by Claus Herther @ calogica.com | Towards Data Science
As part of a longer term project to learn Bayesian Statistics, I’m currently reading Bayesian Data Analysis, 3rd Edition by Andrew Gelman, John Carlin, Hal Stern, David Dunson, Aki Vehtari, and Donald Rubin, commonly known as BDA3. Although I’ve been using Bayesian statistics and probabilistic programming languages, like PyMC3, in projects for the last year or so, this book forces me to go beyond a pure practioner’s approach to modeling, while still delivering very practical value. Below are a few take aways from the earlier chapters in the book I found interesting. They are meant to hopefully inspire others to learn about Bayesian statistics, without trying to be overly formal about the math. If something doesn’t look 100% to the trained mathematicians in the room, please let me know, or just squint a little harder. ;) We’ll cover: Some common conjugate distributions An example of the Dirichlet-Multinomial distribution using dice rolls Two examples involving polling data from BDA3 In Chapter 2 of the book, the authors introduce several choices for prior probability distributions, along with the concept of conjugate distributions in section 2.4. From Wikipedia In Bayesian probability theory, if the posterior distributions p(θ | x) are in the same probability distribution family as the prior probability distribution p(θ), the prior and posterior are then called conjugate distributions, and the prior is called a conjugate prior for the likelihood function. John Cook has this helpful diagram on his website that shows some common families of conjugate distributions: Conjugate distributions are a very important concept in probability theory, owing to a large degree to some nice mathematical properties that make computing the posteriors more tractable. Even with increasingly better computational tools, such as MCMC, models based on conjugate distributions are advantageous. One of the better known examples of conjugate distributions is the Beta-Binomial distribution, which is often used to model series of coin flips (the ever present topic in posts about probability). While the Binomial distribution represents the probability of success in a series of Bernoulli trials, the Beta distribution here represents the prior probability distribution of the probability of success for each trial. Thus, the probability p of a coin landing on head is modeled to be Beta distributed (with parameters α and β), while the likelihood of heads and tails is assumed to follow a Binomial distribution with parameters n (representing the number of flips) and the Beta-distributed p, thus creating the link. p ∼ Beta(α,β) y ∼ Binomial(n,p) Another often-used conjugate distribution is the Gamma-Poisson distribution, so named because the rate parameter λ that parameterizes the Poisson distribution is modeled as a Gamma distribution: λ ∼ Gamma(k,θ) y ∼ Poisson(λ) While the discrete Poisson distribution is often used in applications of count data, such as store customers, eCommerce orders, website visits, the Gamma distribution serves as a useful distribution to model the rate at which these events occur (λ), since the Gamma distribution models positive continuous values only, but is otherwise quite flexible in its parameterization: This distribution is also known as the Negative-Binomial distribution, which we can think of as a mixture of Poission distributions. If you find this confusing, you’re not alone, and maybe you’ll start to appreciate why so often we try to approximate things using the good old Normal distribution... A perhaps even more interesting yet seemingly less talked-about example of conjugate distributions is the Dirichlet-Multinomial distribution, introduced in chapter 3 of BDA3. One way of think about the Dirichlet-Multinomial distribution is that while the Multinomial (i.e. multiple choices) distribution is a generalization of the Binomial distribution (i.e. binary choice), the Dirichlet distribution is a generalization of the Beta distribution. That is, while the Beta distribution models the probability of a single probability p, the Dirichlet models the probabilities of multiple, mutually exclusive choices, parameterized by a which is referred to as the concentration parameter and represents the weights for each choice (we’ll see more on that later). In other words, think of coins for the Beta-Binomial distribution and dice for the Dirichlet-Multinomial distribution. θ ∼ Dirichlet(a) y ∼ Multinomial(n,θ) In the wild, we might encounter the Dirichlet distribution these days often in the context of topic modeling in natural language processing, where it’s commonly used as part of a Latent Dirichlet Allocation (or LDA) model, which is a fancy way of saying we’re trying to figure out the probability of an article belonging to a certain topic given its content. However, for our purposes, let’s look at the Dirichlet-Multinomial in the context of simple multiple choices, and let’s start by throwing dice as a motivating example. (If you want to try out the code snippets here, you’ll need to import the relevant Python libraries first. Or you can follow along with the Jupyter notebook accompanying this article.) import numpy as npfrom scipy import statsimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport pymc3 as pm Let’s first create some data representing 122 rolls of six-sided die, where p represents the expected probability for each side of a fair die, i.e. 1/6. y = np.asarray([20, 21, 17, 19, 17, 28])k = len(y)p = 1/kn = y.sum()print(n, p)(122, 0.16666666666666666) Just looking at a simple bar plot of the data, we suspect that we might not be dealing with a fair die! sns.barplot(x=np.arange(1, k+1), y=y); However, students of Bayesian statistics that we are, we’d like to go further and quantify our uncertainty in the fairness of the die and calculate the probability that someone slipped us loaded dice. Let’s set up a simple model in PyMC3 that not only calculates the posterior probability for theta (i.e. the probability for each side of the die), but also estimates the die’s bias for returning a 6. We will use a PyMC3Deterministic variable for that purpose, in addition to our unobserved (theta) and observed (results) random variables. For the prior on theta, we’ll assume a non-informative Uniform distribution, by initializing the Dirichlet prior with a series of 1s for the parameter a, one for each of the k possible outcomes. This is similar to initializing a Beta distribution as Beta(1,1), which corresponds to the Uniform distribution (more on this here). with pm.Model() as dice_model: # initializes the Dirichlet distribution with a uniform prior: a = np.ones(k) theta = pm.Dirichlet("theta", a=a) # Since theta[5] will hold the posterior probability # of rolling a 6 we'll compare this to the # reference value p = 1/6 to determine the amount of bias # in the die six_bias = pm.Deterministic("six_bias", theta[k-1] - p) results = pm.Multinomial("results", n=n, p=theta, observed=y) Starting with version 3.5, PyMC3 includes a handy function to plot models in plate notation: pm.model_to_graphviz(dice_model) Let’s draw 1,000 samples from the joint posterior using the default NUTS sampler: with dice_model: dice_trace = pm.sample(draws=1000) Auto-assigning NUTS sampler...Initializing NUTS using jitter+adapt_diag...Multiprocess sampling (4 chains in 4 jobs)NUTS: [theta]Sampling 4 chains: 100%|██████████| 6000/6000 [00:01<00:00, 3822.31draws/s] From the traceplot, we can already see that one of the theta posteriors isn’t in line with the rest: with dice_model: pm.traceplot(dice_trace, combined=True, lines={"theta": p}) We’ll plot the posterior distributions for each theta and compare it our reference value p to see if the 95% HPD (Highest Posterior Density) interval includes p=1/6. axes = pm.plot_posterior(dice_trace, varnames=["theta"], ref_val=np.round(p, 3))for i, ax in enumerate(axes): ax.set_title(f"{i+1}") We can clearly see that the HPD for the posterior probability for rolling a 6 barely includes the value we’d expect from a fair die. To be more precise, let’s plot the probability of our die being biased towards 6, by comparing theta[Six] to p. ax = pm.plot_posterior(dice_trace, varnames=["six_bias"], ref_val=[0])ax.set_title(f"P(Theta[Six] - {p:.2%})"); Lastly, we can calculate the probability that the die is biased towards 6 by calculating the density to the right of our reference line at 0: six_bias = dice_trace["six_bias"]six_bias_perc = len(six_bias[six_bias>0])/len(six_bias) print(f'P(Six is biased) = {six_bias_perc:.2%}')P(Six is biased) = 95.25% Thus, there’s a better than 95% chance that our die is biased towards 6. Better get some new dice...! Let’s turn our review of the Dirichlet-Multinomial distribution to another example, concerning polling data. In section 3.4 of BDA3 on multivariate models and, specifically the section on Multinomial Models for Categorical Data, the authors include a, little dated, example of polling data in the 1988 Presidential race between George H.W. Bush and Michael Dukakis. Spoiler alert for those not following politics back then: Bush won by a huge margin. Since 1988, no candidate in a Presidential election has managed to equal or surpass Bush’s share of the electoral or popular vote. Anyway, back to the data problem! Here’s the setup: 1,447 likely voters were surveyed about their preferences in the upcoming presidential election Their responses were:Bush: 727Dukakis: 583Other: 137 What is the probability that more people will vote for Bush over Dukakis?i.e. what is the difference in support for the two major candidates? We set up the data, where k represents the number of choices the respondents had: y = np.asarray([727, 583, 137])n = y.sum()k = len(y) We, again, set up a simple Dirichlet-Multinomial model and include a Deterministic variable that calculates the value of interest - the difference in probability of respondents for Bush vs. Dukakis. with pm.Model() as polling_model: # initializes the Dirichlet distribution with a uniform prior: a = np.ones(k) theta = pm.Dirichlet("theta", a=a) bush_dukakis_diff = pm.Deterministic("bush_dukakis_diff", theta[0] - theta[1]) likelihood = pm.Multinomial("likelihood", n=n, p=theta, observed=y)pm.model_to_graphviz(polling_model) with polling_model: polling_trace = pm.sample(draws=1000) Looking at the % difference between respondents for Bush vs Dukakis, we can see that most of the density is greater than 0%, signifying a strong advantage for Bush in this poll.We’ve also fit a Beta distribution to this data via scipy.stats, and we can see that the posterior of the difference of the 2 theta values fits a Beta distribution very nicely (which is to be expected given the properties of the Dirichlet distribution as a multivariate generalization of the Beta distribution). _, ax = plt.subplots(1,1, figsize=(10, 6))sns.distplot(polling_trace["bush_dukakis_diff"], bins=20, ax=ax, kde=False, fit=stats.beta)ax.axvline(0, c='g', linestyle='dotted')ax.set_title("% Difference Bush vs Dukakis")ax.set_xlabel("% Difference"); Percentage of samples with bush_dukakis_diff > 0: diff = polling_trace["bush_dukakis_diff"]bush_dukakis_diff_perc = len(diff[diff>0])/len(diff) print(f'P(More Responses for Bush) = {bush_dukakis_diff_perc:.0%}')P(More Responses for Bush) = 100% As an extension to the previous model, the authors of BDA include an exercise in chapter 3.10 (Exercise 2) that presents us with polling data from the 1988 Presidential race, taking before and after the one of the debates. Comparison of two multinomial observations: on September 25, 1988, the evening of a presidential campaign debate, ABC News conducted a survey of registered voters in the United States; 639 persons were polled before the debate, and 639 different persons were polled after. The results are displayed in Table 3.2. Assume the surveys are independent simple random samples from the population of registered voters. Model the data with two different multinomial distributions. For j=1,2, let αj be the proportion of voters who preferred Bush, out of those who had a preference for either Bush or Dukakis at the time of survey j. Plot a histogram of the posterior density for α2−α1. What is the posterior probability that there was a shift toward Bush? Let’s copy the data from the exercise and model the problem as a probabilistic model, again using PyMC3: data = pd.DataFrame([ {"candidate": "bush", "pre": 294, "post": 288}, {"candidate": "dukakis", "pre": 307, "post": 332}, {"candidate": "other", "pre": 38, "post": 10} ], columns=["candidate", "pre", "post"]) Convert to 2x3 array: y = data[["pre", "post"]].T.valuesprint(y) array([[294, 307, 38], [288, 332, 10]]) Number of respondents in each survey: n = y.sum(axis=1) print(n)array([639, 630]) Number of respondents for the 2 major candidates in each survey: m = y[:, :2].sum(axis=1) print(m) array([601, 620]) For this model, we’ll need to set up the priors slightly differently. Instead of 1 set of thetas, we need 2, one for each survey (pre/post debate). To do that without creating specific pre/post versions of each variable, we’ll take advantage of PyMC3’s shape parameter, available for most (all?) distributions. In this case, we’ll need a 2-dimensional shape parameter, representing the number of debates n_debates and the number of choices in candidates n_candidates n_debates, n_candidates = y.shapeprint(n_debates, n_candidates) (2, 3) Thus, we need to initialize a Dirichlet distribution prior with shape (2,3) and then refer to the relevant parameters by index where needed. with pm.Model() as polling_model_debates: # initializes the Dirichlet distribution with a uniform prior: shape = (n_debates, n_candidates) a = np.ones(shape) # This creates a separate Dirichlet distribution for each debate # where sum of probabilities across candidates = 100% # for each debate theta = pm.Dirichlet("theta", a=a, shape=shape) # get the "Bush" theta for each debate, at index=0 # and normalize across supporters for the 2 major candidates bush_pref = pm.Deterministic("bush_pref", theta[:, 0] * n / m) # to calculate probability that support for Bush # shifted from debate 1 [0] to 2 [1] bush_shift = pm.Deterministic("bush_shift", bush_pref[1]-bush_pref[0]) # because of the shapes of the inputs, # this essentially creates 2 multinomials, # one for each debate responses = pm.Multinomial("responses", n=n, p=theta, observed=y) For models with multi-dimensional shapes, it’s always good to check the shapes of the various parameters before sampling: for v in polling_model_debates.unobserved_RVs: print(v, v.tag.test_value.shape)theta_stickbreaking__ (2, 2)theta (2, 3)bush_pref (2,)bush_shift () The plate notation visual can also help with that: pm.model_to_graphviz(polling_model_debates) Let’s sample with a slightly higher number of draws and tuning steps: with polling_model_debates: polling_trace_debates = pm.sample(draws=3000, tune=1500) A quick look at the traceplot to make sure the model converged smoothly: with polling_model_debates: pm.traceplot(polling_trace_debates, combined=True) Let’s take a look at the means of the posteriors for theta, indicating the % of support for each candidate pre & post debate: s = ["pre", "post"]candidates = data["candidate"].valuespd.DataFrame(polling_trace_debates["theta"].mean(axis=0), index=s, columns=candidates) Just from the means, we can see that the number of Bush supporters has likely decreased post debate from 48.8% to 46.3% (as a % of supporters of the 2 major candidates): pd.DataFrame(polling_trace_debates["bush_pref"].mean(axis=0), index=s, columns=["bush_pref"]) Let’s compare the results visually, by plotting the posterior distributions of the pre/post debate values for % responses for Bush and the posterior for pre/post difference in Bush supporters: _, ax = plt.subplots(2,1, figsize=(10, 10))sns.distplot(polling_trace_debates["bush_pref"][:,0], hist=False, ax=ax[0], label="Pre-Debate")sns.distplot(polling_trace_debates["bush_pref"][:,1], hist=False, ax=ax[0], label="Post-Debate")ax[0].set_title("% Responses for Bush vs Dukakis")ax[0].set_xlabel("% Responses");sns.distplot(polling_trace_debates["bush_shift"], hist=True, ax=ax[1], label="P(Bush Shift)")ax[1].axvline(0, c='g', linestyle='dotted')ax[1].set_title("% Shift Pre/Prior Debate")ax[1].set_xlabel("% Shift"); From the second plot, we can already see that a large portion of the posterior density is below 0, but let’s be precise and actually calculate the probability that support shifted towards Bush after the debate: bush_shift = polling_trace_debates["bush_shift"]perc_shift = ( len(bush_shift[bush_shift > 0]) /len(bush_shift) )print(f'P(Shift Towards Bush) = {perc_shift:.1%}')P(Shift Towards Bush) = 19.9% While that was a sort of round-about way to show that Bush lost support during the September debate, hopefully this illustrated the flexibility and robustness of probabilistic models (and PyMC3). If you have any thoughts or feedback on this post, please let me know! (This post is also available as a Jupyter Notebook on Github.)
[ { "code": null, "e": 658, "s": 171, "text": "As part of a longer term project to learn Bayesian Statistics, I’m currently reading Bayesian Data Analysis, 3rd Edition by Andrew Gelman, John Carlin, Hal Stern, David Dunson, Aki Vehtari, and Donald Rubin, commonly known as BDA3. Although I’ve been using Bayesian statistics and probabilistic programming languages, like PyMC3, in projects for the last year or so, this book forces me to go beyond a pure practioner’s approach to modeling, while still delivering very practical value." }, { "code": null, "e": 1003, "s": 658, "text": "Below are a few take aways from the earlier chapters in the book I found interesting. They are meant to hopefully inspire others to learn about Bayesian statistics, without trying to be overly formal about the math. If something doesn’t look 100% to the trained mathematicians in the room, please let me know, or just squint a little harder. ;)" }, { "code": null, "e": 1016, "s": 1003, "text": "We’ll cover:" }, { "code": null, "e": 1052, "s": 1016, "text": "Some common conjugate distributions" }, { "code": null, "e": 1122, "s": 1052, "text": "An example of the Dirichlet-Multinomial distribution using dice rolls" }, { "code": null, "e": 1168, "s": 1122, "text": "Two examples involving polling data from BDA3" }, { "code": null, "e": 1335, "s": 1168, "text": "In Chapter 2 of the book, the authors introduce several choices for prior probability distributions, along with the concept of conjugate distributions in section 2.4." }, { "code": null, "e": 1350, "s": 1335, "text": "From Wikipedia" }, { "code": null, "e": 1650, "s": 1350, "text": "In Bayesian probability theory, if the posterior distributions p(θ | x) are in the same probability distribution family as the prior probability distribution p(θ), the prior and posterior are then called conjugate distributions, and the prior is called a conjugate prior for the likelihood function." }, { "code": null, "e": 1760, "s": 1650, "text": "John Cook has this helpful diagram on his website that shows some common families of conjugate distributions:" }, { "code": null, "e": 2071, "s": 1760, "text": "Conjugate distributions are a very important concept in probability theory, owing to a large degree to some nice mathematical properties that make computing the posteriors more tractable. Even with increasingly better computational tools, such as MCMC, models based on conjugate distributions are advantageous." }, { "code": null, "e": 2269, "s": 2071, "text": "One of the better known examples of conjugate distributions is the Beta-Binomial distribution, which is often used to model series of coin flips (the ever present topic in posts about probability)." }, { "code": null, "e": 2491, "s": 2269, "text": "While the Binomial distribution represents the probability of success in a series of Bernoulli trials, the Beta distribution here represents the prior probability distribution of the probability of success for each trial." }, { "code": null, "e": 2792, "s": 2491, "text": "Thus, the probability p of a coin landing on head is modeled to be Beta distributed (with parameters α and β), while the likelihood of heads and tails is assumed to follow a Binomial distribution with parameters n (representing the number of flips) and the Beta-distributed p, thus creating the link." }, { "code": null, "e": 2806, "s": 2792, "text": "p ∼ Beta(α,β)" }, { "code": null, "e": 2824, "s": 2806, "text": "y ∼ Binomial(n,p)" }, { "code": null, "e": 3019, "s": 2824, "text": "Another often-used conjugate distribution is the Gamma-Poisson distribution, so named because the rate parameter λ that parameterizes the Poisson distribution is modeled as a Gamma distribution:" }, { "code": null, "e": 3034, "s": 3019, "text": "λ ∼ Gamma(k,θ)" }, { "code": null, "e": 3049, "s": 3034, "text": "y ∼ Poisson(λ)" }, { "code": null, "e": 3425, "s": 3049, "text": "While the discrete Poisson distribution is often used in applications of count data, such as store customers, eCommerce orders, website visits, the Gamma distribution serves as a useful distribution to model the rate at which these events occur (λ), since the Gamma distribution models positive continuous values only, but is otherwise quite flexible in its parameterization:" }, { "code": null, "e": 3558, "s": 3425, "text": "This distribution is also known as the Negative-Binomial distribution, which we can think of as a mixture of Poission distributions." }, { "code": null, "e": 3725, "s": 3558, "text": "If you find this confusing, you’re not alone, and maybe you’ll start to appreciate why so often we try to approximate things using the good old Normal distribution..." }, { "code": null, "e": 3900, "s": 3725, "text": "A perhaps even more interesting yet seemingly less talked-about example of conjugate distributions is the Dirichlet-Multinomial distribution, introduced in chapter 3 of BDA3." }, { "code": null, "e": 4486, "s": 3900, "text": "One way of think about the Dirichlet-Multinomial distribution is that while the Multinomial (i.e. multiple choices) distribution is a generalization of the Binomial distribution (i.e. binary choice), the Dirichlet distribution is a generalization of the Beta distribution. That is, while the Beta distribution models the probability of a single probability p, the Dirichlet models the probabilities of multiple, mutually exclusive choices, parameterized by a which is referred to as the concentration parameter and represents the weights for each choice (we’ll see more on that later)." }, { "code": null, "e": 4605, "s": 4486, "text": "In other words, think of coins for the Beta-Binomial distribution and dice for the Dirichlet-Multinomial distribution." }, { "code": null, "e": 4622, "s": 4605, "text": "θ ∼ Dirichlet(a)" }, { "code": null, "e": 4643, "s": 4622, "text": "y ∼ Multinomial(n,θ)" }, { "code": null, "e": 5002, "s": 4643, "text": "In the wild, we might encounter the Dirichlet distribution these days often in the context of topic modeling in natural language processing, where it’s commonly used as part of a Latent Dirichlet Allocation (or LDA) model, which is a fancy way of saying we’re trying to figure out the probability of an article belonging to a certain topic given its content." }, { "code": null, "e": 5170, "s": 5002, "text": "However, for our purposes, let’s look at the Dirichlet-Multinomial in the context of simple multiple choices, and let’s start by throwing dice as a motivating example." }, { "code": null, "e": 5355, "s": 5170, "text": "(If you want to try out the code snippets here, you’ll need to import the relevant Python libraries first. Or you can follow along with the Jupyter notebook accompanying this article.)" }, { "code": null, "e": 5486, "s": 5355, "text": "import numpy as npfrom scipy import statsimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport pymc3 as pm" }, { "code": null, "e": 5639, "s": 5486, "text": "Let’s first create some data representing 122 rolls of six-sided die, where p represents the expected probability for each side of a fair die, i.e. 1/6." }, { "code": null, "e": 5746, "s": 5639, "text": "y = np.asarray([20, 21, 17, 19, 17, 28])k = len(y)p = 1/kn = y.sum()print(n, p)(122, 0.16666666666666666)" }, { "code": null, "e": 5850, "s": 5746, "text": "Just looking at a simple bar plot of the data, we suspect that we might not be dealing with a fair die!" }, { "code": null, "e": 5889, "s": 5850, "text": "sns.barplot(x=np.arange(1, k+1), y=y);" }, { "code": null, "e": 6090, "s": 5889, "text": "However, students of Bayesian statistics that we are, we’d like to go further and quantify our uncertainty in the fairness of the die and calculate the probability that someone slipped us loaded dice." }, { "code": null, "e": 6429, "s": 6090, "text": "Let’s set up a simple model in PyMC3 that not only calculates the posterior probability for theta (i.e. the probability for each side of the die), but also estimates the die’s bias for returning a 6. We will use a PyMC3Deterministic variable for that purpose, in addition to our unobserved (theta) and observed (results) random variables." }, { "code": null, "e": 6757, "s": 6429, "text": "For the prior on theta, we’ll assume a non-informative Uniform distribution, by initializing the Dirichlet prior with a series of 1s for the parameter a, one for each of the k possible outcomes. This is similar to initializing a Beta distribution as Beta(1,1), which corresponds to the Uniform distribution (more on this here)." }, { "code": null, "e": 7233, "s": 6757, "text": "with pm.Model() as dice_model: # initializes the Dirichlet distribution with a uniform prior: a = np.ones(k) theta = pm.Dirichlet(\"theta\", a=a) # Since theta[5] will hold the posterior probability # of rolling a 6 we'll compare this to the # reference value p = 1/6 to determine the amount of bias # in the die six_bias = pm.Deterministic(\"six_bias\", theta[k-1] - p) results = pm.Multinomial(\"results\", n=n, p=theta, observed=y)" }, { "code": null, "e": 7326, "s": 7233, "text": "Starting with version 3.5, PyMC3 includes a handy function to plot models in plate notation:" }, { "code": null, "e": 7359, "s": 7326, "text": "pm.model_to_graphviz(dice_model)" }, { "code": null, "e": 7441, "s": 7359, "text": "Let’s draw 1,000 samples from the joint posterior using the default NUTS sampler:" }, { "code": null, "e": 7701, "s": 7441, "text": "with dice_model: dice_trace = pm.sample(draws=1000) Auto-assigning NUTS sampler...Initializing NUTS using jitter+adapt_diag...Multiprocess sampling (4 chains in 4 jobs)NUTS: [theta]Sampling 4 chains: 100%|██████████| 6000/6000 [00:01<00:00, 3822.31draws/s]" }, { "code": null, "e": 7802, "s": 7701, "text": "From the traceplot, we can already see that one of the theta posteriors isn’t in line with the rest:" }, { "code": null, "e": 7882, "s": 7802, "text": "with dice_model: pm.traceplot(dice_trace, combined=True, lines={\"theta\": p})" }, { "code": null, "e": 8048, "s": 7882, "text": "We’ll plot the posterior distributions for each theta and compare it our reference value p to see if the 95% HPD (Highest Posterior Density) interval includes p=1/6." }, { "code": null, "e": 8236, "s": 8048, "text": "axes = pm.plot_posterior(dice_trace, varnames=[\"theta\"], ref_val=np.round(p, 3))for i, ax in enumerate(axes): ax.set_title(f\"{i+1}\")" }, { "code": null, "e": 8369, "s": 8236, "text": "We can clearly see that the HPD for the posterior probability for rolling a 6 barely includes the value we’d expect from a fair die." }, { "code": null, "e": 8481, "s": 8369, "text": "To be more precise, let’s plot the probability of our die being biased towards 6, by comparing theta[Six] to p." }, { "code": null, "e": 8641, "s": 8481, "text": "ax = pm.plot_posterior(dice_trace, varnames=[\"six_bias\"], ref_val=[0])ax.set_title(f\"P(Theta[Six] - {p:.2%})\");" }, { "code": null, "e": 8783, "s": 8641, "text": "Lastly, we can calculate the probability that the die is biased towards 6 by calculating the density to the right of our reference line at 0:" }, { "code": null, "e": 8951, "s": 8783, "text": "six_bias = dice_trace[\"six_bias\"]six_bias_perc = len(six_bias[six_bias>0])/len(six_bias) print(f'P(Six is biased) = {six_bias_perc:.2%}')P(Six is biased) = 95.25%" }, { "code": null, "e": 9053, "s": 8951, "text": "Thus, there’s a better than 95% chance that our die is biased towards 6. Better get some new dice...!" }, { "code": null, "e": 9162, "s": 9053, "text": "Let’s turn our review of the Dirichlet-Multinomial distribution to another example, concerning polling data." }, { "code": null, "e": 9419, "s": 9162, "text": "In section 3.4 of BDA3 on multivariate models and, specifically the section on Multinomial Models for Categorical Data, the authors include a, little dated, example of polling data in the 1988 Presidential race between George H.W. Bush and Michael Dukakis." }, { "code": null, "e": 9635, "s": 9419, "text": "Spoiler alert for those not following politics back then: Bush won by a huge margin. Since 1988, no candidate in a Presidential election has managed to equal or surpass Bush’s share of the electoral or popular vote." }, { "code": null, "e": 9687, "s": 9635, "text": "Anyway, back to the data problem! Here’s the setup:" }, { "code": null, "e": 9783, "s": 9687, "text": "1,447 likely voters were surveyed about their preferences in the upcoming presidential election" }, { "code": null, "e": 9836, "s": 9783, "text": "Their responses were:Bush: 727Dukakis: 583Other: 137" }, { "code": null, "e": 9978, "s": 9836, "text": "What is the probability that more people will vote for Bush over Dukakis?i.e. what is the difference in support for the two major candidates?" }, { "code": null, "e": 10060, "s": 9978, "text": "We set up the data, where k represents the number of choices the respondents had:" }, { "code": null, "e": 10113, "s": 10060, "text": "y = np.asarray([727, 583, 137])n = y.sum()k = len(y)" }, { "code": null, "e": 10312, "s": 10113, "text": "We, again, set up a simple Dirichlet-Multinomial model and include a Deterministic variable that calculates the value of interest - the difference in probability of respondents for Bush vs. Dukakis." }, { "code": null, "e": 10813, "s": 10312, "text": "with pm.Model() as polling_model: # initializes the Dirichlet distribution with a uniform prior: a = np.ones(k) theta = pm.Dirichlet(\"theta\", a=a) bush_dukakis_diff = pm.Deterministic(\"bush_dukakis_diff\", theta[0] - theta[1]) likelihood = pm.Multinomial(\"likelihood\", n=n, p=theta, observed=y)pm.model_to_graphviz(polling_model)" }, { "code": null, "e": 10874, "s": 10813, "text": "with polling_model: polling_trace = pm.sample(draws=1000)" }, { "code": null, "e": 11363, "s": 10874, "text": "Looking at the % difference between respondents for Bush vs Dukakis, we can see that most of the density is greater than 0%, signifying a strong advantage for Bush in this poll.We’ve also fit a Beta distribution to this data via scipy.stats, and we can see that the posterior of the difference of the 2 theta values fits a Beta distribution very nicely (which is to be expected given the properties of the Dirichlet distribution as a multivariate generalization of the Beta distribution)." }, { "code": null, "e": 11616, "s": 11363, "text": "_, ax = plt.subplots(1,1, figsize=(10, 6))sns.distplot(polling_trace[\"bush_dukakis_diff\"], bins=20, ax=ax, kde=False, fit=stats.beta)ax.axvline(0, c='g', linestyle='dotted')ax.set_title(\"% Difference Bush vs Dukakis\")ax.set_xlabel(\"% Difference\");" }, { "code": null, "e": 11666, "s": 11616, "text": "Percentage of samples with bush_dukakis_diff > 0:" }, { "code": null, "e": 11866, "s": 11666, "text": "diff = polling_trace[\"bush_dukakis_diff\"]bush_dukakis_diff_perc = len(diff[diff>0])/len(diff) print(f'P(More Responses for Bush) = {bush_dukakis_diff_perc:.0%}')P(More Responses for Bush) = 100%" }, { "code": null, "e": 12089, "s": 11866, "text": "As an extension to the previous model, the authors of BDA include an exercise in chapter 3.10 (Exercise 2) that presents us with polling data from the 1988 Presidential race, taking before and after the one of the debates." }, { "code": null, "e": 12837, "s": 12089, "text": "Comparison of two multinomial observations: on September 25, 1988, the evening of a presidential campaign debate, ABC News conducted a survey of registered voters in the United States; 639 persons were polled before the debate, and 639 different persons were polled after. The results are displayed in Table 3.2. Assume the surveys are independent simple random samples from the population of registered voters. Model the data with two different multinomial distributions. For j=1,2, let αj be the proportion of voters who preferred Bush, out of those who had a preference for either Bush or Dukakis at the time of survey j. Plot a histogram of the posterior density for α2−α1. What is the posterior probability that there was a shift toward Bush?" }, { "code": null, "e": 12942, "s": 12837, "text": "Let’s copy the data from the exercise and model the problem as a probabilistic model, again using PyMC3:" }, { "code": null, "e": 13177, "s": 12942, "text": "data = pd.DataFrame([ {\"candidate\": \"bush\", \"pre\": 294, \"post\": 288}, {\"candidate\": \"dukakis\", \"pre\": 307, \"post\": 332}, {\"candidate\": \"other\", \"pre\": 38, \"post\": 10} ], columns=[\"candidate\", \"pre\", \"post\"])" }, { "code": null, "e": 13199, "s": 13177, "text": "Convert to 2x3 array:" }, { "code": null, "e": 13290, "s": 13199, "text": "y = data[[\"pre\", \"post\"]].T.valuesprint(y) array([[294, 307, 38], [288, 332, 10]])" }, { "code": null, "e": 13328, "s": 13290, "text": "Number of respondents in each survey:" }, { "code": null, "e": 13372, "s": 13328, "text": "n = y.sum(axis=1) print(n)array([639, 630])" }, { "code": null, "e": 13437, "s": 13372, "text": "Number of respondents for the 2 major candidates in each survey:" }, { "code": null, "e": 13489, "s": 13437, "text": "m = y[:, :2].sum(axis=1) print(m) array([601, 620])" }, { "code": null, "e": 13800, "s": 13489, "text": "For this model, we’ll need to set up the priors slightly differently. Instead of 1 set of thetas, we need 2, one for each survey (pre/post debate). To do that without creating specific pre/post versions of each variable, we’ll take advantage of PyMC3’s shape parameter, available for most (all?) distributions." }, { "code": null, "e": 13956, "s": 13800, "text": "In this case, we’ll need a 2-dimensional shape parameter, representing the number of debates n_debates and the number of choices in candidates n_candidates" }, { "code": null, "e": 14027, "s": 13956, "text": "n_debates, n_candidates = y.shapeprint(n_debates, n_candidates) (2, 3)" }, { "code": null, "e": 14168, "s": 14027, "text": "Thus, we need to initialize a Dirichlet distribution prior with shape (2,3) and then refer to the relevant parameters by index where needed." }, { "code": null, "e": 15104, "s": 14168, "text": "with pm.Model() as polling_model_debates: # initializes the Dirichlet distribution with a uniform prior: shape = (n_debates, n_candidates) a = np.ones(shape) # This creates a separate Dirichlet distribution for each debate # where sum of probabilities across candidates = 100% # for each debate theta = pm.Dirichlet(\"theta\", a=a, shape=shape) # get the \"Bush\" theta for each debate, at index=0 # and normalize across supporters for the 2 major candidates bush_pref = pm.Deterministic(\"bush_pref\", theta[:, 0] * n / m) # to calculate probability that support for Bush # shifted from debate 1 [0] to 2 [1] bush_shift = pm.Deterministic(\"bush_shift\", bush_pref[1]-bush_pref[0]) # because of the shapes of the inputs, # this essentially creates 2 multinomials, # one for each debate responses = pm.Multinomial(\"responses\", n=n, p=theta, observed=y)" }, { "code": null, "e": 15226, "s": 15104, "text": "For models with multi-dimensional shapes, it’s always good to check the shapes of the various parameters before sampling:" }, { "code": null, "e": 15377, "s": 15226, "text": "for v in polling_model_debates.unobserved_RVs: print(v, v.tag.test_value.shape)theta_stickbreaking__ (2, 2)theta (2, 3)bush_pref (2,)bush_shift () " }, { "code": null, "e": 15428, "s": 15377, "text": "The plate notation visual can also help with that:" }, { "code": null, "e": 15472, "s": 15428, "text": "pm.model_to_graphviz(polling_model_debates)" }, { "code": null, "e": 15542, "s": 15472, "text": "Let’s sample with a slightly higher number of draws and tuning steps:" }, { "code": null, "e": 15630, "s": 15542, "text": "with polling_model_debates: polling_trace_debates = pm.sample(draws=3000, tune=1500)" }, { "code": null, "e": 15703, "s": 15630, "text": "A quick look at the traceplot to make sure the model converged smoothly:" }, { "code": null, "e": 15785, "s": 15703, "text": "with polling_model_debates: pm.traceplot(polling_trace_debates, combined=True)" }, { "code": null, "e": 15911, "s": 15785, "text": "Let’s take a look at the means of the posteriors for theta, indicating the % of support for each candidate pre & post debate:" }, { "code": null, "e": 16062, "s": 15911, "text": "s = [\"pre\", \"post\"]candidates = data[\"candidate\"].valuespd.DataFrame(polling_trace_debates[\"theta\"].mean(axis=0), index=s, columns=candidates)" }, { "code": null, "e": 16232, "s": 16062, "text": "Just from the means, we can see that the number of Bush supporters has likely decreased post debate from 48.8% to 46.3% (as a % of supporters of the 2 major candidates):" }, { "code": null, "e": 16331, "s": 16232, "text": "pd.DataFrame(polling_trace_debates[\"bush_pref\"].mean(axis=0), index=s, columns=[\"bush_pref\"])" }, { "code": null, "e": 16524, "s": 16331, "text": "Let’s compare the results visually, by plotting the posterior distributions of the pre/post debate values for % responses for Bush and the posterior for pre/post difference in Bush supporters:" }, { "code": null, "e": 17060, "s": 16524, "text": "_, ax = plt.subplots(2,1, figsize=(10, 10))sns.distplot(polling_trace_debates[\"bush_pref\"][:,0], hist=False, ax=ax[0], label=\"Pre-Debate\")sns.distplot(polling_trace_debates[\"bush_pref\"][:,1], hist=False, ax=ax[0], label=\"Post-Debate\")ax[0].set_title(\"% Responses for Bush vs Dukakis\")ax[0].set_xlabel(\"% Responses\");sns.distplot(polling_trace_debates[\"bush_shift\"], hist=True, ax=ax[1], label=\"P(Bush Shift)\")ax[1].axvline(0, c='g', linestyle='dotted')ax[1].set_title(\"% Shift Pre/Prior Debate\")ax[1].set_xlabel(\"% Shift\");" }, { "code": null, "e": 17271, "s": 17060, "text": "From the second plot, we can already see that a large portion of the posterior density is below 0, but let’s be precise and actually calculate the probability that support shifted towards Bush after the debate:" }, { "code": null, "e": 17502, "s": 17271, "text": "bush_shift = polling_trace_debates[\"bush_shift\"]perc_shift = ( len(bush_shift[bush_shift > 0]) /len(bush_shift) )print(f'P(Shift Towards Bush) = {perc_shift:.1%}')P(Shift Towards Bush) = 19.9%" }, { "code": null, "e": 17698, "s": 17502, "text": "While that was a sort of round-about way to show that Bush lost support during the September debate, hopefully this illustrated the flexibility and robustness of probabilistic models (and PyMC3)." }, { "code": null, "e": 17769, "s": 17698, "text": "If you have any thoughts or feedback on this post, please let me know!" } ]
map insert() in C++ STL - GeeksforGeeks
11 May, 2022 The map::insert() is a built-in function in C++ STL which is used to insert elements with a particular key in the map container. Syntax: iterator map_name.insert({key, element}) Parameters: The function accepts a pair that consists of a key and element which is to be inserted into the map container. The function does not insert the key and element in the map if the key already exists in the map. Return Value: The function returns an iterator pointing to the new element in the container. Below is the illustration of the above syntax: C++ // C++ program to illustrate// map::insert({key, element})#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); // does not inserts key 2 with element 20 mp.insert({ 2, 20 }); mp.insert({ 5, 50 }); // prints the elements cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;} KEY ELEMENT 1 40 2 30 3 60 5 50 Syntax: iterator map_name.insert(iterator position, {key, element}) Parameters: The function accepts two parameters which is described below: {key, element}: This specifies a pair that consists of a key and element which is to be inserted into the map container. position: This does not specify the position where the insertion is to be done, it only points to a position from where the searching operation for insertion is to be started to make the process faster. The insertion is done according to the order which is followed by the map container. Return Value: The function returns an iterator pointing to the new element in the container. Below is the illustration of the above syntax: C++ // C++ program to illustrate // map::insert(iteratorposition, {key, element}) #include <bits/stdc++.h> using namespace std; int main() { // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); auto it = mp.find(2); // inserts {3, 60} starting the search from // position where 2 is present mp.insert(it, { 3, 60 }); // prints the elements cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0; } Output: KEY ELEMENT 1 40 2 30 3 60 Syntax: iterator map_name.insert(iterator position1, iterator position2) Parameters: The function accepts two parameters position1 and position2 which specifies the range of elements. All the elements in the range [position1, last) are inserted in another map container. Return Value: The function returns an iterator pointing to the new element in the container. Below is the illustration of the above syntax: C++ // C++ program to illustrate// map::insert(iteratorposition1, iteratorposition2)#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp, mp1; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); // inserts all elements in range // [begin, end) in mp1 mp1.insert(mp.begin(), mp.end()); // prints the elements cout << "Elements in mp1 are\n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp1.begin(); itr != mp1.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;} Elements in mp1 are KEY ELEMENT 1 40 2 30 arorakashish0911 CPP-Functions cpp-map STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Virtual Function in C++ C++ Classes and Objects Bitwise Operators in C/C++ Templates in C++ with Examples Constructors in C++ Operator Overloading in C++ Socket Programming in C/C++ Polymorphism in C++ Object Oriented Programming in C++
[ { "code": null, "e": 26380, "s": 26352, "text": "\n11 May, 2022" }, { "code": null, "e": 26510, "s": 26380, "text": "The map::insert() is a built-in function in C++ STL which is used to insert elements with a particular key in the map container. " }, { "code": null, "e": 26519, "s": 26510, "text": "Syntax: " }, { "code": null, "e": 26564, "s": 26519, "text": "iterator map_name.insert({key, element})\n\n\n\n" }, { "code": null, "e": 26786, "s": 26564, "text": "Parameters: The function accepts a pair that consists of a key and element which is to be inserted into the map container. The function does not insert the key and element in the map if the key already exists in the map. " }, { "code": null, "e": 26880, "s": 26786, "text": "Return Value: The function returns an iterator pointing to the new element in the container. " }, { "code": null, "e": 26928, "s": 26880, "text": "Below is the illustration of the above syntax: " }, { "code": null, "e": 26932, "s": 26928, "text": "C++" }, { "code": "// C++ program to illustrate// map::insert({key, element})#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); // does not inserts key 2 with element 20 mp.insert({ 2, 20 }); mp.insert({ 5, 50 }); // prints the elements cout << \"KEY\\tELEMENT\\n\"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\\t' << itr->second << '\\n'; } return 0;}", "e": 27513, "s": 26932, "text": null }, { "code": null, "e": 27564, "s": 27513, "text": "KEY ELEMENT\n1 40\n2 30\n3 60\n5 50\n\n\n\n" }, { "code": null, "e": 27575, "s": 27566, "text": "Syntax: " }, { "code": null, "e": 27639, "s": 27575, "text": "iterator map_name.insert(iterator position, {key, element})\n\n\n\n" }, { "code": null, "e": 27714, "s": 27639, "text": "Parameters: The function accepts two parameters which is described below: " }, { "code": null, "e": 27835, "s": 27714, "text": "{key, element}: This specifies a pair that consists of a key and element which is to be inserted into the map container." }, { "code": null, "e": 28123, "s": 27835, "text": "position: This does not specify the position where the insertion is to be done, it only points to a position from where the searching operation for insertion is to be started to make the process faster. The insertion is done according to the order which is followed by the map container." }, { "code": null, "e": 28216, "s": 28123, "text": "Return Value: The function returns an iterator pointing to the new element in the container." }, { "code": null, "e": 28263, "s": 28216, "text": "Below is the illustration of the above syntax:" }, { "code": null, "e": 28267, "s": 28263, "text": "C++" }, { "code": "// C++ program to illustrate // map::insert(iteratorposition, {key, element}) #include <bits/stdc++.h> using namespace std; int main() { // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); auto it = mp.find(2); // inserts {3, 60} starting the search from // position where 2 is present mp.insert(it, { 3, 60 }); // prints the elements cout << \"KEY\\tELEMENT\\n\"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\\t' << itr->second << '\\n'; } return 0; } ", "e": 28907, "s": 28267, "text": null }, { "code": null, "e": 28915, "s": 28907, "text": "Output:" }, { "code": null, "e": 28956, "s": 28915, "text": "KEY ELEMENT\n1 40\n2 30\n3 60\n\n" }, { "code": null, "e": 28965, "s": 28956, "text": "Syntax: " }, { "code": null, "e": 29034, "s": 28965, "text": "iterator map_name.insert(iterator position1, iterator position2)\n\n\n\n" }, { "code": null, "e": 29233, "s": 29034, "text": "Parameters: The function accepts two parameters position1 and position2 which specifies the range of elements. All the elements in the range [position1, last) are inserted in another map container. " }, { "code": null, "e": 29327, "s": 29233, "text": "Return Value: The function returns an iterator pointing to the new element in the container. " }, { "code": null, "e": 29375, "s": 29327, "text": "Below is the illustration of the above syntax: " }, { "code": null, "e": 29379, "s": 29375, "text": "C++" }, { "code": "// C++ program to illustrate// map::insert(iteratorposition1, iteratorposition2)#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp, mp1; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); // inserts all elements in range // [begin, end) in mp1 mp1.insert(mp.begin(), mp.end()); // prints the elements cout << \"Elements in mp1 are\\n\"; cout << \"KEY\\tELEMENT\\n\"; for (auto itr = mp1.begin(); itr != mp1.end(); ++itr) { cout << itr->first << '\\t' << itr->second << '\\n'; } return 0;}", "e": 30004, "s": 29379, "text": null }, { "code": null, "e": 30059, "s": 30004, "text": "Elements in mp1 are\nKEY ELEMENT\n1 40\n2 30\n\n\n\n" }, { "code": null, "e": 30082, "s": 30065, "text": "arorakashish0911" }, { "code": null, "e": 30096, "s": 30082, "text": "CPP-Functions" }, { "code": null, "e": 30104, "s": 30096, "text": "cpp-map" }, { "code": null, "e": 30108, "s": 30104, "text": "STL" }, { "code": null, "e": 30112, "s": 30108, "text": "C++" }, { "code": null, "e": 30116, "s": 30112, "text": "STL" }, { "code": null, "e": 30120, "s": 30116, "text": "CPP" }, { "code": null, "e": 30218, "s": 30120, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30237, "s": 30218, "text": "Inheritance in C++" }, { "code": null, "e": 30261, "s": 30237, "text": "Virtual Function in C++" }, { "code": null, "e": 30285, "s": 30261, "text": "C++ Classes and Objects" }, { "code": null, "e": 30312, "s": 30285, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 30343, "s": 30312, "text": "Templates in C++ with Examples" }, { "code": null, "e": 30363, "s": 30343, "text": "Constructors in C++" }, { "code": null, "e": 30391, "s": 30363, "text": "Operator Overloading in C++" }, { "code": null, "e": 30419, "s": 30391, "text": "Socket Programming in C/C++" }, { "code": null, "e": 30439, "s": 30419, "text": "Polymorphism in C++" } ]
time.Time.Second() Function in Golang with Examples - GeeksforGeeks
19 Apr, 2020 In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Second() function in Go language is used to find the second offset within the minute as provided by “t” and the range is [0, 59]. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions. Syntax: func (t Time) Second() int Here, “t” is the stated time. Return Value: It returns the second offset within the minute as provided by “t”. Example 1: // Golang program to illustrate the usage of// Time.Second() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Declaring t in UTC t := time.Date(2017, 2, 3, 13, 12, 34, 50, time.UTC) // Calling Second method sec := t.Second() // Prints second as specified fmt.Printf("The stated second is: %v\n", sec)} Output: The stated second is: 34 Example 2: // Golang program to illustrate the usage of// Time.Second() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Declaring t in UTC t := time.Date(2017, 2, 3, 13, 12, 67, 50, time.UTC) // Calling Second method sec := t.Second() // Prints second as specified fmt.Printf("The stated second is: %v\n", sec)} Output: The stated second is: 7 Here, the seconds stated in the above code is out of usual range but it is normalized while conversion. GoLang-time Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Strings in Golang Time Durations in Golang How to Parse JSON in Golang? 6 Best Books to Learn Go Programming Language Structures in Golang Defer Keyword in Golang How to iterate over an Array using for loop in Golang? Rune in Golang Class and Object in Golang Loops in Go Language
[ { "code": null, "e": 25813, "s": 25785, "text": "\n19 Apr, 2020" }, { "code": null, "e": 26182, "s": 25813, "text": "In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Second() function in Go language is used to find the second offset within the minute as provided by “t” and the range is [0, 59]. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions." }, { "code": null, "e": 26190, "s": 26182, "text": "Syntax:" }, { "code": null, "e": 26218, "s": 26190, "text": "func (t Time) Second() int\n" }, { "code": null, "e": 26248, "s": 26218, "text": "Here, “t” is the stated time." }, { "code": null, "e": 26329, "s": 26248, "text": "Return Value: It returns the second offset within the minute as provided by “t”." }, { "code": null, "e": 26340, "s": 26329, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// Time.Second() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Declaring t in UTC t := time.Date(2017, 2, 3, 13, 12, 34, 50, time.UTC) // Calling Second method sec := t.Second() // Prints second as specified fmt.Printf(\"The stated second is: %v\\n\", sec)}", "e": 26763, "s": 26340, "text": null }, { "code": null, "e": 26771, "s": 26763, "text": "Output:" }, { "code": null, "e": 26797, "s": 26771, "text": "The stated second is: 34\n" }, { "code": null, "e": 26808, "s": 26797, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// Time.Second() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Declaring t in UTC t := time.Date(2017, 2, 3, 13, 12, 67, 50, time.UTC) // Calling Second method sec := t.Second() // Prints second as specified fmt.Printf(\"The stated second is: %v\\n\", sec)}", "e": 27230, "s": 26808, "text": null }, { "code": null, "e": 27238, "s": 27230, "text": "Output:" }, { "code": null, "e": 27263, "s": 27238, "text": "The stated second is: 7\n" }, { "code": null, "e": 27367, "s": 27263, "text": "Here, the seconds stated in the above code is out of usual range but it is normalized while conversion." }, { "code": null, "e": 27379, "s": 27367, "text": "GoLang-time" }, { "code": null, "e": 27391, "s": 27379, "text": "Go Language" }, { "code": null, "e": 27489, "s": 27391, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27507, "s": 27489, "text": "Strings in Golang" }, { "code": null, "e": 27532, "s": 27507, "text": "Time Durations in Golang" }, { "code": null, "e": 27561, "s": 27532, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 27607, "s": 27561, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 27628, "s": 27607, "text": "Structures in Golang" }, { "code": null, "e": 27652, "s": 27628, "text": "Defer Keyword in Golang" }, { "code": null, "e": 27707, "s": 27652, "text": "How to iterate over an Array using for loop in Golang?" }, { "code": null, "e": 27722, "s": 27707, "text": "Rune in Golang" }, { "code": null, "e": 27749, "s": 27722, "text": "Class and Object in Golang" } ]
MySQLi - Select Query
The SQL SELECT command is used to fetch data from the MySQL database. You can use this command at mysql> prompt as well as in any script like PHP. Here is generic SQL syntax of SELECT command to fetch data from the MySQL table − SELECT field1, field2,...fieldN FROM table_name1, table_name2... [WHERE Clause] [OFFSET M ][LIMIT N] You can use one or more tables separated by comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command. You can use one or more tables separated by comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command. You can fetch one or more fields in a single SELECT command. You can fetch one or more fields in a single SELECT command. You can specify star (*) in place of fields. In this case, SELECT will return all the fields. You can specify star (*) in place of fields. In this case, SELECT will return all the fields. You can specify any condition using the WHERE clause. You can specify any condition using the WHERE clause. You can specify an offset using OFFSET from where SELECT will start returning records. By default, the offset starts at zero. You can specify an offset using OFFSET from where SELECT will start returning records. By default, the offset starts at zero. You can limit the number of returns using the LIMIT attribute. You can limit the number of returns using the LIMIT attribute. This will use SQL SELECT command to fetch data from the MySQL table tutorials_tbl. The following example will return all the records from the tutorials_tbl table − root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> SELECT * from tutorials_tbl +-------------+----------------+-----------------+-----------------+ | tutorial_id | tutorial_title | tutorial_author | submission_date | +-------------+----------------+-----------------+-----------------+ | 1 | Learn PHP | John Poul | 2007-05-21 | | 2 | Learn MySQL | Abdul S | 2007-05-21 | | 3 | JAVA Tutorial | Sanjay | 2007-05-21 | +-------------+----------------+-----------------+-----------------+ 3 rows in set (0.01 sec) mysql> PHP uses mysqli query() or mysql_query() function to select records from a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure. $mysqli→query($sql,$resultmode) $sql Required - SQL query to select records from a MySQL table. $resultmode Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used. Try the following example to select a record from a table − Copy and paste the following example as mysql_example.php − <html> <head> <title>Creating MySQL Table</title> </head> <body> <?php $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'root@123'; $dbname = 'TUTORIALS'; $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if($mysqli→connect_errno ) { printf("Connect failed: %s<br />", $mysqli→connect_error); exit(); } printf('Connected successfully.<br />'); $sql = "SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl"; $result = $mysqli->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { printf("Id: %s, Title: %s, Author: %s, Date: %d <br />", $row["tutorial_id"], $row["tutorial_title"], $row["tutorial_author"], $row["submission_date"]); } } else { printf('No record found.<br />'); } mysqli_free_result($result); $mysqli→close(); ?> </body> </html> Access the mysql_example.php deployed on apache web server and verify the output. Here we've entered multiple records in the table before running the select script. Connected successfully. Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021 Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021 Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021 Id: 4, Title: Java Tutorial, Author: Mahesh, Date: 2021 Id: 5, Title: Apache Tutorial, Author: Suresh, Date: 2021
[ { "code": null, "e": 2544, "s": 2397, "text": "The SQL SELECT command is used to fetch data from the MySQL database. You can use this command at mysql> prompt as well as in any script like PHP." }, { "code": null, "e": 2626, "s": 2544, "text": "Here is generic SQL syntax of SELECT command to fetch data from the MySQL table −" }, { "code": null, "e": 2729, "s": 2626, "text": "SELECT field1, field2,...fieldN \nFROM table_name1, table_name2...\n[WHERE Clause]\n[OFFSET M ][LIMIT N]\n" }, { "code": null, "e": 2895, "s": 2729, "text": "You can use one or more tables separated by comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command." }, { "code": null, "e": 3061, "s": 2895, "text": "You can use one or more tables separated by comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command." }, { "code": null, "e": 3122, "s": 3061, "text": "You can fetch one or more fields in a single SELECT command." }, { "code": null, "e": 3183, "s": 3122, "text": "You can fetch one or more fields in a single SELECT command." }, { "code": null, "e": 3277, "s": 3183, "text": "You can specify star (*) in place of fields. In this case, SELECT will return all the fields." }, { "code": null, "e": 3371, "s": 3277, "text": "You can specify star (*) in place of fields. In this case, SELECT will return all the fields." }, { "code": null, "e": 3425, "s": 3371, "text": "You can specify any condition using the WHERE clause." }, { "code": null, "e": 3479, "s": 3425, "text": "You can specify any condition using the WHERE clause." }, { "code": null, "e": 3605, "s": 3479, "text": "You can specify an offset using OFFSET from where SELECT will start returning records. By default, the offset starts at zero." }, { "code": null, "e": 3731, "s": 3605, "text": "You can specify an offset using OFFSET from where SELECT will start returning records. By default, the offset starts at zero." }, { "code": null, "e": 3794, "s": 3731, "text": "You can limit the number of returns using the LIMIT attribute." }, { "code": null, "e": 3857, "s": 3794, "text": "You can limit the number of returns using the LIMIT attribute." }, { "code": null, "e": 3940, "s": 3857, "text": "This will use SQL SELECT command to fetch data from the MySQL table tutorials_tbl." }, { "code": null, "e": 4021, "s": 3940, "text": "The following example will return all the records from the tutorials_tbl table −" }, { "code": null, "e": 4673, "s": 4021, "text": "root@host# mysql -u root -p password;\nEnter password:*******\nmysql> use TUTORIALS;\nDatabase changed\nmysql> SELECT * from tutorials_tbl \n+-------------+----------------+-----------------+-----------------+\n| tutorial_id | tutorial_title | tutorial_author | submission_date |\n+-------------+----------------+-----------------+-----------------+\n| 1 | Learn PHP | John Poul | 2007-05-21 |\n| 2 | Learn MySQL | Abdul S | 2007-05-21 |\n| 3 | JAVA Tutorial | Sanjay | 2007-05-21 |\n+-------------+----------------+-----------------+-----------------+\n3 rows in set (0.01 sec)\n\nmysql>" }, { "code": null, "e": 4845, "s": 4673, "text": "PHP uses mysqli query() or mysql_query() function to select records from a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure." }, { "code": null, "e": 4878, "s": 4845, "text": "$mysqli→query($sql,$resultmode)\n" }, { "code": null, "e": 4883, "s": 4878, "text": "$sql" }, { "code": null, "e": 4942, "s": 4883, "text": "Required - SQL query to select records from a MySQL table." }, { "code": null, "e": 4954, "s": 4942, "text": "$resultmode" }, { "code": null, "e": 5102, "s": 4954, "text": "Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used." }, { "code": null, "e": 5163, "s": 5102, "text": "Try the following example to select a record from a table −" }, { "code": null, "e": 5223, "s": 5163, "text": "Copy and paste the following example as mysql_example.php −" }, { "code": null, "e": 6400, "s": 5223, "text": "<html>\n <head>\n <title>Creating MySQL Table</title>\n </head>\n <body>\n <?php\n $dbhost = 'localhost';\n $dbuser = 'root';\n $dbpass = 'root@123';\n $dbname = 'TUTORIALS';\n $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);\n \n if($mysqli→connect_errno ) {\n printf(\"Connect failed: %s<br />\", $mysqli→connect_error);\n exit();\n }\n printf('Connected successfully.<br />');\n \n $sql = \"SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl\";\n\t\t \n $result = $mysqli->query($sql);\n \n if ($result->num_rows > 0) {\n while($row = $result->fetch_assoc()) {\n printf(\"Id: %s, Title: %s, Author: %s, Date: %d <br />\", \n $row[\"tutorial_id\"], \n $row[\"tutorial_title\"], \n $row[\"tutorial_author\"],\n $row[\"submission_date\"]); \n }\n } else {\n printf('No record found.<br />');\n }\n mysqli_free_result($result);\n $mysqli→close();\n ?>\n </body>\n</html>" }, { "code": null, "e": 6565, "s": 6400, "text": "Access the mysql_example.php deployed on apache web server and verify the output. Here we've entered multiple records in the table before running the select script." } ]
Python – Obtain title, views and likes of YouTube video using BeautifulSoup
29 Dec, 2020 In this article, we will learn how can we obtain data (like title, views, likes, dislikes etc) from any YouTube video using a Python script. For this task, we are going to use very famous library for web scraping BeautifulSoup and Requests. Modules required and Installation : Requests :Requests allows you to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to your URLs. pip install requests Beautiful Soup:Beautiful Soup is a library that makes it easy to scrape information from web pages. It sits atop an HTML or XML parser, providing Pythonic idioms for iterating, searching, and modifying the parse tree. pip install beautifulsoup4 For a given URL of video, data scraping will be done. Then parsing of data (title, views, likes element) will be done using find() method of Beautiful Soup. It will find and store the values in the dictionary. Code : # importing the librariesfrom bs4 import BeautifulSoupimport requests # creating functiondef scrape_info(url): # getting the request from url r = requests.get(url) # converting the text s = BeautifulSoup(r.text, "html.parser") # finding meta info for title title = s.find("span", class_="watch-title").text.replace("\n", "") # finding meta info for views views = s.find("div", class_="watch-view-count").text # finding meta info for likes likes = s.find("span", class_="like-button-renderer").span.button.text # saving this data in dictionary data = {'title':title, 'views':views, 'likes':likes} # returning the dictionary return data # main functionif __name__ == "__main__": # URL of the video url ="https://www.youtube.com/watch?time_continue=17&v=2wEA8nuThj8" # calling the function data = scrape_info(url) # printing the dictionary print(data) Output: {‘title’: ‘ Placement100 | GeeksforGeeks ‘, ‘views’: ’18, 964 views’, ‘likes’: ’37’} Python web-scraping-exercises Python-BS3 Python-requests Web-scraping Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Dec, 2020" }, { "code": null, "e": 295, "s": 54, "text": "In this article, we will learn how can we obtain data (like title, views, likes, dislikes etc) from any YouTube video using a Python script. For this task, we are going to use very famous library for web scraping BeautifulSoup and Requests." }, { "code": null, "e": 331, "s": 295, "text": "Modules required and Installation :" }, { "code": null, "e": 465, "s": 331, "text": "Requests :Requests allows you to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to your URLs." }, { "code": null, "e": 486, "s": 465, "text": "pip install requests" }, { "code": null, "e": 704, "s": 486, "text": "Beautiful Soup:Beautiful Soup is a library that makes it easy to scrape information from web pages. It sits atop an HTML or XML parser, providing Pythonic idioms for iterating, searching, and modifying the parse tree." }, { "code": null, "e": 731, "s": 704, "text": "pip install beautifulsoup4" }, { "code": null, "e": 941, "s": 731, "text": "For a given URL of video, data scraping will be done. Then parsing of data (title, views, likes element) will be done using find() method of Beautiful Soup. It will find and store the values in the dictionary." }, { "code": null, "e": 948, "s": 941, "text": "Code :" }, { "code": "# importing the librariesfrom bs4 import BeautifulSoupimport requests # creating functiondef scrape_info(url): # getting the request from url r = requests.get(url) # converting the text s = BeautifulSoup(r.text, \"html.parser\") # finding meta info for title title = s.find(\"span\", class_=\"watch-title\").text.replace(\"\\n\", \"\") # finding meta info for views views = s.find(\"div\", class_=\"watch-view-count\").text # finding meta info for likes likes = s.find(\"span\", class_=\"like-button-renderer\").span.button.text # saving this data in dictionary data = {'title':title, 'views':views, 'likes':likes} # returning the dictionary return data # main functionif __name__ == \"__main__\": # URL of the video url =\"https://www.youtube.com/watch?time_continue=17&v=2wEA8nuThj8\" # calling the function data = scrape_info(url) # printing the dictionary print(data)", "e": 1919, "s": 948, "text": null }, { "code": null, "e": 1927, "s": 1919, "text": "Output:" }, { "code": null, "e": 2012, "s": 1927, "text": "{‘title’: ‘ Placement100 | GeeksforGeeks ‘, ‘views’: ’18, 964 views’, ‘likes’: ’37’}" }, { "code": null, "e": 2042, "s": 2012, "text": "Python web-scraping-exercises" }, { "code": null, "e": 2053, "s": 2042, "text": "Python-BS3" }, { "code": null, "e": 2069, "s": 2053, "text": "Python-requests" }, { "code": null, "e": 2082, "s": 2069, "text": "Web-scraping" }, { "code": null, "e": 2089, "s": 2082, "text": "Python" }, { "code": null, "e": 2187, "s": 2089, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2229, "s": 2187, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2251, "s": 2229, "text": "Enumerate() in Python" }, { "code": null, "e": 2277, "s": 2251, "text": "Python String | replace()" }, { "code": null, "e": 2309, "s": 2277, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2338, "s": 2309, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2365, "s": 2338, "text": "Python Classes and Objects" }, { "code": null, "e": 2401, "s": 2365, "text": "Convert integer to string in Python" }, { "code": null, "e": 2422, "s": 2401, "text": "Python OOPs Concepts" }, { "code": null, "e": 2453, "s": 2422, "text": "Python | os.path.join() method" } ]
Missing number in array | Practice | GeeksforGeeks
Given an array of size N-1 such that it only contains distinct integers in the range of 1 to N. Find the missing element. Example 1: Input: N = 5 A[] = {1,2,3,5} Output: 4 Example 2: Input: N = 10 A[] = {6,1,2,8,3,4,7,10,5} Output: 9 Your Task : You don't need to read input or print anything. Complete the function MissingNumber() that takes array and N as input parameters and returns the value of the missing number. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N ≤ 106 1 ≤ A[i] ≤ 106 0 ianuragin 3 hours Using Bit Manipulation int MissingNumber(vector<int>& array, int n) { // Your code goes here int xr=0; for(auto i: array){ xr^=i; } for(int i=1;i<=n;i++){ xr^=i; } return xr; } +1 20102067amitnarain 2 hours Java Code class Solution { int MissingNumber(int array[], int n) { int total_sum = (n * (n + 1)) / 2; for (int i = 0; i < n-1; i++) { // as the value of n is 5 but the //total elements are 4 in the array so the loop will run from 0 to 3 // simply you can use array.length total_sum = total_sum - array[i]; } return total_sum; }} 0 anshu_sharma_4 hours ago class Solution { int MissingNumber(int array[], int n) { // Your Code Here int sum=0; int Total_sum=n*(n+1)/2; for(int i=0;i<array.length;i++){ sum=sum+array[i]; } return (Total_sum-sum); }} 0 wajidhossain19 hours ago CPP Solution: int MissingNumber(vector<int>& array, int n) { int missing_number; int sum2= 0; int sum = n*(n+1)/2; for(int i =0;i<array.size();i++) { sum2+=array[i]; } return missing_number = sum-sum2; } +1 arunkhw19981 day ago class Solution: def MissingNumber(self,array,n): s = n*(n+1)//2 for i in array: s -= i return s 0 prateekgoyal21 day ago How do we think and reach the solution? Explained simply here:- 0 swatidubey9142 days ago Best solution in java class Solution { int MissingNumber(int array[], int n) { //The formula of the sum of first n natural numbers is S=n(n+1)/2 . //No_ele = total_no_of_elements_expected //total_sum = sum_total_no_of_elements_expected int No_ele = n; // n = array.length + 1 int total_sum = No_ele *(No_ele + 1)/2; int sum = 0; for(int i = 0 ; i < array.length ; i++){ sum = sum + array[i]; } return (total_sum - sum); }} 0 dsouzapraveen242 days ago total = n * (n + 1)/2 arraySum = sum(array) #len(arr) - 1return round(total - arraySum) 0 dsouzapraveen24 This comment was deleted. 0 rahuldutta3872 days ago //why my code is not running for multiple testcases whats wrong with this ... it is running for 200 testcases but for 40 it is showing wrong answer.// class Solution{ public: int MissingNumber(vector<int>& array, int n) { // Your code goes here unordered_set<int> s; for(int i=0;i<n;i++){ s.insert(array[i]); } for(int i=1;i<=n;i++){ if(s.find(i)==s.end()){ return i; } } return 0; }}; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 360, "s": 238, "text": "Given an array of size N-1 such that it only contains distinct integers in the range of 1 to N. Find the missing element." }, { "code": null, "e": 371, "s": 360, "text": "Example 1:" }, { "code": null, "e": 411, "s": 371, "text": "Input:\nN = 5\nA[] = {1,2,3,5}\nOutput: 4\n" }, { "code": null, "e": 422, "s": 411, "text": "Example 2:" }, { "code": null, "e": 473, "s": 422, "text": "Input:\nN = 10\nA[] = {6,1,2,8,3,4,7,10,5}\nOutput: 9" }, { "code": null, "e": 661, "s": 473, "text": "\nYour Task :\nYou don't need to read input or print anything. Complete the function MissingNumber() that takes array and N as input parameters and returns the value of the missing number." }, { "code": null, "e": 724, "s": 661, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 765, "s": 724, "text": "\nConstraints:\n1 ≤ N ≤ 106\n1 ≤ A[i] ≤ 106" }, { "code": null, "e": 767, "s": 765, "text": "0" }, { "code": null, "e": 785, "s": 767, "text": "ianuragin 3 hours" }, { "code": null, "e": 808, "s": 785, "text": "Using Bit Manipulation" }, { "code": null, "e": 1046, "s": 808, "text": "int MissingNumber(vector<int>& array, int n) {\n // Your code goes here\n int xr=0;\n for(auto i: array){\n xr^=i;\n }\n for(int i=1;i<=n;i++){\n xr^=i;\n }\n return xr;\n }" }, { "code": null, "e": 1049, "s": 1046, "text": "+1" }, { "code": null, "e": 1076, "s": 1049, "text": "20102067amitnarain 2 hours" }, { "code": null, "e": 1086, "s": 1076, "text": "Java Code" }, { "code": null, "e": 1329, "s": 1086, "text": "class Solution { int MissingNumber(int array[], int n) { int total_sum = (n * (n + 1)) / 2; for (int i = 0; i < n-1; i++) { // as the value of n is 5 but the //total elements are 4 in the array so the loop will run from 0 to 3" }, { "code": null, "e": 1452, "s": 1329, "text": "// simply you can use array.length total_sum = total_sum - array[i]; } return total_sum; }}" }, { "code": null, "e": 1454, "s": 1452, "text": "0" }, { "code": null, "e": 1479, "s": 1454, "text": "anshu_sharma_4 hours ago" }, { "code": null, "e": 1736, "s": 1479, "text": "class Solution { int MissingNumber(int array[], int n) { // Your Code Here int sum=0; int Total_sum=n*(n+1)/2; for(int i=0;i<array.length;i++){ sum=sum+array[i]; } return (Total_sum-sum); }}" }, { "code": null, "e": 1738, "s": 1736, "text": "0" }, { "code": null, "e": 1763, "s": 1738, "text": "wajidhossain19 hours ago" }, { "code": null, "e": 1778, "s": 1763, "text": "CPP Solution: " }, { "code": null, "e": 2022, "s": 1778, "text": "int MissingNumber(vector<int>& array, int n) { int missing_number; int sum2= 0; int sum = n*(n+1)/2; for(int i =0;i<array.size();i++) { sum2+=array[i]; } return missing_number = sum-sum2; }" }, { "code": null, "e": 2025, "s": 2022, "text": "+1" }, { "code": null, "e": 2046, "s": 2025, "text": "arunkhw19981 day ago" }, { "code": null, "e": 2157, "s": 2046, "text": "class Solution: def MissingNumber(self,array,n): s = n*(n+1)//2 for i in array: s -= i" }, { "code": null, "e": 2173, "s": 2157, "text": " return s" }, { "code": null, "e": 2175, "s": 2173, "text": "0" }, { "code": null, "e": 2198, "s": 2175, "text": "prateekgoyal21 day ago" }, { "code": null, "e": 2263, "s": 2198, "text": "How do we think and reach the solution? Explained simply here:- " }, { "code": null, "e": 2269, "s": 2267, "text": "0" }, { "code": null, "e": 2293, "s": 2269, "text": "swatidubey9142 days ago" }, { "code": null, "e": 2315, "s": 2293, "text": "Best solution in java" }, { "code": null, "e": 2814, "s": 2317, "text": "class Solution { int MissingNumber(int array[], int n) { //The formula of the sum of first n natural numbers is S=n(n+1)/2 . //No_ele = total_no_of_elements_expected //total_sum = sum_total_no_of_elements_expected int No_ele = n; // n = array.length + 1 int total_sum = No_ele *(No_ele + 1)/2; int sum = 0; for(int i = 0 ; i < array.length ; i++){ sum = sum + array[i]; } return (total_sum - sum); }}" }, { "code": null, "e": 2816, "s": 2814, "text": "0" }, { "code": null, "e": 2842, "s": 2816, "text": "dsouzapraveen242 days ago" }, { "code": null, "e": 2930, "s": 2842, "text": "total = n * (n + 1)/2 arraySum = sum(array) #len(arr) - 1return round(total - arraySum)" }, { "code": null, "e": 2932, "s": 2930, "text": "0" }, { "code": null, "e": 2948, "s": 2932, "text": "dsouzapraveen24" }, { "code": null, "e": 2974, "s": 2948, "text": "This comment was deleted." }, { "code": null, "e": 2976, "s": 2974, "text": "0" }, { "code": null, "e": 3000, "s": 2976, "text": "rahuldutta3872 days ago" }, { "code": null, "e": 3151, "s": 3000, "text": "//why my code is not running for multiple testcases whats wrong with this ... it is running for 200 testcases but for 40 it is showing wrong answer.//" }, { "code": null, "e": 3476, "s": 3151, "text": "class Solution{ public: int MissingNumber(vector<int>& array, int n) { // Your code goes here unordered_set<int> s; for(int i=0;i<n;i++){ s.insert(array[i]); } for(int i=1;i<=n;i++){ if(s.find(i)==s.end()){ return i; } } return 0; }};" }, { "code": null, "e": 3622, "s": 3476, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 3658, "s": 3622, "text": " Login to access your submissions. " }, { "code": null, "e": 3668, "s": 3658, "text": "\nProblem\n" }, { "code": null, "e": 3678, "s": 3668, "text": "\nContest\n" }, { "code": null, "e": 3741, "s": 3678, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3926, "s": 3741, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 4210, "s": 3926, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 4356, "s": 4210, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 4433, "s": 4356, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 4474, "s": 4433, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 4502, "s": 4474, "text": "Disable browser extensions." }, { "code": null, "e": 4573, "s": 4502, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 4760, "s": 4573, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
Power BI – Drilling Down and Up in Hierarchies
18 Sep, 2020 Prerequisite: Tools and Functionalities This article shows how to drill up and down so as to visualize the data through different levels in Power BI. Using drill-down and drill up on your data points, you can explore in-depth details about your data. When a visual has a hierarchy, you can drill down to reveal additional details. What is Drilling?Drilling enables you to navigate through different levels within the dimensional hierarchy of your data source. This allows you to review underlying data for a particular area, and move through the structure of your data source based on your informational needs. Drilling can be performed in two ways: Drill upDrill down Drill up Drill down Dataset Used:The dataset used is of ‘Office Stock Supplies’. Refer to the dataset to follow along with the below-given sections of the article. You can download the dataset from here : Dataset Before getting to understand how Drilling works, we need to create a bar chart. Creating a Bar Chart: To create a Bar Chart (stacked column chart), do the following steps : Step 1 - Upload your dataset into your Power-BI Model. Step 2 - Drag columns [order date, Units] from Fields section. Step 3 - Click on the Stacked Column Chart in the Visualization Panel. NOTE: Power BI drill down feature requires hierarchy. [ Example : Hierarchy of OrderDate ] (shown in above image) Hierarchy Display Panel: Drilling in Hierarchies:Drilling down allows us to get a granular view of the data in the datasets and we use Drill up to get back the original data. Step 1 - Click on the drill down icon to turn it ON. Step 2 - Click on any of the column bars (say column 2) to Drill it down. (This will show the data of that particular column only) Example : Year (2015) --> Quarter (2) --> Month (May) --> Day (Days in month of May only) [Shown in image below] Power BI : Drill Up and Drill Down Advanced Drilling in Hierarchies – Switch to Next LevelIn this, drilling is done on the entire data, rather than just a particular section of data.Higher-level hierarchies are not preserved when switching to next level. In simple terms, on switching to the next level, say from year to quarter we cannot see which quarter belongs to which year. As per the hierarchy of OrderDate [ Year –> Quarter –> Month –> Day ], on clicking this button, Power BI completely disregards which year we want to drill into, and shows all the data available in Quarterly format. See in the image given below, how data is shown after switching to each next level. Switch to next level NOTE : You can use Drill Up to get back the original data every time. Expand down one level:Unlike the previous approach, here on expanding to the next level, the data of the previous level is preserved. (i.e. on switching to the next level, from year to quarter we can see which quarter belongs to which year.) The information of the previous levels is preserved in the shown level. These were the various hierarchies of data and its interpretation of using various techniques. Understanding the data at every level is a very important task when making large business decisions. Therefore, it is very important to understand such techniques while making reports to make a well-informed decision. For any doubts/queries, comment below. Data Visualization Power-BI Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Search Algorithms in AI Decision Tree Introduction with example ML | Monte Carlo Tree Search (MCTS) Introduction to Recurrent Neural Network Getting started with Machine Learning Markov Decision Process Elbow Method for optimal value of k in KMeans Support Vector Machine Algorithm Random Forest Regression in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Sep, 2020" }, { "code": null, "e": 68, "s": 28, "text": "Prerequisite: Tools and Functionalities" }, { "code": null, "e": 359, "s": 68, "text": "This article shows how to drill up and down so as to visualize the data through different levels in Power BI. Using drill-down and drill up on your data points, you can explore in-depth details about your data. When a visual has a hierarchy, you can drill down to reveal additional details." }, { "code": null, "e": 639, "s": 359, "text": "What is Drilling?Drilling enables you to navigate through different levels within the dimensional hierarchy of your data source. This allows you to review underlying data for a particular area, and move through the structure of your data source based on your informational needs." }, { "code": null, "e": 678, "s": 639, "text": "Drilling can be performed in two ways:" }, { "code": null, "e": 697, "s": 678, "text": "Drill upDrill down" }, { "code": null, "e": 706, "s": 697, "text": "Drill up" }, { "code": null, "e": 717, "s": 706, "text": "Drill down" }, { "code": null, "e": 910, "s": 717, "text": "Dataset Used:The dataset used is of ‘Office Stock Supplies’. Refer to the dataset to follow along with the below-given sections of the article. You can download the dataset from here : Dataset" }, { "code": null, "e": 990, "s": 910, "text": "Before getting to understand how Drilling works, we need to create a bar chart." }, { "code": null, "e": 1012, "s": 990, "text": "Creating a Bar Chart:" }, { "code": null, "e": 1083, "s": 1012, "text": "To create a Bar Chart (stacked column chart), do the following steps :" }, { "code": null, "e": 1275, "s": 1083, "text": "Step 1 - Upload your dataset into your Power-BI Model.\nStep 2 - Drag columns [order date, Units] from Fields section. \nStep 3 - Click on the Stacked Column Chart in the Visualization Panel. \n" }, { "code": null, "e": 1389, "s": 1275, "text": "NOTE: Power BI drill down feature requires hierarchy. [ Example : Hierarchy of OrderDate ] (shown in above image)" }, { "code": null, "e": 1414, "s": 1389, "text": "Hierarchy Display Panel:" }, { "code": null, "e": 1564, "s": 1414, "text": "Drilling in Hierarchies:Drilling down allows us to get a granular view of the data in the datasets and we use Drill up to get back the original data." }, { "code": null, "e": 1867, "s": 1564, "text": "Step 1 - Click on the drill down icon to turn it ON. \nStep 2 - Click on any of the column bars (say column 2) to Drill it down.\n(This will show the data of that particular column only) \n\nExample : Year (2015) --> Quarter (2) --> Month (May) --> Day (Days in month of May only) [Shown in image below]\n" }, { "code": null, "e": 1902, "s": 1867, "text": "Power BI : Drill Up and Drill Down" }, { "code": null, "e": 2247, "s": 1902, "text": "Advanced Drilling in Hierarchies – Switch to Next LevelIn this, drilling is done on the entire data, rather than just a particular section of data.Higher-level hierarchies are not preserved when switching to next level. In simple terms, on switching to the next level, say from year to quarter we cannot see which quarter belongs to which year." }, { "code": null, "e": 2546, "s": 2247, "text": "As per the hierarchy of OrderDate [ Year –> Quarter –> Month –> Day ], on clicking this button, Power BI completely disregards which year we want to drill into, and shows all the data available in Quarterly format. See in the image given below, how data is shown after switching to each next level." }, { "code": null, "e": 2567, "s": 2546, "text": "Switch to next level" }, { "code": null, "e": 2637, "s": 2567, "text": "NOTE : You can use Drill Up to get back the original data every time." }, { "code": null, "e": 2879, "s": 2637, "text": "Expand down one level:Unlike the previous approach, here on expanding to the next level, the data of the previous level is preserved. (i.e. on switching to the next level, from year to quarter we can see which quarter belongs to which year.)" }, { "code": null, "e": 2951, "s": 2879, "text": "The information of the previous levels is preserved in the shown level." }, { "code": null, "e": 3303, "s": 2951, "text": "These were the various hierarchies of data and its interpretation of using various techniques. Understanding the data at every level is a very important task when making large business decisions. Therefore, it is very important to understand such techniques while making reports to make a well-informed decision. For any doubts/queries, comment below." }, { "code": null, "e": 3322, "s": 3303, "text": "Data Visualization" }, { "code": null, "e": 3331, "s": 3322, "text": "Power-BI" }, { "code": null, "e": 3348, "s": 3331, "text": "Machine Learning" }, { "code": null, "e": 3365, "s": 3348, "text": "Machine Learning" }, { "code": null, "e": 3463, "s": 3365, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3486, "s": 3463, "text": "ML | Linear Regression" }, { "code": null, "e": 3510, "s": 3486, "text": "Search Algorithms in AI" }, { "code": null, "e": 3550, "s": 3510, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 3586, "s": 3550, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 3627, "s": 3586, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 3665, "s": 3627, "text": "Getting started with Machine Learning" }, { "code": null, "e": 3689, "s": 3665, "text": "Markov Decision Process" }, { "code": null, "e": 3735, "s": 3689, "text": "Elbow Method for optimal value of k in KMeans" }, { "code": null, "e": 3768, "s": 3735, "text": "Support Vector Machine Algorithm" } ]
How to create a pop-up div on mouse over and stay when click using jQuery ?
21 May, 2021 In this article, we will learn how to create a pop-up div on mouseover and stay when click using jQuery. Approach: First, we create an HTML div element that we want to pop up when we mouse over on an element and set its display property to none in CSS style. display:none; In the script tag, we create a variable flag and set its value to -1. $flag = -1; Now in the script tag, we will select the element on which we want to mouseover. It is an HTML a element with class gfg. We select element a with class gfg, and then use the hover() function that is used to apply an effect when we mouse hover on an element. We use two functions, first one executes when the mouse-enter event occurs. We select div with class popup and set its display property to block using the jQuery attr(). When the mouse-leave event occurs, the second function executes with the divs display value to none when the flag is not equal to -1. JavaScript Code: $("a.gfg").hover( function () { $("div.popup").attr("style", "display:block"); }, function () { if ($flag == -1) { $("div.popup").attr("style", "display:none"); } } ); We add a jQuery click event on element a. When we click on element a, the function sets the variable flag value to 1, so the div element stays after clicking. $("a.gfg").click(function () { $flag = 1; }); HTML Code: Below is the full implementation of the above approach. HTML <!DOCTYPE html><html> <head> <!-- JQuery CDN --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <style> center { font-size: 30px; color: green; } .popup { display: none; width: 500px; border: solid red 3px } </style></head> <body> <center> <p> Hover <a href="#" class="gfg">here</a> to see the changes. </p> <div class="popup"> GeeksforGeeks </div> </center> <script> $flag = -1; $("a.gfg").hover( function () { $("div.popup").attr("style", "display:block"); }, function () { if ($flag == -1) { $("div.popup").attr("style", "display:none"); } } ); $("a.gfg").click(function () { $flag = 1; }); </script></body> </html> Output: pop up mouse hover CSS-Properties jQuery-Methods jQuery-Questions Picked CSS HTML JQuery 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": "\n21 May, 2021" }, { "code": null, "e": 133, "s": 28, "text": "In this article, we will learn how to create a pop-up div on mouseover and stay when click using jQuery." }, { "code": null, "e": 144, "s": 133, "text": "Approach: " }, { "code": null, "e": 288, "s": 144, "text": "First, we create an HTML div element that we want to pop up when we mouse over on an element and set its display property to none in CSS style." }, { "code": null, "e": 302, "s": 288, "text": "display:none;" }, { "code": null, "e": 372, "s": 302, "text": "In the script tag, we create a variable flag and set its value to -1." }, { "code": null, "e": 385, "s": 372, "text": " $flag = -1;" }, { "code": null, "e": 643, "s": 385, "text": "Now in the script tag, we will select the element on which we want to mouseover. It is an HTML a element with class gfg. We select element a with class gfg, and then use the hover() function that is used to apply an effect when we mouse hover on an element." }, { "code": null, "e": 947, "s": 643, "text": "We use two functions, first one executes when the mouse-enter event occurs. We select div with class popup and set its display property to block using the jQuery attr(). When the mouse-leave event occurs, the second function executes with the divs display value to none when the flag is not equal to -1." }, { "code": null, "e": 964, "s": 947, "text": "JavaScript Code:" }, { "code": null, "e": 1184, "s": 964, "text": "$(\"a.gfg\").hover(\n function () {\n $(\"div.popup\").attr(\"style\", \"display:block\");\n },\n function () {\n if ($flag == -1) {\n $(\"div.popup\").attr(\"style\", \"display:none\");\n }\n }\n);" }, { "code": null, "e": 1343, "s": 1184, "text": "We add a jQuery click event on element a. When we click on element a, the function sets the variable flag value to 1, so the div element stays after clicking." }, { "code": null, "e": 1393, "s": 1343, "text": "$(\"a.gfg\").click(function () {\n $flag = 1;\n});" }, { "code": null, "e": 1460, "s": 1393, "text": "HTML Code: Below is the full implementation of the above approach." }, { "code": null, "e": 1465, "s": 1460, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- JQuery CDN --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <style> center { font-size: 30px; color: green; } .popup { display: none; width: 500px; border: solid red 3px } </style></head> <body> <center> <p> Hover <a href=\"#\" class=\"gfg\">here</a> to see the changes. </p> <div class=\"popup\"> GeeksforGeeks </div> </center> <script> $flag = -1; $(\"a.gfg\").hover( function () { $(\"div.popup\").attr(\"style\", \"display:block\"); }, function () { if ($flag == -1) { $(\"div.popup\").attr(\"style\", \"display:none\"); } } ); $(\"a.gfg\").click(function () { $flag = 1; }); </script></body> </html>", "e": 2470, "s": 1465, "text": null }, { "code": null, "e": 2478, "s": 2470, "text": "Output:" }, { "code": null, "e": 2497, "s": 2478, "text": "pop up mouse hover" }, { "code": null, "e": 2512, "s": 2497, "text": "CSS-Properties" }, { "code": null, "e": 2527, "s": 2512, "text": "jQuery-Methods" }, { "code": null, "e": 2544, "s": 2527, "text": "jQuery-Questions" }, { "code": null, "e": 2551, "s": 2544, "text": "Picked" }, { "code": null, "e": 2555, "s": 2551, "text": "CSS" }, { "code": null, "e": 2560, "s": 2555, "text": "HTML" }, { "code": null, "e": 2567, "s": 2560, "text": "JQuery" }, { "code": null, "e": 2584, "s": 2567, "text": "Web Technologies" }, { "code": null, "e": 2589, "s": 2584, "text": "HTML" } ]
How to get the list of all the commands available in the PowerShell?
To get the list of all the commands installed in the system use the below command line. It will include all the Alias, Functions and Cmdlets. Get-Command To export them into the CSV file, Get-Command | Export-Csv D:\Temp\PowerShellcommands.csv - NoTypeInformation To get only the cmdlets commands, Get-Command -CommandType Cmdlet Similarly, you can get the commands for the alias and functions. If you want the list of commands starting with getting, you parameter –Verb. Get-Command -Verb Get To get command starting with Set, Get-Command -Verb Set
[ { "code": null, "e": 1329, "s": 1187, "text": "To get the list of all the commands installed in the system use the below command line. It\nwill include all the Alias, Functions and Cmdlets." }, { "code": null, "e": 1341, "s": 1329, "text": "Get-Command" }, { "code": null, "e": 1375, "s": 1341, "text": "To export them into the CSV file," }, { "code": null, "e": 1451, "s": 1375, "text": "Get-Command | Export-Csv D:\\Temp\\PowerShellcommands.csv -\nNoTypeInformation" }, { "code": null, "e": 1485, "s": 1451, "text": "To get only the cmdlets commands," }, { "code": null, "e": 1517, "s": 1485, "text": "Get-Command -CommandType Cmdlet" }, { "code": null, "e": 1582, "s": 1517, "text": "Similarly, you can get the commands for the alias and functions." }, { "code": null, "e": 1659, "s": 1582, "text": "If you want the list of commands starting with getting, you parameter –Verb." }, { "code": null, "e": 1681, "s": 1659, "text": "Get-Command -Verb Get" }, { "code": null, "e": 1715, "s": 1681, "text": "To get command starting with Set," }, { "code": null, "e": 1738, "s": 1715, "text": "Get-Command -Verb Set\n" } ]
Compute the inverse of a matrix using NumPy
26 Feb, 2021 The inverse of a matrix is just a reciprocal of the matrix as we do in normal arithmetic for a single number which is used to solve the equations to find the value of unknown variables. The inverse of a matrix is that matrix which when multiplied with the original matrix will give as an identity matrix. The inverse of a matrix exists only if the matrix is non-singular i.e., determinant should not be 0. Using determinant and adjoint, we can easily find the inverse of a square matrix using below formula, if det(A) != 0 A-1 = adj(A)/det(A) else "Inverse doesn't exist" where, A-1: The inverse of matrix A x: The unknown variable column B: The solution matrix We can find out the inverse of any square matrix with the function numpy.linalg.inv(array). Syntax: numpy.linalg.inv(a) Parameters: a: Matrix to be inverted Returns: Inverse of the matrix a. Example 1: Python3 # Importing Libraryimport numpy as np # Finding an inverse of given arrayarr = np.array([[1, 2], [5, 6]])inverse_array = np.linalg.inv(arr)print("Inverse array is ")print(inverse_array)print() # inverse of 3X3 matrixarr = np.array([[1, 2, 3], [4, 9, 6], [7, 8, 9]]) inverse_array = np.linalg.inv(arr)print("Inverse array is ")print(inverse_array)print() # inverse of 4X4 matrixarr = np.array([[1, 2, 3, 4], [10, 11, 14, 25], [20, 8, 7, 55], [40, 41, 42, 43]]) inverse_array = np.linalg.inv(arr)print("Inverse array is ")print(inverse_array)print() # inverse of 1X1 matrixarr = np.array([[1]])inverse_array = np.linalg.inv(arr)print("Inverse array is ")print(inverse_array) Output: Inverse array is [[-1.5 0.5 ] [ 1.25 -0.25]] Inverse array is [[-0.6875 -0.125 0.3125 ] [-0.125 0.25 -0.125 ] [ 0.64583333 -0.125 -0.02083333]] Inverse array is [[-15.07692308 4.9 -0.8 -0.42307692] [ 32.48717949 -10.9 1.8 1.01282051] [-20.84615385 7.1 -1.2 -0.65384615] [ 3.41025641 -1.1 0.2 0.08974359]] Inverse array is [[1.]] Example 2: Python3 # Import required package import numpy as np # Inverses of several matrices can # be computed at once A = np.array([[[1., 2.], [3., 4.]], [[1, 3], [3, 5]]]) # Calculating the inverse of the matrix print(np.linalg.inv(A)) Output: [[[-2. 1. ] [ 1.5 -0.5 ]] [[-1.25 0.75] [ 0.75 -0.25]]] Python numpy-Matrix Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Feb, 2021" }, { "code": null, "e": 536, "s": 28, "text": "The inverse of a matrix is just a reciprocal of the matrix as we do in normal arithmetic for a single number which is used to solve the equations to find the value of unknown variables. The inverse of a matrix is that matrix which when multiplied with the original matrix will give as an identity matrix. The inverse of a matrix exists only if the matrix is non-singular i.e., determinant should not be 0. Using determinant and adjoint, we can easily find the inverse of a square matrix using below formula," }, { "code": null, "e": 611, "s": 536, "text": "if det(A) != 0\n A-1 = adj(A)/det(A)\nelse\n \"Inverse doesn't exist\" \n" }, { "code": null, "e": 618, "s": 611, "text": "where," }, { "code": null, "e": 647, "s": 618, "text": "A-1: The inverse of matrix A" }, { "code": null, "e": 678, "s": 647, "text": "x: The unknown variable column" }, { "code": null, "e": 701, "s": 678, "text": "B: The solution matrix" }, { "code": null, "e": 794, "s": 701, "text": "We can find out the inverse of any square matrix with the function numpy.linalg.inv(array). " }, { "code": null, "e": 822, "s": 794, "text": "Syntax: numpy.linalg.inv(a)" }, { "code": null, "e": 834, "s": 822, "text": "Parameters:" }, { "code": null, "e": 859, "s": 834, "text": "a: Matrix to be inverted" }, { "code": null, "e": 893, "s": 859, "text": "Returns: Inverse of the matrix a." }, { "code": null, "e": 904, "s": 893, "text": "Example 1:" }, { "code": null, "e": 912, "s": 904, "text": "Python3" }, { "code": "# Importing Libraryimport numpy as np # Finding an inverse of given arrayarr = np.array([[1, 2], [5, 6]])inverse_array = np.linalg.inv(arr)print(\"Inverse array is \")print(inverse_array)print() # inverse of 3X3 matrixarr = np.array([[1, 2, 3], [4, 9, 6], [7, 8, 9]]) inverse_array = np.linalg.inv(arr)print(\"Inverse array is \")print(inverse_array)print() # inverse of 4X4 matrixarr = np.array([[1, 2, 3, 4], [10, 11, 14, 25], [20, 8, 7, 55], [40, 41, 42, 43]]) inverse_array = np.linalg.inv(arr)print(\"Inverse array is \")print(inverse_array)print() # inverse of 1X1 matrixarr = np.array([[1]])inverse_array = np.linalg.inv(arr)print(\"Inverse array is \")print(inverse_array)", "e": 1670, "s": 912, "text": null }, { "code": null, "e": 1678, "s": 1670, "text": "Output:" }, { "code": null, "e": 2131, "s": 1678, "text": "Inverse array is \n[[-1.5 0.5 ]\n [ 1.25 -0.25]]\n\nInverse array is \n[[-0.6875 -0.125 0.3125 ]\n [-0.125 0.25 -0.125 ]\n [ 0.64583333 -0.125 -0.02083333]]\n\nInverse array is \n[[-15.07692308 4.9 -0.8 -0.42307692]\n [ 32.48717949 -10.9 1.8 1.01282051]\n [-20.84615385 7.1 -1.2 -0.65384615]\n [ 3.41025641 -1.1 0.2 0.08974359]]\n\nInverse array is \n[[1.]]\n" }, { "code": null, "e": 2142, "s": 2131, "text": "Example 2:" }, { "code": null, "e": 2150, "s": 2142, "text": "Python3" }, { "code": "# Import required package import numpy as np # Inverses of several matrices can # be computed at once A = np.array([[[1., 2.], [3., 4.]], [[1, 3], [3, 5]]]) # Calculating the inverse of the matrix print(np.linalg.inv(A))", "e": 2393, "s": 2150, "text": null }, { "code": null, "e": 2401, "s": 2393, "text": "Output:" }, { "code": null, "e": 2470, "s": 2401, "text": "[[[-2. 1. ]\n [ 1.5 -0.5 ]]\n\n [[-1.25 0.75]\n [ 0.75 -0.25]]]\n" }, { "code": null, "e": 2499, "s": 2470, "text": "Python numpy-Matrix Function" }, { "code": null, "e": 2512, "s": 2499, "text": "Python-numpy" }, { "code": null, "e": 2519, "s": 2512, "text": "Python" } ]
which command in Linux with examples
27 May, 2019 which command in Linux is a command which is used to locate the executable file associated with the given command by searching it in the path environment variable. It has 3 return status as follows: 0 : If all specified commands are found and executable. 1 : If one or more specified commands is nonexistent or not executable. 2 : If an invalid option is specified. Syntax: which [filename1] [filename2] ... Options: which -a : This option print all matching pathnames of each argument. info which : It displays help information. linux-command Linux-Shell-Commands Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples 'crontab' in Linux with Examples Tail command in Linux with examples Docker - COPY Instruction UDP Server-Client implementation in C scp command in Linux with Examples diff command in Linux with examples echo command in Linux with Examples Cat command in Linux with examples touch command in Linux with Examples
[ { "code": null, "e": 52, "s": 24, "text": "\n27 May, 2019" }, { "code": null, "e": 251, "s": 52, "text": "which command in Linux is a command which is used to locate the executable file associated with the given command by searching it in the path environment variable. It has 3 return status as follows:" }, { "code": null, "e": 307, "s": 251, "text": "0 : If all specified commands are found and executable." }, { "code": null, "e": 379, "s": 307, "text": "1 : If one or more specified commands is nonexistent or not executable." }, { "code": null, "e": 418, "s": 379, "text": "2 : If an invalid option is specified." }, { "code": null, "e": 426, "s": 418, "text": "Syntax:" }, { "code": null, "e": 460, "s": 426, "text": "which [filename1] [filename2] ..." }, { "code": null, "e": 469, "s": 460, "text": "Options:" }, { "code": null, "e": 539, "s": 469, "text": "which -a : This option print all matching pathnames of each argument." }, { "code": null, "e": 582, "s": 539, "text": "info which : It displays help information." }, { "code": null, "e": 596, "s": 582, "text": "linux-command" }, { "code": null, "e": 617, "s": 596, "text": "Linux-Shell-Commands" }, { "code": null, "e": 628, "s": 617, "text": "Linux-Unix" }, { "code": null, "e": 647, "s": 628, "text": "Technical Scripter" }, { "code": null, "e": 745, "s": 647, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 780, "s": 745, "text": "tar command in Linux with examples" }, { "code": null, "e": 813, "s": 780, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 849, "s": 813, "text": "Tail command in Linux with examples" }, { "code": null, "e": 875, "s": 849, "text": "Docker - COPY Instruction" }, { "code": null, "e": 913, "s": 875, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 948, "s": 913, "text": "scp command in Linux with Examples" }, { "code": null, "e": 984, "s": 948, "text": "diff command in Linux with examples" }, { "code": null, "e": 1020, "s": 984, "text": "echo command in Linux with Examples" }, { "code": null, "e": 1055, "s": 1020, "text": "Cat command in Linux with examples" } ]
Python – seaborn.pairplot() method
15 Jul, 2020 Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. Seaborn helps resolve the two major problems faced by Matplotlib; the problems are ? Default Matplotlib parameters Working with data frames As Seaborn compliments and extends Matplotlib, the learning curve is quite gradual. If you know Matplotlib, you are already half way through Seaborn. To plot multiple pairwise bivariate distributions in a dataset, you can use the pairplot() function. This shows the relationship for (n, 2) combination of variable in a DataFrame as a matrix of plots and the diagonal plots are the univariate plots. seaborn.pairplot( data, \*\*kwargs ) Seaborn.pairplot uses many arguments as input, main of which are described below in form of table: Below is the implementation of above method: Python3 # importing packagesimport seabornimport matplotlib.pyplot as plt ############# Main Section ############# loading dataset using seaborndf = seaborn.load_dataset('tips')# pairplot with hue sexseaborn.pairplot(df, hue ='sex')# to showplt.show() # This code is contributed by Deepanshu Rustagi. Python3 # importing packagesimport seabornimport matplotlib.pyplot as plt ############# Main Section ############# loading dataset using seaborndf = seaborn.load_dataset('tips')# pairplot with hue dayseaborn.pairplot(df, hue ='day')# to showplt.show() # This code is contributed by Deepanshu Rustagi. Data Visualization Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Different ways to create Pandas Dataframe Taking input in Python Enumerate() in Python Read a file line by line in Python Python String | replace()
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Jul, 2020" }, { "code": null, "e": 303, "s": 54, "text": "Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. Seaborn helps resolve the two major problems faced by Matplotlib; the problems are ?" }, { "code": null, "e": 333, "s": 303, "text": "Default Matplotlib parameters" }, { "code": null, "e": 358, "s": 333, "text": "Working with data frames" }, { "code": null, "e": 508, "s": 358, "text": "As Seaborn compliments and extends Matplotlib, the learning curve is quite gradual. If you know Matplotlib, you are already half way through Seaborn." }, { "code": null, "e": 757, "s": 508, "text": "To plot multiple pairwise bivariate distributions in a dataset, you can use the pairplot() function. This shows the relationship for (n, 2) combination of variable in a DataFrame as a matrix of plots and the diagonal plots are the univariate plots." }, { "code": null, "e": 820, "s": 757, "text": " seaborn.pairplot( data, \\*\\*kwargs )\n\n" }, { "code": null, "e": 919, "s": 820, "text": "Seaborn.pairplot uses many arguments as input, main of which are described below in form of table:" }, { "code": null, "e": 964, "s": 919, "text": "Below is the implementation of above method:" }, { "code": null, "e": 972, "s": 964, "text": "Python3" }, { "code": "# importing packagesimport seabornimport matplotlib.pyplot as plt ############# Main Section ############# loading dataset using seaborndf = seaborn.load_dataset('tips')# pairplot with hue sexseaborn.pairplot(df, hue ='sex')# to showplt.show() # This code is contributed by Deepanshu Rustagi.", "e": 1267, "s": 972, "text": null }, { "code": null, "e": 1280, "s": 1272, "text": "Python3" }, { "code": "# importing packagesimport seabornimport matplotlib.pyplot as plt ############# Main Section ############# loading dataset using seaborndf = seaborn.load_dataset('tips')# pairplot with hue dayseaborn.pairplot(df, hue ='day')# to showplt.show() # This code is contributed by Deepanshu Rustagi.", "e": 1575, "s": 1280, "text": null }, { "code": null, "e": 1599, "s": 1580, "text": "Data Visualization" }, { "code": null, "e": 1614, "s": 1599, "text": "Python-Seaborn" }, { "code": null, "e": 1621, "s": 1614, "text": "Python" }, { "code": null, "e": 1719, "s": 1621, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1747, "s": 1719, "text": "Read JSON file using Python" }, { "code": null, "e": 1797, "s": 1747, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 1819, "s": 1797, "text": "Python map() function" }, { "code": null, "e": 1863, "s": 1819, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 1881, "s": 1863, "text": "Python Dictionary" }, { "code": null, "e": 1923, "s": 1881, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1946, "s": 1923, "text": "Taking input in Python" }, { "code": null, "e": 1968, "s": 1946, "text": "Enumerate() in Python" }, { "code": null, "e": 2003, "s": 1968, "text": "Read a file line by line in Python" } ]
Remove duplicates from a given string
06 Jul, 2022 C++ Java Python3 C# Javascript // CPP program to remove duplicate character// from character array and print in sorted// order#include <bits/stdc++.h>using namespace std; char *removeDuplicate(char str[], int n){ // create a set using string characters // excluding '\0' unordered_set<char>s (str, str+n-1); // print content of the set int i = 0; for (auto x : s) str[i++] = x; str[i] = '\0'; return str;} // Driver codeint main(){ char str[]= "geeksforgeeks"; int n = sizeof(str) / sizeof(str[0]); cout << removeDuplicate(str, n); return 0;} // Java program to remove duplicate character// from character array and print in sorted// orderimport java.util.*; class GFG { static void removeDuplicate(char str[], int n) { // Create a set using String characters // excluding '\0' HashSet<Character> s = new LinkedHashSet<>(n - 1); // HashSet doesn't allow repetition of elements for (char x : str) s.add(x); // Print content of the set for (char x : s) System.out.print(x); } // Driver code public static void main(String[] args) { char str[] = "geeksforgeeks".toCharArray(); int n = str.length; removeDuplicate(str, n); }} // This code is contributed by todaysgaurav # Python program to remove duplicate character# from character array and print in sorted# orderdef removeDuplicate(str, n): s = set() # Create a set using String characters for i in str: s.add(i) # Print content of the set st = "" for i in s: st = st+i return st # Driver codestr = "geeksforgeeks"n = len(str)print(removeDuplicate(list(str), n)) # This code is contributed by rajsanghavi9. // C# program to remove duplicate character// from character array and print in sorted// orderusing System;using System.Collections.Generic; public class GFG{ static char []removeDuplicate(char []str, int n){ // Create a set using String characters // excluding '\0' HashSet<char>s = new HashSet<char>(n - 1); foreach(char x in str) s.Add(x); char[] st = new char[s.Count]; // Print content of the set int i = 0; foreach(char x in s) st[i++] = x; return st;} // Driver codepublic static void Main(String[] args){ char []str= "geeksforgeeks".ToCharArray(); int n = str.Length; Console.Write(removeDuplicate(str, n));}} // This code contributed by gauravrajput1 <script>// javascript program to remove duplicate character// from character array and print in sorted// order function removeDuplicate( str , n) { // Create a set using String characters // excluding '\0' var s = new Set(); // HashSet doesn't allow repetition of elements for (var i = 0;i<n;i++) s.add(str[i]); // Print content of the set for (const v of s) { document.write(v); } } // Driver code var str = "geeksforgeeks"; var n = str.length; removeDuplicate(str, n); // This code is contributed by umadevi9616</script> Given a string S, the task is to remove all the duplicates in the given string. Below are the different methods to remove duplicates in a string. METHOD 1 (Simple) C++ Java Python3 C# Javascript // CPP program to remove duplicate character// from character array and print in sorted// order#include <bits/stdc++.h>using namespace std; char *removeDuplicate(char str[], int n){ // Used as index in the modified string int index = 0; // Traverse through all characters for (int i=0; i<n; i++) { // Check if str[i] is present before it int j; for (j=0; j<i; j++) if (str[i] == str[j]) break; // If not present, then add it to // result. if (j == i) str[index++] = str[i]; } return str;} // Driver codeint main(){ char str[]= "geeksforgeeks"; int n = sizeof(str) / sizeof(str[0]); cout << removeDuplicate(str, n); return 0;} // Java program to remove duplicate character// from character array and print in sorted// orderimport java.util.*; class GFG{ static String removeDuplicate(char str[], int n) { // Used as index in the modified string int index = 0; // Traverse through all characters for (int i = 0; i < n; i++) { // Check if str[i] is present before it int j; for (j = 0; j < i; j++) { if (str[i] == str[j]) { break; } } // If not present, then add it to // result. if (j == i) { str[index++] = str[i]; } } return String.valueOf(Arrays.copyOf(str, index)); } // Driver code public static void main(String[] args) { char str[] = "geeksforgeeks".toCharArray(); int n = str.length; System.out.println(removeDuplicate(str, n)); }} // This code is contributed by Rajput-Ji string="geeksforgeeks"p=""for char in string: if char not in p: p=p+charprint(p)k=list("geeksforgeeks") // C# program to remove duplicate character// from character array and print in sorted// orderusing System;using System.Collections.Generic;class GFG{static String removeDuplicate(char []str, int n){ // Used as index in the modified string int index = 0; // Traverse through all characters for (int i = 0; i < n; i++) { // Check if str[i] is present before it int j; for (j = 0; j < i; j++) { if (str[i] == str[j]) { break; } } // If not present, then add it to // result. if (j == i) { str[index++] = str[i]; } } char [] ans = new char[index]; Array.Copy(str, ans, index); return String.Join("", ans);} // Driver codepublic static void Main(String[] args){ char []str = "geeksforgeeks".ToCharArray(); int n = str.Length; Console.WriteLine(removeDuplicate(str, n));}} // This code is contributed by PrinciRaj1992 <script> // JavaScript program to remove duplicate character// from character array and print in sorted// orderfunction removeDuplicate(str, n) { // Used as index in the modified string var index = 0; // Traverse through all characters for (var i = 0; i < n; i++) { // Check if str[i] is present before it var j; for (j = 0; j < i; j++) { if (str[i] == str[j]) { break; } } // If not present, then add it to // result. if (j == i) { str[index++] = str[i]; } } return str.join("").slice(str, index); } // Driver code var str = "geeksforgeeks".split(""); var n = str.length; document.write(removeDuplicate(str, n)); // This code is contributed by shivanisinghss2110 </script> Output: geksfor Time Complexity: O(n * n) Auxiliary Space: O(1) Keeps order of elements the same as the input. METHOD 2 (using set)Use set to store only one instance of any value. C++ Java Python3 C# Javascript // CPP program to remove duplicate character// from character array and print in sorted// order#include <bits/stdc++.h>using namespace std; char *removeDuplicate(char str[], int n){ // create a set using string characters // excluding '\0' unordered_set<char>s (str, str+n-1); // print content of the set int i = 0; for (auto x : s) str[i++] = x; str[i] = '\0'; return str;} // Driver codeint main(){ char str[]= "geeksforgeeks"; int n = sizeof(str) / sizeof(str[0]); cout << removeDuplicate(str, n); return 0;} // Java program to remove duplicate character// from character array and print in sorted// orderimport java.util.*; class GFG { static void removeDuplicate(char str[], int n) { // Create a set using String characters // excluding '\0' HashSet<Character> s = new LinkedHashSet<>(n - 1); // HashSet doesn't allow repetition of elements for (char x : str) s.add(x); // Print content of the set for (char x : s) System.out.print(x); } // Driver code public static void main(String[] args) { char str[] = "geeksforgeeks".toCharArray(); int n = str.length; removeDuplicate(str, n); }} // This code is contributed by todaysgaurav # Python program to remove duplicate character# from character array and print in sorted# orderdef removeDuplicate(str, n): s = set() # Create a set using String characters for i in str: s.add(i) # Print content of the set st = "" for i in s: st = st+i return st # Driver codestr = "geeksforgeeks"n = len(str)print(removeDuplicate(list(str), n)) # This code is contributed by rajsanghavi9. // C# program to remove duplicate character// from character array and print in sorted// orderusing System;using System.Collections.Generic; public class GFG{ static char []removeDuplicate(char []str, int n){ // Create a set using String characters // excluding '\0' HashSet<char>s = new HashSet<char>(n - 1); foreach(char x in str) s.Add(x); char[] st = new char[s.Count]; // Print content of the set int i = 0; foreach(char x in s) st[i++] = x; return st;} // Driver codepublic static void Main(String[] args){ char []str= "geeksforgeeks".ToCharArray(); int n = str.Length; Console.Write(removeDuplicate(str, n));}} // This code contributed by gauravrajput1 <script>// javascript program to remove duplicate character// from character array and print in sorted// order function removeDuplicate( str , n) { // Create a set using String characters // excluding '\0' var s = new Set(); // HashSet doesn't allow repetition of elements for (var i = 0;i<n;i++) s.add(str[i]); // Print content of the set for (const v of s) { document.write(v); } } // Driver code var str = "geeksforgeeks"; var n = str.length; removeDuplicate(str, n); // This code is contributed by umadevi9616</script> Output: efgkors Time Complexity: O(n) Auxiliary Space: O(n) Thanks to Anivesh Tiwari for suggesting this approach. It does not keep the order of elements the same as the input but prints them in sorted order. METHOD 3 (Use Sorting) Algorithm: 1) Sort the elements. 2) Now in a loop, remove duplicates by comparing the current character with previous character. 3) Remove extra characters at the end of the resultant string. Example: Input string: geeksforgeeks 1) Sort the characters eeeefggkkorss 2) Remove duplicates efgkorskkorss 3) Remove extra characters efgkors Note that, this method doesn’t keep the original order of the input string. For example, if we are to remove duplicates for geeksforgeeks and keep the order of characters the same, then the output should be geksfor, but the above function returns efgkos. We can modify this method by storing the original order. Implementation: C++ C Java Python3 C# Javascript // C++ program to remove duplicates, the order of// characters is not maintained in this program#include<bits/stdc++.h>using namespace std; /* Function to remove duplicates in a sorted array */char *removeDupsSorted(char *str){ int res_ind = 1, ip_ind = 1; /* In place removal of duplicate characters*/ while (*(str + ip_ind)) { if (*(str + ip_ind) != *(str + ip_ind - 1)) { *(str + res_ind) = *(str + ip_ind); res_ind++; } ip_ind++; } /* After above step string is efgkorskkorss. Removing extra kkorss after string*/ *(str + res_ind) = '\0'; return str;} /* Function removes duplicate characters from the string This function work in-place and fills null characters in the extra space left */char *removeDups(char *str){ int n = strlen(str); // Sort the character array sort(str, str+n); // Remove duplicates from sorted return removeDupsSorted(str);} /* Driver program to test removeDups */int main(){ char str[] = "geeksforgeeks"; cout << removeDups(str); return 0;} // C program to remove duplicates, the order of// characters is not maintained in this program# include <stdio.h># include <stdlib.h># include <string.h>/* Function to remove duplicates in a sorted array */char *removeDupsSorted(char *str); /* Utility function to sort array A[] */void quickSort(char A[], int si, int ei); /* Function removes duplicate characters from the string This function work in-place and fills null characters in the extra space left */char *removeDups(char *str){ int len = strlen(str); quickSort(str, 0, len-1); return removeDupsSorted(str);} /* Function to remove duplicates in a sorted array */char *removeDupsSorted(char *str){ int res_ind = 1, ip_ind = 1; /* In place removal of duplicate characters*/ while (*(str + ip_ind)) { if (*(str + ip_ind) != *(str + ip_ind - 1)) { *(str + res_ind) = *(str + ip_ind); res_ind++; } ip_ind++; } /* After above step string is efgkorskkorss. Removing extra kkorss after string*/ *(str + res_ind) = '\0'; return str;} /* Driver program to test removeDups */int main(){ char str[] = "geeksforgeeks"; printf("%s", removeDups(str)); getchar(); return 0;} /* FOLLOWING FUNCTIONS ARE ONLY FOR SORTING PURPOSE */void exchange(char *a, char *b){ char temp; temp = *a; *a = *b; *b = temp;} int partition(char A[], int si, int ei){ char x = A[ei]; int i = (si - 1); int j; for (j = si; j <= ei - 1; j++) { if (A[j] <= x) { i++; exchange(&A[i], &A[j]); } } exchange (&A[i + 1], &A[ei]); return (i + 1);} /* Implementation of Quick SortA[] --> Array to be sortedsi --> Starting indexei --> Ending index*/void quickSort(char A[], int si, int ei){ int pi; /* Partitioning index */ if (si < ei) { pi = partition(A, si, ei); quickSort(A, si, pi - 1); quickSort(A, pi + 1, ei); }} // Java program to remove duplicates, the order of// characters is not maintained in this program import java.util.Arrays; public class GFG{ /* Method to remove duplicates in a sorted array */ static String removeDupsSorted(String str) { int res_ind = 1, ip_ind = 1; // Character array for removal of duplicate characters char arr[] = str.toCharArray(); /* In place removal of duplicate characters*/ while (ip_ind != arr.length) { if(arr[ip_ind] != arr[ip_ind-1]) { arr[res_ind] = arr[ip_ind]; res_ind++; } ip_ind++; } str = new String(arr); return str.substring(0,res_ind); } /* Method removes duplicate characters from the string This function work in-place and fills null characters in the extra space left */ static String removeDups(String str) { // Sort the character array char temp[] = str.toCharArray(); Arrays.sort(temp); str = new String(temp); // Remove duplicates from sorted return removeDupsSorted(str); } // Driver Method public static void main(String[] args) { String str = "geeksforgeeks"; System.out.println(removeDups(str)); }} # Python3 program to remove duplicates, the order of# characters is not maintained in this program # Utility function to convert string to listdef toMutable(string): temp = [] for x in string: temp.append(x) return temp # Utility function to convert string to listdef toString(List): return ''.join(List) # Function to remove duplicates in a sorted arraydef removeDupsSorted(List): res_ind = 1 ip_ind = 1 # In place removal of duplicate characters while ip_ind != len(List): if List[ip_ind] != List[ip_ind-1]: List[res_ind] = List[ip_ind] res_ind += 1 ip_ind+=1 # After above step string is efgkorskkorss. # Removing extra kkorss after string string = toString(List[0:res_ind]) return string # Function removes duplicate characters from the string# This function work in-place and fills null characters# in the extra space leftdef removeDups(string): # Convert string to list List = toMutable(string) # Sort the character list List.sort() # Remove duplicates from sorted return removeDupsSorted(List) # Driver program to test the above functionsstring = "geeksforgeeks"print(removeDups(string)) # This code is contributed by Bhavya Jain // C# program to remove duplicates, the order of// characters is not maintained in this programusing System; class GFG{ /* Method to remove duplicates in a sorted array */ static String removeDupsSorted(String str) { int res_ind = 1, ip_ind = 1; // Character array for removal of duplicate characters char []arr = str.ToCharArray(); /* In place removal of duplicate characters*/ while (ip_ind != arr.Length) { if(arr[ip_ind] != arr[ip_ind-1]) { arr[res_ind] = arr[ip_ind]; res_ind++; } ip_ind++; } str = new String(arr); return str.Substring(0,res_ind); } /* Method removes duplicate characters from the string This function work in-place and fills null characters in the extra space left */ static String removeDups(String str) { // Sort the character array char []temp = str.ToCharArray(); Array.Sort(temp); str = String.Join("",temp); // Remove duplicates from sorted return removeDupsSorted(str); } // Driver Method public static void Main(String[] args) { String str = "geeksforgeeks"; Console.WriteLine(removeDups(str)); }} // This code is contributed by 29AjayKumar <script> function removeDuplicate(string){ return string.split('') .filter(function(item, pos, self) { return self.indexOf(item) == pos; } ).join('');} var str = "geeksforgeeks";document.write( " "+removeDuplicate(str)); //This code is contributed by SoumikMondal</script> Output: efgkors Time Complexity: O(n log n) If we use some nlogn sorting algorithm instead of quicksort. Auxiliary Space: O(1) METHOD 4 (Use Hashing ) Algorithm: 1: Initialize: str = "test string" /* input string */ ip_ind = 0 /* index to keep track of location of next character in input string */ res_ind = 0 /* index to keep track of location of next character in the resultant string */ bin_hash[0..255] = {0,0, ....} /* Binary hash to see if character is already processed or not */ 2: Do following for each character *(str + ip_ind) in input string: (a) if bin_hash is not set for *(str + ip_ind) then // if program sees the character *(str + ip_ind) first time (i) Set bin_hash for *(str + ip_ind) (ii) Move *(str + ip_ind) to the resultant string. This is done in-place. (iii) res_ind++ (b) ip_ind++ /* String obtained after this step is "the stringing" */ 3: Remove extra characters at the end of the resultant string. /* String obtained after this step is "te string" */ Implementation: C++ C Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std;# define NO_OF_CHARS 256# define bool int /* Function removes duplicate characters from the stringThis function work in-place and fills null charactersin the extra space left */char *removeDups(char str[]){ bool bin_hash[NO_OF_CHARS] = {0}; int ip_ind = 0, res_ind = 0; char temp; /* In place removal of duplicate characters*/ while (*(str + ip_ind)) { temp = *(str + ip_ind); if (bin_hash[temp] == 0) { bin_hash[temp] = 1; *(str + res_ind) = *(str + ip_ind); res_ind++; } ip_ind++; } /* After above step string is stringiittg. Removing extra iittg after string*/ *(str+res_ind) = '\0'; return str;} /* Driver code */int main(){ char str[] = "geeksforgeeks"; cout << removeDups(str); return 0;} // This code is contributed by rathbhupendra # include <stdio.h># include <stdlib.h># define NO_OF_CHARS 256# define bool int /* Function removes duplicate characters from the string This function work in-place and fills null characters in the extra space left */char *removeDups(char *str){ bool bin_hash[NO_OF_CHARS] = {0}; int ip_ind = 0, res_ind = 0; char temp; /* In place removal of duplicate characters*/ while (*(str + ip_ind)) { temp = *(str + ip_ind); if (bin_hash[temp] == 0) { bin_hash[temp] = 1; *(str + res_ind) = *(str + ip_ind); res_ind++; } ip_ind++; } /* After above step string is stringiittg. Removing extra iittg after string*/ *(str+res_ind) = '\0'; return str;} /* Driver program to test removeDups */int main(){ char str[] = "geeksforgeeks"; printf("%s", removeDups(str)); getchar(); return 0;} // Java program to remove duplicatesimport java.util.*; class RemoveDuplicates{ /* Function removes duplicate characters from the string This function work in-place */ void removeDuplicates(String str) { LinkedHashSet<Character> lhs = new LinkedHashSet<>(); for(int i=0;i<str.length();i++) lhs.add(str.charAt(i)); // print string after deleting duplicate elements for(Character ch : lhs) System.out.print(ch); } /* Driver program to test removeDuplicates */ public static void main(String args[]) { String str = "geeksforgeeks"; RemoveDuplicates r = new RemoveDuplicates(); r.removeDuplicates(str); }} // This code has been contributed by Amit Khandelwal (Amit Khandelwal 1) # Python3 program to remove duplicate characters from an# input stringNO_OF_CHARS = 256 # Since strings in Python are immutable and cannot be changed# This utility function will convert the string to listdef toMutable(string): List = [] for i in string: List.append(i) return List # Utility function that changes list to stringdef toString(List): return ''.join(List) # Function removes duplicate characters from the string# This function work in-place and fills null characters# in the extra space leftdef removeDups(string): bin_hash = [0] * NO_OF_CHARS ip_ind = 0 res_ind = 0 temp = '' mutableString = toMutable(string) # In place removal of duplicate characters while ip_ind != len(mutableString): temp = mutableString[ip_ind] if bin_hash[ord(temp)] == 0: bin_hash[ord(temp)] = 1 mutableString[res_ind] = mutableString[ip_ind] res_ind+=1 ip_ind+=1 # After above step string is stringiittg. # Removing extra iittg after string return toString(mutableString[0:res_ind]) # Driver program to test the above functionsstring = "geeksforgeeks"print(removeDups(string)) # A shorter version for this program is as follows# import collections# print ''.join(collections.OrderedDict.fromkeys(string)) # This code is contributed by Bhavya Jain // C# program to remove duplicatesusing System;using System.Collections.Generic; class GFG{ /* Function removes duplicate characters from the string. This function work in-place */ void removeDuplicates(String str) { HashSet<char> lhs = new HashSet<char>(); for(int i = 0; i < str.Length; i++) lhs.Add(str[i]); // print string after deleting // duplicate elements foreach(char ch in lhs) Console.Write(ch); } // Driver Code public static void Main(String []args) { String str = "geeksforgeeks"; GFG r = new GFG(); r.removeDuplicates(str); }} // This code is contributed by Rajput-Ji <script>// javascript program to remove duplicates /* * Function removes duplicate characters from the string This function work * in-place */ function removeDuplicates( str) { var lhs = new Set(); for (var i = 0; i < str.length; i++) lhs.add(str[i]); // print string after deleting duplicate elements for (var ch of lhs) document.write(ch); } /* Driver program to test removeDuplicates */ var str = "geeksforgeeks"; removeDuplicates(str); // This code is contributed by umadevi9616</script> Output: geksfor Time Complexity: O(n) Auxiliary Space: O(1) Important Points: Method 2 doesn’t maintain the characters as original strings, but method 4 does. It is assumed that the number of possible characters in the input string is 256. NO_OF_CHARS should be changed accordingly. calloc() is used instead of malloc() for memory allocations of a counting array (count) to initialize allocated memory to ‘\0’. the malloc() followed by memset() could also be used. The above algorithm also works for integer array inputs if the range of the integers in the array is given. An example problem is to find the maximum occurring number in an input array given that the input array contains integers only between 1000 to 1100 Method 5 (Using IndexOf() method) : Prerequisite : Java IndexOf() method C++ Java Python3 C# Javascript // C++ program to create a unique string#include <bits/stdc++.h>using namespace std; // Function to make the string uniquestring unique(string s){ string str; int len = s.length(); // loop to traverse the string and // check for repeating chars using // IndexOf() method in Java for(int i = 0; i < len; i++) { // character at i'th index of s char c = s[i]; // If c is present in str, it returns // the index of c, else it returns npos auto found = str.find(c); if (found == std::string::npos) { // Adding c to str if npos is returned str += c; } } return str;} // Driver codeint main(){ // Input string with repeating chars string s = "geeksforgeeks"; cout << unique(s) << endl;} // This code is contributed by nirajgusain5 // Java program to create a unique stringimport java.util.*; class IndexOf { // Function to make the string unique public static String unique(String s) { String str = new String(); int len = s.length(); // loop to traverse the string and // check for repeating chars using // IndexOf() method in Java for (int i = 0; i < len; i++) { // character at i'th index of s char c = s.charAt(i); // if c is present in str, it returns // the index of c, else it returns -1 if (str.indexOf(c) < 0) { // adding c to str if -1 is returned str += c; } } return str; } // Driver code public static void main(String[] args) { // Input string with repeating chars String s = "geeksforgeeks"; System.out.println(unique(s)); }} # Python 3 program to create a unique string # Function to make the string unique def unique(s): st = "" length = len(s) # loop to traverse the string and # check for repeating chars using # IndexOf() method in Java for i in range(length): # character at i'th index of s c = s[i] # if c is present in str, it returns # the index of c, else it returns - 1 # print(st.index(c)) if c not in st: # adding c to str if -1 is returned st += c return st # Driver codeif __name__ == "__main__": # Input string with repeating chars s = "geeksforgeeks" print(unique(s)) # This code is contributed by ukasp. // C# program to create a unique stringusing System; public class IndexOf{ // Function to make the string unique public static String unique(String s) { String str = ""; int len = s.Length; // loop to traverse the string and // check for repeating chars using // IndexOf() method in Java for (int i = 0; i < len; i++) { // character at i'th index of s char c = s[i]; // if c is present in str, it returns // the index of c, else it returns -1 if (str.IndexOf(c) < 0) { // adding c to str if -1 is returned str += c; } } return str; } // Driver code public static void Main(String[] args) { // Input string with repeating chars String s = "geeksforgeeks"; Console.WriteLine(unique(s)); }} // This code is contributed by Princi Singh <script> // JavaScript program to create a unique string // Function to make the string unique function unique(s) { let str = ""; let len = s.length; // loop to traverse the string and // check for repeating chars using // IndexOf() method in Java for (let i = 0; i < len; i++) { // character at i'th index of s let c = s[i]; // if c is present in str, it returns // the index of c, else it returns -1 if (str.indexOf(c) < 0) { // adding c to str if -1 is returned str += c; } } return str; } // Input string with repeating chars let s = "geeksforgeeks"; document.write(unique(s)); </script> Output: geksfor Thanks debjitdbb for suggesting this approach. Method 6 (Using unordered_map STL method) : Prerequisite : unordered_map STL C++ method C++ Java Python3 C# Javascript // C++ program to create a unique string using unordered_map /* access time in unordered_map on is O(1) generally if no collisions occurand therefore it helps us check if an element exists in a string in O(1)time complexity with constant space. */ #include <bits/stdc++.h>using namespace std;char* removeDuplicates(char *s,int n){ unordered_map<char,int> exists; int index = 0; for(int i=0;i<n;i++){ if(exists[s[i]]==0) { s[index++] = s[i]; exists[s[i]]++; } } return s;} //driver codeint main(){ char s[] = "geeksforgeeks"; int n = sizeof(s)/sizeof(s[0]); cout<<removeDuplicates(s,n)<<endl; return 0;} // Java program to create a unique String using unordered_map /* access time in unordered_map on is O(1) generally if no collisions occurand therefore it helps us check if an element exists in a String in O(1)time complexity with constant space. */import java.util.*; class GFG{static char[] removeDuplicates(char []s,int n){ Map<Character,Integer> exists = new HashMap<>(); String st = ""; for(int i = 0; i < n; i++){ if(!exists.containsKey(s[i])) { st += s[i]; exists.put(s[i], 1); } } return st.toCharArray();} // driver codepublic static void main(String[] args){ char s[] = "geeksforgeeks".toCharArray(); int n = s.length; System.out.print(removeDuplicates(s,n));}} // This code is contributed by gauravrajput1 # Python program to create a unique string using unordered_map # access time in unordered_map on is O(1) generally if no collisions occur# and therefore it helps us check if an element exists in a string in O(1)# time complexity with constant space.def removeDuplicates(s, n): exists = {} index = 0 ans = "" for i in range(0, n): if s[i] not in exists or exists[s[i]] == 0: s[index] = s[i] print(s[index], end='') index += 1 exists[s[i]] = 1 # driver codes = "geeksforgeeks"s1 = list(s)n = len(s1)removeDuplicates(s1, n) # This code is contributed by Palak Gupta // C# program to create a unique String using unordered_map /* access time in unordered_map on is O(1) generally if no collisions occurand therefore it helps us check if an element exists in a String in O(1)time complexity with constant space. */using System;using System.Collections.Generic; public class GFG{static char[] removeDuplicates(char []s,int n){ Dictionary<char,int> exists = new Dictionary<char, int>(); String st = ""; for(int i = 0; i < n; i++){ if(!exists.ContainsKey(s[i])) { st += s[i]; exists.Add(s[i], 1); } } return st.ToCharArray();} // driver codepublic static void Main(String[] args){ char []s = "geeksforgeeks".ToCharArray(); int n = s.Length; Console.Write(removeDuplicates(s,n));}} // This code is contributed by umadevi9616 <script>// javascript program to create a unique String using unordered_map /* access time in unordered_map on is O(1) generally if no collisions occurand therefore it helps us check if an element exists in a String in O(1)time complexity with constant space. */ function removeDuplicates( s , n) { var exists = new Map(); var st = ""; for (var i = 0; i < n; i++) { if (!exists.has(s[i])) { st += s[i]; exists.set(s[i], 1); } } return st; } // driver code var s = "geeksforgeeks"; var n = s.length; document.write(removeDuplicates(s, n));// This code contributed by umadevi9616</script> Output: geksfor Time Complexity : O(n) Auxiliary Space : O(n)Thanks, Allen James Vinoy for suggesting this approach. METHOD 7 (Simple) C++ Java Python3 C# Javascript #include <iostream>using namespace std; int main(){ string s = "abcdabd"; string temp = ""; temp += s.at(0); for (int i = 1; i < s.length(); i++) { if (!(temp.find(s.at(i)) < temp.length())) temp = temp + s.at(i); } cout << temp; return 0;}//This code is contributed by KaaL-EL. import java.io.*; class GFG { public static void main(String[] args) { String s = "abcdabd"; String temp = "" + s.charAt(0); for (int i = 1; i < s.length(); i++) { if (!temp.contains( String.valueOf(s.charAt(i)))) temp = temp + s.charAt(i); } System.out.println(temp); }} # Python code for the above Approachs = "abcdabd"temp = "" + s[0] for i in range(1,len(s)): if (s[i] not in temp): temp = temp + s[i] # Printing the Resultprint(temp) # This code is contributed by kothavvsaakash. using System; public class GFG{ static public void Main (){ string s = "abcdabd"; string temp = ""; temp += s[0]; for (int i = 1; i < s.Length; i++) { if (temp.IndexOf(s[i]) == -1) temp = temp + s[i]; } System.Console.WriteLine(temp); }} // This code is contributed by akashish__ <script> // JavaScript code for the above Approachlet s = "abcdabd"let temp = "" + s[0] for(let i=1;i<s.length;i++){ if (temp.indexOf(s[i]) == -1) temp = temp + s[i]} // Printing the Resultdocument.write(temp,"</br>") // This code is contributed by shinjanpatra </script> abcd Time Complexity : O(n) Auxiliary Space: O(n) rathbhupendra 29AjayKumar princi singh ALLENJAMESVINOY17BCE0748 Rajput-Ji princiraj1992 SHUBHAMSINGH10 amirthanand ukasp SoumikMondal todaysgaurav vaibhavrabadiya3 nirajgusain5 shivanisinghss2110 as5853535 surindertarika1234 GauravRajput1 rajsanghavi9 saunaknandi021000 umadevi9616 adnanirshad158 simranarora5sos rishavmahato348 prachisoda1234 simmytarika5 raghavendra777 sumitgumber28 surinderdawra388 amartyaghoshgfg sagar0719kumar ninja_hattori harendrakumar123 rajivkumarinfo kothavvsaakash shinjanpatra shivamanandrj9 kaalel akashish__ frequency-counting Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 56, "s": 52, "text": "C++" }, { "code": null, "e": 61, "s": 56, "text": "Java" }, { "code": null, "e": 69, "s": 61, "text": "Python3" }, { "code": null, "e": 72, "s": 69, "text": "C#" }, { "code": null, "e": 83, "s": 72, "text": "Javascript" }, { "code": "// CPP program to remove duplicate character// from character array and print in sorted// order#include <bits/stdc++.h>using namespace std; char *removeDuplicate(char str[], int n){ // create a set using string characters // excluding '\\0' unordered_set<char>s (str, str+n-1); // print content of the set int i = 0; for (auto x : s) str[i++] = x; str[i] = '\\0'; return str;} // Driver codeint main(){ char str[]= \"geeksforgeeks\"; int n = sizeof(str) / sizeof(str[0]); cout << removeDuplicate(str, n); return 0;}", "e": 635, "s": 83, "text": null }, { "code": "// Java program to remove duplicate character// from character array and print in sorted// orderimport java.util.*; class GFG { static void removeDuplicate(char str[], int n) { // Create a set using String characters // excluding '\\0' HashSet<Character> s = new LinkedHashSet<>(n - 1); // HashSet doesn't allow repetition of elements for (char x : str) s.add(x); // Print content of the set for (char x : s) System.out.print(x); } // Driver code public static void main(String[] args) { char str[] = \"geeksforgeeks\".toCharArray(); int n = str.length; removeDuplicate(str, n); }} // This code is contributed by todaysgaurav", "e": 1372, "s": 635, "text": null }, { "code": "# Python program to remove duplicate character# from character array and print in sorted# orderdef removeDuplicate(str, n): s = set() # Create a set using String characters for i in str: s.add(i) # Print content of the set st = \"\" for i in s: st = st+i return st # Driver codestr = \"geeksforgeeks\"n = len(str)print(removeDuplicate(list(str), n)) # This code is contributed by rajsanghavi9.", "e": 1804, "s": 1372, "text": null }, { "code": "// C# program to remove duplicate character// from character array and print in sorted// orderusing System;using System.Collections.Generic; public class GFG{ static char []removeDuplicate(char []str, int n){ // Create a set using String characters // excluding '\\0' HashSet<char>s = new HashSet<char>(n - 1); foreach(char x in str) s.Add(x); char[] st = new char[s.Count]; // Print content of the set int i = 0; foreach(char x in s) st[i++] = x; return st;} // Driver codepublic static void Main(String[] args){ char []str= \"geeksforgeeks\".ToCharArray(); int n = str.Length; Console.Write(removeDuplicate(str, n));}} // This code contributed by gauravrajput1", "e": 2537, "s": 1804, "text": null }, { "code": "<script>// javascript program to remove duplicate character// from character array and print in sorted// order function removeDuplicate( str , n) { // Create a set using String characters // excluding '\\0' var s = new Set(); // HashSet doesn't allow repetition of elements for (var i = 0;i<n;i++) s.add(str[i]); // Print content of the set for (const v of s) { document.write(v); } } // Driver code var str = \"geeksforgeeks\"; var n = str.length; removeDuplicate(str, n); // This code is contributed by umadevi9616</script>", "e": 3186, "s": 2537, "text": null }, { "code": null, "e": 3332, "s": 3186, "text": "Given a string S, the task is to remove all the duplicates in the given string. Below are the different methods to remove duplicates in a string." }, { "code": null, "e": 3351, "s": 3332, "text": "METHOD 1 (Simple) " }, { "code": null, "e": 3355, "s": 3351, "text": "C++" }, { "code": null, "e": 3360, "s": 3355, "text": "Java" }, { "code": null, "e": 3368, "s": 3360, "text": "Python3" }, { "code": null, "e": 3371, "s": 3368, "text": "C#" }, { "code": null, "e": 3382, "s": 3371, "text": "Javascript" }, { "code": "// CPP program to remove duplicate character// from character array and print in sorted// order#include <bits/stdc++.h>using namespace std; char *removeDuplicate(char str[], int n){ // Used as index in the modified string int index = 0; // Traverse through all characters for (int i=0; i<n; i++) { // Check if str[i] is present before it int j; for (j=0; j<i; j++) if (str[i] == str[j]) break; // If not present, then add it to // result. if (j == i) str[index++] = str[i]; } return str;} // Driver codeint main(){ char str[]= \"geeksforgeeks\"; int n = sizeof(str) / sizeof(str[0]); cout << removeDuplicate(str, n); return 0;}", "e": 4102, "s": 3382, "text": null }, { "code": "// Java program to remove duplicate character// from character array and print in sorted// orderimport java.util.*; class GFG{ static String removeDuplicate(char str[], int n) { // Used as index in the modified string int index = 0; // Traverse through all characters for (int i = 0; i < n; i++) { // Check if str[i] is present before it int j; for (j = 0; j < i; j++) { if (str[i] == str[j]) { break; } } // If not present, then add it to // result. if (j == i) { str[index++] = str[i]; } } return String.valueOf(Arrays.copyOf(str, index)); } // Driver code public static void main(String[] args) { char str[] = \"geeksforgeeks\".toCharArray(); int n = str.length; System.out.println(removeDuplicate(str, n)); }} // This code is contributed by Rajput-Ji", "e": 5139, "s": 4102, "text": null }, { "code": "string=\"geeksforgeeks\"p=\"\"for char in string: if char not in p: p=p+charprint(p)k=list(\"geeksforgeeks\")", "e": 5253, "s": 5139, "text": null }, { "code": "// C# program to remove duplicate character// from character array and print in sorted// orderusing System;using System.Collections.Generic;class GFG{static String removeDuplicate(char []str, int n){ // Used as index in the modified string int index = 0; // Traverse through all characters for (int i = 0; i < n; i++) { // Check if str[i] is present before it int j; for (j = 0; j < i; j++) { if (str[i] == str[j]) { break; } } // If not present, then add it to // result. if (j == i) { str[index++] = str[i]; } } char [] ans = new char[index]; Array.Copy(str, ans, index); return String.Join(\"\", ans);} // Driver codepublic static void Main(String[] args){ char []str = \"geeksforgeeks\".ToCharArray(); int n = str.Length; Console.WriteLine(removeDuplicate(str, n));}} // This code is contributed by PrinciRaj1992", "e": 6234, "s": 5253, "text": null }, { "code": "<script> // JavaScript program to remove duplicate character// from character array and print in sorted// orderfunction removeDuplicate(str, n) { // Used as index in the modified string var index = 0; // Traverse through all characters for (var i = 0; i < n; i++) { // Check if str[i] is present before it var j; for (j = 0; j < i; j++) { if (str[i] == str[j]) { break; } } // If not present, then add it to // result. if (j == i) { str[index++] = str[i]; } } return str.join(\"\").slice(str, index); } // Driver code var str = \"geeksforgeeks\".split(\"\"); var n = str.length; document.write(removeDuplicate(str, n)); // This code is contributed by shivanisinghss2110 </script>", "e": 7193, "s": 6234, "text": null }, { "code": null, "e": 7203, "s": 7193, "text": "Output: " }, { "code": null, "e": 7211, "s": 7203, "text": "geksfor" }, { "code": null, "e": 7307, "s": 7211, "text": "Time Complexity: O(n * n) Auxiliary Space: O(1) Keeps order of elements the same as the input. " }, { "code": null, "e": 7377, "s": 7307, "text": "METHOD 2 (using set)Use set to store only one instance of any value. " }, { "code": null, "e": 7381, "s": 7377, "text": "C++" }, { "code": null, "e": 7386, "s": 7381, "text": "Java" }, { "code": null, "e": 7394, "s": 7386, "text": "Python3" }, { "code": null, "e": 7397, "s": 7394, "text": "C#" }, { "code": null, "e": 7408, "s": 7397, "text": "Javascript" }, { "code": "// CPP program to remove duplicate character// from character array and print in sorted// order#include <bits/stdc++.h>using namespace std; char *removeDuplicate(char str[], int n){ // create a set using string characters // excluding '\\0' unordered_set<char>s (str, str+n-1); // print content of the set int i = 0; for (auto x : s) str[i++] = x; str[i] = '\\0'; return str;} // Driver codeint main(){ char str[]= \"geeksforgeeks\"; int n = sizeof(str) / sizeof(str[0]); cout << removeDuplicate(str, n); return 0;}", "e": 7960, "s": 7408, "text": null }, { "code": "// Java program to remove duplicate character// from character array and print in sorted// orderimport java.util.*; class GFG { static void removeDuplicate(char str[], int n) { // Create a set using String characters // excluding '\\0' HashSet<Character> s = new LinkedHashSet<>(n - 1); // HashSet doesn't allow repetition of elements for (char x : str) s.add(x); // Print content of the set for (char x : s) System.out.print(x); } // Driver code public static void main(String[] args) { char str[] = \"geeksforgeeks\".toCharArray(); int n = str.length; removeDuplicate(str, n); }} // This code is contributed by todaysgaurav", "e": 8697, "s": 7960, "text": null }, { "code": "# Python program to remove duplicate character# from character array and print in sorted# orderdef removeDuplicate(str, n): s = set() # Create a set using String characters for i in str: s.add(i) # Print content of the set st = \"\" for i in s: st = st+i return st # Driver codestr = \"geeksforgeeks\"n = len(str)print(removeDuplicate(list(str), n)) # This code is contributed by rajsanghavi9.", "e": 9129, "s": 8697, "text": null }, { "code": "// C# program to remove duplicate character// from character array and print in sorted// orderusing System;using System.Collections.Generic; public class GFG{ static char []removeDuplicate(char []str, int n){ // Create a set using String characters // excluding '\\0' HashSet<char>s = new HashSet<char>(n - 1); foreach(char x in str) s.Add(x); char[] st = new char[s.Count]; // Print content of the set int i = 0; foreach(char x in s) st[i++] = x; return st;} // Driver codepublic static void Main(String[] args){ char []str= \"geeksforgeeks\".ToCharArray(); int n = str.Length; Console.Write(removeDuplicate(str, n));}} // This code contributed by gauravrajput1", "e": 9862, "s": 9129, "text": null }, { "code": "<script>// javascript program to remove duplicate character// from character array and print in sorted// order function removeDuplicate( str , n) { // Create a set using String characters // excluding '\\0' var s = new Set(); // HashSet doesn't allow repetition of elements for (var i = 0;i<n;i++) s.add(str[i]); // Print content of the set for (const v of s) { document.write(v); } } // Driver code var str = \"geeksforgeeks\"; var n = str.length; removeDuplicate(str, n); // This code is contributed by umadevi9616</script>", "e": 10511, "s": 9862, "text": null }, { "code": null, "e": 10521, "s": 10511, "text": "Output: " }, { "code": null, "e": 10531, "s": 10521, "text": " efgkors" }, { "code": null, "e": 10575, "s": 10531, "text": "Time Complexity: O(n) Auxiliary Space: O(n)" }, { "code": null, "e": 10630, "s": 10575, "text": "Thanks to Anivesh Tiwari for suggesting this approach." }, { "code": null, "e": 10724, "s": 10630, "text": "It does not keep the order of elements the same as the input but prints them in sorted order." }, { "code": null, "e": 10759, "s": 10724, "text": "METHOD 3 (Use Sorting) Algorithm: " }, { "code": null, "e": 10954, "s": 10759, "text": " 1) Sort the elements.\n 2) Now in a loop, remove duplicates by comparing the \n current character with previous character.\n 3) Remove extra characters at the end of the resultant string." }, { "code": null, "e": 10965, "s": 10954, "text": "Example: " }, { "code": null, "e": 11113, "s": 10965, "text": "Input string: geeksforgeeks\n1) Sort the characters\n eeeefggkkorss\n2) Remove duplicates\n efgkorskkorss\n3) Remove extra characters\n efgkors" }, { "code": null, "e": 11425, "s": 11113, "text": "Note that, this method doesn’t keep the original order of the input string. For example, if we are to remove duplicates for geeksforgeeks and keep the order of characters the same, then the output should be geksfor, but the above function returns efgkos. We can modify this method by storing the original order." }, { "code": null, "e": 11443, "s": 11425, "text": "Implementation: " }, { "code": null, "e": 11447, "s": 11443, "text": "C++" }, { "code": null, "e": 11449, "s": 11447, "text": "C" }, { "code": null, "e": 11454, "s": 11449, "text": "Java" }, { "code": null, "e": 11462, "s": 11454, "text": "Python3" }, { "code": null, "e": 11465, "s": 11462, "text": "C#" }, { "code": null, "e": 11476, "s": 11465, "text": "Javascript" }, { "code": "// C++ program to remove duplicates, the order of// characters is not maintained in this program#include<bits/stdc++.h>using namespace std; /* Function to remove duplicates in a sorted array */char *removeDupsSorted(char *str){ int res_ind = 1, ip_ind = 1; /* In place removal of duplicate characters*/ while (*(str + ip_ind)) { if (*(str + ip_ind) != *(str + ip_ind - 1)) { *(str + res_ind) = *(str + ip_ind); res_ind++; } ip_ind++; } /* After above step string is efgkorskkorss. Removing extra kkorss after string*/ *(str + res_ind) = '\\0'; return str;} /* Function removes duplicate characters from the string This function work in-place and fills null characters in the extra space left */char *removeDups(char *str){ int n = strlen(str); // Sort the character array sort(str, str+n); // Remove duplicates from sorted return removeDupsSorted(str);} /* Driver program to test removeDups */int main(){ char str[] = \"geeksforgeeks\"; cout << removeDups(str); return 0;}", "e": 12548, "s": 11476, "text": null }, { "code": "// C program to remove duplicates, the order of// characters is not maintained in this program# include <stdio.h># include <stdlib.h># include <string.h>/* Function to remove duplicates in a sorted array */char *removeDupsSorted(char *str); /* Utility function to sort array A[] */void quickSort(char A[], int si, int ei); /* Function removes duplicate characters from the string This function work in-place and fills null characters in the extra space left */char *removeDups(char *str){ int len = strlen(str); quickSort(str, 0, len-1); return removeDupsSorted(str);} /* Function to remove duplicates in a sorted array */char *removeDupsSorted(char *str){ int res_ind = 1, ip_ind = 1; /* In place removal of duplicate characters*/ while (*(str + ip_ind)) { if (*(str + ip_ind) != *(str + ip_ind - 1)) { *(str + res_ind) = *(str + ip_ind); res_ind++; } ip_ind++; } /* After above step string is efgkorskkorss. Removing extra kkorss after string*/ *(str + res_ind) = '\\0'; return str;} /* Driver program to test removeDups */int main(){ char str[] = \"geeksforgeeks\"; printf(\"%s\", removeDups(str)); getchar(); return 0;} /* FOLLOWING FUNCTIONS ARE ONLY FOR SORTING PURPOSE */void exchange(char *a, char *b){ char temp; temp = *a; *a = *b; *b = temp;} int partition(char A[], int si, int ei){ char x = A[ei]; int i = (si - 1); int j; for (j = si; j <= ei - 1; j++) { if (A[j] <= x) { i++; exchange(&A[i], &A[j]); } } exchange (&A[i + 1], &A[ei]); return (i + 1);} /* Implementation of Quick SortA[] --> Array to be sortedsi --> Starting indexei --> Ending index*/void quickSort(char A[], int si, int ei){ int pi; /* Partitioning index */ if (si < ei) { pi = partition(A, si, ei); quickSort(A, si, pi - 1); quickSort(A, pi + 1, ei); }}", "e": 14394, "s": 12548, "text": null }, { "code": "// Java program to remove duplicates, the order of// characters is not maintained in this program import java.util.Arrays; public class GFG{ /* Method to remove duplicates in a sorted array */ static String removeDupsSorted(String str) { int res_ind = 1, ip_ind = 1; // Character array for removal of duplicate characters char arr[] = str.toCharArray(); /* In place removal of duplicate characters*/ while (ip_ind != arr.length) { if(arr[ip_ind] != arr[ip_ind-1]) { arr[res_ind] = arr[ip_ind]; res_ind++; } ip_ind++; } str = new String(arr); return str.substring(0,res_ind); } /* Method removes duplicate characters from the string This function work in-place and fills null characters in the extra space left */ static String removeDups(String str) { // Sort the character array char temp[] = str.toCharArray(); Arrays.sort(temp); str = new String(temp); // Remove duplicates from sorted return removeDupsSorted(str); } // Driver Method public static void main(String[] args) { String str = \"geeksforgeeks\"; System.out.println(removeDups(str)); }}", "e": 15732, "s": 14394, "text": null }, { "code": "# Python3 program to remove duplicates, the order of# characters is not maintained in this program # Utility function to convert string to listdef toMutable(string): temp = [] for x in string: temp.append(x) return temp # Utility function to convert string to listdef toString(List): return ''.join(List) # Function to remove duplicates in a sorted arraydef removeDupsSorted(List): res_ind = 1 ip_ind = 1 # In place removal of duplicate characters while ip_ind != len(List): if List[ip_ind] != List[ip_ind-1]: List[res_ind] = List[ip_ind] res_ind += 1 ip_ind+=1 # After above step string is efgkorskkorss. # Removing extra kkorss after string string = toString(List[0:res_ind]) return string # Function removes duplicate characters from the string# This function work in-place and fills null characters# in the extra space leftdef removeDups(string): # Convert string to list List = toMutable(string) # Sort the character list List.sort() # Remove duplicates from sorted return removeDupsSorted(List) # Driver program to test the above functionsstring = \"geeksforgeeks\"print(removeDups(string)) # This code is contributed by Bhavya Jain", "e": 16971, "s": 15732, "text": null }, { "code": "// C# program to remove duplicates, the order of// characters is not maintained in this programusing System; class GFG{ /* Method to remove duplicates in a sorted array */ static String removeDupsSorted(String str) { int res_ind = 1, ip_ind = 1; // Character array for removal of duplicate characters char []arr = str.ToCharArray(); /* In place removal of duplicate characters*/ while (ip_ind != arr.Length) { if(arr[ip_ind] != arr[ip_ind-1]) { arr[res_ind] = arr[ip_ind]; res_ind++; } ip_ind++; } str = new String(arr); return str.Substring(0,res_ind); } /* Method removes duplicate characters from the string This function work in-place and fills null characters in the extra space left */ static String removeDups(String str) { // Sort the character array char []temp = str.ToCharArray(); Array.Sort(temp); str = String.Join(\"\",temp); // Remove duplicates from sorted return removeDupsSorted(str); } // Driver Method public static void Main(String[] args) { String str = \"geeksforgeeks\"; Console.WriteLine(removeDups(str)); }} // This code is contributed by 29AjayKumar", "e": 18314, "s": 16971, "text": null }, { "code": "<script> function removeDuplicate(string){ return string.split('') .filter(function(item, pos, self) { return self.indexOf(item) == pos; } ).join('');} var str = \"geeksforgeeks\";document.write( \" \"+removeDuplicate(str)); //This code is contributed by SoumikMondal</script>", "e": 18605, "s": 18314, "text": null }, { "code": null, "e": 18615, "s": 18605, "text": "Output: " }, { "code": null, "e": 18623, "s": 18615, "text": "efgkors" }, { "code": null, "e": 18712, "s": 18623, "text": "Time Complexity: O(n log n) If we use some nlogn sorting algorithm instead of quicksort." }, { "code": null, "e": 18734, "s": 18712, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 18759, "s": 18734, "text": "METHOD 4 (Use Hashing ) " }, { "code": null, "e": 18772, "s": 18759, "text": "Algorithm: " }, { "code": null, "e": 19889, "s": 18772, "text": "1: Initialize:\n str = \"test string\" /* input string */\n ip_ind = 0 /* index to keep track of location of next\n character in input string */\n res_ind = 0 /* index to keep track of location of\n next character in the resultant string */\n bin_hash[0..255] = {0,0, ....} /* Binary hash to see if character is \n already processed or not */\n2: Do following for each character *(str + ip_ind) in input string:\n (a) if bin_hash is not set for *(str + ip_ind) then\n // if program sees the character *(str + ip_ind) first time\n (i) Set bin_hash for *(str + ip_ind)\n (ii) Move *(str + ip_ind) to the resultant string.\n This is done in-place.\n (iii) res_ind++\n (b) ip_ind++\n /* String obtained after this step is \"the stringing\" */\n3: Remove extra characters at the end of the resultant string.\n /* String obtained after this step is \"te string\" */" }, { "code": null, "e": 19907, "s": 19889, "text": "Implementation: " }, { "code": null, "e": 19911, "s": 19907, "text": "C++" }, { "code": null, "e": 19913, "s": 19911, "text": "C" }, { "code": null, "e": 19918, "s": 19913, "text": "Java" }, { "code": null, "e": 19926, "s": 19918, "text": "Python3" }, { "code": null, "e": 19929, "s": 19926, "text": "C#" }, { "code": null, "e": 19940, "s": 19929, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std;# define NO_OF_CHARS 256# define bool int /* Function removes duplicate characters from the stringThis function work in-place and fills null charactersin the extra space left */char *removeDups(char str[]){ bool bin_hash[NO_OF_CHARS] = {0}; int ip_ind = 0, res_ind = 0; char temp; /* In place removal of duplicate characters*/ while (*(str + ip_ind)) { temp = *(str + ip_ind); if (bin_hash[temp] == 0) { bin_hash[temp] = 1; *(str + res_ind) = *(str + ip_ind); res_ind++; } ip_ind++; } /* After above step string is stringiittg. Removing extra iittg after string*/ *(str+res_ind) = '\\0'; return str;} /* Driver code */int main(){ char str[] = \"geeksforgeeks\"; cout << removeDups(str); return 0;} // This code is contributed by rathbhupendra", "e": 20853, "s": 19940, "text": null }, { "code": "# include <stdio.h># include <stdlib.h># define NO_OF_CHARS 256# define bool int /* Function removes duplicate characters from the string This function work in-place and fills null characters in the extra space left */char *removeDups(char *str){ bool bin_hash[NO_OF_CHARS] = {0}; int ip_ind = 0, res_ind = 0; char temp; /* In place removal of duplicate characters*/ while (*(str + ip_ind)) { temp = *(str + ip_ind); if (bin_hash[temp] == 0) { bin_hash[temp] = 1; *(str + res_ind) = *(str + ip_ind); res_ind++; } ip_ind++; } /* After above step string is stringiittg. Removing extra iittg after string*/ *(str+res_ind) = '\\0'; return str;} /* Driver program to test removeDups */int main(){ char str[] = \"geeksforgeeks\"; printf(\"%s\", removeDups(str)); getchar(); return 0;}", "e": 21706, "s": 20853, "text": null }, { "code": "// Java program to remove duplicatesimport java.util.*; class RemoveDuplicates{ /* Function removes duplicate characters from the string This function work in-place */ void removeDuplicates(String str) { LinkedHashSet<Character> lhs = new LinkedHashSet<>(); for(int i=0;i<str.length();i++) lhs.add(str.charAt(i)); // print string after deleting duplicate elements for(Character ch : lhs) System.out.print(ch); } /* Driver program to test removeDuplicates */ public static void main(String args[]) { String str = \"geeksforgeeks\"; RemoveDuplicates r = new RemoveDuplicates(); r.removeDuplicates(str); }} // This code has been contributed by Amit Khandelwal (Amit Khandelwal 1)", "e": 22493, "s": 21706, "text": null }, { "code": "# Python3 program to remove duplicate characters from an# input stringNO_OF_CHARS = 256 # Since strings in Python are immutable and cannot be changed# This utility function will convert the string to listdef toMutable(string): List = [] for i in string: List.append(i) return List # Utility function that changes list to stringdef toString(List): return ''.join(List) # Function removes duplicate characters from the string# This function work in-place and fills null characters# in the extra space leftdef removeDups(string): bin_hash = [0] * NO_OF_CHARS ip_ind = 0 res_ind = 0 temp = '' mutableString = toMutable(string) # In place removal of duplicate characters while ip_ind != len(mutableString): temp = mutableString[ip_ind] if bin_hash[ord(temp)] == 0: bin_hash[ord(temp)] = 1 mutableString[res_ind] = mutableString[ip_ind] res_ind+=1 ip_ind+=1 # After above step string is stringiittg. # Removing extra iittg after string return toString(mutableString[0:res_ind]) # Driver program to test the above functionsstring = \"geeksforgeeks\"print(removeDups(string)) # A shorter version for this program is as follows# import collections# print ''.join(collections.OrderedDict.fromkeys(string)) # This code is contributed by Bhavya Jain", "e": 23836, "s": 22493, "text": null }, { "code": "// C# program to remove duplicatesusing System;using System.Collections.Generic; class GFG{ /* Function removes duplicate characters from the string. This function work in-place */ void removeDuplicates(String str) { HashSet<char> lhs = new HashSet<char>(); for(int i = 0; i < str.Length; i++) lhs.Add(str[i]); // print string after deleting // duplicate elements foreach(char ch in lhs) Console.Write(ch); } // Driver Code public static void Main(String []args) { String str = \"geeksforgeeks\"; GFG r = new GFG(); r.removeDuplicates(str); }} // This code is contributed by Rajput-Ji", "e": 24538, "s": 23836, "text": null }, { "code": "<script>// javascript program to remove duplicates /* * Function removes duplicate characters from the string This function work * in-place */ function removeDuplicates( str) { var lhs = new Set(); for (var i = 0; i < str.length; i++) lhs.add(str[i]); // print string after deleting duplicate elements for (var ch of lhs) document.write(ch); } /* Driver program to test removeDuplicates */ var str = \"geeksforgeeks\"; removeDuplicates(str); // This code is contributed by umadevi9616</script>", "e": 25125, "s": 24538, "text": null }, { "code": null, "e": 25135, "s": 25125, "text": "Output: " }, { "code": null, "e": 25143, "s": 25135, "text": "geksfor" }, { "code": null, "e": 25165, "s": 25143, "text": "Time Complexity: O(n)" }, { "code": null, "e": 25187, "s": 25165, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 25207, "s": 25187, "text": "Important Points: " }, { "code": null, "e": 25288, "s": 25207, "text": "Method 2 doesn’t maintain the characters as original strings, but method 4 does." }, { "code": null, "e": 25412, "s": 25288, "text": "It is assumed that the number of possible characters in the input string is 256. NO_OF_CHARS should be changed accordingly." }, { "code": null, "e": 25594, "s": 25412, "text": "calloc() is used instead of malloc() for memory allocations of a counting array (count) to initialize allocated memory to ‘\\0’. the malloc() followed by memset() could also be used." }, { "code": null, "e": 25850, "s": 25594, "text": "The above algorithm also works for integer array inputs if the range of the integers in the array is given. An example problem is to find the maximum occurring number in an input array given that the input array contains integers only between 1000 to 1100" }, { "code": null, "e": 25925, "s": 25850, "text": "Method 5 (Using IndexOf() method) : Prerequisite : Java IndexOf() method " }, { "code": null, "e": 25929, "s": 25925, "text": "C++" }, { "code": null, "e": 25934, "s": 25929, "text": "Java" }, { "code": null, "e": 25942, "s": 25934, "text": "Python3" }, { "code": null, "e": 25945, "s": 25942, "text": "C#" }, { "code": null, "e": 25956, "s": 25945, "text": "Javascript" }, { "code": "// C++ program to create a unique string#include <bits/stdc++.h>using namespace std; // Function to make the string uniquestring unique(string s){ string str; int len = s.length(); // loop to traverse the string and // check for repeating chars using // IndexOf() method in Java for(int i = 0; i < len; i++) { // character at i'th index of s char c = s[i]; // If c is present in str, it returns // the index of c, else it returns npos auto found = str.find(c); if (found == std::string::npos) { // Adding c to str if npos is returned str += c; } } return str;} // Driver codeint main(){ // Input string with repeating chars string s = \"geeksforgeeks\"; cout << unique(s) << endl;} // This code is contributed by nirajgusain5", "e": 26824, "s": 25956, "text": null }, { "code": "// Java program to create a unique stringimport java.util.*; class IndexOf { // Function to make the string unique public static String unique(String s) { String str = new String(); int len = s.length(); // loop to traverse the string and // check for repeating chars using // IndexOf() method in Java for (int i = 0; i < len; i++) { // character at i'th index of s char c = s.charAt(i); // if c is present in str, it returns // the index of c, else it returns -1 if (str.indexOf(c) < 0) { // adding c to str if -1 is returned str += c; } } return str; } // Driver code public static void main(String[] args) { // Input string with repeating chars String s = \"geeksforgeeks\"; System.out.println(unique(s)); }}", "e": 27795, "s": 26824, "text": null }, { "code": "# Python 3 program to create a unique string # Function to make the string unique def unique(s): st = \"\" length = len(s) # loop to traverse the string and # check for repeating chars using # IndexOf() method in Java for i in range(length): # character at i'th index of s c = s[i] # if c is present in str, it returns # the index of c, else it returns - 1 # print(st.index(c)) if c not in st: # adding c to str if -1 is returned st += c return st # Driver codeif __name__ == \"__main__\": # Input string with repeating chars s = \"geeksforgeeks\" print(unique(s)) # This code is contributed by ukasp.", "e": 28498, "s": 27795, "text": null }, { "code": "// C# program to create a unique stringusing System; public class IndexOf{ // Function to make the string unique public static String unique(String s) { String str = \"\"; int len = s.Length; // loop to traverse the string and // check for repeating chars using // IndexOf() method in Java for (int i = 0; i < len; i++) { // character at i'th index of s char c = s[i]; // if c is present in str, it returns // the index of c, else it returns -1 if (str.IndexOf(c) < 0) { // adding c to str if -1 is returned str += c; } } return str; } // Driver code public static void Main(String[] args) { // Input string with repeating chars String s = \"geeksforgeeks\"; Console.WriteLine(unique(s)); }} // This code is contributed by Princi Singh", "e": 29495, "s": 28498, "text": null }, { "code": "<script> // JavaScript program to create a unique string // Function to make the string unique function unique(s) { let str = \"\"; let len = s.length; // loop to traverse the string and // check for repeating chars using // IndexOf() method in Java for (let i = 0; i < len; i++) { // character at i'th index of s let c = s[i]; // if c is present in str, it returns // the index of c, else it returns -1 if (str.indexOf(c) < 0) { // adding c to str if -1 is returned str += c; } } return str; } // Input string with repeating chars let s = \"geeksforgeeks\"; document.write(unique(s)); </script>", "e": 30333, "s": 29495, "text": null }, { "code": null, "e": 30343, "s": 30333, "text": "Output: " }, { "code": null, "e": 30351, "s": 30343, "text": "geksfor" }, { "code": null, "e": 30399, "s": 30351, "text": "Thanks debjitdbb for suggesting this approach. " }, { "code": null, "e": 30489, "s": 30399, "text": "Method 6 (Using unordered_map STL method) : Prerequisite : unordered_map STL C++ method " }, { "code": null, "e": 30493, "s": 30489, "text": "C++" }, { "code": null, "e": 30498, "s": 30493, "text": "Java" }, { "code": null, "e": 30506, "s": 30498, "text": "Python3" }, { "code": null, "e": 30509, "s": 30506, "text": "C#" }, { "code": null, "e": 30520, "s": 30509, "text": "Javascript" }, { "code": "// C++ program to create a unique string using unordered_map /* access time in unordered_map on is O(1) generally if no collisions occurand therefore it helps us check if an element exists in a string in O(1)time complexity with constant space. */ #include <bits/stdc++.h>using namespace std;char* removeDuplicates(char *s,int n){ unordered_map<char,int> exists; int index = 0; for(int i=0;i<n;i++){ if(exists[s[i]]==0) { s[index++] = s[i]; exists[s[i]]++; } } return s;} //driver codeint main(){ char s[] = \"geeksforgeeks\"; int n = sizeof(s)/sizeof(s[0]); cout<<removeDuplicates(s,n)<<endl; return 0;}", "e": 31151, "s": 30520, "text": null }, { "code": "// Java program to create a unique String using unordered_map /* access time in unordered_map on is O(1) generally if no collisions occurand therefore it helps us check if an element exists in a String in O(1)time complexity with constant space. */import java.util.*; class GFG{static char[] removeDuplicates(char []s,int n){ Map<Character,Integer> exists = new HashMap<>(); String st = \"\"; for(int i = 0; i < n; i++){ if(!exists.containsKey(s[i])) { st += s[i]; exists.put(s[i], 1); } } return st.toCharArray();} // driver codepublic static void main(String[] args){ char s[] = \"geeksforgeeks\".toCharArray(); int n = s.length; System.out.print(removeDuplicates(s,n));}} // This code is contributed by gauravrajput1", "e": 31895, "s": 31151, "text": null }, { "code": "# Python program to create a unique string using unordered_map # access time in unordered_map on is O(1) generally if no collisions occur# and therefore it helps us check if an element exists in a string in O(1)# time complexity with constant space.def removeDuplicates(s, n): exists = {} index = 0 ans = \"\" for i in range(0, n): if s[i] not in exists or exists[s[i]] == 0: s[index] = s[i] print(s[index], end='') index += 1 exists[s[i]] = 1 # driver codes = \"geeksforgeeks\"s1 = list(s)n = len(s1)removeDuplicates(s1, n) # This code is contributed by Palak Gupta", "e": 32522, "s": 31895, "text": null }, { "code": "// C# program to create a unique String using unordered_map /* access time in unordered_map on is O(1) generally if no collisions occurand therefore it helps us check if an element exists in a String in O(1)time complexity with constant space. */using System;using System.Collections.Generic; public class GFG{static char[] removeDuplicates(char []s,int n){ Dictionary<char,int> exists = new Dictionary<char, int>(); String st = \"\"; for(int i = 0; i < n; i++){ if(!exists.ContainsKey(s[i])) { st += s[i]; exists.Add(s[i], 1); } } return st.ToCharArray();} // driver codepublic static void Main(String[] args){ char []s = \"geeksforgeeks\".ToCharArray(); int n = s.Length; Console.Write(removeDuplicates(s,n));}} // This code is contributed by umadevi9616", "e": 33303, "s": 32522, "text": null }, { "code": "<script>// javascript program to create a unique String using unordered_map /* access time in unordered_map on is O(1) generally if no collisions occurand therefore it helps us check if an element exists in a String in O(1)time complexity with constant space. */ function removeDuplicates( s , n) { var exists = new Map(); var st = \"\"; for (var i = 0; i < n; i++) { if (!exists.has(s[i])) { st += s[i]; exists.set(s[i], 1); } } return st; } // driver code var s = \"geeksforgeeks\"; var n = s.length; document.write(removeDuplicates(s, n));// This code contributed by umadevi9616</script>", "e": 34015, "s": 33303, "text": null }, { "code": null, "e": 34025, "s": 34015, "text": "Output: " }, { "code": null, "e": 34033, "s": 34025, "text": "geksfor" }, { "code": null, "e": 34134, "s": 34033, "text": "Time Complexity : O(n) Auxiliary Space : O(n)Thanks, Allen James Vinoy for suggesting this approach." }, { "code": null, "e": 34153, "s": 34134, "text": "METHOD 7 (Simple) " }, { "code": null, "e": 34157, "s": 34153, "text": "C++" }, { "code": null, "e": 34162, "s": 34157, "text": "Java" }, { "code": null, "e": 34170, "s": 34162, "text": "Python3" }, { "code": null, "e": 34173, "s": 34170, "text": "C#" }, { "code": null, "e": 34184, "s": 34173, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; int main(){ string s = \"abcdabd\"; string temp = \"\"; temp += s.at(0); for (int i = 1; i < s.length(); i++) { if (!(temp.find(s.at(i)) < temp.length())) temp = temp + s.at(i); } cout << temp; return 0;}//This code is contributed by KaaL-EL.", "e": 34503, "s": 34184, "text": null }, { "code": "import java.io.*; class GFG { public static void main(String[] args) { String s = \"abcdabd\"; String temp = \"\" + s.charAt(0); for (int i = 1; i < s.length(); i++) { if (!temp.contains( String.valueOf(s.charAt(i)))) temp = temp + s.charAt(i); } System.out.println(temp); }}", "e": 34865, "s": 34503, "text": null }, { "code": "# Python code for the above Approachs = \"abcdabd\"temp = \"\" + s[0] for i in range(1,len(s)): if (s[i] not in temp): temp = temp + s[i] # Printing the Resultprint(temp) # This code is contributed by kothavvsaakash.", "e": 35082, "s": 34865, "text": null }, { "code": "using System; public class GFG{ static public void Main (){ string s = \"abcdabd\"; string temp = \"\"; temp += s[0]; for (int i = 1; i < s.Length; i++) { if (temp.IndexOf(s[i]) == -1) temp = temp + s[i]; } System.Console.WriteLine(temp); }} // This code is contributed by akashish__", "e": 35396, "s": 35082, "text": null }, { "code": "<script> // JavaScript code for the above Approachlet s = \"abcdabd\"let temp = \"\" + s[0] for(let i=1;i<s.length;i++){ if (temp.indexOf(s[i]) == -1) temp = temp + s[i]} // Printing the Resultdocument.write(temp,\"</br>\") // This code is contributed by shinjanpatra </script>", "e": 35678, "s": 35396, "text": null }, { "code": null, "e": 35683, "s": 35678, "text": "abcd" }, { "code": null, "e": 35707, "s": 35683, "text": "Time Complexity : O(n) " }, { "code": null, "e": 35730, "s": 35707, "text": "Auxiliary Space: O(n) " }, { "code": null, "e": 35744, "s": 35730, "text": "rathbhupendra" }, { "code": null, "e": 35756, "s": 35744, "text": "29AjayKumar" }, { "code": null, "e": 35769, "s": 35756, "text": "princi singh" }, { "code": null, "e": 35794, "s": 35769, "text": "ALLENJAMESVINOY17BCE0748" }, { "code": null, "e": 35804, "s": 35794, "text": "Rajput-Ji" }, { "code": null, "e": 35818, "s": 35804, "text": "princiraj1992" }, { "code": null, "e": 35833, "s": 35818, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 35845, "s": 35833, "text": "amirthanand" }, { "code": null, "e": 35851, "s": 35845, "text": "ukasp" }, { "code": null, "e": 35864, "s": 35851, "text": "SoumikMondal" }, { "code": null, "e": 35877, "s": 35864, "text": "todaysgaurav" }, { "code": null, "e": 35894, "s": 35877, "text": "vaibhavrabadiya3" }, { "code": null, "e": 35907, "s": 35894, "text": "nirajgusain5" }, { "code": null, "e": 35926, "s": 35907, "text": "shivanisinghss2110" }, { "code": null, "e": 35936, "s": 35926, "text": "as5853535" }, { "code": null, "e": 35955, "s": 35936, "text": "surindertarika1234" }, { "code": null, "e": 35969, "s": 35955, "text": "GauravRajput1" }, { "code": null, "e": 35982, "s": 35969, "text": "rajsanghavi9" }, { "code": null, "e": 36000, "s": 35982, "text": "saunaknandi021000" }, { "code": null, "e": 36012, "s": 36000, "text": "umadevi9616" }, { "code": null, "e": 36027, "s": 36012, "text": "adnanirshad158" }, { "code": null, "e": 36043, "s": 36027, "text": "simranarora5sos" }, { "code": null, "e": 36059, "s": 36043, "text": "rishavmahato348" }, { "code": null, "e": 36074, "s": 36059, "text": "prachisoda1234" }, { "code": null, "e": 36087, "s": 36074, "text": "simmytarika5" }, { "code": null, "e": 36102, "s": 36087, "text": "raghavendra777" }, { "code": null, "e": 36116, "s": 36102, "text": "sumitgumber28" }, { "code": null, "e": 36133, "s": 36116, "text": "surinderdawra388" }, { "code": null, "e": 36149, "s": 36133, "text": "amartyaghoshgfg" }, { "code": null, "e": 36164, "s": 36149, "text": "sagar0719kumar" }, { "code": null, "e": 36178, "s": 36164, "text": "ninja_hattori" }, { "code": null, "e": 36195, "s": 36178, "text": "harendrakumar123" }, { "code": null, "e": 36210, "s": 36195, "text": "rajivkumarinfo" }, { "code": null, "e": 36225, "s": 36210, "text": "kothavvsaakash" }, { "code": null, "e": 36238, "s": 36225, "text": "shinjanpatra" }, { "code": null, "e": 36253, "s": 36238, "text": "shivamanandrj9" }, { "code": null, "e": 36260, "s": 36253, "text": "kaalel" }, { "code": null, "e": 36271, "s": 36260, "text": "akashish__" }, { "code": null, "e": 36290, "s": 36271, "text": "frequency-counting" }, { "code": null, "e": 36298, "s": 36290, "text": "Strings" }, { "code": null, "e": 36306, "s": 36298, "text": "Strings" } ]
Elasticsearch | Differences between Queries and Filters
09 Aug, 2021 Elasticsearch is a full-text search and analytics engine based on Apache Lucene. Elasticsearch makes it easier to perform data aggregation operations on data from multiple sources and to perform unstructured queries such as fuzzy searches on the stored data. Elasticsearch document would look like: { "first_name": " Kumar", "last_name":"Gaurav", "email":"kumar@gmail.com", "dob":"04-11-1995", "country":"India" } Before the version of 2, the Elasticsearch perform Queries and Filters separately, after that they combined both and produce more effective search results. So first we discuss both the topics and after that, we will compare them to each other. Queries: A query calculates how relevant each document is to the query, and assigns it a relevance score, which is later used to sort matching documents by relevance. This concept of relevance is well suited to full-text search, where there is seldom a completely “correct” answer. The query also asks the question like below: How well does this document match? What is the created adate of Elasticsearch? What is the distance of lat_lon field from the specified point? A typical use for a query is to find documents best matching the words full-text search, containing the word run, but maybe also matching runs, running, jog, or sprint and containing the words quick, brown, etc. Filters: The output from most filter clauses is a simple list of the documents that match the filter. It is quick to calculate and easy to cache in memory, using only 1 bit per document. These cached filters can be reused efficiently for subsequent requests. A filter asks a yes or no question of every document and is used for fields that contain exact values: Is the created date in the range 2013 – 2014? Does the status field contain the term published? Is the lat_lon field within 10km of a specified point? Note: Query clauses and filter clauses are similar in nature but have slightly different purposes. Important points: Queries are not only find matching documents but also calculate how relevant each document is, which typically makes queries heavier than filters. Also, query results are not cachable. Thanks to the inverted index, a simple query that matches just a few documents may perform as well or better than a cached filter that spans millions of documents. In general, however, a cached filter will outperform a query and will do so consistently. The goal of filters is to reduce the number of documents that have to be examined by the query Differences between Queries and Filters: Note: After version 2 Query and Filter are combined to perform better results, run a query then set a filter will help you to get the actual result that you want. abhishek0719kadiyan Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) Remove elements from a JavaScript Array How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? How to Open URL in New Tab using JavaScript ? File uploading in React.js
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Aug, 2021" }, { "code": null, "e": 288, "s": 28, "text": "Elasticsearch is a full-text search and analytics engine based on Apache Lucene. Elasticsearch makes it easier to perform data aggregation operations on data from multiple sources and to perform unstructured queries such as fuzzy searches on the stored data. " }, { "code": null, "e": 330, "s": 288, "text": "Elasticsearch document would look like: " }, { "code": null, "e": 455, "s": 330, "text": "{\n \"first_name\": \" Kumar\",\n \"last_name\":\"Gaurav\",\n \"email\":\"kumar@gmail.com\",\n \"dob\":\"04-11-1995\",\n \"country\":\"India\"\n}" }, { "code": null, "e": 700, "s": 455, "text": "Before the version of 2, the Elasticsearch perform Queries and Filters separately, after that they combined both and produce more effective search results. So first we discuss both the topics and after that, we will compare them to each other. " }, { "code": null, "e": 1028, "s": 700, "text": "Queries: A query calculates how relevant each document is to the query, and assigns it a relevance score, which is later used to sort matching documents by relevance. This concept of relevance is well suited to full-text search, where there is seldom a completely “correct” answer. The query also asks the question like below: " }, { "code": null, "e": 1065, "s": 1030, "text": "How well does this document match?" }, { "code": null, "e": 1109, "s": 1065, "text": "What is the created adate of Elasticsearch?" }, { "code": null, "e": 1173, "s": 1109, "text": "What is the distance of lat_lon field from the specified point?" }, { "code": null, "e": 1386, "s": 1173, "text": "A typical use for a query is to find documents best matching the words full-text search, containing the word run, but maybe also matching runs, running, jog, or sprint and containing the words quick, brown, etc. " }, { "code": null, "e": 1750, "s": 1386, "text": "Filters: The output from most filter clauses is a simple list of the documents that match the filter. It is quick to calculate and easy to cache in memory, using only 1 bit per document. These cached filters can be reused efficiently for subsequent requests. A filter asks a yes or no question of every document and is used for fields that contain exact values: " }, { "code": null, "e": 1796, "s": 1750, "text": "Is the created date in the range 2013 – 2014?" }, { "code": null, "e": 1846, "s": 1796, "text": "Does the status field contain the term published?" }, { "code": null, "e": 1901, "s": 1846, "text": "Is the lat_lon field within 10km of a specified point?" }, { "code": null, "e": 2001, "s": 1901, "text": "Note: Query clauses and filter clauses are similar in nature but have slightly different purposes. " }, { "code": null, "e": 2554, "s": 2001, "text": "Important points: Queries are not only find matching documents but also calculate how relevant each document is, which typically makes queries heavier than filters. Also, query results are not cachable. Thanks to the inverted index, a simple query that matches just a few documents may perform as well or better than a cached filter that spans millions of documents. In general, however, a cached filter will outperform a query and will do so consistently. The goal of filters is to reduce the number of documents that have to be examined by the query " }, { "code": null, "e": 2597, "s": 2554, "text": "Differences between Queries and Filters: " }, { "code": null, "e": 2761, "s": 2597, "text": "Note: After version 2 Query and Filter are combined to perform better results, run a query then set a filter will help you to get the actual result that you want. " }, { "code": null, "e": 2781, "s": 2761, "text": "abhishek0719kadiyan" }, { "code": null, "e": 2798, "s": 2781, "text": "Web Technologies" }, { "code": null, "e": 2825, "s": 2798, "text": "Web technologies Questions" }, { "code": null, "e": 2923, "s": 2825, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2984, "s": 2923, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3027, "s": 2984, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 3099, "s": 3027, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3139, "s": 3099, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3163, "s": 3139, "text": "REST API (Introduction)" }, { "code": null, "e": 3203, "s": 3163, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3263, "s": 3203, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 3324, "s": 3263, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 3370, "s": 3324, "text": "How to Open URL in New Tab using JavaScript ?" } ]
Logger exiting() method in Java with Examples
28 Mar, 2019 The exiting() method of a Logger class used to Log a method return. There are two types of exiting() method depending upon the parameters passed. exiting(String sourceClass, String sourceMethod): This method is used to Log a method return. we need to log what method returns and this is a convenience method that can be used to log returning from a method. This method logs with the message “RETURN”, log level FINER, and the given sourceMethod and sourceClass are also logged.Syntax:public void exiting(String sourceClass, String sourceMethod) Parameters: This method accepts two parameters:sourceClass is the name of the class that issued the logging request,sourceMethod is the name of the methodReturn value: This method returns nothing.Below program illustrate exiting(String sourceClass, String sourceMethod) method:Program 1:// Java program to demonstrate// exiting(String, String) method import java.io.IOException;import java.util.logging.FileHandler;import java.util.logging.Level;import java.util.logging.Logger;import java.util.logging.SimpleFormatter; public class GFG { public static void main(String[] args) throws SecurityException, IOException { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a file handler object FileHandler handler = new FileHandler("logs.txt"); handler.setFormatter(new SimpleFormatter()); // Add file handler as // handler of logs logger.addHandler(handler); // set Logger level() logger.setLevel(Level.FINER); // call exiting methods with class // name = GFG and method name = main logger.exiting(GFG.class.getName(), GFG.class.getMethods()[0].getName()); }}The output printed on log.txg file is shown below.Output:exiting(String sourceClass, String sourceMethod, Object result): This method is used to Log a method entry, with result object. This is a very helpful method to log entry related to a method of a class with its return value. This method logs with the message “RETURN {0}”, log level FINER, and the gives sourceMethod, sourceClass, and result object is logged.Syntax:public void exiting(String sourceClass, String sourceMethod, Object result) Parameters: This method accepts three parameters:sourceClass is the name of the class that issued the logging request,sourceMethod is the name of the method andObject that is being returned.Return value: This method returns nothing.Below programs illustrate exiting(String sourceClass, String sourceMethod, Object result) method:Program 1:// Java program to demonstrate// exiting(String, String, Object) method import java.io.IOException;import java.util.logging.FileHandler;import java.util.logging.Level;import java.util.logging.Logger;import java.util.logging.SimpleFormatter; public class GFG { public static void main(String[] args) throws SecurityException, IOException { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a file handler object FileHandler handler = new FileHandler("logs.txt"); handler.setFormatter(new SimpleFormatter()); // Add file handler as // handler of logs logger.addHandler(handler); // set Logger level() logger.setLevel(Level.FINER); // set Logger level() logger.setLevel(Level.FINER); // call exiting method with class // name = GFG and method name = main logger.exiting(GFG.class.getName(), GFG.class.getMethods()[0].getName(), new String("Java is Platform Independent")); }}The output printed on log.txt is shown below.Output: exiting(String sourceClass, String sourceMethod): This method is used to Log a method return. we need to log what method returns and this is a convenience method that can be used to log returning from a method. This method logs with the message “RETURN”, log level FINER, and the given sourceMethod and sourceClass are also logged.Syntax:public void exiting(String sourceClass, String sourceMethod) Parameters: This method accepts two parameters:sourceClass is the name of the class that issued the logging request,sourceMethod is the name of the methodReturn value: This method returns nothing.Below program illustrate exiting(String sourceClass, String sourceMethod) method:Program 1:// Java program to demonstrate// exiting(String, String) method import java.io.IOException;import java.util.logging.FileHandler;import java.util.logging.Level;import java.util.logging.Logger;import java.util.logging.SimpleFormatter; public class GFG { public static void main(String[] args) throws SecurityException, IOException { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a file handler object FileHandler handler = new FileHandler("logs.txt"); handler.setFormatter(new SimpleFormatter()); // Add file handler as // handler of logs logger.addHandler(handler); // set Logger level() logger.setLevel(Level.FINER); // call exiting methods with class // name = GFG and method name = main logger.exiting(GFG.class.getName(), GFG.class.getMethods()[0].getName()); }}The output printed on log.txg file is shown below.Output: Syntax: public void exiting(String sourceClass, String sourceMethod) Parameters: This method accepts two parameters: sourceClass is the name of the class that issued the logging request, sourceMethod is the name of the method Return value: This method returns nothing. Below program illustrate exiting(String sourceClass, String sourceMethod) method:Program 1: // Java program to demonstrate// exiting(String, String) method import java.io.IOException;import java.util.logging.FileHandler;import java.util.logging.Level;import java.util.logging.Logger;import java.util.logging.SimpleFormatter; public class GFG { public static void main(String[] args) throws SecurityException, IOException { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a file handler object FileHandler handler = new FileHandler("logs.txt"); handler.setFormatter(new SimpleFormatter()); // Add file handler as // handler of logs logger.addHandler(handler); // set Logger level() logger.setLevel(Level.FINER); // call exiting methods with class // name = GFG and method name = main logger.exiting(GFG.class.getName(), GFG.class.getMethods()[0].getName()); }} The output printed on log.txg file is shown below.Output: exiting(String sourceClass, String sourceMethod, Object result): This method is used to Log a method entry, with result object. This is a very helpful method to log entry related to a method of a class with its return value. This method logs with the message “RETURN {0}”, log level FINER, and the gives sourceMethod, sourceClass, and result object is logged.Syntax:public void exiting(String sourceClass, String sourceMethod, Object result) Parameters: This method accepts three parameters:sourceClass is the name of the class that issued the logging request,sourceMethod is the name of the method andObject that is being returned.Return value: This method returns nothing.Below programs illustrate exiting(String sourceClass, String sourceMethod, Object result) method:Program 1:// Java program to demonstrate// exiting(String, String, Object) method import java.io.IOException;import java.util.logging.FileHandler;import java.util.logging.Level;import java.util.logging.Logger;import java.util.logging.SimpleFormatter; public class GFG { public static void main(String[] args) throws SecurityException, IOException { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a file handler object FileHandler handler = new FileHandler("logs.txt"); handler.setFormatter(new SimpleFormatter()); // Add file handler as // handler of logs logger.addHandler(handler); // set Logger level() logger.setLevel(Level.FINER); // set Logger level() logger.setLevel(Level.FINER); // call exiting method with class // name = GFG and method name = main logger.exiting(GFG.class.getName(), GFG.class.getMethods()[0].getName(), new String("Java is Platform Independent")); }}The output printed on log.txt is shown below.Output: Syntax: public void exiting(String sourceClass, String sourceMethod, Object result) Parameters: This method accepts three parameters: sourceClass is the name of the class that issued the logging request, sourceMethod is the name of the method and Object that is being returned. Return value: This method returns nothing. Below programs illustrate exiting(String sourceClass, String sourceMethod, Object result) method:Program 1: // Java program to demonstrate// exiting(String, String, Object) method import java.io.IOException;import java.util.logging.FileHandler;import java.util.logging.Level;import java.util.logging.Logger;import java.util.logging.SimpleFormatter; public class GFG { public static void main(String[] args) throws SecurityException, IOException { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a file handler object FileHandler handler = new FileHandler("logs.txt"); handler.setFormatter(new SimpleFormatter()); // Add file handler as // handler of logs logger.addHandler(handler); // set Logger level() logger.setLevel(Level.FINER); // set Logger level() logger.setLevel(Level.FINER); // call exiting method with class // name = GFG and method name = main logger.exiting(GFG.class.getName(), GFG.class.getMethods()[0].getName(), new String("Java is Platform Independent")); }} The output printed on log.txt is shown below.Output: References: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#exiting(java.lang.String, java.lang.String, java.lang.Object) https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#exiting(java.lang.String, java.lang.String) Java - util package Java-Functions Java-Logger Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Stack Class in Java Initialize an ArrayList in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Mar, 2019" }, { "code": null, "e": 96, "s": 28, "text": "The exiting() method of a Logger class used to Log a method return." }, { "code": null, "e": 174, "s": 96, "text": "There are two types of exiting() method depending upon the parameters passed." }, { "code": null, "e": 3924, "s": 174, "text": "exiting(String sourceClass, String sourceMethod): This method is used to Log a method return. we need to log what method returns and this is a convenience method that can be used to log returning from a method. This method logs with the message “RETURN”, log level FINER, and the given sourceMethod and sourceClass are also logged.Syntax:public void exiting(String sourceClass,\n String sourceMethod)\nParameters: This method accepts two parameters:sourceClass is the name of the class that issued the logging request,sourceMethod is the name of the methodReturn value: This method returns nothing.Below program illustrate exiting(String sourceClass, String sourceMethod) method:Program 1:// Java program to demonstrate// exiting(String, String) method import java.io.IOException;import java.util.logging.FileHandler;import java.util.logging.Level;import java.util.logging.Logger;import java.util.logging.SimpleFormatter; public class GFG { public static void main(String[] args) throws SecurityException, IOException { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a file handler object FileHandler handler = new FileHandler(\"logs.txt\"); handler.setFormatter(new SimpleFormatter()); // Add file handler as // handler of logs logger.addHandler(handler); // set Logger level() logger.setLevel(Level.FINER); // call exiting methods with class // name = GFG and method name = main logger.exiting(GFG.class.getName(), GFG.class.getMethods()[0].getName()); }}The output printed on log.txg file is shown below.Output:exiting(String sourceClass, String sourceMethod, Object result): This method is used to Log a method entry, with result object. This is a very helpful method to log entry related to a method of a class with its return value. This method logs with the message “RETURN {0}”, log level FINER, and the gives sourceMethod, sourceClass, and result object is logged.Syntax:public void exiting(String sourceClass,\n String sourceMethod,\n Object result)\nParameters: This method accepts three parameters:sourceClass is the name of the class that issued the logging request,sourceMethod is the name of the method andObject that is being returned.Return value: This method returns nothing.Below programs illustrate exiting(String sourceClass, String sourceMethod, Object result) method:Program 1:// Java program to demonstrate// exiting(String, String, Object) method import java.io.IOException;import java.util.logging.FileHandler;import java.util.logging.Level;import java.util.logging.Logger;import java.util.logging.SimpleFormatter; public class GFG { public static void main(String[] args) throws SecurityException, IOException { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a file handler object FileHandler handler = new FileHandler(\"logs.txt\"); handler.setFormatter(new SimpleFormatter()); // Add file handler as // handler of logs logger.addHandler(handler); // set Logger level() logger.setLevel(Level.FINER); // set Logger level() logger.setLevel(Level.FINER); // call exiting method with class // name = GFG and method name = main logger.exiting(GFG.class.getName(), GFG.class.getMethods()[0].getName(), new String(\"Java is Platform Independent\")); }}The output printed on log.txt is shown below.Output:" }, { "code": null, "e": 5674, "s": 3924, "text": "exiting(String sourceClass, String sourceMethod): This method is used to Log a method return. we need to log what method returns and this is a convenience method that can be used to log returning from a method. This method logs with the message “RETURN”, log level FINER, and the given sourceMethod and sourceClass are also logged.Syntax:public void exiting(String sourceClass,\n String sourceMethod)\nParameters: This method accepts two parameters:sourceClass is the name of the class that issued the logging request,sourceMethod is the name of the methodReturn value: This method returns nothing.Below program illustrate exiting(String sourceClass, String sourceMethod) method:Program 1:// Java program to demonstrate// exiting(String, String) method import java.io.IOException;import java.util.logging.FileHandler;import java.util.logging.Level;import java.util.logging.Logger;import java.util.logging.SimpleFormatter; public class GFG { public static void main(String[] args) throws SecurityException, IOException { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a file handler object FileHandler handler = new FileHandler(\"logs.txt\"); handler.setFormatter(new SimpleFormatter()); // Add file handler as // handler of logs logger.addHandler(handler); // set Logger level() logger.setLevel(Level.FINER); // call exiting methods with class // name = GFG and method name = main logger.exiting(GFG.class.getName(), GFG.class.getMethods()[0].getName()); }}The output printed on log.txg file is shown below.Output:" }, { "code": null, "e": 5682, "s": 5674, "text": "Syntax:" }, { "code": null, "e": 5764, "s": 5682, "text": "public void exiting(String sourceClass,\n String sourceMethod)\n" }, { "code": null, "e": 5812, "s": 5764, "text": "Parameters: This method accepts two parameters:" }, { "code": null, "e": 5882, "s": 5812, "text": "sourceClass is the name of the class that issued the logging request," }, { "code": null, "e": 5921, "s": 5882, "text": "sourceMethod is the name of the method" }, { "code": null, "e": 5964, "s": 5921, "text": "Return value: This method returns nothing." }, { "code": null, "e": 6056, "s": 5964, "text": "Below program illustrate exiting(String sourceClass, String sourceMethod) method:Program 1:" }, { "code": "// Java program to demonstrate// exiting(String, String) method import java.io.IOException;import java.util.logging.FileHandler;import java.util.logging.Level;import java.util.logging.Logger;import java.util.logging.SimpleFormatter; public class GFG { public static void main(String[] args) throws SecurityException, IOException { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a file handler object FileHandler handler = new FileHandler(\"logs.txt\"); handler.setFormatter(new SimpleFormatter()); // Add file handler as // handler of logs logger.addHandler(handler); // set Logger level() logger.setLevel(Level.FINER); // call exiting methods with class // name = GFG and method name = main logger.exiting(GFG.class.getName(), GFG.class.getMethods()[0].getName()); }}", "e": 7043, "s": 6056, "text": null }, { "code": null, "e": 7101, "s": 7043, "text": "The output printed on log.txg file is shown below.Output:" }, { "code": null, "e": 9102, "s": 7101, "text": "exiting(String sourceClass, String sourceMethod, Object result): This method is used to Log a method entry, with result object. This is a very helpful method to log entry related to a method of a class with its return value. This method logs with the message “RETURN {0}”, log level FINER, and the gives sourceMethod, sourceClass, and result object is logged.Syntax:public void exiting(String sourceClass,\n String sourceMethod,\n Object result)\nParameters: This method accepts three parameters:sourceClass is the name of the class that issued the logging request,sourceMethod is the name of the method andObject that is being returned.Return value: This method returns nothing.Below programs illustrate exiting(String sourceClass, String sourceMethod, Object result) method:Program 1:// Java program to demonstrate// exiting(String, String, Object) method import java.io.IOException;import java.util.logging.FileHandler;import java.util.logging.Level;import java.util.logging.Logger;import java.util.logging.SimpleFormatter; public class GFG { public static void main(String[] args) throws SecurityException, IOException { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a file handler object FileHandler handler = new FileHandler(\"logs.txt\"); handler.setFormatter(new SimpleFormatter()); // Add file handler as // handler of logs logger.addHandler(handler); // set Logger level() logger.setLevel(Level.FINER); // set Logger level() logger.setLevel(Level.FINER); // call exiting method with class // name = GFG and method name = main logger.exiting(GFG.class.getName(), GFG.class.getMethods()[0].getName(), new String(\"Java is Platform Independent\")); }}The output printed on log.txt is shown below.Output:" }, { "code": null, "e": 9110, "s": 9102, "text": "Syntax:" }, { "code": null, "e": 9227, "s": 9110, "text": "public void exiting(String sourceClass,\n String sourceMethod,\n Object result)\n" }, { "code": null, "e": 9277, "s": 9227, "text": "Parameters: This method accepts three parameters:" }, { "code": null, "e": 9347, "s": 9277, "text": "sourceClass is the name of the class that issued the logging request," }, { "code": null, "e": 9390, "s": 9347, "text": "sourceMethod is the name of the method and" }, { "code": null, "e": 9421, "s": 9390, "text": "Object that is being returned." }, { "code": null, "e": 9464, "s": 9421, "text": "Return value: This method returns nothing." }, { "code": null, "e": 9572, "s": 9464, "text": "Below programs illustrate exiting(String sourceClass, String sourceMethod, Object result) method:Program 1:" }, { "code": "// Java program to demonstrate// exiting(String, String, Object) method import java.io.IOException;import java.util.logging.FileHandler;import java.util.logging.Level;import java.util.logging.Logger;import java.util.logging.SimpleFormatter; public class GFG { public static void main(String[] args) throws SecurityException, IOException { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a file handler object FileHandler handler = new FileHandler(\"logs.txt\"); handler.setFormatter(new SimpleFormatter()); // Add file handler as // handler of logs logger.addHandler(handler); // set Logger level() logger.setLevel(Level.FINER); // set Logger level() logger.setLevel(Level.FINER); // call exiting method with class // name = GFG and method name = main logger.exiting(GFG.class.getName(), GFG.class.getMethods()[0].getName(), new String(\"Java is Platform Independent\")); }}", "e": 10700, "s": 9572, "text": null }, { "code": null, "e": 10753, "s": 10700, "text": "The output printed on log.txt is shown below.Output:" }, { "code": null, "e": 10765, "s": 10753, "text": "References:" }, { "code": null, "e": 10900, "s": 10765, "text": "https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#exiting(java.lang.String, java.lang.String, java.lang.Object)" }, { "code": null, "e": 11017, "s": 10900, "text": "https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#exiting(java.lang.String, java.lang.String)" }, { "code": null, "e": 11037, "s": 11017, "text": "Java - util package" }, { "code": null, "e": 11052, "s": 11037, "text": "Java-Functions" }, { "code": null, "e": 11064, "s": 11052, "text": "Java-Logger" }, { "code": null, "e": 11069, "s": 11064, "text": "Java" }, { "code": null, "e": 11074, "s": 11069, "text": "Java" }, { "code": null, "e": 11172, "s": 11074, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11191, "s": 11172, "text": "Interfaces in Java" }, { "code": null, "e": 11221, "s": 11191, "text": "HashMap in Java with Examples" }, { "code": null, "e": 11236, "s": 11221, "text": "Stream In Java" }, { "code": null, "e": 11254, "s": 11236, "text": "ArrayList in Java" }, { "code": null, "e": 11274, "s": 11254, "text": "Collections in Java" }, { "code": null, "e": 11298, "s": 11274, "text": "Singleton Class in Java" }, { "code": null, "e": 11330, "s": 11298, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 11342, "s": 11330, "text": "Set in Java" }, { "code": null, "e": 11362, "s": 11342, "text": "Stack Class in Java" } ]
MySQL | Group_CONCAT() Function
16 Aug, 2021 The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value. Otherwise, it returns NULL. Syntax: SELECT col1, col2, ..., colN GROUP_CONCAT ( [DISTINCT] col_name1 [ORDER BY clause] [SEPARATOR str_val] ) FROM table_name GROUP BY col_name2; col1, col2, ...colN : These are the column names of table. col_name1: Column of the table whose values are concatenated into a single field for each group. table_name: Name of table. col_name2: Column of the table according to which grouping is done. Use of various clauses inside GROUP_CONCAT() function: Distinct: It eliminates the repetition of values from result. Order By: It sort the values of group in specific order and then concatenate them. Separator: By default, the values of group are separated by (, ) operator. In order to change this separator value, Separator clause is used followed by a string literal. It is given as Separator ‘str_value’. Examples: Let, consider an “Employee” table: Queries: 1. Using simple GROUP_CONCAT() function- SELECT emp_id, fname, lname, dept_id, GROUP_CONCAT ( strength ) as "strengths" FROM employee group by emp_id; Output: 2. Using a DISTINCT clause- SELECT dept_id, GROUP_CONCAT ( DISTINCT strength) as "employees strengths" from employee group by dept_id; Output: 3. Use of ORDER BY clause: SELECT dept_id, GROUP_CONCAT ( DISTINCT emp_id ORDER BY emp_id SEPARATOR', ') as "employees ids" from employee group by dept_id; Here, Separator ‘, ‘ will separate the values by a comma (, ) and a whitespace character. Output: How to concatenate multiple rows of different columns in a single field.Till now we have seen the use of GROUP_CONCAT() function to group the values of multiple rows that belongs to same column. But, using concat() function and group_concat() function together, we can combine more than one column values of different rows into single field. Example:Considering above table “employee”, if we wish to find employees strength along with employees id in second query then it is written as- SELECT dept_id, GROUP_CONCAT ( strengths SEPARATOR ' ') as "emp-id : strengths" FROM ( SELECT dept_id, CONCAT ( emp_id, ':', GROUP_CONCATt(strength SEPARATOR', ') ) as "strengths" FROM employee GROUP BYy emp_id )as emp GROUP BY dept_id; Explanation:The above query consists of two SELECT statements an inner one and the outer one. The inner SELECT statement – SELECT dept_id, concat ( emp_id, ':', GROUP_CONCAT ( strength separator ', ' ) ) as "strengths" FROM employee GROUP BY emp_id It will group the rows of employee table according to “emp_id”. The first resulted column displays dept_id, second column displays emp_id along with their strengths list. Output for inner SELECT statement- The outer SELECT statement will now group these rows according to “dept_id”. Output: Note: The result of GROUP_CONCAT() function is truncated to the maximum length i.e 1024 which is given by system variable group_concat_max_len. However, the value of group_concat_max_len variable can be changed at runtime by using SETcommand as- SET [GLOBAL | SESSION] group_concat_max_len = value; value: It is the new value set to the variable. abhishek0719kadiyan rajeev0719singh DBMS-SQL mysql SQL-Functions SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL SQL Trigger | Student Database How to Update Multiple Columns in Single Update Statement in SQL? SQL Interview Questions SQL | Views Difference between DELETE, DROP and TRUNCATE Difference between DDL and DML in DBMS SQL | Sub queries in From Clause SQL Correlated Subqueries SQL | GROUP BY
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Aug, 2021" }, { "code": null, "e": 302, "s": 52, "text": "The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value. Otherwise, it returns NULL." }, { "code": null, "e": 310, "s": 302, "text": "Syntax:" }, { "code": null, "e": 707, "s": 310, "text": "SELECT col1, col2, ..., colN\nGROUP_CONCAT ( [DISTINCT] col_name1 \n[ORDER BY clause] [SEPARATOR str_val] ) \nFROM table_name GROUP BY col_name2;\n\n\ncol1, col2, ...colN : These are the column names of table.\ncol_name1: Column of the table whose values are concatenated into a single field for each group.\ntable_name: Name of table.\ncol_name2: Column of the table according to which grouping is done." }, { "code": null, "e": 762, "s": 707, "text": "Use of various clauses inside GROUP_CONCAT() function:" }, { "code": null, "e": 824, "s": 762, "text": "Distinct: It eliminates the repetition of values from result." }, { "code": null, "e": 907, "s": 824, "text": "Order By: It sort the values of group in specific order and then concatenate them." }, { "code": null, "e": 1116, "s": 907, "text": "Separator: By default, the values of group are separated by (, ) operator. In order to change this separator value, Separator clause is used followed by a string literal. It is given as Separator ‘str_value’." }, { "code": null, "e": 1126, "s": 1116, "text": "Examples:" }, { "code": null, "e": 1161, "s": 1126, "text": "Let, consider an “Employee” table:" }, { "code": null, "e": 1170, "s": 1161, "text": "Queries:" }, { "code": null, "e": 1211, "s": 1170, "text": "1. Using simple GROUP_CONCAT() function-" }, { "code": null, "e": 1323, "s": 1211, "text": "SELECT emp_id, fname, lname, dept_id, \nGROUP_CONCAT ( strength ) as \"strengths\" \nFROM employee group by emp_id;" }, { "code": null, "e": 1331, "s": 1323, "text": "Output:" }, { "code": null, "e": 1359, "s": 1331, "text": "2. Using a DISTINCT clause-" }, { "code": null, "e": 1470, "s": 1359, "text": "SELECT dept_id, \nGROUP_CONCAT ( DISTINCT strength) \nas \"employees strengths\" \nfrom employee group by dept_id;" }, { "code": null, "e": 1478, "s": 1470, "text": "Output:" }, { "code": null, "e": 1505, "s": 1478, "text": "3. Use of ORDER BY clause:" }, { "code": null, "e": 1638, "s": 1505, "text": "SELECT dept_id, \nGROUP_CONCAT ( DISTINCT emp_id ORDER BY emp_id SEPARATOR', ') \nas \"employees ids\" \nfrom employee group by dept_id;" }, { "code": null, "e": 1728, "s": 1638, "text": "Here, Separator ‘, ‘ will separate the values by a comma (, ) and a whitespace character." }, { "code": null, "e": 1736, "s": 1728, "text": "Output:" }, { "code": null, "e": 2078, "s": 1736, "text": "How to concatenate multiple rows of different columns in a single field.Till now we have seen the use of GROUP_CONCAT() function to group the values of multiple rows that belongs to same column. But, using concat() function and group_concat() function together, we can combine more than one column values of different rows into single field." }, { "code": null, "e": 2223, "s": 2078, "text": "Example:Considering above table “employee”, if we wish to find employees strength along with employees id in second query then it is written as-" }, { "code": null, "e": 2461, "s": 2223, "text": "SELECT dept_id, GROUP_CONCAT ( strengths SEPARATOR ' ') as \"emp-id : strengths\"\nFROM ( SELECT dept_id, CONCAT ( emp_id, ':', GROUP_CONCATt(strength SEPARATOR', ') )\nas \"strengths\" FROM employee GROUP BYy emp_id )as emp GROUP BY dept_id;" }, { "code": null, "e": 2555, "s": 2461, "text": "Explanation:The above query consists of two SELECT statements an inner one and the outer one." }, { "code": null, "e": 2584, "s": 2555, "text": "The inner SELECT statement –" }, { "code": null, "e": 2712, "s": 2584, "text": "SELECT dept_id, concat ( emp_id, ':',\nGROUP_CONCAT ( strength separator ', ' ) ) as \"strengths\" \nFROM employee GROUP BY emp_id" }, { "code": null, "e": 2883, "s": 2712, "text": "It will group the rows of employee table according to “emp_id”. The first resulted column displays dept_id, second column displays emp_id along with their strengths list." }, { "code": null, "e": 2918, "s": 2883, "text": "Output for inner SELECT statement-" }, { "code": null, "e": 2995, "s": 2918, "text": "The outer SELECT statement will now group these rows according to “dept_id”." }, { "code": null, "e": 3003, "s": 2995, "text": "Output:" }, { "code": null, "e": 3249, "s": 3003, "text": "Note: The result of GROUP_CONCAT() function is truncated to the maximum length i.e 1024 which is given by system variable group_concat_max_len. However, the value of group_concat_max_len variable can be changed at runtime by using SETcommand as-" }, { "code": null, "e": 3351, "s": 3249, "text": "SET [GLOBAL | SESSION] group_concat_max_len = value;\n\nvalue: It is the new value set to the variable." }, { "code": null, "e": 3371, "s": 3351, "text": "abhishek0719kadiyan" }, { "code": null, "e": 3387, "s": 3371, "text": "rajeev0719singh" }, { "code": null, "e": 3396, "s": 3387, "text": "DBMS-SQL" }, { "code": null, "e": 3402, "s": 3396, "text": "mysql" }, { "code": null, "e": 3416, "s": 3402, "text": "SQL-Functions" }, { "code": null, "e": 3420, "s": 3416, "text": "SQL" }, { "code": null, "e": 3424, "s": 3420, "text": "SQL" }, { "code": null, "e": 3522, "s": 3424, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3533, "s": 3522, "text": "CTE in SQL" }, { "code": null, "e": 3564, "s": 3533, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 3630, "s": 3564, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 3654, "s": 3630, "text": "SQL Interview Questions" }, { "code": null, "e": 3666, "s": 3654, "text": "SQL | Views" }, { "code": null, "e": 3711, "s": 3666, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 3750, "s": 3711, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 3783, "s": 3750, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 3809, "s": 3783, "text": "SQL Correlated Subqueries" } ]
numpy.stack() in Python
06 Jan, 2019 numpy.stack() function is used to join a sequence of same dimension arrays along a new axis.The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension. Syntax : numpy.stack(arrays, axis) Parameters :arrays : [array_like] Sequence of arrays of the same shape.axis : [int] Axis in the resultant array along which the input arrays are stacked. Return : [stacked ndarray] The stacked array of the input arrays which has one more dimension than the input arrays. Code #1 : # Python program explaining# stack() function import numpy as geek # input arrayin_arr1 = geek.array([ 1, 2, 3] )print ("1st Input array : \n", in_arr1) in_arr2 = geek.array([ 4, 5, 6] )print ("2nd Input array : \n", in_arr2) # Stacking the two arrays along axis 0out_arr1 = geek.stack((in_arr1, in_arr2), axis = 0)print ("Output stacked array along axis 0:\n ", out_arr1) # Stacking the two arrays along axis 1out_arr2 = geek.stack((in_arr1, in_arr2), axis = 1)print ("Output stacked array along axis 1:\n ", out_arr2) 1st Input array : [1 2 3] 2nd Input array : [4 5 6] Output stacked array along axis 0: [[1 2 3] [4 5 6]] Output stacked array along axis 1: [[1 4] [2 5] [3 6]] Code #2 : # Python program explaining# stack() function import numpy as geek # input arrayin_arr1 = geek.array([[ 1, 2, 3], [ -1, -2, -3]] )print ("1st Input array : \n", in_arr1) in_arr2 = geek.array([[ 4, 5, 6], [ -4, -5, -6]] )print ("2nd Input array : \n", in_arr2) # Stacking the two arrays along axis 0out_arr1 = geek.stack((in_arr1, in_arr2), axis = 0)print ("Output stacked array along axis 0:\n ", out_arr1) # Stacking the two arrays along axis 1out_arr2 = geek.stack((in_arr1, in_arr2), axis = 1)print ("Output stacked array along axis 1:\n ", out_arr2) # Stacking the two arrays along last axis out_arr3 = geek.stack((in_arr1, in_arr2), axis = -1)print ("Output stacked array along last axis :\n ", out_arr3) 1st Input array : [[ 1 2 3] [-1 -2 -3]] 2nd Input array : [[ 4 5 6] [-4 -5 -6]] Output stacked array along axis 0: [[[ 1 2 3] [-1 -2 -3]] [[ 4 5 6] [-4 -5 -6]]] Output stacked array along axis 1: [[[ 1 2 3] [ 4 5 6]] [[-1 -2 -3] [-4 -5 -6]]] Output stacked array along last axis : [[[ 1 4] [ 2 5] [ 3 6]] [[-1 -4] [-2 -5] [-3 -6]]] Python numpy-arrayManipulation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jan, 2019" }, { "code": null, "e": 332, "s": 52, "text": "numpy.stack() function is used to join a sequence of same dimension arrays along a new axis.The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension." }, { "code": null, "e": 367, "s": 332, "text": "Syntax : numpy.stack(arrays, axis)" }, { "code": null, "e": 521, "s": 367, "text": "Parameters :arrays : [array_like] Sequence of arrays of the same shape.axis : [int] Axis in the resultant array along which the input arrays are stacked." }, { "code": null, "e": 638, "s": 521, "text": "Return : [stacked ndarray] The stacked array of the input arrays which has one more dimension than the input arrays." }, { "code": null, "e": 648, "s": 638, "text": "Code #1 :" }, { "code": "# Python program explaining# stack() function import numpy as geek # input arrayin_arr1 = geek.array([ 1, 2, 3] )print (\"1st Input array : \\n\", in_arr1) in_arr2 = geek.array([ 4, 5, 6] )print (\"2nd Input array : \\n\", in_arr2) # Stacking the two arrays along axis 0out_arr1 = geek.stack((in_arr1, in_arr2), axis = 0)print (\"Output stacked array along axis 0:\\n \", out_arr1) # Stacking the two arrays along axis 1out_arr2 = geek.stack((in_arr1, in_arr2), axis = 1)print (\"Output stacked array along axis 1:\\n \", out_arr2)", "e": 1175, "s": 648, "text": null }, { "code": null, "e": 1347, "s": 1175, "text": "1st Input array : \n [1 2 3]\n2nd Input array : \n [4 5 6]\nOutput stacked array along axis 0:\n [[1 2 3]\n [4 5 6]]\nOutput stacked array along axis 1:\n [[1 4]\n [2 5]\n [3 6]]\n" }, { "code": null, "e": 1358, "s": 1347, "text": " Code #2 :" }, { "code": "# Python program explaining# stack() function import numpy as geek # input arrayin_arr1 = geek.array([[ 1, 2, 3], [ -1, -2, -3]] )print (\"1st Input array : \\n\", in_arr1) in_arr2 = geek.array([[ 4, 5, 6], [ -4, -5, -6]] )print (\"2nd Input array : \\n\", in_arr2) # Stacking the two arrays along axis 0out_arr1 = geek.stack((in_arr1, in_arr2), axis = 0)print (\"Output stacked array along axis 0:\\n \", out_arr1) # Stacking the two arrays along axis 1out_arr2 = geek.stack((in_arr1, in_arr2), axis = 1)print (\"Output stacked array along axis 1:\\n \", out_arr2) # Stacking the two arrays along last axis out_arr3 = geek.stack((in_arr1, in_arr2), axis = -1)print (\"Output stacked array along last axis :\\n \", out_arr3)", "e": 2076, "s": 1358, "text": null }, { "code": null, "e": 2458, "s": 2076, "text": "1st Input array : \n [[ 1 2 3]\n [-1 -2 -3]]\n2nd Input array : \n [[ 4 5 6]\n [-4 -5 -6]]\nOutput stacked array along axis 0:\n [[[ 1 2 3]\n [-1 -2 -3]]\n\n [[ 4 5 6]\n [-4 -5 -6]]]\nOutput stacked array along axis 1:\n [[[ 1 2 3]\n [ 4 5 6]]\n\n [[-1 -2 -3]\n [-4 -5 -6]]]\nOutput stacked array along last axis :\n [[[ 1 4]\n [ 2 5]\n [ 3 6]]\n\n [[-1 -4]\n [-2 -5]\n [-3 -6]]]\n" }, { "code": null, "e": 2489, "s": 2458, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 2502, "s": 2489, "text": "Python-numpy" }, { "code": null, "e": 2509, "s": 2502, "text": "Python" } ]
How to Drop the Index Column in Pandas?
28 Nov, 2021 In this article, we will discuss how to drop the index column in pandas using Python. First we have to create the dataframe with student details and set the index by using set_index() function Syntax: dataframe.set_index([pandas.Index([index_values.......])]) where dataframe is the input dataframe Index_values are the values to be given as indexes to the dataframe Example: Setting index column for the dataset. The initial plot does that the changes are apparent. Python3 # import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ "id": [7058, 7059, 7072, 7054], "name": ['sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'python', 'html/php', 'php/js']}) # set the index valuesdata = data.set_index( [pd.Index(['student-1', 'student-2', 'student-3', 'student-4'])]) # display dataframeprint(data) Output: Now we can drop the index columns by using reset_index() method. It will remove the index values and set the default values from 0 to n values Syntax: dataframe.reset_index(drop=True, inplace=True) where dataframe is the input dataframe drop is set to True to remove index values inplace is to set the default integers Example: Drop the index columns Python3 # import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ "id": [7058, 7059, 7072, 7054], "name": ['sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'python', 'html/php', 'php/js']}) # set the index valuesdata = data.set_index( [pd.Index(['student-1', 'student-2', 'student-3', 'student-4'])]) # display dataframeprint(data) # drop the index columnsdata.reset_index(drop=True, inplace=True) # displayprint(data) Output: pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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": 28, "s": 0, "text": "\n28 Nov, 2021" }, { "code": null, "e": 114, "s": 28, "text": "In this article, we will discuss how to drop the index column in pandas using Python." }, { "code": null, "e": 221, "s": 114, "text": "First we have to create the dataframe with student details and set the index by using set_index() function" }, { "code": null, "e": 229, "s": 221, "text": "Syntax:" }, { "code": null, "e": 288, "s": 229, "text": "dataframe.set_index([pandas.Index([index_values.......])])" }, { "code": null, "e": 294, "s": 288, "text": "where" }, { "code": null, "e": 327, "s": 294, "text": "dataframe is the input dataframe" }, { "code": null, "e": 395, "s": 327, "text": "Index_values are the values to be given as indexes to the dataframe" }, { "code": null, "e": 495, "s": 395, "text": "Example: Setting index column for the dataset. The initial plot does that the changes are apparent." }, { "code": null, "e": 503, "s": 495, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ \"id\": [7058, 7059, 7072, 7054], \"name\": ['sravan', 'jyothika', 'harsha', 'ramya'], \"subjects\": ['java', 'python', 'html/php', 'php/js']}) # set the index valuesdata = data.set_index( [pd.Index(['student-1', 'student-2', 'student-3', 'student-4'])]) # display dataframeprint(data)", "e": 895, "s": 503, "text": null }, { "code": null, "e": 903, "s": 895, "text": "Output:" }, { "code": null, "e": 1046, "s": 903, "text": "Now we can drop the index columns by using reset_index() method. It will remove the index values and set the default values from 0 to n values" }, { "code": null, "e": 1054, "s": 1046, "text": "Syntax:" }, { "code": null, "e": 1101, "s": 1054, "text": "dataframe.reset_index(drop=True, inplace=True)" }, { "code": null, "e": 1107, "s": 1101, "text": "where" }, { "code": null, "e": 1140, "s": 1107, "text": "dataframe is the input dataframe" }, { "code": null, "e": 1183, "s": 1140, "text": "drop is set to True to remove index values" }, { "code": null, "e": 1222, "s": 1183, "text": "inplace is to set the default integers" }, { "code": null, "e": 1254, "s": 1222, "text": "Example: Drop the index columns" }, { "code": null, "e": 1262, "s": 1254, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ \"id\": [7058, 7059, 7072, 7054], \"name\": ['sravan', 'jyothika', 'harsha', 'ramya'], \"subjects\": ['java', 'python', 'html/php', 'php/js']}) # set the index valuesdata = data.set_index( [pd.Index(['student-1', 'student-2', 'student-3', 'student-4'])]) # display dataframeprint(data) # drop the index columnsdata.reset_index(drop=True, inplace=True) # displayprint(data)", "e": 1745, "s": 1262, "text": null }, { "code": null, "e": 1753, "s": 1745, "text": "Output:" }, { "code": null, "e": 1778, "s": 1753, "text": "pandas-dataframe-program" }, { "code": null, "e": 1785, "s": 1778, "text": "Picked" }, { "code": null, "e": 1809, "s": 1785, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1823, "s": 1809, "text": "Python-pandas" }, { "code": null, "e": 1830, "s": 1823, "text": "Python" }, { "code": null, "e": 1928, "s": 1830, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1960, "s": 1928, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1987, "s": 1960, "text": "Python Classes and Objects" }, { "code": null, "e": 2008, "s": 1987, "text": "Python OOPs Concepts" }, { "code": null, "e": 2031, "s": 2008, "text": "Introduction To PYTHON" }, { "code": null, "e": 2062, "s": 2031, "text": "Python | os.path.join() method" }, { "code": null, "e": 2118, "s": 2062, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2160, "s": 2118, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2202, "s": 2160, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2241, "s": 2202, "text": "Python | Get unique values from a list" } ]
Largest substring with same Characters
25 May, 2022 Given a string s of size N. The task is to find the largest substring which consists of the same charactersExamples: Input : s = “abcdddddeff” Output : 5 Substring is “ddddd”Input : s = aabceebeee Output : 3 Approach : Traverse through the string from left to right. Take two variables ans and temp. If the current element is the same as the previous element then increment temp. If the current element is not equal to the previous element then make temp as 1 and update ans.Below is the implementation of the above approach : C++ Java Python3 C# PHP Javascript // CPP program to find largest sub// string with same characters#include <bits/stdc++.h>using namespace std; // Function to find largest sub// string with same charactersint Substring(string s){ int ans = 1, temp = 1; // Traverse the string for (int i = 1; i < s.size(); i++) { // If character is same as // previous increment temp value if (s[i] == s[i - 1]) { ++temp; } else { ans = max(ans, temp); temp = 1; } } ans = max(ans, temp); // Return the required answer return ans;} // Driver codeint main(){ string s = "abcdddddeff"; // Function call cout << Substring(s); return 0;} // Java program to find largest sub// string with same charactersimport java.util.*; class GFG{ // Function to find largest sub// string with same charactersstatic int Substring(String s){ int ans = 1, temp = 1; // Traverse the string for (int i = 1; i < s.length(); i++) { // If character is same as // previous increment temp value if (s.charAt(i) == s.charAt(i - 1)) { ++temp; } else { ans = Math.max(ans, temp); temp = 1; } } ans = Math.max(ans, temp); // Return the required answer return ans;} // Driver codepublic static void main(String[] args){ String s = "abcdddddeff"; // Function call System.out.println(Substring(s));}} // This code is contributed by 29AjayKumar # Python3 program to find largest sub# with same characters # Function to find largest sub# with same charactersdef Substring(s): ans, temp = 1, 1 # Traverse the string for i in range(1, len(s)): # If character is same as # previous increment temp value if (s[i] == s[i - 1]): temp += 1 else: ans = max(ans, temp) temp = 1 ans = max(ans, temp) # Return the required answer return ans # Driver codes = "abcdddddeff" # Function callprint(Substring(s)) # This code is contributed by Mohit Kumar // C# program to find largest sub// string with same charactersusing System;class GFG{ // Function to find largest sub// string with same charactersstatic int Substring(String s){ int ans = 1, temp = 1; // Traverse the string for (int i = 1; i < s.Length; i++) { // If character is same as // previous increment temp value if (s[i] == s[i - 1]) { ++temp; } else { ans = Math.Max(ans, temp); temp = 1; } } ans = Math.Max(ans, temp); // Return the required answer return ans;} // Driver codepublic static void Main(String[] args){ String s = "abcdddddeff"; // Function call Console.WriteLine(Substring(s));}} // This code is contributed by Rajput-Ji <?php// PHP program to find largest sub// string with same characters // Function to find largest sub// string with same charactersfunction Substring($s){ $ans = 1; $temp = 1; // Traverse the string for ($i = 1; $i < strlen($s); $i++) { // If character is same as // previous increment temp value if ($s[$i] == $s[$i - 1]) { ++$temp; } else { $ans = max($ans, $temp); $temp = 1; } } $ans = max($ans, $temp); // Return the required answer return $ans;} // Driver code$s = "abcdddddeff"; // Function callecho Substring($s); // This code is contributed by Naman_Garg?> <script> // Javascript program to find largest sub// string with same characters // Function to find largest sub// string with same charactersfunction Substring(s){ var ans = 1, temp = 1; // Traverse the string for (var i = 1; i < s.length; i++) { // If character is same as // previous increment temp value if (s[i] == s[i - 1]) { ++temp; } else { ans = Math.max(ans, temp); temp = 1; } } ans = Math.max(ans, temp); // Return the required answer return ans;} // Driver codevar s = "abcdddddeff";// Function calldocument.write( Substring(s)); </script> Output: 5 Time Complexity: O(N) Auxiliary Space: O(1) mohit kumar 29 29AjayKumar Rajput-Ji Naman_Garg mbmd3 rrrtnx rohitmishra051000 substring Combinatorial Greedy Strings Strings Greedy Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of subsets with sum equal to X Combinational Sum Find the K-th Permutation Sequence of first N natural numbers Count ways to reach the nth stair using step 1, 2 or 3 Count Derangements (Permutation such that no element appears in its original position) Dijkstra's shortest path algorithm | Greedy Algo-7 Program for array rotation Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 54, "s": 26, "text": "\n25 May, 2022" }, { "code": null, "e": 173, "s": 54, "text": "Given a string s of size N. The task is to find the largest substring which consists of the same charactersExamples: " }, { "code": null, "e": 266, "s": 173, "text": "Input : s = “abcdddddeff” Output : 5 Substring is “ddddd”Input : s = aabceebeee Output : 3 " }, { "code": null, "e": 589, "s": 268, "text": "Approach : Traverse through the string from left to right. Take two variables ans and temp. If the current element is the same as the previous element then increment temp. If the current element is not equal to the previous element then make temp as 1 and update ans.Below is the implementation of the above approach : " }, { "code": null, "e": 593, "s": 589, "text": "C++" }, { "code": null, "e": 598, "s": 593, "text": "Java" }, { "code": null, "e": 606, "s": 598, "text": "Python3" }, { "code": null, "e": 609, "s": 606, "text": "C#" }, { "code": null, "e": 613, "s": 609, "text": "PHP" }, { "code": null, "e": 624, "s": 613, "text": "Javascript" }, { "code": "// CPP program to find largest sub// string with same characters#include <bits/stdc++.h>using namespace std; // Function to find largest sub// string with same charactersint Substring(string s){ int ans = 1, temp = 1; // Traverse the string for (int i = 1; i < s.size(); i++) { // If character is same as // previous increment temp value if (s[i] == s[i - 1]) { ++temp; } else { ans = max(ans, temp); temp = 1; } } ans = max(ans, temp); // Return the required answer return ans;} // Driver codeint main(){ string s = \"abcdddddeff\"; // Function call cout << Substring(s); return 0;}", "e": 1319, "s": 624, "text": null }, { "code": "// Java program to find largest sub// string with same charactersimport java.util.*; class GFG{ // Function to find largest sub// string with same charactersstatic int Substring(String s){ int ans = 1, temp = 1; // Traverse the string for (int i = 1; i < s.length(); i++) { // If character is same as // previous increment temp value if (s.charAt(i) == s.charAt(i - 1)) { ++temp; } else { ans = Math.max(ans, temp); temp = 1; } } ans = Math.max(ans, temp); // Return the required answer return ans;} // Driver codepublic static void main(String[] args){ String s = \"abcdddddeff\"; // Function call System.out.println(Substring(s));}} // This code is contributed by 29AjayKumar", "e": 2120, "s": 1319, "text": null }, { "code": "# Python3 program to find largest sub# with same characters # Function to find largest sub# with same charactersdef Substring(s): ans, temp = 1, 1 # Traverse the string for i in range(1, len(s)): # If character is same as # previous increment temp value if (s[i] == s[i - 1]): temp += 1 else: ans = max(ans, temp) temp = 1 ans = max(ans, temp) # Return the required answer return ans # Driver codes = \"abcdddddeff\" # Function callprint(Substring(s)) # This code is contributed by Mohit Kumar", "e": 2704, "s": 2120, "text": null }, { "code": "// C# program to find largest sub// string with same charactersusing System;class GFG{ // Function to find largest sub// string with same charactersstatic int Substring(String s){ int ans = 1, temp = 1; // Traverse the string for (int i = 1; i < s.Length; i++) { // If character is same as // previous increment temp value if (s[i] == s[i - 1]) { ++temp; } else { ans = Math.Max(ans, temp); temp = 1; } } ans = Math.Max(ans, temp); // Return the required answer return ans;} // Driver codepublic static void Main(String[] args){ String s = \"abcdddddeff\"; // Function call Console.WriteLine(Substring(s));}} // This code is contributed by Rajput-Ji", "e": 3477, "s": 2704, "text": null }, { "code": "<?php// PHP program to find largest sub// string with same characters // Function to find largest sub// string with same charactersfunction Substring($s){ $ans = 1; $temp = 1; // Traverse the string for ($i = 1; $i < strlen($s); $i++) { // If character is same as // previous increment temp value if ($s[$i] == $s[$i - 1]) { ++$temp; } else { $ans = max($ans, $temp); $temp = 1; } } $ans = max($ans, $temp); // Return the required answer return $ans;} // Driver code$s = \"abcdddddeff\"; // Function callecho Substring($s); // This code is contributed by Naman_Garg?>", "e": 4183, "s": 3477, "text": null }, { "code": "<script> // Javascript program to find largest sub// string with same characters // Function to find largest sub// string with same charactersfunction Substring(s){ var ans = 1, temp = 1; // Traverse the string for (var i = 1; i < s.length; i++) { // If character is same as // previous increment temp value if (s[i] == s[i - 1]) { ++temp; } else { ans = Math.max(ans, temp); temp = 1; } } ans = Math.max(ans, temp); // Return the required answer return ans;} // Driver codevar s = \"abcdddddeff\";// Function calldocument.write( Substring(s)); </script>", "e": 4835, "s": 4183, "text": null }, { "code": null, "e": 4845, "s": 4835, "text": "Output: " }, { "code": null, "e": 4847, "s": 4845, "text": "5" }, { "code": null, "e": 4869, "s": 4847, "text": "Time Complexity: O(N)" }, { "code": null, "e": 4892, "s": 4869, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 4907, "s": 4892, "text": "mohit kumar 29" }, { "code": null, "e": 4919, "s": 4907, "text": "29AjayKumar" }, { "code": null, "e": 4929, "s": 4919, "text": "Rajput-Ji" }, { "code": null, "e": 4940, "s": 4929, "text": "Naman_Garg" }, { "code": null, "e": 4946, "s": 4940, "text": "mbmd3" }, { "code": null, "e": 4953, "s": 4946, "text": "rrrtnx" }, { "code": null, "e": 4971, "s": 4953, "text": "rohitmishra051000" }, { "code": null, "e": 4981, "s": 4971, "text": "substring" }, { "code": null, "e": 4995, "s": 4981, "text": "Combinatorial" }, { "code": null, "e": 5002, "s": 4995, "text": "Greedy" }, { "code": null, "e": 5010, "s": 5002, "text": "Strings" }, { "code": null, "e": 5018, "s": 5010, "text": "Strings" }, { "code": null, "e": 5025, "s": 5018, "text": "Greedy" }, { "code": null, "e": 5039, "s": 5025, "text": "Combinatorial" }, { "code": null, "e": 5137, "s": 5039, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5174, "s": 5137, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 5192, "s": 5174, "text": "Combinational Sum" }, { "code": null, "e": 5254, "s": 5192, "text": "Find the K-th Permutation Sequence of first N natural numbers" }, { "code": null, "e": 5309, "s": 5254, "text": "Count ways to reach the nth stair using step 1, 2 or 3" }, { "code": null, "e": 5396, "s": 5309, "text": "Count Derangements (Permutation such that no element appears in its original position)" }, { "code": null, "e": 5447, "s": 5396, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 5474, "s": 5447, "text": "Program for array rotation" }, { "code": null, "e": 5525, "s": 5474, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 5583, "s": 5525, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" } ]
C# Program to count the number of lines in a file
Firstly, create a file using StreamWriter class and add content to it − using (StreamWriter sw = new StreamWriter("hello.txt")) { sw.WriteLine("This is demo line 1"); sw.WriteLine("This is demo line 2"); sw.WriteLine("This is demo line 3"); } Now use the ReadAllLines() method to read all the lines. With that, the Length property is to be used to get the count of lines − int count = File.ReadAllLines("hello.txt").Length; Here is the complete code − Live Demo using System; using System.Collections.Generic; using System.IO; public class Program { public static void Main() { using (StreamWriter sw = new StreamWriter("hello.txt")) { sw.WriteLine("This is demo line 1"); sw.WriteLine("This is demo line 2"); sw.WriteLine("This is demo line 3"); } int count = File.ReadAllLines("hello.txt").Length; Console.WriteLine("Number of lines: "+count); } } Number of lines: 3
[ { "code": null, "e": 1259, "s": 1187, "text": "Firstly, create a file using StreamWriter class and add content to it −" }, { "code": null, "e": 1439, "s": 1259, "text": "using (StreamWriter sw = new StreamWriter(\"hello.txt\")) {\n sw.WriteLine(\"This is demo line 1\");\n sw.WriteLine(\"This is demo line 2\");\n sw.WriteLine(\"This is demo line 3\");\n}" }, { "code": null, "e": 1569, "s": 1439, "text": "Now use the ReadAllLines() method to read all the lines. With that, the Length property is to be used to get the count of lines −" }, { "code": null, "e": 1620, "s": 1569, "text": "int count = File.ReadAllLines(\"hello.txt\").Length;" }, { "code": null, "e": 1648, "s": 1620, "text": "Here is the complete code −" }, { "code": null, "e": 1659, "s": 1648, "text": " Live Demo" }, { "code": null, "e": 2104, "s": 1659, "text": "using System;\nusing System.Collections.Generic;\nusing System.IO;\npublic class Program {\n public static void Main() {\n using (StreamWriter sw = new StreamWriter(\"hello.txt\")) {\n sw.WriteLine(\"This is demo line 1\");\n sw.WriteLine(\"This is demo line 2\");\n sw.WriteLine(\"This is demo line 3\");\n }\n int count = File.ReadAllLines(\"hello.txt\").Length;\n Console.WriteLine(\"Number of lines: \"+count);\n }\n}" }, { "code": null, "e": 2123, "s": 2104, "text": "Number of lines: 3" } ]
Java Program to Demonstrate the Double-Check Locking For Singleton Class
07 Jan, 2021 One of the key challenges faced by junior developers is the way to keep Singleton class as Singleton i.e. the way to prevent multiple instances of Singleton class. Double checked locking of Singleton is a way to make sure that only one instance of Singleton class is created through an application life cycle. In double-checked locking, code checks for an existing instance of Singleton class twice with and without locking to make sure that only one instance of singleton gets created. Need of Double-checked Locking of Singleton Class: Java private static Singleton instance; public static Singleton getInstance1(){ if (instance == null) { instance = new Singleton(); } return instance;} The above code will create multiple instances of Singleton class if called by more than one thread in parallel(known as multithreading). The primary solution to the current problem will be to make getInstance() method synchronized. Though it’s thread-safe and solves the issue of multiple instances, it isn’t very efficient. You need to bear cost of synchronization every time you call this method, while synchronization is only needed on first class, when Singleton instance is created. This brings us to double checked locking pattern, where only a critical section of code is locked. Why is it called Double Checked Locking? It is called double-checked locking because there are two checks for instance == null, one without locking and other with locking (inside synchronized) block. How Double Checked Locking looks like in Java: Java public static Singleton getInstance2(){ // Single Checked if (instance == null) { synchronized (Singleton.class) { // Double checked if (instance == null) { instance = new Singleton(); } } } return instance;} Implementation double-checked locking on Singleton class: Java // Java Program to write double checked locking // of Singleton class class Singleton { private volatile static Singleton instance; private Singleton() {} // 1st version: creates multiple instances if two thread // access this method simultaneously public static Singleton getInstance1() { if (instance == null) { instance = new Singleton(); } return instance; } // 2nd version : this is thread-safe and only // creates one instance of Singleton on concurrent // environment but it is unnecessarily expensive due to // cost of synchronization at every call. public static synchronized Singleton getInstance2() { if (instance == null) { instance = new Singleton(); } return instance; } // 3rd version : An implementation of double checked // locking of Singleton. Intention is to reduce cost // of synchronization and improve performance, by only // locking critical section of code, the code which // creates instance of Singleton class. public static Singleton getInstance3() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; }} Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Jan, 2021" }, { "code": null, "e": 540, "s": 53, "text": "One of the key challenges faced by junior developers is the way to keep Singleton class as Singleton i.e. the way to prevent multiple instances of Singleton class. Double checked locking of Singleton is a way to make sure that only one instance of Singleton class is created through an application life cycle. In double-checked locking, code checks for an existing instance of Singleton class twice with and without locking to make sure that only one instance of singleton gets created." }, { "code": null, "e": 591, "s": 540, "text": "Need of Double-checked Locking of Singleton Class:" }, { "code": null, "e": 596, "s": 591, "text": "Java" }, { "code": "private static Singleton instance; public static Singleton getInstance1(){ if (instance == null) { instance = new Singleton(); } return instance;}", "e": 760, "s": 596, "text": null }, { "code": null, "e": 898, "s": 760, "text": "The above code will create multiple instances of Singleton class if called by more than one thread in parallel(known as multithreading). " }, { "code": null, "e": 994, "s": 898, "text": "The primary solution to the current problem will be to make getInstance() method synchronized. " }, { "code": null, "e": 1250, "s": 994, "text": "Though it’s thread-safe and solves the issue of multiple instances, it isn’t very efficient. You need to bear cost of synchronization every time you call this method, while synchronization is only needed on first class, when Singleton instance is created." }, { "code": null, "e": 1350, "s": 1250, "text": "This brings us to double checked locking pattern, where only a critical section of code is locked. " }, { "code": null, "e": 1391, "s": 1350, "text": "Why is it called Double Checked Locking?" }, { "code": null, "e": 1550, "s": 1391, "text": "It is called double-checked locking because there are two checks for instance == null, one without locking and other with locking (inside synchronized) block." }, { "code": null, "e": 1597, "s": 1550, "text": "How Double Checked Locking looks like in Java:" }, { "code": null, "e": 1602, "s": 1597, "text": "Java" }, { "code": "public static Singleton getInstance2(){ // Single Checked if (instance == null) { synchronized (Singleton.class) { // Double checked if (instance == null) { instance = new Singleton(); } } } return instance;}", "e": 1902, "s": 1602, "text": null }, { "code": null, "e": 1960, "s": 1902, "text": "Implementation double-checked locking on Singleton class:" }, { "code": null, "e": 1965, "s": 1960, "text": "Java" }, { "code": "// Java Program to write double checked locking // of Singleton class class Singleton { private volatile static Singleton instance; private Singleton() {} // 1st version: creates multiple instances if two thread // access this method simultaneously public static Singleton getInstance1() { if (instance == null) { instance = new Singleton(); } return instance; } // 2nd version : this is thread-safe and only // creates one instance of Singleton on concurrent // environment but it is unnecessarily expensive due to // cost of synchronization at every call. public static synchronized Singleton getInstance2() { if (instance == null) { instance = new Singleton(); } return instance; } // 3rd version : An implementation of double checked // locking of Singleton. Intention is to reduce cost // of synchronization and improve performance, by only // locking critical section of code, the code which // creates instance of Singleton class. public static Singleton getInstance3() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; }}", "e": 3323, "s": 1965, "text": null }, { "code": null, "e": 3330, "s": 3323, "text": "Picked" }, { "code": null, "e": 3354, "s": 3330, "text": "Technical Scripter 2020" }, { "code": null, "e": 3359, "s": 3354, "text": "Java" }, { "code": null, "e": 3373, "s": 3359, "text": "Java Programs" }, { "code": null, "e": 3392, "s": 3373, "text": "Technical Scripter" }, { "code": null, "e": 3397, "s": 3392, "text": "Java" } ]
Get clicked item and its position in RecyclerView?
This example demonstrate about how to get clicked item and its position in RecyclerView Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <android.support.design.widget.CoordinatorLayout android:layout_width = "match_parent" android:layout_height = "match_parent" xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto"> <android.support.design.widget.AppBarLayout android:layout_width = "match_parent" android:layout_height = "wrap_content"> <android.support.v7.widget.Toolbar android:id = "@+id/appbarlayout_tool_bar" android:background = "@color/colorPrimary" android:layout_width = "match_parent" android:layout_height = "?attr/actionBarSize" app:layout_scrollFlags = "scroll|snap|enterAlways" app:theme = "@style/ThemeOverlay.AppCompat.Dark.ActionBar" app:popupTheme = "@style/ThemeOverlay.AppCompat.Light" /> </android.support.design.widget.AppBarLayout> <android.support.v7.widget.RecyclerView android:id = "@+id/recycler_view" android:layout_width = "match_parent" android:layout_height = "match_parent" app:layout_behavior = "@string/appbar_scrolling_view_behavior"/> </android.support.design.widget.CoordinatorLayout> In the above code, we have taken recycerview. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { TextView text; ArrayList<String> list = new ArrayList<>(); private RecyclerView recyclerView; private customAdapter mAdapter; private onClickInterface onclickInterface; @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.appbarlayout_tool_bar); toolbar.setTitle("This is toolbar."); setSupportActionBar(toolbar); onclickInterface = new onClickInterface() { @Override public void setClick(int abc) { list.remove(abc); Toast.makeText(MainActivity.this,"Position is"+abc,Toast.LENGTH_LONG).show(); mAdapter.notifyDataSetChanged(); } }; recyclerView = (RecyclerView) findViewById(R.id.recycler_view); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); mAdapter = new customAdapter(this, list, onclickInterface); recyclerView.setAdapter(mAdapter); recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL)); list.add("sairamm"); list.add("Krishna"); list.add("prasad"); list.add("sairamm"); list.add("Krishna"); list.add("prasad"); list.add("sairamm"); list.add("Krishna"); list.add("prasad"); list.add("sairamm"); list.add("Krishna"); list.add("prasad"); list.add("Krishna"); list.add("prasad"); list.add("sairamm"); list.add("Krishna"); list.add("prasad"); list.add("sairamm"); list.add("Krishna"); list.add("prasad"); } } Step 4 − Add the following code to src/ customAdapter.java package com.example.myapplication; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; public class customAdapter extends RecyclerView.Adapter<customAdapter.MyViewHolder> { Context context; ArrayList<String> list; onClickInterface onClickInterface; public class MyViewHolder extends RecyclerView.ViewHolder { public TextView title; public MyViewHolder(View view) { super(view); title = (TextView) view.findViewById(R.id.title); } } public customAdapter(Context context, ArrayList<String> list, onClickInterface onClickInterface) { this.context = context; this.list = list; this.onClickInterface = onClickInterface; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, viewGroup, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int i) { myViewHolder.title.setText(list.get(i)); myViewHolder.title.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClickInterface.setClick(i); } }); } @Override public int getItemCount() { return list.size(); } } Step 5 − Add the following code to res/layout/ list_row.xml. <?xml version = "1.0" encoding = "utf-8"?> <android.support.v7.widget.CardView 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 = "wrap_content" app:cardElevation = "10dp" app:cardCornerRadius = "20dp" tools:context = ".MainActivity"> <LinearLayout android:layout_width = "match_parent" android:layout_height = "wrap_content" android:gravity = "center" android:orientation = "vertical"> <ImageView android:id = "@+id/imageView2" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:src = "@drawable/logo" /> <TextView android:id = "@+id/title" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:gravity = "center" android:textSize = "30sp" /> <TextView android:id = "@+id/textview2" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:gravity = "center" android:text = "Sairamkrishan" android:textSize = "30sp" /> </LinearLayout> </android.support.v7.widget.CardView> Step 6 − Add the following code to src/ onClickInterface. package com.example.myapplication; public interface onClickInterface { void setClick(int abc); } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Now click on textview, it will show result as follows
[ { "code": null, "e": 1275, "s": 1187, "text": "This example demonstrate about how to get clicked item and its position in RecyclerView" }, { "code": null, "e": 1404, "s": 1275, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1469, "s": 1404, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2660, "s": 1469, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.design.widget.CoordinatorLayout android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\">\n <android.support.design.widget.AppBarLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\">\n <android.support.v7.widget.Toolbar\n android:id = \"@+id/appbarlayout_tool_bar\"\n android:background = \"@color/colorPrimary\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"?attr/actionBarSize\"\n app:layout_scrollFlags = \"scroll|snap|enterAlways\"\n app:theme = \"@style/ThemeOverlay.AppCompat.Dark.ActionBar\"\n app:popupTheme = \"@style/ThemeOverlay.AppCompat.Light\" />\n </android.support.design.widget.AppBarLayout>\n <android.support.v7.widget.RecyclerView\n android:id = \"@+id/recycler_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n app:layout_behavior = \"@string/appbar_scrolling_view_behavior\"/>\n</android.support.design.widget.CoordinatorLayout>" }, { "code": null, "e": 2706, "s": 2660, "text": "In the above code, we have taken recycerview." }, { "code": null, "e": 2763, "s": 2706, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 5248, "s": 2763, "text": "package com.example.myapplication;\nimport android.annotation.TargetApi;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.DefaultItemAnimator;\nimport android.support.v7.widget.DividerItemDecoration;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.support.v7.widget.Toolbar;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport java.util.ArrayList;\n\npublic class MainActivity extends AppCompatActivity {\n TextView text;\n ArrayList<String> list = new ArrayList<>();\n private RecyclerView recyclerView;\n private customAdapter mAdapter;\n private onClickInterface onclickInterface;\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.appbarlayout_tool_bar);\n toolbar.setTitle(\"This is toolbar.\");\n setSupportActionBar(toolbar);\n onclickInterface = new onClickInterface() {\n @Override\n public void setClick(int abc) {\n list.remove(abc);\n Toast.makeText(MainActivity.this,\"Position is\"+abc,Toast.LENGTH_LONG).show();\n mAdapter.notifyDataSetChanged();\n }\n };\n recyclerView = (RecyclerView) findViewById(R.id.recycler_view);\n RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());\n recyclerView.setLayoutManager(mLayoutManager);\n recyclerView.setItemAnimator(new DefaultItemAnimator());\n mAdapter = new customAdapter(this, list, onclickInterface);\n recyclerView.setAdapter(mAdapter);\n recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL));\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n }\n}" }, { "code": null, "e": 5307, "s": 5248, "text": "Step 4 − Add the following code to src/ customAdapter.java" }, { "code": null, "e": 6906, "s": 5307, "text": "package com.example.myapplication;\nimport android.content.Context;\nimport android.support.annotation.NonNull;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\nimport java.util.ArrayList;\n\npublic class customAdapter extends RecyclerView.Adapter<customAdapter.MyViewHolder> {\n Context context;\n ArrayList<String> list;\n onClickInterface onClickInterface;\n public class MyViewHolder extends RecyclerView.ViewHolder {\n public TextView title;\n public MyViewHolder(View view) {\n super(view);\n title = (TextView) view.findViewById(R.id.title);\n }\n }\n public customAdapter(Context context, ArrayList<String> list, onClickInterface onClickInterface) {\n this.context = context;\n this.list = list;\n this.onClickInterface = onClickInterface;\n }\n @NonNull\n @Override\n public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {\n View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, viewGroup, false);\n return new MyViewHolder(itemView);\n }\n @Override\n public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int i) {\n myViewHolder.title.setText(list.get(i));\n myViewHolder.title.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onClickInterface.setClick(i);\n }\n });\n }\n @Override\n public int getItemCount() {\n return list.size();\n }\n}" }, { "code": null, "e": 6967, "s": 6906, "text": "Step 5 − Add the following code to res/layout/ list_row.xml." }, { "code": null, "e": 8259, "s": 6967, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.v7.widget.CardView xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n app:cardElevation = \"10dp\"\n app:cardCornerRadius = \"20dp\"\n tools:context = \".MainActivity\">\n <LinearLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:gravity = \"center\"\n android:orientation = \"vertical\">\n <ImageView\n android:id = \"@+id/imageView2\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:src = \"@drawable/logo\" />\n <TextView\n android:id = \"@+id/title\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:gravity = \"center\"\n android:textSize = \"30sp\" />\n <TextView\n android:id = \"@+id/textview2\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:gravity = \"center\"\n android:text = \"Sairamkrishan\"\n android:textSize = \"30sp\" />\n </LinearLayout>\n</android.support.v7.widget.CardView>" }, { "code": null, "e": 8317, "s": 8259, "text": "Step 6 − Add the following code to src/ onClickInterface." }, { "code": null, "e": 8417, "s": 8317, "text": "package com.example.myapplication;\npublic interface onClickInterface {\n void setClick(int abc);\n}" }, { "code": null, "e": 8764, "s": 8417, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 8818, "s": 8764, "text": "Now click on textview, it will show result as follows" } ]
HTML <img> Tag
27 Aug, 2021 HTML <img> tag is used to add image inside webpage/website. Nowadays website does not directly add images to a web page, as the images are linked to web pages by using the <img> tag which holds space for the image. Syntax: <img src="" alt="" width="" height=""> Attributes: The <img> tag has following attributes. src: It is used to specify the path to the image. alt: It is used to specify an alternate text for the image. It is useful as it informs the user about what the image means and also due to any network issue if the image cannot be displayed then this alternate text will be displayed. crossorigin: It is used to import images from third-party sites that allow cross-origin access to be used with canvas. height: It is used to specify the height of the image. width: It is used to specify the width of the image. ismap: It is used to specify an image as a server-side image map. loading: It is used to specify whether a browser should defer loading of images until some conditions are met or load an image immediately. longdesc: It is used to specify a URL to a detailed description of an image. referrerpolicy: It is used to specify which referrer information to use when fetching an image i.e. no-referrer, no-referrer-when-downgrade, origin, origin-when-cross-origin, unsafe-url. sizes: It is used to specify image sizes for different page layouts. srcset: It is used to specify a list of image files to use in different situations. usemap: It is used to specify an image as a client-side image map. Example 1: In this example we are using the <img> tag along with src, width, height, and alt attributes. HTML <!DOCTYPE html><html> <body style="text-align: center;"> <h3>GeeksforGeeks logo</h3> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-13.png" width="420" height="100" alt="Geeksforgeeks.org"></body> </html> Output: img src with width and height Example 2: In this example, we are adding the style attribute to add a border to the image. HTML <!DOCTYPE html><html> <body style="text-align: center;"> <h3>GeeksforGeeks logo</h3> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-13.png" width="420" height="100" alt="Geeksforgeeks.org" style="border:5px solid black"></body> </html> Output: image source with border Supported Browsers: Google Chrome Internet Explorer Safari Opera firefox hritikbhatnagar2182 HTML-Attributes HTML-Tags Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Aug, 2021" }, { "code": null, "e": 269, "s": 54, "text": "HTML <img> tag is used to add image inside webpage/website. Nowadays website does not directly add images to a web page, as the images are linked to web pages by using the <img> tag which holds space for the image." }, { "code": null, "e": 279, "s": 269, "text": "Syntax: " }, { "code": null, "e": 318, "s": 279, "text": "<img src=\"\" alt=\"\" width=\"\" height=\"\">" }, { "code": null, "e": 370, "s": 318, "text": "Attributes: The <img> tag has following attributes." }, { "code": null, "e": 422, "s": 372, "text": "src: It is used to specify the path to the image." }, { "code": null, "e": 656, "s": 422, "text": "alt: It is used to specify an alternate text for the image. It is useful as it informs the user about what the image means and also due to any network issue if the image cannot be displayed then this alternate text will be displayed." }, { "code": null, "e": 775, "s": 656, "text": "crossorigin: It is used to import images from third-party sites that allow cross-origin access to be used with canvas." }, { "code": null, "e": 830, "s": 775, "text": "height: It is used to specify the height of the image." }, { "code": null, "e": 883, "s": 830, "text": "width: It is used to specify the width of the image." }, { "code": null, "e": 949, "s": 883, "text": "ismap: It is used to specify an image as a server-side image map." }, { "code": null, "e": 1089, "s": 949, "text": "loading: It is used to specify whether a browser should defer loading of images until some conditions are met or load an image immediately." }, { "code": null, "e": 1166, "s": 1089, "text": "longdesc: It is used to specify a URL to a detailed description of an image." }, { "code": null, "e": 1353, "s": 1166, "text": "referrerpolicy: It is used to specify which referrer information to use when fetching an image i.e. no-referrer, no-referrer-when-downgrade, origin, origin-when-cross-origin, unsafe-url." }, { "code": null, "e": 1422, "s": 1353, "text": "sizes: It is used to specify image sizes for different page layouts." }, { "code": null, "e": 1506, "s": 1422, "text": "srcset: It is used to specify a list of image files to use in different situations." }, { "code": null, "e": 1573, "s": 1506, "text": "usemap: It is used to specify an image as a client-side image map." }, { "code": null, "e": 1680, "s": 1575, "text": "Example 1: In this example we are using the <img> tag along with src, width, height, and alt attributes." }, { "code": null, "e": 1687, "s": 1682, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body style=\"text-align: center;\"> <h3>GeeksforGeeks logo</h3> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-13.png\" width=\"420\" height=\"100\" alt=\"Geeksforgeeks.org\"></body> </html>", "e": 1949, "s": 1687, "text": null }, { "code": null, "e": 1957, "s": 1949, "text": "Output:" }, { "code": null, "e": 1987, "s": 1957, "text": "img src with width and height" }, { "code": null, "e": 2079, "s": 1987, "text": "Example 2: In this example, we are adding the style attribute to add a border to the image." }, { "code": null, "e": 2084, "s": 2079, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body style=\"text-align: center;\"> <h3>GeeksforGeeks logo</h3> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-13.png\" width=\"420\" height=\"100\" alt=\"Geeksforgeeks.org\" style=\"border:5px solid black\"></body> </html>", "e": 2381, "s": 2084, "text": null }, { "code": null, "e": 2389, "s": 2381, "text": "Output:" }, { "code": null, "e": 2414, "s": 2389, "text": "image source with border" }, { "code": null, "e": 2435, "s": 2414, "text": "Supported Browsers: " }, { "code": null, "e": 2449, "s": 2435, "text": "Google Chrome" }, { "code": null, "e": 2467, "s": 2449, "text": "Internet Explorer" }, { "code": null, "e": 2474, "s": 2467, "text": "Safari" }, { "code": null, "e": 2480, "s": 2474, "text": "Opera" }, { "code": null, "e": 2488, "s": 2480, "text": "firefox" }, { "code": null, "e": 2508, "s": 2488, "text": "hritikbhatnagar2182" }, { "code": null, "e": 2524, "s": 2508, "text": "HTML-Attributes" }, { "code": null, "e": 2534, "s": 2524, "text": "HTML-Tags" }, { "code": null, "e": 2541, "s": 2534, "text": "Picked" }, { "code": null, "e": 2546, "s": 2541, "text": "HTML" }, { "code": null, "e": 2563, "s": 2546, "text": "Web Technologies" }, { "code": null, "e": 2568, "s": 2563, "text": "HTML" } ]
UGC-NET | UGC NET CS 2017 Jan – II | Question 1
26 Mar, 2018 Consider a sequence F00 defined as :F00(0) = 1, F00(1) = 1F00(n) = 10 ∗ F00(n – 1) + 100F00(n – 2) for n ≥ 2Then what shall be the set of values of the sequence F00 ?(A) (1, 110, 1200)(B) (1, 110, 600, 1200)(C) (1, 2, 55, 110, 600, 1200)(D) (1, 55, 110, 600, 1200)Answer: (A)Explanation: F00(0) = 1, F00(1) = 1 F00(n) = 10 ∗ F00(n – 1) + 100 F00(2) = 10 * F00(1) + 100 = 10 * 1 + 100 = 10 + 100 = 110 Similarly: F00(3) = 10 * F00(2) + 100 = 10 * 110 + 100 = 1100 + 100 = 1200 The sequence will be (1, 110, 1200). So, (A) will be the answer.Quiz of this Question UGC-NET Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. UGC-NET | UGC NET CS 2018 July - II | Question 23 UGC-NET | UGC NET CS 2015 Jun - III | Question 35 UGC-NET | UGC NET CS 2015 Jun - III | Question 32 UGC-NET | UGC NET CS 2015 Jun - III | Question 33 UGC-NET | UGC NET CS 2016 Aug - III | Question 32 UGC-NET | UGC NET CS 2015 Jun - III | Question 64 UGC-NET | UGC NET CS 2015 Dec - II | Question 16 UGC-NET | UGC NET CS 2016 July – II | Question 22 UGC-NET | UGC NET CS 2014 Dec - II | Question 35 UGC-NET | UGC NET CS 2015 Jun - III | Question 31
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2018" }, { "code": null, "e": 316, "s": 28, "text": "Consider a sequence F00 defined as :F00(0) = 1, F00(1) = 1F00(n) = 10 ∗ F00(n – 1) + 100F00(n – 2) for n ≥ 2Then what shall be the set of values of the sequence F00 ?(A) (1, 110, 1200)(B) (1, 110, 600, 1200)(C) (1, 2, 55, 110, 600, 1200)(D) (1, 55, 110, 600, 1200)Answer: (A)Explanation:" }, { "code": null, "e": 550, "s": 316, "text": " F00(0) = 1, F00(1) = 1\n F00(n) = 10 ∗ F00(n – 1) + 100\n F00(2) = 10 * F00(1) + 100\n = 10 * 1 + 100\n = 10 + 100\n = 110\nSimilarly:\nF00(3) = 10 * F00(2) + 100\n = 10 * 110 + 100\n = 1100 + 100\n = 1200\nThe sequence will be (1, 110, 1200)." }, { "code": null, "e": 599, "s": 550, "text": "So, (A) will be the answer.Quiz of this Question" }, { "code": null, "e": 607, "s": 599, "text": "UGC-NET" }, { "code": null, "e": 705, "s": 607, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 755, "s": 705, "text": "UGC-NET | UGC NET CS 2018 July - II | Question 23" }, { "code": null, "e": 805, "s": 755, "text": "UGC-NET | UGC NET CS 2015 Jun - III | Question 35" }, { "code": null, "e": 855, "s": 805, "text": "UGC-NET | UGC NET CS 2015 Jun - III | Question 32" }, { "code": null, "e": 905, "s": 855, "text": "UGC-NET | UGC NET CS 2015 Jun - III | Question 33" }, { "code": null, "e": 955, "s": 905, "text": "UGC-NET | UGC NET CS 2016 Aug - III | Question 32" }, { "code": null, "e": 1005, "s": 955, "text": "UGC-NET | UGC NET CS 2015 Jun - III | Question 64" }, { "code": null, "e": 1054, "s": 1005, "text": "UGC-NET | UGC NET CS 2015 Dec - II | Question 16" }, { "code": null, "e": 1104, "s": 1054, "text": "UGC-NET | UGC NET CS 2016 July – II | Question 22" }, { "code": null, "e": 1153, "s": 1104, "text": "UGC-NET | UGC NET CS 2014 Dec - II | Question 35" } ]
JavaScript | Redirect a URL
19 Feb, 2019 Prerequisites: Learn Basic HTML Learn Basic Javascript Redirecting a URL in JavaScript is nothing but sending the user from a URL to another URL. In Javascript, window.location function is used to redirect to a URL. <!DOCTYPE html><html><head> <title>Redirect url in Javascript</title></head><body><script> var url= "https://www.geeksforgeeks.org"; window.location = url;</script></body></html> Output: Code #2:Below code takes an input url from the user and the url is stored in a variable through getElementById() and window.location takes the page to that url. <!DOCTYPE html><html><head> <title>Redirect url in Javascript</title></head><body><input id = "url" type = "text" name = "url" placeholder = "Enter a url here"><input type = "submit" name = "button" onclick = "fun()"><script>function fun() { var url= document.getElementById("url").value; document.write("Redirecting to the url in 3 seconds..."); setTimeout(function(){window.location = url;}, 3000);}</script></body></html> Output:At first this will be the output, and then if the link like (https://www.geeksforgeeks.org/) is put inside the box, it will redirect to the home page of the GeeksforGeeks and will be shown like below. Steps for executing above codes: Save these files with .html extension as file_name.html Then open the files in a browser, it will get redirect to the GeeksforGeeks homepage. JavaScript-Misc HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Feb, 2019" }, { "code": null, "e": 69, "s": 54, "text": "Prerequisites:" }, { "code": null, "e": 86, "s": 69, "text": "Learn Basic HTML" }, { "code": null, "e": 109, "s": 86, "text": "Learn Basic Javascript" }, { "code": null, "e": 270, "s": 109, "text": "Redirecting a URL in JavaScript is nothing but sending the user from a URL to another URL. In Javascript, window.location function is used to redirect to a URL." }, { "code": "<!DOCTYPE html><html><head> <title>Redirect url in Javascript</title></head><body><script> var url= \"https://www.geeksforgeeks.org\"; window.location = url;</script></body></html>", "e": 458, "s": 270, "text": null }, { "code": null, "e": 466, "s": 458, "text": "Output:" }, { "code": null, "e": 627, "s": 466, "text": "Code #2:Below code takes an input url from the user and the url is stored in a variable through getElementById() and window.location takes the page to that url." }, { "code": "<!DOCTYPE html><html><head> <title>Redirect url in Javascript</title></head><body><input id = \"url\" type = \"text\" name = \"url\" placeholder = \"Enter a url here\"><input type = \"submit\" name = \"button\" onclick = \"fun()\"><script>function fun() { var url= document.getElementById(\"url\").value; document.write(\"Redirecting to the url in 3 seconds...\"); setTimeout(function(){window.location = url;}, 3000);}</script></body></html>", "e": 1088, "s": 627, "text": null }, { "code": null, "e": 1296, "s": 1088, "text": "Output:At first this will be the output, and then if the link like (https://www.geeksforgeeks.org/) is put inside the box, it will redirect to the home page of the GeeksforGeeks and will be shown like below." }, { "code": null, "e": 1329, "s": 1296, "text": "Steps for executing above codes:" }, { "code": null, "e": 1385, "s": 1329, "text": "Save these files with .html extension as file_name.html" }, { "code": null, "e": 1471, "s": 1385, "text": "Then open the files in a browser, it will get redirect to the GeeksforGeeks homepage." }, { "code": null, "e": 1487, "s": 1471, "text": "JavaScript-Misc" }, { "code": null, "e": 1492, "s": 1487, "text": "HTML" }, { "code": null, "e": 1503, "s": 1492, "text": "JavaScript" }, { "code": null, "e": 1520, "s": 1503, "text": "Web Technologies" }, { "code": null, "e": 1525, "s": 1520, "text": "HTML" } ]
Minimum inversions required so that no two adjacent elements are same
01 Mar, 2022 Given a binary array arr[] of size N. The task is to find the minimum number of inversions required so that no two adjacent elements are same. After a single inversion, an element could change from 0 to 1 or from 1 to 0.Examples: Input: arr[] = {1, 1, 1} Output: 1 Change arr[1] from 1 to 0 and the array becomes {1, 0, 1}.Input: arr[] = {1, 0, 0, 1, 0, 0, 1, 0} Output: 3 Approach: There are only two possibilities to make the array {1, 0, 1, 0, 1, 0, 1, ...} or {0, 1, 0, 1, 0, 1, 0, ...}. Let ans_a and ans_b be the count of changes required to get these arrays respectively. Now, the final answer will be min(ans_a, ans_b).Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum// inversions required so that no// two adjacent elements are sameint min_changes(int a[], int n){ // To store the inversions required // to make the array {1, 0, 1, 0, 1, 0, 1, ...} // and {0, 1, 0, 1, 0, 1, 0, ...} respectively int ans_a = 0, ans_b = 0; // Find all the changes required for (int i = 0; i < n; i++) { if (i % 2 == 0) { if (a[i] == 0) ans_a++; else ans_b++; } else { if (a[i] == 0) ans_b++; else ans_a++; } } // Return the required answer return min(ans_a, ans_b);} // Driver codeint main(){ int a[] = { 1, 0, 0, 1, 0, 0, 1, 0 }; int n = sizeof(a) / sizeof(a[0]); cout << min_changes(a, n); return 0;} // Java implementation of the approachclass GFG{ // Function to return the minimum// inversions required so that no// two adjacent elements are samestatic int min_changes(int a[], int n){ // To store the inversions required // to make the array {1, 0, 1, 0, 1, 0, 1, ...} // and {0, 1, 0, 1, 0, 1, 0, ...} respectively int ans_a = 0, ans_b = 0; // Find all the changes required for (int i = 0; i < n; i++) { if (i % 2 == 0) { if (a[i] == 0) ans_a++; else ans_b++; } else { if (a[i] == 0) ans_b++; else ans_a++; } } // Return the required answer return Math.min(ans_a, ans_b);} // Driver codepublic static void main(String[] args){ int a[] = { 1, 0, 0, 1, 0, 0, 1, 0 }; int n = a.length; System.out.println(min_changes(a, n));}} // This code is contributed by Rajput-Ji # Python3 implementation of the approach # Function to return the minimum# inversions required so that no# two adjacent elements are samedef min_changes(a, n): # To store the inversions required # to make the array {1, 0, 1, 0, 1, 0, 1, ...} # and {0, 1, 0, 1, 0, 1, 0, ...} respectively ans_a = 0; ans_b = 0; # Find all the changes required for i in range(n): if (i % 2 == 0): if (a[i] == 0): ans_a += 1; else: ans_b += 1; else: if (a[i] == 0): ans_b += 1; else: ans_a += 1; # Return the required answer return min(ans_a, ans_b); # Driver codeif __name__ == '__main__': a = [ 1, 0, 0, 1, 0, 0, 1, 0 ]; n = len(a); print(min_changes(a, n)); # This code is contributed by Rajput-Ji // C# implementation of the approachusing System; class GFG{ // Function to return the minimum// inversions required so that no// two adjacent elements are samestatic int min_changes(int []a, int n){ // To store the inversions required // to make the array {1, 0, 1, 0, 1, 0, 1, ...} // and {0, 1, 0, 1, 0, 1, 0, ...} respectively int ans_a = 0, ans_b = 0; // Find all the changes required for (int i = 0; i < n; i++) { if (i % 2 == 0) { if (a[i] == 0) ans_a++; else ans_b++; } else { if (a[i] == 0) ans_b++; else ans_a++; } } // Return the required answer return Math.Min(ans_a, ans_b);} // Driver codepublic static void Main(String[] args){ int []a = { 1, 0, 0, 1, 0, 0, 1, 0 }; int n = a.Length; Console.WriteLine(min_changes(a, n));}} // This code is contributed by Rajput-Ji <script> // JavaScript implementation of the approach // Function to return the minimum// inversions required so that no// two adjacent elements are samefunction min_changes(a, n) { // To store the inversions required // to make the array {1, 0, 1, 0, 1, 0, 1, ...} // and {0, 1, 0, 1, 0, 1, 0, ...} respectively let ans_a = 0, ans_b = 0; // Find all the changes required for (let i = 0; i < n; i++) { if (i % 2 == 0) { if (a[i] == 0) ans_a++; else ans_b++; } else { if (a[i] == 0) ans_b++; else ans_a++; } } // Return the required answer return Math.min(ans_a, ans_b);} // Driver codelet a = [1, 0, 0, 1, 0, 0, 1, 0];let n = a.length; document.write(min_changes(a, n)); </script> 3 Time Complexity: O(n) Auxiliary Space: O(1) Rajput-Ji gfgking subham348 Constructive Algorithms Arrays Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Mar, 2022" }, { "code": null, "e": 286, "s": 54, "text": "Given a binary array arr[] of size N. The task is to find the minimum number of inversions required so that no two adjacent elements are same. After a single inversion, an element could change from 0 to 1 or from 1 to 0.Examples: " }, { "code": null, "e": 431, "s": 286, "text": "Input: arr[] = {1, 1, 1} Output: 1 Change arr[1] from 1 to 0 and the array becomes {1, 0, 1}.Input: arr[] = {1, 0, 0, 1, 0, 0, 1, 0} Output: 3 " }, { "code": null, "e": 740, "s": 433, "text": "Approach: There are only two possibilities to make the array {1, 0, 1, 0, 1, 0, 1, ...} or {0, 1, 0, 1, 0, 1, 0, ...}. Let ans_a and ans_b be the count of changes required to get these arrays respectively. Now, the final answer will be min(ans_a, ans_b).Below is the implementation of the above approach: " }, { "code": null, "e": 744, "s": 740, "text": "C++" }, { "code": null, "e": 749, "s": 744, "text": "Java" }, { "code": null, "e": 757, "s": 749, "text": "Python3" }, { "code": null, "e": 760, "s": 757, "text": "C#" }, { "code": null, "e": 771, "s": 760, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum// inversions required so that no// two adjacent elements are sameint min_changes(int a[], int n){ // To store the inversions required // to make the array {1, 0, 1, 0, 1, 0, 1, ...} // and {0, 1, 0, 1, 0, 1, 0, ...} respectively int ans_a = 0, ans_b = 0; // Find all the changes required for (int i = 0; i < n; i++) { if (i % 2 == 0) { if (a[i] == 0) ans_a++; else ans_b++; } else { if (a[i] == 0) ans_b++; else ans_a++; } } // Return the required answer return min(ans_a, ans_b);} // Driver codeint main(){ int a[] = { 1, 0, 0, 1, 0, 0, 1, 0 }; int n = sizeof(a) / sizeof(a[0]); cout << min_changes(a, n); return 0;}", "e": 1680, "s": 771, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the minimum// inversions required so that no// two adjacent elements are samestatic int min_changes(int a[], int n){ // To store the inversions required // to make the array {1, 0, 1, 0, 1, 0, 1, ...} // and {0, 1, 0, 1, 0, 1, 0, ...} respectively int ans_a = 0, ans_b = 0; // Find all the changes required for (int i = 0; i < n; i++) { if (i % 2 == 0) { if (a[i] == 0) ans_a++; else ans_b++; } else { if (a[i] == 0) ans_b++; else ans_a++; } } // Return the required answer return Math.min(ans_a, ans_b);} // Driver codepublic static void main(String[] args){ int a[] = { 1, 0, 0, 1, 0, 0, 1, 0 }; int n = a.length; System.out.println(min_changes(a, n));}} // This code is contributed by Rajput-Ji", "e": 2637, "s": 1680, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the minimum# inversions required so that no# two adjacent elements are samedef min_changes(a, n): # To store the inversions required # to make the array {1, 0, 1, 0, 1, 0, 1, ...} # and {0, 1, 0, 1, 0, 1, 0, ...} respectively ans_a = 0; ans_b = 0; # Find all the changes required for i in range(n): if (i % 2 == 0): if (a[i] == 0): ans_a += 1; else: ans_b += 1; else: if (a[i] == 0): ans_b += 1; else: ans_a += 1; # Return the required answer return min(ans_a, ans_b); # Driver codeif __name__ == '__main__': a = [ 1, 0, 0, 1, 0, 0, 1, 0 ]; n = len(a); print(min_changes(a, n)); # This code is contributed by Rajput-Ji", "e": 3478, "s": 2637, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the minimum// inversions required so that no// two adjacent elements are samestatic int min_changes(int []a, int n){ // To store the inversions required // to make the array {1, 0, 1, 0, 1, 0, 1, ...} // and {0, 1, 0, 1, 0, 1, 0, ...} respectively int ans_a = 0, ans_b = 0; // Find all the changes required for (int i = 0; i < n; i++) { if (i % 2 == 0) { if (a[i] == 0) ans_a++; else ans_b++; } else { if (a[i] == 0) ans_b++; else ans_a++; } } // Return the required answer return Math.Min(ans_a, ans_b);} // Driver codepublic static void Main(String[] args){ int []a = { 1, 0, 0, 1, 0, 0, 1, 0 }; int n = a.Length; Console.WriteLine(min_changes(a, n));}} // This code is contributed by Rajput-Ji", "e": 4446, "s": 3478, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to return the minimum// inversions required so that no// two adjacent elements are samefunction min_changes(a, n) { // To store the inversions required // to make the array {1, 0, 1, 0, 1, 0, 1, ...} // and {0, 1, 0, 1, 0, 1, 0, ...} respectively let ans_a = 0, ans_b = 0; // Find all the changes required for (let i = 0; i < n; i++) { if (i % 2 == 0) { if (a[i] == 0) ans_a++; else ans_b++; } else { if (a[i] == 0) ans_b++; else ans_a++; } } // Return the required answer return Math.min(ans_a, ans_b);} // Driver codelet a = [1, 0, 0, 1, 0, 0, 1, 0];let n = a.length; document.write(min_changes(a, n)); </script>", "e": 5288, "s": 4446, "text": null }, { "code": null, "e": 5290, "s": 5288, "text": "3" }, { "code": null, "e": 5314, "s": 5292, "text": "Time Complexity: O(n)" }, { "code": null, "e": 5336, "s": 5314, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 5346, "s": 5336, "text": "Rajput-Ji" }, { "code": null, "e": 5354, "s": 5346, "text": "gfgking" }, { "code": null, "e": 5364, "s": 5354, "text": "subham348" }, { "code": null, "e": 5388, "s": 5364, "text": "Constructive Algorithms" }, { "code": null, "e": 5395, "s": 5388, "text": "Arrays" }, { "code": null, "e": 5408, "s": 5395, "text": "Mathematical" }, { "code": null, "e": 5415, "s": 5408, "text": "Arrays" }, { "code": null, "e": 5428, "s": 5415, "text": "Mathematical" } ]
Time Functions in Python | Set-2 (Date Manipulations)
11 May, 2017 Some of Time Functions are discussed in Set 1 Date manipulation can also be performed using Python using “datetime” module and using “date” class in it. Operations on Date : 1. MINYEAR :- It displays the minimum year that can be represented using date class. 2. MAXYEAR :- It displays the maximum year that can be represented using date class. # Python code to demonstrate the working of# MINYEAR and MAXYEAR # importing built in module datetimeimport datetimefrom datetime import date # using MINYEAR to print minimum representable yearprint ("Minimum representable year is : ",end="")print (datetime.MINYEAR) # using MAXYEAR to print maximum representable yearprint ("Maximum representable year is : ",end="")print (datetime.MAXYEAR) Output: Minimum representable year is : 1 Maximum representable year is : 9999 3. date(yyyy-mm-dd) :- This function returns a string with passed arguments in order of year, months and date. 4. today() :- Returns the date of present day in the format yyyy-mm-dd. # Python code to demonstrate the working of# date() and today() # importing built in module datetimeimport datetimefrom datetime import date # using date() to represent dateprint ("The represented date is : ",end="")print (datetime.date(1997,4,1)) # using today() to print present dateprint ("Present date is : ",end="")print (date.today()) Output: The represented date is : 1997-04-01 Present date is : 2016-08-02 5. fromtimestamp(sec) :- It returns the date calculated from the seconds elapsed since epoch mentioned in arguments. 6. min() :- This returns the minimum date that can be represented by date class. 7. max() :- This returns the maximum date that can be represented by date class. # Python code to demonstrate the working of# fromtimestamp(), min() and max() # importing built in module datetimeimport datetimefrom datetime import date # using fromtimestamp() to calculate dateprint ("The calculated date from seconds is : ",end="")print (date.fromtimestamp(3452435)) # using min() to print minimum representable dateprint ("Minimum representable date is : ",end="")print (date.min) # using max() to print minimum representable dateprint ("Maximum representable date is : ",end="")print (date.max) Output: The calculated date from seconds is : 1970-02-09 Minimum representable date is : 0001-01-01 Maximum representable date is : 9999-12-31 This article is contributed by Manjeet Singh. 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. date-time-program Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n11 May, 2017" }, { "code": null, "e": 98, "s": 52, "text": "Some of Time Functions are discussed in Set 1" }, { "code": null, "e": 205, "s": 98, "text": "Date manipulation can also be performed using Python using “datetime” module and using “date” class in it." }, { "code": null, "e": 226, "s": 205, "text": "Operations on Date :" }, { "code": null, "e": 311, "s": 226, "text": "1. MINYEAR :- It displays the minimum year that can be represented using date class." }, { "code": null, "e": 396, "s": 311, "text": "2. MAXYEAR :- It displays the maximum year that can be represented using date class." }, { "code": "# Python code to demonstrate the working of# MINYEAR and MAXYEAR # importing built in module datetimeimport datetimefrom datetime import date # using MINYEAR to print minimum representable yearprint (\"Minimum representable year is : \",end=\"\")print (datetime.MINYEAR) # using MAXYEAR to print maximum representable yearprint (\"Maximum representable year is : \",end=\"\")print (datetime.MAXYEAR)", "e": 791, "s": 396, "text": null }, { "code": null, "e": 799, "s": 791, "text": "Output:" }, { "code": null, "e": 871, "s": 799, "text": "Minimum representable year is : 1\nMaximum representable year is : 9999\n" }, { "code": null, "e": 982, "s": 871, "text": "3. date(yyyy-mm-dd) :- This function returns a string with passed arguments in order of year, months and date." }, { "code": null, "e": 1054, "s": 982, "text": "4. today() :- Returns the date of present day in the format yyyy-mm-dd." }, { "code": "# Python code to demonstrate the working of# date() and today() # importing built in module datetimeimport datetimefrom datetime import date # using date() to represent dateprint (\"The represented date is : \",end=\"\")print (datetime.date(1997,4,1)) # using today() to print present dateprint (\"Present date is : \",end=\"\")print (date.today())", "e": 1398, "s": 1054, "text": null }, { "code": null, "e": 1406, "s": 1398, "text": "Output:" }, { "code": null, "e": 1473, "s": 1406, "text": "The represented date is : 1997-04-01\nPresent date is : 2016-08-02\n" }, { "code": null, "e": 1590, "s": 1473, "text": "5. fromtimestamp(sec) :- It returns the date calculated from the seconds elapsed since epoch mentioned in arguments." }, { "code": null, "e": 1671, "s": 1590, "text": "6. min() :- This returns the minimum date that can be represented by date class." }, { "code": null, "e": 1752, "s": 1671, "text": "7. max() :- This returns the maximum date that can be represented by date class." }, { "code": "# Python code to demonstrate the working of# fromtimestamp(), min() and max() # importing built in module datetimeimport datetimefrom datetime import date # using fromtimestamp() to calculate dateprint (\"The calculated date from seconds is : \",end=\"\")print (date.fromtimestamp(3452435)) # using min() to print minimum representable dateprint (\"Minimum representable date is : \",end=\"\")print (date.min) # using max() to print minimum representable dateprint (\"Maximum representable date is : \",end=\"\")print (date.max)", "e": 2273, "s": 1752, "text": null }, { "code": null, "e": 2281, "s": 2273, "text": "Output:" }, { "code": null, "e": 2417, "s": 2281, "text": "The calculated date from seconds is : 1970-02-09\nMinimum representable date is : 0001-01-01\nMaximum representable date is : 9999-12-31\n" }, { "code": null, "e": 2718, "s": 2417, "text": "This article is contributed by Manjeet Singh. 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": 2843, "s": 2718, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2861, "s": 2843, "text": "date-time-program" }, { "code": null, "e": 2868, "s": 2861, "text": "Python" }, { "code": null, "e": 2966, "s": 2868, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2984, "s": 2966, "text": "Python Dictionary" }, { "code": null, "e": 3026, "s": 2984, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3048, "s": 3026, "text": "Enumerate() in Python" }, { "code": null, "e": 3083, "s": 3048, "text": "Read a file line by line in Python" }, { "code": null, "e": 3115, "s": 3083, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3144, "s": 3115, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3171, "s": 3144, "text": "Python Classes and Objects" }, { "code": null, "e": 3201, "s": 3171, "text": "Iterate over a list in Python" }, { "code": null, "e": 3222, "s": 3201, "text": "Python OOPs Concepts" } ]
Find the Sum of the series 1 + 1/3 + 1/5 + 1/7 + ... till N terms
25 Nov, 2021 Given a number N, the task is to find the sum of the below series till N terms. Examples: Input: N = 10 Output: 2.133256 Explanation: The sum of series 1 + 1/3 + 1/5 + 1/7 + 1/9 + 1/11 is 2.133256.Input: N = 20 Output: 2.479674 Explanation: The sum of series 1 + 1/3 + 1/5 + 1/7 + ... + 1/41 is 2.479674. Approach: From the given series, find the formula for Nth term: 1st term = 1 2nd term = 1/3 3rd term = 1/5 4th term = 1/7 . . Nthe term = 1 / (2 * N - 1)) Therefore: Nth term of the series *** QuickLaTeX cannot compile formula: *** Error message: Error: Nothing to show, formula is empty Then iterate over numbers in the range [1, N] to find all the terms using the above formula and compute their sum.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the sum of the// series 1 + 1/3 + 1/5 + ... #include <iostream>using namespace std; // Function to find the sum of the// given seriesvoid printSumSeries(int N){ // Initialise the sum to 0 float sum = 0; for (int i = 1; i <= N; i++) { // Generate the ith term and // add it to the sum sum += 1.0 / (2 * i - 1); } // Print the final sum cout << sum << endl;} // Driver Codeint main(){ int N = 6; printSumSeries(N); return 0;} // Java program to find the sum of the// series 1 + 1/3 + 1/5 + ...class GFG { // Function to find the sum of the // given series static void printSumSeries(int N) { // Initialise the sum to 0 float sum = 0; for (int i = 1; i <= N; i++) { // Generate the ith term and // add it to the sum sum += 1.0 / (2 * i - 1); } // Print the final sum System.out.println(sum); } // Driver Code public static void main (String[] args) { int N = 6; printSumSeries(N); } } // This code is contributed by AnkitRai01 # Python3 program to find the sum of the# series 1 + 1/3 + 1/5 + ... # Function to find the sum of the# given seriesdef printSumSeries(N) : # Initialise the sum to 0 sum = 0; for i in range(1, N + 1) : # Generate the ith term and # add it to the sum sum += 1.0 / (2 * i - 1); # Print the final sum print(sum); # Driver Codeif __name__ == "__main__" : N = 6; printSumSeries(N); # This code is contributed by AnkitRai01 // C# program to find the sum of the// series 1 + 1/3 + 1/5 + ...using System; class GFG { // Function to find the sum of the // given series static void printSumSeries(int N) { // Initialise the sum to 0 float sum = 0; for (int i = 1; i <= N; i++) { // Generate the ith term and // add it to the sum sum += (float)1.0 / (2 * i - 1); } // Print the final sum Console.WriteLine(sum); } // Driver Code public static void Main (string[] args) { int N = 6; printSumSeries(N); } } // This code is contributed by AnkitRai01 <script> // javascript program to find the sum of the// series 1 + 1/3 + 1/5 + ... // Function to find the sum of the// given seriesfunction printSumSeries( N){ // Initialise the sum to 0 let sum = 0; for (let i = 1; i <= N; i++) { // Generate the ith term and // add it to the sum sum += 1.0 / (2 * i - 1); } // Print the final sum document.write(sum.toFixed(5));} // Driver Code let N = 6; printSumSeries(N); // This code is contributed by todaysgaurav </script> 1.87821 Time Complexity: O(N) Auxiliary Space: O(1) ankthon todaysgaurav sooda367 souravmahato348 series-sum Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Merge two sorted arrays with O(1) extra space Segment Tree | Set 1 (Sum of given range) Fizz Buzz Implementation Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Nov, 2021" }, { "code": null, "e": 133, "s": 52, "text": "Given a number N, the task is to find the sum of the below series till N terms. " }, { "code": null, "e": 145, "s": 133, "text": "Examples: " }, { "code": null, "e": 362, "s": 145, "text": "Input: N = 10 Output: 2.133256 Explanation: The sum of series 1 + 1/3 + 1/5 + 1/7 + 1/9 + 1/11 is 2.133256.Input: N = 20 Output: 2.479674 Explanation: The sum of series 1 + 1/3 + 1/5 + 1/7 + ... + 1/41 is 2.479674. " }, { "code": null, "e": 430, "s": 364, "text": "Approach: From the given series, find the formula for Nth term: " }, { "code": null, "e": 521, "s": 430, "text": "1st term = 1\n2nd term = 1/3\n3rd term = 1/5\n4th term = 1/7\n.\n.\nNthe term = 1 / (2 * N - 1))" }, { "code": null, "e": 534, "s": 521, "text": "Therefore: " }, { "code": null, "e": 558, "s": 534, "text": "Nth term of the series " }, { "code": null, "e": 661, "s": 558, "text": "*** QuickLaTeX cannot compile formula:\n \n\n*** Error message:\nError: Nothing to show, formula is empty\n" }, { "code": null, "e": 828, "s": 661, "text": "Then iterate over numbers in the range [1, N] to find all the terms using the above formula and compute their sum.Below is the implementation of the above approach: " }, { "code": null, "e": 832, "s": 828, "text": "C++" }, { "code": null, "e": 837, "s": 832, "text": "Java" }, { "code": null, "e": 845, "s": 837, "text": "Python3" }, { "code": null, "e": 848, "s": 845, "text": "C#" }, { "code": null, "e": 859, "s": 848, "text": "Javascript" }, { "code": "// C++ program to find the sum of the// series 1 + 1/3 + 1/5 + ... #include <iostream>using namespace std; // Function to find the sum of the// given seriesvoid printSumSeries(int N){ // Initialise the sum to 0 float sum = 0; for (int i = 1; i <= N; i++) { // Generate the ith term and // add it to the sum sum += 1.0 / (2 * i - 1); } // Print the final sum cout << sum << endl;} // Driver Codeint main(){ int N = 6; printSumSeries(N); return 0;}", "e": 1358, "s": 859, "text": null }, { "code": "// Java program to find the sum of the// series 1 + 1/3 + 1/5 + ...class GFG { // Function to find the sum of the // given series static void printSumSeries(int N) { // Initialise the sum to 0 float sum = 0; for (int i = 1; i <= N; i++) { // Generate the ith term and // add it to the sum sum += 1.0 / (2 * i - 1); } // Print the final sum System.out.println(sum); } // Driver Code public static void main (String[] args) { int N = 6; printSumSeries(N); } } // This code is contributed by AnkitRai01", "e": 2009, "s": 1358, "text": null }, { "code": "# Python3 program to find the sum of the# series 1 + 1/3 + 1/5 + ... # Function to find the sum of the# given seriesdef printSumSeries(N) : # Initialise the sum to 0 sum = 0; for i in range(1, N + 1) : # Generate the ith term and # add it to the sum sum += 1.0 / (2 * i - 1); # Print the final sum print(sum); # Driver Codeif __name__ == \"__main__\" : N = 6; printSumSeries(N); # This code is contributed by AnkitRai01", "e": 2475, "s": 2009, "text": null }, { "code": "// C# program to find the sum of the// series 1 + 1/3 + 1/5 + ...using System; class GFG { // Function to find the sum of the // given series static void printSumSeries(int N) { // Initialise the sum to 0 float sum = 0; for (int i = 1; i <= N; i++) { // Generate the ith term and // add it to the sum sum += (float)1.0 / (2 * i - 1); } // Print the final sum Console.WriteLine(sum); } // Driver Code public static void Main (string[] args) { int N = 6; printSumSeries(N); } } // This code is contributed by AnkitRai01", "e": 3141, "s": 2475, "text": null }, { "code": "<script> // javascript program to find the sum of the// series 1 + 1/3 + 1/5 + ... // Function to find the sum of the// given seriesfunction printSumSeries( N){ // Initialise the sum to 0 let sum = 0; for (let i = 1; i <= N; i++) { // Generate the ith term and // add it to the sum sum += 1.0 / (2 * i - 1); } // Print the final sum document.write(sum.toFixed(5));} // Driver Code let N = 6; printSumSeries(N); // This code is contributed by todaysgaurav </script>", "e": 3661, "s": 3141, "text": null }, { "code": null, "e": 3669, "s": 3661, "text": "1.87821" }, { "code": null, "e": 3693, "s": 3671, "text": "Time Complexity: O(N)" }, { "code": null, "e": 3715, "s": 3693, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3723, "s": 3715, "text": "ankthon" }, { "code": null, "e": 3736, "s": 3723, "text": "todaysgaurav" }, { "code": null, "e": 3745, "s": 3736, "text": "sooda367" }, { "code": null, "e": 3761, "s": 3745, "text": "souravmahato348" }, { "code": null, "e": 3772, "s": 3761, "text": "series-sum" }, { "code": null, "e": 3785, "s": 3772, "text": "Mathematical" }, { "code": null, "e": 3804, "s": 3785, "text": "School Programming" }, { "code": null, "e": 3817, "s": 3804, "text": "Mathematical" }, { "code": null, "e": 3915, "s": 3817, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3947, "s": 3915, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 3991, "s": 3947, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 4037, "s": 3991, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 4079, "s": 4037, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 4104, "s": 4079, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 4122, "s": 4104, "text": "Python Dictionary" }, { "code": null, "e": 4147, "s": 4122, "text": "Reverse a string in Java" }, { "code": null, "e": 4163, "s": 4147, "text": "Arrays in C/C++" }, { "code": null, "e": 4186, "s": 4163, "text": "Introduction To PYTHON" } ]
Garbage Collection in JavaScript - GeeksforGeeks
29 Jun, 2020 This article will explain the concept of garbage collection in JavaScript. In order to understand the need of garbage collection, we must first understand Memory Life Cycle Memory Life Cycle: The memory life cycle is pretty much the same for any programming language, it has 3 major steps. Allocate the memory. Use the allocated memory either to read or write or both. Release the allocated memory when it is no longer required. An overview behind garbage collection: The majority of memory management issues occur when we try to release the allocated memory. The main concern that arises is the determination of unused memory resources. In case of the low-level languages where the developer has to manually decide when the memory is no longer needed, high-level languages such as JavaScript use an automated form of memory management known as Garbage Collection(GC). Garbage Collection: The below section will explain the concepts that are necessary to understand the main garbage collection algorithms and their limitations. The main concept of the algorithms designed for garbage collection is the concept of reference. An object can have a reference to another object if the previous object has access to the latter. For example, a JavaScript object can have an implicit reference(when the reference is to its prototypes) and explicit( when the reference is to its properties values).Below we will explain the algorithms used for Garbage Collection. Reference-counting garbage collection: This algorithm is considered to be the most basic kind of garbage collection algorithm. What these algorithms do is that rather than determining whether any resource is important or not it scans the memory to determine if an object has any other objects referring to it. An object with zero references is considered to be garbage or “collectible”.Example:javascriptjavascript// Consider the following example // Declare an objectvar object_1 = { object_2: { object_3: 7 }}; // In this example, create two objects// One object is referred by another // as one of its properties. Currently, // none can be garbage collected // The "object_4" variable is the second// thing that has a reference to the objectvar object_4 = object_1; // The object that was originally in // "object_1" has a unique reference // embodied by the "object_4" variableobject_1 = 1; //Reference to "object_2" property of// the object. This object now has 2 // references: 1 as a property,// The other as the "object_5" variable.var object_5 = object_4.object_2; // The object that was in "object_1" has// now zero references to it. It can be // garbage-collected. However its "object_2"// property is still referenced by the// "object_5" variable, so it cannot be freed.object_4 = "Geeks For Geeks"; // Now the "object_2" property has no // references to it and hence it can// be garbage collected.object_5 = null;Obstructions: Circular referencesLimitations arise when it comes to circular references. A circular reference occurs when two objects are created with properties that refer each other, thus creating a cycle. The reference-counting algorithm fails to reclaim the these memory resources as each object has at least one reference pointing to them which prevents both the objects from being marked for garbage collection. Circular references are one of the major cause for memory leaks.Below example shows an instance of said case.Example:javascriptjavascriptfunction Demo() { var one = {}; var two = {}; // one reference to two one.object = two; // two reference to one two.object = one; return 'circular';} Demo();Mark-and-sweep-algorithm: This algorithm modifies the problem statement from the “object being no longer needed” to the object being “unreachable”. This algorithm demands a prerequisite of the knowledge of roots which are a set of objects. In JavaScript, a root is a global object. On a regular basis, the garbage collector starts from these roots and finds all the objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will find all the objects that are reachable and mark all the non-reachable objects. Cycles are no longer problem: After the function call returns, the two objects are no longer referenced by any resource that is reachable from the root or global object. Hence, these will be marked as unreachable by the garbage collector and have their allocated memory reclaimed. Some Limitations: The only limitation that can be found is that it is not possible to explicitly or programmatically trigger garbage collector in JavaScript.Hence if there are cases when it would be convenient to manually program when to release memory, there are no provisions in JavaScript to trigger such an event. My Personal Notes arrow_drop_upSave Reference-counting garbage collection: This algorithm is considered to be the most basic kind of garbage collection algorithm. What these algorithms do is that rather than determining whether any resource is important or not it scans the memory to determine if an object has any other objects referring to it. An object with zero references is considered to be garbage or “collectible”.Example:javascriptjavascript// Consider the following example // Declare an objectvar object_1 = { object_2: { object_3: 7 }}; // In this example, create two objects// One object is referred by another // as one of its properties. Currently, // none can be garbage collected // The "object_4" variable is the second// thing that has a reference to the objectvar object_4 = object_1; // The object that was originally in // "object_1" has a unique reference // embodied by the "object_4" variableobject_1 = 1; //Reference to "object_2" property of// the object. This object now has 2 // references: 1 as a property,// The other as the "object_5" variable.var object_5 = object_4.object_2; // The object that was in "object_1" has// now zero references to it. It can be // garbage-collected. However its "object_2"// property is still referenced by the// "object_5" variable, so it cannot be freed.object_4 = "Geeks For Geeks"; // Now the "object_2" property has no // references to it and hence it can// be garbage collected.object_5 = null;Obstructions: Circular referencesLimitations arise when it comes to circular references. A circular reference occurs when two objects are created with properties that refer each other, thus creating a cycle. The reference-counting algorithm fails to reclaim the these memory resources as each object has at least one reference pointing to them which prevents both the objects from being marked for garbage collection. Circular references are one of the major cause for memory leaks.Below example shows an instance of said case.Example:javascriptjavascriptfunction Demo() { var one = {}; var two = {}; // one reference to two one.object = two; // two reference to one two.object = one; return 'circular';} Demo(); Reference-counting garbage collection: This algorithm is considered to be the most basic kind of garbage collection algorithm. What these algorithms do is that rather than determining whether any resource is important or not it scans the memory to determine if an object has any other objects referring to it. An object with zero references is considered to be garbage or “collectible”. Example: javascript // Consider the following example // Declare an objectvar object_1 = { object_2: { object_3: 7 }}; // In this example, create two objects// One object is referred by another // as one of its properties. Currently, // none can be garbage collected // The "object_4" variable is the second// thing that has a reference to the objectvar object_4 = object_1; // The object that was originally in // "object_1" has a unique reference // embodied by the "object_4" variableobject_1 = 1; //Reference to "object_2" property of// the object. This object now has 2 // references: 1 as a property,// The other as the "object_5" variable.var object_5 = object_4.object_2; // The object that was in "object_1" has// now zero references to it. It can be // garbage-collected. However its "object_2"// property is still referenced by the// "object_5" variable, so it cannot be freed.object_4 = "Geeks For Geeks"; // Now the "object_2" property has no // references to it and hence it can// be garbage collected.object_5 = null; Limitations arise when it comes to circular references. A circular reference occurs when two objects are created with properties that refer each other, thus creating a cycle. The reference-counting algorithm fails to reclaim the these memory resources as each object has at least one reference pointing to them which prevents both the objects from being marked for garbage collection. Circular references are one of the major cause for memory leaks.Below example shows an instance of said case. Example: javascript function Demo() { var one = {}; var two = {}; // one reference to two one.object = two; // two reference to one two.object = one; return 'circular';} Demo(); Mark-and-sweep-algorithm: This algorithm modifies the problem statement from the “object being no longer needed” to the object being “unreachable”. This algorithm demands a prerequisite of the knowledge of roots which are a set of objects. In JavaScript, a root is a global object. On a regular basis, the garbage collector starts from these roots and finds all the objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will find all the objects that are reachable and mark all the non-reachable objects. Cycles are no longer problem: After the function call returns, the two objects are no longer referenced by any resource that is reachable from the root or global object. Hence, these will be marked as unreachable by the garbage collector and have their allocated memory reclaimed. Some Limitations: The only limitation that can be found is that it is not possible to explicitly or programmatically trigger garbage collector in JavaScript.Hence if there are cases when it would be convenient to manually program when to release memory, there are no provisions in JavaScript to trigger such an event. My Personal Notes arrow_drop_upSave Cycles are no longer problem: After the function call returns, the two objects are no longer referenced by any resource that is reachable from the root or global object. Hence, these will be marked as unreachable by the garbage collector and have their allocated memory reclaimed. Some Limitations: The only limitation that can be found is that it is not possible to explicitly or programmatically trigger garbage collector in JavaScript.Hence if there are cases when it would be convenient to manually program when to release memory, there are no provisions in JavaScript to trigger such an event. javascript-basics JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Roadmap to Become a Web Developer in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Installation of Node.js on Linux
[ { "code": null, "e": 24544, "s": 24516, "text": "\n29 Jun, 2020" }, { "code": null, "e": 24717, "s": 24544, "text": "This article will explain the concept of garbage collection in JavaScript. In order to understand the need of garbage collection, we must first understand Memory Life Cycle" }, { "code": null, "e": 24834, "s": 24717, "text": "Memory Life Cycle: The memory life cycle is pretty much the same for any programming language, it has 3 major steps." }, { "code": null, "e": 24855, "s": 24834, "text": "Allocate the memory." }, { "code": null, "e": 24913, "s": 24855, "text": "Use the allocated memory either to read or write or both." }, { "code": null, "e": 24973, "s": 24913, "text": "Release the allocated memory when it is no longer required." }, { "code": null, "e": 25413, "s": 24973, "text": "An overview behind garbage collection: The majority of memory management issues occur when we try to release the allocated memory. The main concern that arises is the determination of unused memory resources. In case of the low-level languages where the developer has to manually decide when the memory is no longer needed, high-level languages such as JavaScript use an automated form of memory management known as Garbage Collection(GC)." }, { "code": null, "e": 25999, "s": 25413, "text": "Garbage Collection: The below section will explain the concepts that are necessary to understand the main garbage collection algorithms and their limitations. The main concept of the algorithms designed for garbage collection is the concept of reference. An object can have a reference to another object if the previous object has access to the latter. For example, a JavaScript object can have an implicit reference(when the reference is to its prototypes) and explicit( when the reference is to its properties values).Below we will explain the algorithms used for Garbage Collection." }, { "code": null, "e": 29410, "s": 25999, "text": "Reference-counting garbage collection: This algorithm is considered to be the most basic kind of garbage collection algorithm. What these algorithms do is that rather than determining whether any resource is important or not it scans the memory to determine if an object has any other objects referring to it. An object with zero references is considered to be garbage or “collectible”.Example:javascriptjavascript// Consider the following example // Declare an objectvar object_1 = { object_2: { object_3: 7 }}; // In this example, create two objects// One object is referred by another // as one of its properties. Currently, // none can be garbage collected // The \"object_4\" variable is the second// thing that has a reference to the objectvar object_4 = object_1; // The object that was originally in // \"object_1\" has a unique reference // embodied by the \"object_4\" variableobject_1 = 1; //Reference to \"object_2\" property of// the object. This object now has 2 // references: 1 as a property,// The other as the \"object_5\" variable.var object_5 = object_4.object_2; // The object that was in \"object_1\" has// now zero references to it. It can be // garbage-collected. However its \"object_2\"// property is still referenced by the// \"object_5\" variable, so it cannot be freed.object_4 = \"Geeks For Geeks\"; // Now the \"object_2\" property has no // references to it and hence it can// be garbage collected.object_5 = null;Obstructions: Circular referencesLimitations arise when it comes to circular references. A circular reference occurs when two objects are created with properties that refer each other, thus creating a cycle. The reference-counting algorithm fails to reclaim the these memory resources as each object has at least one reference pointing to them which prevents both the objects from being marked for garbage collection. Circular references are one of the major cause for memory leaks.Below example shows an instance of said case.Example:javascriptjavascriptfunction Demo() { var one = {}; var two = {}; // one reference to two one.object = two; // two reference to one two.object = one; return 'circular';} Demo();Mark-and-sweep-algorithm: This algorithm modifies the problem statement from the “object being no longer needed” to the object being “unreachable”. This algorithm demands a prerequisite of the knowledge of roots which are a set of objects. In JavaScript, a root is a global object. On a regular basis, the garbage collector starts from these roots and finds all the objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will find all the objects that are reachable and mark all the non-reachable objects. Cycles are no longer problem: After the function call returns, the two objects are no longer referenced by any resource that is reachable from the root or global object. Hence, these will be marked as unreachable by the garbage collector and have their allocated memory reclaimed. Some Limitations: The only limitation that can be found is that it is not possible to explicitly or programmatically trigger garbage collector in JavaScript.Hence if there are cases when it would be convenient to manually program when to release memory, there are no provisions in JavaScript to trigger such an event. My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 31598, "s": 29410, "text": "Reference-counting garbage collection: This algorithm is considered to be the most basic kind of garbage collection algorithm. What these algorithms do is that rather than determining whether any resource is important or not it scans the memory to determine if an object has any other objects referring to it. An object with zero references is considered to be garbage or “collectible”.Example:javascriptjavascript// Consider the following example // Declare an objectvar object_1 = { object_2: { object_3: 7 }}; // In this example, create two objects// One object is referred by another // as one of its properties. Currently, // none can be garbage collected // The \"object_4\" variable is the second// thing that has a reference to the objectvar object_4 = object_1; // The object that was originally in // \"object_1\" has a unique reference // embodied by the \"object_4\" variableobject_1 = 1; //Reference to \"object_2\" property of// the object. This object now has 2 // references: 1 as a property,// The other as the \"object_5\" variable.var object_5 = object_4.object_2; // The object that was in \"object_1\" has// now zero references to it. It can be // garbage-collected. However its \"object_2\"// property is still referenced by the// \"object_5\" variable, so it cannot be freed.object_4 = \"Geeks For Geeks\"; // Now the \"object_2\" property has no // references to it and hence it can// be garbage collected.object_5 = null;Obstructions: Circular referencesLimitations arise when it comes to circular references. A circular reference occurs when two objects are created with properties that refer each other, thus creating a cycle. The reference-counting algorithm fails to reclaim the these memory resources as each object has at least one reference pointing to them which prevents both the objects from being marked for garbage collection. Circular references are one of the major cause for memory leaks.Below example shows an instance of said case.Example:javascriptjavascriptfunction Demo() { var one = {}; var two = {}; // one reference to two one.object = two; // two reference to one two.object = one; return 'circular';} Demo();" }, { "code": null, "e": 31985, "s": 31598, "text": "Reference-counting garbage collection: This algorithm is considered to be the most basic kind of garbage collection algorithm. What these algorithms do is that rather than determining whether any resource is important or not it scans the memory to determine if an object has any other objects referring to it. An object with zero references is considered to be garbage or “collectible”." }, { "code": null, "e": 31994, "s": 31985, "text": "Example:" }, { "code": null, "e": 32005, "s": 31994, "text": "javascript" }, { "code": "// Consider the following example // Declare an objectvar object_1 = { object_2: { object_3: 7 }}; // In this example, create two objects// One object is referred by another // as one of its properties. Currently, // none can be garbage collected // The \"object_4\" variable is the second// thing that has a reference to the objectvar object_4 = object_1; // The object that was originally in // \"object_1\" has a unique reference // embodied by the \"object_4\" variableobject_1 = 1; //Reference to \"object_2\" property of// the object. This object now has 2 // references: 1 as a property,// The other as the \"object_5\" variable.var object_5 = object_4.object_2; // The object that was in \"object_1\" has// now zero references to it. It can be // garbage-collected. However its \"object_2\"// property is still referenced by the// \"object_5\" variable, so it cannot be freed.object_4 = \"Geeks For Geeks\"; // Now the \"object_2\" property has no // references to it and hence it can// be garbage collected.object_5 = null;", "e": 33039, "s": 32005, "text": null }, { "code": null, "e": 33534, "s": 33039, "text": "Limitations arise when it comes to circular references. A circular reference occurs when two objects are created with properties that refer each other, thus creating a cycle. The reference-counting algorithm fails to reclaim the these memory resources as each object has at least one reference pointing to them which prevents both the objects from being marked for garbage collection. Circular references are one of the major cause for memory leaks.Below example shows an instance of said case." }, { "code": null, "e": 33543, "s": 33534, "text": "Example:" }, { "code": null, "e": 33554, "s": 33543, "text": "javascript" }, { "code": "function Demo() { var one = {}; var two = {}; // one reference to two one.object = two; // two reference to one two.object = one; return 'circular';} Demo();", "e": 33740, "s": 33554, "text": null }, { "code": null, "e": 34964, "s": 33740, "text": "Mark-and-sweep-algorithm: This algorithm modifies the problem statement from the “object being no longer needed” to the object being “unreachable”. This algorithm demands a prerequisite of the knowledge of roots which are a set of objects. In JavaScript, a root is a global object. On a regular basis, the garbage collector starts from these roots and finds all the objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will find all the objects that are reachable and mark all the non-reachable objects. Cycles are no longer problem: After the function call returns, the two objects are no longer referenced by any resource that is reachable from the root or global object. Hence, these will be marked as unreachable by the garbage collector and have their allocated memory reclaimed. Some Limitations: The only limitation that can be found is that it is not possible to explicitly or programmatically trigger garbage collector in JavaScript.Hence if there are cases when it would be convenient to manually program when to release memory, there are no provisions in JavaScript to trigger such an event. My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 35246, "s": 34964, "text": "Cycles are no longer problem: After the function call returns, the two objects are no longer referenced by any resource that is reachable from the root or global object. Hence, these will be marked as unreachable by the garbage collector and have their allocated memory reclaimed. " }, { "code": null, "e": 35565, "s": 35246, "text": "Some Limitations: The only limitation that can be found is that it is not possible to explicitly or programmatically trigger garbage collector in JavaScript.Hence if there are cases when it would be convenient to manually program when to release memory, there are no provisions in JavaScript to trigger such an event. " }, { "code": null, "e": 35583, "s": 35565, "text": "javascript-basics" }, { "code": null, "e": 35594, "s": 35583, "text": "JavaScript" }, { "code": null, "e": 35611, "s": 35594, "text": "Web Technologies" }, { "code": null, "e": 35709, "s": 35611, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35754, "s": 35709, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 35815, "s": 35754, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 35887, "s": 35815, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 35939, "s": 35887, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 35979, "s": 35939, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 36021, "s": 35979, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 36083, "s": 36021, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 36126, "s": 36083, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 36171, "s": 36126, "text": "Convert a string to an integer in JavaScript" } ]
JSP - Lifecycle
In this chapter, we will discuss the lifecycle of JSP. The key to understanding the low-level functionality of JSP is to understand the simple life cycle they follow. A JSP life cycle is defined as the process from its creation till the destruction. This is similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet. The following are the paths followed by a JSP − Compilation Initialization Execution Cleanup The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The four phases have been described below − When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page. The compilation process involves three steps − Parsing the JSP. Turning the JSP into a servlet. Compiling the servlet. When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform JSP-specific initialization, override the jspInit() method − public void jspInit(){ // Initialization code... } Typically, initialization is performed only once and as with the servlet init method, you generally initialize database connections, open files, and create lookup tables in the jspInit method. This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed. Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP. The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows − void _jspService(HttpServletRequest request, HttpServletResponse response) { // Service handling code... } The _jspService() method of a JSP is invoked on request basis. This is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods, i.e, GET, POST, DELETE, etc. The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container. The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when you need to perform any cleanup, such as releasing database connections or closing open files. The jspDestroy() method has the following form − public void jspDestroy() { // Your cleanup code goes here. } 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2406, "s": 2239, "text": "In this chapter, we will discuss the lifecycle of JSP. The key to understanding the low-level functionality of JSP is to understand the simple life cycle they follow." }, { "code": null, "e": 2602, "s": 2406, "text": "A JSP life cycle is defined as the process from its creation till the destruction. This is similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet." }, { "code": null, "e": 2650, "s": 2602, "text": "The following are the paths followed by a JSP −" }, { "code": null, "e": 2662, "s": 2650, "text": "Compilation" }, { "code": null, "e": 2677, "s": 2662, "text": "Initialization" }, { "code": null, "e": 2687, "s": 2677, "text": "Execution" }, { "code": null, "e": 2695, "s": 2687, "text": "Cleanup" }, { "code": null, "e": 2825, "s": 2695, "text": "The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The four phases have been described below −" }, { "code": null, "e": 3060, "s": 2825, "text": "When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page." }, { "code": null, "e": 3107, "s": 3060, "text": "The compilation process involves three steps −" }, { "code": null, "e": 3124, "s": 3107, "text": "Parsing the JSP." }, { "code": null, "e": 3156, "s": 3124, "text": "Turning the JSP into a servlet." }, { "code": null, "e": 3179, "s": 3156, "text": "Compiling the servlet." }, { "code": null, "e": 3355, "s": 3179, "text": "When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform JSP-specific initialization, override the jspInit() method −" }, { "code": null, "e": 3409, "s": 3355, "text": "public void jspInit(){\n // Initialization code...\n}" }, { "code": null, "e": 3602, "s": 3409, "text": "Typically, initialization is performed only once and as with the servlet init method, you generally initialize database connections, open files, and create lookup tables in the jspInit method." }, { "code": null, "e": 3705, "s": 3602, "text": "This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed." }, { "code": null, "e": 3845, "s": 3705, "text": "Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP." }, { "code": null, "e": 3956, "s": 3845, "text": "The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows −" }, { "code": null, "e": 4066, "s": 3956, "text": "void _jspService(HttpServletRequest request, HttpServletResponse response) {\n // Service handling code...\n}" }, { "code": null, "e": 4318, "s": 4066, "text": "The _jspService() method of a JSP is invoked on request basis. This is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods, i.e, GET, POST, DELETE, etc." }, { "code": null, "e": 4426, "s": 4318, "text": "The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container." }, { "code": null, "e": 4628, "s": 4426, "text": "The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when you need to perform any cleanup, such as releasing database connections or closing open files." }, { "code": null, "e": 4677, "s": 4628, "text": "The jspDestroy() method has the following form −" }, { "code": null, "e": 4741, "s": 4677, "text": "public void jspDestroy() {\n // Your cleanup code goes here.\n}" }, { "code": null, "e": 4776, "s": 4741, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 4791, "s": 4776, "text": " Chaand Sheikh" }, { "code": null, "e": 4826, "s": 4791, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 4841, "s": 4826, "text": " Chaand Sheikh" }, { "code": null, "e": 4876, "s": 4841, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4890, "s": 4876, "text": " Karthikeya T" }, { "code": null, "e": 4925, "s": 4890, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4941, "s": 4925, "text": " TELCOMA Global" }, { "code": null, "e": 4974, "s": 4941, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 4990, "s": 4974, "text": " TELCOMA Global" }, { "code": null, "e": 5024, "s": 4990, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 5032, "s": 5024, "text": " Uplatz" }, { "code": null, "e": 5039, "s": 5032, "text": " Print" }, { "code": null, "e": 5050, "s": 5039, "text": " Add Notes" } ]
Tryit Editor v3.6 - Show Python
f = open("D:\\myfiles\welcome.txt", "r")
[]
PHP date_time_set() Function
The date_time_set() function is an alias of the DateTime::setTime() function. Using this, you can (re)set the time of a DateTime object. date_time_set($object, $hours, $minutes, $seconds, $microseconds) object(Mandatory) This is a DateTime object to which you need to set the date. hours(Mandatory) This is an integer value representing the hour of the time to be set. minute(Mandatory) This is an integer value representing the minute of the time to be set. seconds(Optional) This is an integer value representing the seconds of the time to be set. microseconds(Optional) This is an integer value representing the microseconds of the time to be set. PHP date_time_set() function returns the DateTime object with modified (time) value. Incase of failure, this function returns the boolean value false. This function was first introduced in PHP Version 5.2.0 and, works with all the later versions. Following example demonstrates the usage of the date_time_set function − <?php //Creating a date $date = new DateTime(); //Setting the date date_time_set($date, 7, 20, 35); print("Date: ".date_format($date, "Y/m/d H:i:s")); ?> This will produce following result − Date: 2020/05/10 07:20:35 Following example creates a DateTime object and modifies its t using the date_time_set() function. − <?php //Date string $date_string = "25-09-1989 10:42:12"; //Creating a DateTime object $date_time_Obj = date_create($date_string); print("Original Date: ".date_format($date_time_Obj, "Y/m/d H:i:s")); print("\n"); //Setting the date $date = date_time_set($date_time_Obj, 6, 36, 3 ); print("Modified Date: ".date_format($date, "Y/m/d H:i:s")); ?> This will produce following result − Original Date: 1989/09/25 10:42:12 Modified Date: 1989/09/25 06:36:03 While invoking this function if you pass the day and month values exceeding their range, they will be added to their parent values − <?php //Creating a date $date = new DateTime(); //Setting the date date_time_set($date, 24, 15, 36); print("Date: ".date_format($date, "Y/m/d H:i:s")); ?> Since we have set the month value as 15. Three months are added to the appropriate time − Date: 2020/05/11 00:15:36 $dateSrc = '2007-04-19 12:50 GMT'; $dateTime = date_create( $dateSrc);; $retval = date_time_set( $dateTime, 20, 40, 10); echo 'DateTime::format(): '.$dateTime->format('Y:M:D:H:i:s'); echo "\n"; # Using second function. $dateTime = new DateTime($dateSrc); $retval = $dateTime->setTime(20, 56,6); echo 'DateTime::format(): '.$dateTime->format('Y:M:D:H:i:s'); This will produce the following result − DateTime::format(): 2007:Apr:Thu:20:40:10 DateTime::format(): 2007:Apr:Thu:20:56:06 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": 2894, "s": 2757, "text": "The date_time_set() function is an alias of the DateTime::setTime() function. Using this, you can (re)set the time of a DateTime object." }, { "code": null, "e": 2961, "s": 2894, "text": "date_time_set($object, $hours, $minutes, $seconds, $microseconds)\n" }, { "code": null, "e": 2979, "s": 2961, "text": "object(Mandatory)" }, { "code": null, "e": 3040, "s": 2979, "text": "This is a DateTime object to which you need to set the date." }, { "code": null, "e": 3057, "s": 3040, "text": "hours(Mandatory)" }, { "code": null, "e": 3127, "s": 3057, "text": "This is an integer value representing the hour of the time to be set." }, { "code": null, "e": 3145, "s": 3127, "text": "minute(Mandatory)" }, { "code": null, "e": 3217, "s": 3145, "text": "This is an integer value representing the minute of the time to be set." }, { "code": null, "e": 3235, "s": 3217, "text": "seconds(Optional)" }, { "code": null, "e": 3308, "s": 3235, "text": "This is an integer value representing the seconds of the time to be set." }, { "code": null, "e": 3331, "s": 3308, "text": "microseconds(Optional)" }, { "code": null, "e": 3409, "s": 3331, "text": "This is an integer value representing the microseconds of the time to be set." }, { "code": null, "e": 3560, "s": 3409, "text": "PHP date_time_set() function returns the DateTime object with modified (time) value. Incase of failure, this function returns the boolean value false." }, { "code": null, "e": 3656, "s": 3560, "text": "This function was first introduced in PHP Version 5.2.0 and, works with all the later versions." }, { "code": null, "e": 3729, "s": 3656, "text": "Following example demonstrates the usage of the date_time_set function −" }, { "code": null, "e": 3901, "s": 3729, "text": "<?php\n //Creating a date\n $date = new DateTime();\n //Setting the date\n date_time_set($date, 7, 20, 35); \n print(\"Date: \".date_format($date, \"Y/m/d H:i:s\"));\n?>" }, { "code": null, "e": 3938, "s": 3901, "text": "This will produce following result −" }, { "code": null, "e": 3964, "s": 3938, "text": "Date: 2020/05/10 07:20:35" }, { "code": null, "e": 4065, "s": 3964, "text": "Following example creates a DateTime object and modifies its t using the date_time_set() function. −" }, { "code": null, "e": 4440, "s": 4065, "text": "<?php\n //Date string\n $date_string = \"25-09-1989 10:42:12\";\n //Creating a DateTime object\n $date_time_Obj = date_create($date_string);\n print(\"Original Date: \".date_format($date_time_Obj, \"Y/m/d H:i:s\"));\n print(\"\\n\");\n //Setting the date\n $date = date_time_set($date_time_Obj, 6, 36, 3 ); \n print(\"Modified Date: \".date_format($date, \"Y/m/d H:i:s\"));\n?>" }, { "code": null, "e": 4477, "s": 4440, "text": "This will produce following result −" }, { "code": null, "e": 4548, "s": 4477, "text": "Original Date: 1989/09/25 10:42:12\nModified Date: 1989/09/25 06:36:03\n" }, { "code": null, "e": 4681, "s": 4548, "text": "While invoking this function if you pass the day and month values exceeding their range, they will be added to their parent values −" }, { "code": null, "e": 4854, "s": 4681, "text": "<?php\n //Creating a date\n $date = new DateTime();\n //Setting the date\n date_time_set($date, 24, 15, 36); \n print(\"Date: \".date_format($date, \"Y/m/d H:i:s\"));\n?>" }, { "code": null, "e": 4944, "s": 4854, "text": "Since we have set the month value as 15. Three months are added to the appropriate time −" }, { "code": null, "e": 4971, "s": 4944, "text": "Date: 2020/05/11 00:15:36\n" }, { "code": null, "e": 5337, "s": 4971, "text": "$dateSrc = '2007-04-19 12:50 GMT';\n$dateTime = date_create( $dateSrc);;\n$retval = date_time_set( $dateTime, 20, 40, 10);\n \necho 'DateTime::format(): '.$dateTime->format('Y:M:D:H:i:s');\necho \"\\n\";\n\n# Using second function.\n$dateTime = new DateTime($dateSrc);\n$retval = $dateTime->setTime(20, 56,6);\n \necho 'DateTime::format(): '.$dateTime->format('Y:M:D:H:i:s');" }, { "code": null, "e": 5378, "s": 5337, "text": "This will produce the following result −" }, { "code": null, "e": 5463, "s": 5378, "text": "DateTime::format(): 2007:Apr:Thu:20:40:10\nDateTime::format(): 2007:Apr:Thu:20:56:06\n" }, { "code": null, "e": 5496, "s": 5463, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 5512, "s": 5496, "text": " Malhar Lathkar" }, { "code": null, "e": 5545, "s": 5512, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 5556, "s": 5545, "text": " Syed Raza" }, { "code": null, "e": 5591, "s": 5556, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5608, "s": 5591, "text": " Frahaan Hussain" }, { "code": null, "e": 5641, "s": 5608, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 5656, "s": 5641, "text": " Nivedita Jain" }, { "code": null, "e": 5691, "s": 5656, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 5703, "s": 5691, "text": " Azaz Patel" }, { "code": null, "e": 5738, "s": 5703, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5766, "s": 5738, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 5773, "s": 5766, "text": " Print" }, { "code": null, "e": 5784, "s": 5773, "text": " Add Notes" } ]
Let’s build a simple distributed computing system, for modern cloud | by Tharindu Bandara | Towards Data Science
The way of writing software is much different now. Being cloud native is one of the key goals for almost every software system architecture out there. In this article, we will explore how can we build a simple and extensible distributed computing framework, tailored for the modern cloud. We are going to design, build and test a fresh framework from scratch while discussing the key design decisions. This article provides a good guide to understand how distributed systems work, and implementing extensible systems targetting modern cloud infrastructures. At a high level, there are three major components in this system. Client — Actual users or user agents submitting jobsMaster — Accepts jobs from clients, orchestrate the system and get the jobs executed, and finally return expected outcomes to clientsWorker — Accepts a job, execute it, and provide the expected outcomes. Client — Actual users or user agents submitting jobs Master — Accepts jobs from clients, orchestrate the system and get the jobs executed, and finally return expected outcomes to clients Worker — Accepts a job, execute it, and provide the expected outcomes. Altogether clients submit jobs to the master, master schedules and get them executed with the available workers, and finally return job outcome back to the client. We are developing this system for the modern cloud and in a community first approach. Therefore throughout the design, we will keep following three things in our mind. Simple — Simple systems are easy to implement and easy to diagnoseModern — Systems run on the latest infrastructures utilizing the latest technologies are usually much faster, efficient, and obviously up-to date.Extensible — Extensible systems are vital for community as requirements differ from one use-case to other, thus allow developers to avoid implementing the common components, re-use and achieve use-cases with minimum implementation. Simple — Simple systems are easy to implement and easy to diagnose Modern — Systems run on the latest infrastructures utilizing the latest technologies are usually much faster, efficient, and obviously up-to date. Extensible — Extensible systems are vital for community as requirements differ from one use-case to other, thus allow developers to avoid implementing the common components, re-use and achieve use-cases with minimum implementation. This is the system architecture of the distributed computing framework. The above image is pretty self-explanatory. To explain some of the key elements of it, Worker microservice A worker has a self-isolated workspace which allows it to be containarized and act independantly. Also, the system expects that all workers are homogenious in terms of the resource capacities. i.e. Fixed CPU power, RAM, Storage, etc. In other words, workers do not scale. This makes workers simple thus easier to manage. Workers are actually gRPC servers in-terms of the default implementation. But it is also extensible thus can be implemented with any framework, or even from scratch. The default gRPC implementation ensure that master-worker communication happens via RPC(remote procedure calls). This takes away all the complexity when compared to the other popular method, RESTful APIs. Besides, gRPC is also scalable, code-friendly, and fast(about 7 times faster that the RESTful APIs). Master microservice Master talks with clients and negtiates with workers. It acts as a gRPC client to the workers, and a server serving RESTful APIs to the clients. RESTful APIs are built on top of Spring Boot framework + Open API 3 code generator in an API first development approach. RESTful APIs are much human friendly thus suits better for Master and Client communications. Also, these API calls do not require to be blazing fast as they are not frequent. Master is also expected to be operating on its own self-isolated environment thus making it ideal for containerisation. The master consists of several loosely coupled components. Each of these components have their own responsibilities and are independant in-terms of the work they do. This makes the Master itself much simpler to understand. Also, each of the components are extensible which makes the behaviour of the master can be modified and extended at a more fine-grained level. Task Manager — Orchestrate data flow among the component. It includes a periodically running task which checks and copies completed jobs from worker services, and dispatch scheduled jobs afterwards.Task Scheduler — Persist jobs in a priority queue until they get dispatched to workers.Task Prioratizer — Assign a priority value based on diffrent attributes of the job such as deadline, etc. The default implementation implements the “Earliest deadline first” approach.Task Distributor — Communicates with the worker pool and dispatch a task to a free worker. If there are no free workers available, then it puts the task back to scheduling.Worker Pool Manager — Manages the communication with worker services.Central Store — Store job data until they get completed, and to be obtained by clients. The default implementation uses local storage based store, in which tasks are stored in folders created in a given isolated workspace. Task Manager — Orchestrate data flow among the component. It includes a periodically running task which checks and copies completed jobs from worker services, and dispatch scheduled jobs afterwards. Task Scheduler — Persist jobs in a priority queue until they get dispatched to workers. Task Prioratizer — Assign a priority value based on diffrent attributes of the job such as deadline, etc. The default implementation implements the “Earliest deadline first” approach. Task Distributor — Communicates with the worker pool and dispatch a task to a free worker. If there are no free workers available, then it puts the task back to scheduling. Worker Pool Manager — Manages the communication with worker services. Central Store — Store job data until they get completed, and to be obtained by clients. The default implementation uses local storage based store, in which tasks are stored in folders created in a given isolated workspace. As mentioned earlier, anyone can plug-in their own implementation of any of the above components, thus making the system extensible by design. Before we begin, the complete implementation of the system that we discussed so far can be found in the link below. It is an open source project distributed under the Apache 2.0 licence. github.com The system we just designed, is named as ORION. This project has four main components. Master — Contains the Spring boot + Open API 3 + gRPC client code based implementation of the Master microservice. This is a pure JAVA module. Worker — Cotains the gRPC server based implementation of the Worker microservice. This also is a pure JAVA module. Monitor App — Contains the React + Material UI based implementation of the ORION monitoring SPA(single page application). This is a pure JavaScript module. Integration — Contains test scripts, and test resources to configure the test environment. The scripts are Postman test collections and test resources includes the data requires to execute the collection. Configuring and running the test suit We will be using the v0.1 release of the ORION to conduct our test scenarios. Download the v0.1 release artifacts and extract both zipped files. Create an empty folder for the testing workspace. Let’s name it as theworkspace . Open the following file, <downloaded-artifacts>/integration/environment/init-setup.sh Edit the following variables with the correct file paths. WORKER_JAR_PATH=<path to the orion-v0.1-worker.jar file>MASTER_JAR_PATH=<path to the orion-v0.1-master.jar file>WORKSPACE=<path to the workspace directory> Save the changes. Open the following file. <downloaded-artifacts>/integration/environment/stop-setup.sh Edit the following variable with the correct file path. WORKSPACE=<path to the workspace directory> Save the changes. Now we are ready to start the ORION system. Open a terminal window and execute the following to run the init-setup.sh script. cd <downloaded-artifacts>/integration/environmentsh init-setup.sh This copies relavant files to the workspace directory and starts three microservices for the master and two workers. If you observe the workspace directory, following folders are created. active-processes — PIDs of the three services. logs — Log files from the three services. master — Artifacts related to the master service. worker-1 — Artifacts related to the first worker service. worker-2 — Artifacts related to the second worker service. Execute the following command to observe master logs. tail -f <workspace>/logs/master.log Following tailing log should be there if the service started successfully. ...2021-06-25 02:14:22.022 INFO 10125 --- [ main] o.c.orion.master.RESTfulEndpoint : Started RESTfulEndpoint in 1.194 seconds (JVM running for 1.658) Likewise, logs of the worker services can be tailed in the same manner using the correct file name in the same folder. Now start Postman and import the following test script collection. <downloaded-artifacts>/integration/test-scripts/ORION Test Suit - Executing heavy tasks.postman_collection There are four task submission API calls in this collection. You need to set the executable shell script and input text file for each of them(these files are submitted as multi-part form data). Relevant artifacts can be found in the corresponding folder. <downloaded-artifacts>/integration/test-scripts/task-files/task-<number> Tasks we are using in this test are nothing more than a shell script and an input file. Following is one of those scripts. ...sleep 50cat in.txt > out.txt 2>&1 What it does it wait for some time and then create a new file named out.txt and copy everything from in.txt to the out.txt. This is to mimic a task that takes some time to process, and involves input and output files. We are now almost ready to execute the test suit. But before that, lets start the monitoring app. Execute the following in a terminal(you need to have npm installed at this point). cd <downloaded-artifacts>/sdnpm inpm start This should start the monitoring app. Once tasks are submitted, this will show how they first inserted into the queue, sent to workers for execution, and finally stored in the central store upon completion. Let’s start the test. In the postman collection, submit all four tasks. You should recieve the following response saying each task is executing in the ORION. Now open the monitoring app window and observe the life cycle of the submitted jobs! For each task, progress and it’s unique id is shown. Finally, stop the ORION system by executing the following. cd <downloaded-artifacts>/integration/environmentsh stop-setup.sh In this article, we gradually developed a distributed computing system tailored for the modern cloud. We started by designing the architecture focusing on being simple, modern and extensible. Then we moved to test the implemented system and successfully ran a test suite and observed how submitted tasks are handled. Thank you for staying until the end of this article. Your ideas, suggestions, and questions regarding this work, are highly appreciated.
[ { "code": null, "e": 323, "s": 172, "text": "The way of writing software is much different now. Being cloud native is one of the key goals for almost every software system architecture out there." }, { "code": null, "e": 574, "s": 323, "text": "In this article, we will explore how can we build a simple and extensible distributed computing framework, tailored for the modern cloud. We are going to design, build and test a fresh framework from scratch while discussing the key design decisions." }, { "code": null, "e": 730, "s": 574, "text": "This article provides a good guide to understand how distributed systems work, and implementing extensible systems targetting modern cloud infrastructures." }, { "code": null, "e": 796, "s": 730, "text": "At a high level, there are three major components in this system." }, { "code": null, "e": 1052, "s": 796, "text": "Client — Actual users or user agents submitting jobsMaster — Accepts jobs from clients, orchestrate the system and get the jobs executed, and finally return expected outcomes to clientsWorker — Accepts a job, execute it, and provide the expected outcomes." }, { "code": null, "e": 1105, "s": 1052, "text": "Client — Actual users or user agents submitting jobs" }, { "code": null, "e": 1239, "s": 1105, "text": "Master — Accepts jobs from clients, orchestrate the system and get the jobs executed, and finally return expected outcomes to clients" }, { "code": null, "e": 1310, "s": 1239, "text": "Worker — Accepts a job, execute it, and provide the expected outcomes." }, { "code": null, "e": 1474, "s": 1310, "text": "Altogether clients submit jobs to the master, master schedules and get them executed with the available workers, and finally return job outcome back to the client." }, { "code": null, "e": 1642, "s": 1474, "text": "We are developing this system for the modern cloud and in a community first approach. Therefore throughout the design, we will keep following three things in our mind." }, { "code": null, "e": 2086, "s": 1642, "text": "Simple — Simple systems are easy to implement and easy to diagnoseModern — Systems run on the latest infrastructures utilizing the latest technologies are usually much faster, efficient, and obviously up-to date.Extensible — Extensible systems are vital for community as requirements differ from one use-case to other, thus allow developers to avoid implementing the common components, re-use and achieve use-cases with minimum implementation." }, { "code": null, "e": 2153, "s": 2086, "text": "Simple — Simple systems are easy to implement and easy to diagnose" }, { "code": null, "e": 2300, "s": 2153, "text": "Modern — Systems run on the latest infrastructures utilizing the latest technologies are usually much faster, efficient, and obviously up-to date." }, { "code": null, "e": 2532, "s": 2300, "text": "Extensible — Extensible systems are vital for community as requirements differ from one use-case to other, thus allow developers to avoid implementing the common components, re-use and achieve use-cases with minimum implementation." }, { "code": null, "e": 2604, "s": 2532, "text": "This is the system architecture of the distributed computing framework." }, { "code": null, "e": 2691, "s": 2604, "text": "The above image is pretty self-explanatory. To explain some of the key elements of it," }, { "code": null, "e": 2711, "s": 2691, "text": "Worker microservice" }, { "code": null, "e": 2983, "s": 2711, "text": "A worker has a self-isolated workspace which allows it to be containarized and act independantly. Also, the system expects that all workers are homogenious in terms of the resource capacities. i.e. Fixed CPU power, RAM, Storage, etc. In other words, workers do not scale." }, { "code": null, "e": 3198, "s": 2983, "text": "This makes workers simple thus easier to manage. Workers are actually gRPC servers in-terms of the default implementation. But it is also extensible thus can be implemented with any framework, or even from scratch." }, { "code": null, "e": 3504, "s": 3198, "text": "The default gRPC implementation ensure that master-worker communication happens via RPC(remote procedure calls). This takes away all the complexity when compared to the other popular method, RESTful APIs. Besides, gRPC is also scalable, code-friendly, and fast(about 7 times faster that the RESTful APIs)." }, { "code": null, "e": 3524, "s": 3504, "text": "Master microservice" }, { "code": null, "e": 3790, "s": 3524, "text": "Master talks with clients and negtiates with workers. It acts as a gRPC client to the workers, and a server serving RESTful APIs to the clients. RESTful APIs are built on top of Spring Boot framework + Open API 3 code generator in an API first development approach." }, { "code": null, "e": 3965, "s": 3790, "text": "RESTful APIs are much human friendly thus suits better for Master and Client communications. Also, these API calls do not require to be blazing fast as they are not frequent." }, { "code": null, "e": 4085, "s": 3965, "text": "Master is also expected to be operating on its own self-isolated environment thus making it ideal for containerisation." }, { "code": null, "e": 4451, "s": 4085, "text": "The master consists of several loosely coupled components. Each of these components have their own responsibilities and are independant in-terms of the work they do. This makes the Master itself much simpler to understand. Also, each of the components are extensible which makes the behaviour of the master can be modified and extended at a more fine-grained level." }, { "code": null, "e": 5383, "s": 4451, "text": "Task Manager — Orchestrate data flow among the component. It includes a periodically running task which checks and copies completed jobs from worker services, and dispatch scheduled jobs afterwards.Task Scheduler — Persist jobs in a priority queue until they get dispatched to workers.Task Prioratizer — Assign a priority value based on diffrent attributes of the job such as deadline, etc. The default implementation implements the “Earliest deadline first” approach.Task Distributor — Communicates with the worker pool and dispatch a task to a free worker. If there are no free workers available, then it puts the task back to scheduling.Worker Pool Manager — Manages the communication with worker services.Central Store — Store job data until they get completed, and to be obtained by clients. The default implementation uses local storage based store, in which tasks are stored in folders created in a given isolated workspace." }, { "code": null, "e": 5582, "s": 5383, "text": "Task Manager — Orchestrate data flow among the component. It includes a periodically running task which checks and copies completed jobs from worker services, and dispatch scheduled jobs afterwards." }, { "code": null, "e": 5670, "s": 5582, "text": "Task Scheduler — Persist jobs in a priority queue until they get dispatched to workers." }, { "code": null, "e": 5854, "s": 5670, "text": "Task Prioratizer — Assign a priority value based on diffrent attributes of the job such as deadline, etc. The default implementation implements the “Earliest deadline first” approach." }, { "code": null, "e": 6027, "s": 5854, "text": "Task Distributor — Communicates with the worker pool and dispatch a task to a free worker. If there are no free workers available, then it puts the task back to scheduling." }, { "code": null, "e": 6097, "s": 6027, "text": "Worker Pool Manager — Manages the communication with worker services." }, { "code": null, "e": 6320, "s": 6097, "text": "Central Store — Store job data until they get completed, and to be obtained by clients. The default implementation uses local storage based store, in which tasks are stored in folders created in a given isolated workspace." }, { "code": null, "e": 6463, "s": 6320, "text": "As mentioned earlier, anyone can plug-in their own implementation of any of the above components, thus making the system extensible by design." }, { "code": null, "e": 6650, "s": 6463, "text": "Before we begin, the complete implementation of the system that we discussed so far can be found in the link below. It is an open source project distributed under the Apache 2.0 licence." }, { "code": null, "e": 6661, "s": 6650, "text": "github.com" }, { "code": null, "e": 6748, "s": 6661, "text": "The system we just designed, is named as ORION. This project has four main components." }, { "code": null, "e": 6891, "s": 6748, "text": "Master — Contains the Spring boot + Open API 3 + gRPC client code based implementation of the Master microservice. This is a pure JAVA module." }, { "code": null, "e": 7006, "s": 6891, "text": "Worker — Cotains the gRPC server based implementation of the Worker microservice. This also is a pure JAVA module." }, { "code": null, "e": 7162, "s": 7006, "text": "Monitor App — Contains the React + Material UI based implementation of the ORION monitoring SPA(single page application). This is a pure JavaScript module." }, { "code": null, "e": 7367, "s": 7162, "text": "Integration — Contains test scripts, and test resources to configure the test environment. The scripts are Postman test collections and test resources includes the data requires to execute the collection." }, { "code": null, "e": 7405, "s": 7367, "text": "Configuring and running the test suit" }, { "code": null, "e": 7483, "s": 7405, "text": "We will be using the v0.1 release of the ORION to conduct our test scenarios." }, { "code": null, "e": 7550, "s": 7483, "text": "Download the v0.1 release artifacts and extract both zipped files." }, { "code": null, "e": 7632, "s": 7550, "text": "Create an empty folder for the testing workspace. Let’s name it as theworkspace ." }, { "code": null, "e": 7657, "s": 7632, "text": "Open the following file," }, { "code": null, "e": 7718, "s": 7657, "text": "<downloaded-artifacts>/integration/environment/init-setup.sh" }, { "code": null, "e": 7776, "s": 7718, "text": "Edit the following variables with the correct file paths." }, { "code": null, "e": 7932, "s": 7776, "text": "WORKER_JAR_PATH=<path to the orion-v0.1-worker.jar file>MASTER_JAR_PATH=<path to the orion-v0.1-master.jar file>WORKSPACE=<path to the workspace directory>" }, { "code": null, "e": 7950, "s": 7932, "text": "Save the changes." }, { "code": null, "e": 7975, "s": 7950, "text": "Open the following file." }, { "code": null, "e": 8036, "s": 7975, "text": "<downloaded-artifacts>/integration/environment/stop-setup.sh" }, { "code": null, "e": 8092, "s": 8036, "text": "Edit the following variable with the correct file path." }, { "code": null, "e": 8136, "s": 8092, "text": "WORKSPACE=<path to the workspace directory>" }, { "code": null, "e": 8154, "s": 8136, "text": "Save the changes." }, { "code": null, "e": 8280, "s": 8154, "text": "Now we are ready to start the ORION system. Open a terminal window and execute the following to run the init-setup.sh script." }, { "code": null, "e": 8346, "s": 8280, "text": "cd <downloaded-artifacts>/integration/environmentsh init-setup.sh" }, { "code": null, "e": 8463, "s": 8346, "text": "This copies relavant files to the workspace directory and starts three microservices for the master and two workers." }, { "code": null, "e": 8534, "s": 8463, "text": "If you observe the workspace directory, following folders are created." }, { "code": null, "e": 8581, "s": 8534, "text": "active-processes — PIDs of the three services." }, { "code": null, "e": 8623, "s": 8581, "text": "logs — Log files from the three services." }, { "code": null, "e": 8673, "s": 8623, "text": "master — Artifacts related to the master service." }, { "code": null, "e": 8731, "s": 8673, "text": "worker-1 — Artifacts related to the first worker service." }, { "code": null, "e": 8790, "s": 8731, "text": "worker-2 — Artifacts related to the second worker service." }, { "code": null, "e": 8844, "s": 8790, "text": "Execute the following command to observe master logs." }, { "code": null, "e": 8880, "s": 8844, "text": "tail -f <workspace>/logs/master.log" }, { "code": null, "e": 8955, "s": 8880, "text": "Following tailing log should be there if the service started successfully." }, { "code": null, "e": 9124, "s": 8955, "text": "...2021-06-25 02:14:22.022 INFO 10125 --- [ main] o.c.orion.master.RESTfulEndpoint : Started RESTfulEndpoint in 1.194 seconds (JVM running for 1.658)" }, { "code": null, "e": 9243, "s": 9124, "text": "Likewise, logs of the worker services can be tailed in the same manner using the correct file name in the same folder." }, { "code": null, "e": 9310, "s": 9243, "text": "Now start Postman and import the following test script collection." }, { "code": null, "e": 9417, "s": 9310, "text": "<downloaded-artifacts>/integration/test-scripts/ORION Test Suit - Executing heavy tasks.postman_collection" }, { "code": null, "e": 9672, "s": 9417, "text": "There are four task submission API calls in this collection. You need to set the executable shell script and input text file for each of them(these files are submitted as multi-part form data). Relevant artifacts can be found in the corresponding folder." }, { "code": null, "e": 9745, "s": 9672, "text": "<downloaded-artifacts>/integration/test-scripts/task-files/task-<number>" }, { "code": null, "e": 9868, "s": 9745, "text": "Tasks we are using in this test are nothing more than a shell script and an input file. Following is one of those scripts." }, { "code": null, "e": 9905, "s": 9868, "text": "...sleep 50cat in.txt > out.txt 2>&1" }, { "code": null, "e": 10123, "s": 9905, "text": "What it does it wait for some time and then create a new file named out.txt and copy everything from in.txt to the out.txt. This is to mimic a task that takes some time to process, and involves input and output files." }, { "code": null, "e": 10221, "s": 10123, "text": "We are now almost ready to execute the test suit. But before that, lets start the monitoring app." }, { "code": null, "e": 10304, "s": 10221, "text": "Execute the following in a terminal(you need to have npm installed at this point)." }, { "code": null, "e": 10347, "s": 10304, "text": "cd <downloaded-artifacts>/sdnpm inpm start" }, { "code": null, "e": 10385, "s": 10347, "text": "This should start the monitoring app." }, { "code": null, "e": 10554, "s": 10385, "text": "Once tasks are submitted, this will show how they first inserted into the queue, sent to workers for execution, and finally stored in the central store upon completion." }, { "code": null, "e": 10712, "s": 10554, "text": "Let’s start the test. In the postman collection, submit all four tasks. You should recieve the following response saying each task is executing in the ORION." }, { "code": null, "e": 10797, "s": 10712, "text": "Now open the monitoring app window and observe the life cycle of the submitted jobs!" }, { "code": null, "e": 10850, "s": 10797, "text": "For each task, progress and it’s unique id is shown." }, { "code": null, "e": 10909, "s": 10850, "text": "Finally, stop the ORION system by executing the following." }, { "code": null, "e": 10975, "s": 10909, "text": "cd <downloaded-artifacts>/integration/environmentsh stop-setup.sh" }, { "code": null, "e": 11292, "s": 10975, "text": "In this article, we gradually developed a distributed computing system tailored for the modern cloud. We started by designing the architecture focusing on being simple, modern and extensible. Then we moved to test the implemented system and successfully ran a test suite and observed how submitted tasks are handled." } ]
CSS Lists - GeeksforGeeks
29 Oct, 2021 The List in CSS specifies the listing of the contents or items in a particular manner i.e., it can either be organized orderly or unorder way, which helps to make a clean webpage. It can be used to arrange the huge with a variety of content as they are flexible and easy to manage. The default style for the list is borderless. The list can be categorized into 2 types: Unordered List: In unordered lists, the list items are marked with bullets i.e small black circles by default. Ordered List: In ordered lists, the list items are marked with numbers and an alphabet. List Item Marker: This property specifies the type of item marker i.e. unordered list or ordered. The list-style-type property specifies the appearance of the list item marker (such as a disc, character, or custom counter style) of a list item element. Its default value is a disc. Syntax: list-style-type:value; The following value can be used: circle decimal , eg :1,2,3,etc decimal-leading-zeroes , eg :01,02,03,04,etc lower-roman upper-roman lower-alpha, eg : a,b,c,etc upper-alpha, eg : A,B,C,etc square Example: This example describes the CSS List with the various list-style-type where the values are set to square & lower-alpha. HTML <!DOCTYPE html><html> <head> <style> ul.a { list-style-type: square; } ol.c { list-style-type: lower-alpha; } </style></head> <body> <h2> GeeksforGeeks </h2> <p> Unordered lists </p> <ul class="a"> <li>one</li> <li>two</li> <li>three</li> </ul> <ul class="b"> <li>one</li> <li>two</li> <li>three</li> </ul> <p> Ordered Lists </p> <ol class="c"> <li>one</li> <li>two</li> <li>three</li> </ol> <ol class="d"> <li>one</li> <li>two</li> <li>three</li> </ol></body> </html> Output: Image as List Marker: This property specifies the image as a list item marker. The list-style-image property is used to sets an image to be used as the list item marker. Its default value is “none”. Syntax: list-style-image: url; Example: This example describes the CSS List with the various list-style-image where the values are set to url of the image. HTML <!DOCTYPE html><html> <head> <title> CSS list-style-image Property </title> <style> ul { list-style-image: url("https://contribute.geeksforgeeks.org/wp-content/uploads/listitem-1.png"); } </style></head> <body> <h1> GeeksforGeeks </h1> <p> Unordered lists </p> <ul> <li>1</li> <li>2</li> <li>3</li> </ul></body> </html> Output: List Marker Position: This property specifies the position of the list item marker. The list-style-position property is used to sets the position of the marker relative to a list item. Its default value is “outside”. There are 2 types of position markers: list-style-position: outside; In this, the bullet points will be outside the list item. The start of each line of the list will be aligned vertically. Syntax: list-style-position: outside; Example: This example describes the CSS List with the various list-style-position where the value is set to outside. HTML <!DOCTYPE html><html> <head> <style> ul.a { list-style-position: outside; } </style></head> <body> <h2> GeeksforGeeks </h2> <p> Unordered lists </p> <ul class="a"> <li>one <br> In this the bullet points will be outside the list item.</li> <li>two <br> The start of each line of the list will be aligned vertically. </li> <li>three</li> </ul></body> </html> Output: list-style-position: inside; In this, the bullet points will be inside the list. The line along with the bullet points will be aligned vertically. Syntax: list-style-position: inside; Example: This example describes the CSS List with the various list-style-position where the value is set to inside. HTML <!DOCTYPE html><html> <head> <style> ul.a { list-style-position: inside; } </style></head> <body> <h2> GeeksforGeeks </h2> <p> Unordered lists </p> <ul class="a"> <li>one <br> In this the bullet points will be inside the list item.</li> <li>two <br> The line along with the bullet points will be aligned vertically.. </li> <li>three</li> </ul></body> </html> Output: Shorthand Property: This property allows us to set all the list properties in one command. The order of property is a type, position, and image. If any of the properties is missing, the default value is inserted. Example: This example describes the CSS List using the shorthand property. HTML <!DOCTYPE html><html> <head> <style> ul.a { list-style: square inside; } </style></head> <body> <h2> GeeksforGeeks </h2> <p> Unordered lists </p> <ul class="a"> <li>one</li> <li>two</li> <li>three</li> </ul></body> </html> Output: Styling Lists: The list can be formatted in CSS. Different colors, borders, backgrounds, and paddings can be set for the lists. Example: This example describes the CSS List where the various styling properties are applied to the element. HTML <!DOCTYPE html><html> <head> <style> ul.a { list-style: square; background: pink; padding: 20px; } </style></head> <body> <h2> GeeksforGeeks </h2> <p> Unordered lists </p> <ul class="a"> <li>one</li> <li>two</li> <li>three</li> </ul></body> </html> Output: Nested List: Lists can also be nested. We have sub-sections for sections, so we need the nesting of lists. Example: This example describes the CSS List having a list declared inside another list. HTML <!DOCTYPE html><html> <head></head> <body> <h2> GeeksforGeeks </h2> <ul> <li> one <ul> <li>sub one</li> <li>sub two</li> </ul> </li> <li> two <ul> <li>sub one</li> <li>sub two</li> </ul> </li> <li> three <ul> <li>sub one</li> <li>sub two</li> </ul> </li> </ul></body> </html> Output: Supported Browsers: Google Chrome 95.0 Microsoft Edge 95.0 Firefox 93.0 Internet Explorer 11.0 Opera 80.0 Safari 15.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. bhaskargeeksforgeeks CSS-Basics CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 27655, "s": 27627, "text": "\n29 Oct, 2021" }, { "code": null, "e": 28025, "s": 27655, "text": "The List in CSS specifies the listing of the contents or items in a particular manner i.e., it can either be organized orderly or unorder way, which helps to make a clean webpage. It can be used to arrange the huge with a variety of content as they are flexible and easy to manage. The default style for the list is borderless. The list can be categorized into 2 types:" }, { "code": null, "e": 28136, "s": 28025, "text": "Unordered List: In unordered lists, the list items are marked with bullets i.e small black circles by default." }, { "code": null, "e": 28224, "s": 28136, "text": "Ordered List: In ordered lists, the list items are marked with numbers and an alphabet." }, { "code": null, "e": 28506, "s": 28224, "text": "List Item Marker: This property specifies the type of item marker i.e. unordered list or ordered. The list-style-type property specifies the appearance of the list item marker (such as a disc, character, or custom counter style) of a list item element. Its default value is a disc." }, { "code": null, "e": 28515, "s": 28506, "text": "Syntax: " }, { "code": null, "e": 28538, "s": 28515, "text": "list-style-type:value;" }, { "code": null, "e": 28571, "s": 28538, "text": "The following value can be used:" }, { "code": null, "e": 28578, "s": 28571, "text": "circle" }, { "code": null, "e": 28602, "s": 28578, "text": "decimal , eg :1,2,3,etc" }, { "code": null, "e": 28647, "s": 28602, "text": "decimal-leading-zeroes , eg :01,02,03,04,etc" }, { "code": null, "e": 28659, "s": 28647, "text": "lower-roman" }, { "code": null, "e": 28671, "s": 28659, "text": "upper-roman" }, { "code": null, "e": 28699, "s": 28671, "text": "lower-alpha, eg : a,b,c,etc" }, { "code": null, "e": 28727, "s": 28699, "text": "upper-alpha, eg : A,B,C,etc" }, { "code": null, "e": 28734, "s": 28727, "text": "square" }, { "code": null, "e": 28862, "s": 28734, "text": "Example: This example describes the CSS List with the various list-style-type where the values are set to square & lower-alpha." }, { "code": null, "e": 28867, "s": 28862, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> ul.a { list-style-type: square; } ol.c { list-style-type: lower-alpha; } </style></head> <body> <h2> GeeksforGeeks </h2> <p> Unordered lists </p> <ul class=\"a\"> <li>one</li> <li>two</li> <li>three</li> </ul> <ul class=\"b\"> <li>one</li> <li>two</li> <li>three</li> </ul> <p> Ordered Lists </p> <ol class=\"c\"> <li>one</li> <li>two</li> <li>three</li> </ol> <ol class=\"d\"> <li>one</li> <li>two</li> <li>three</li> </ol></body> </html>", "e": 29515, "s": 28867, "text": null }, { "code": null, "e": 29523, "s": 29515, "text": "Output:" }, { "code": null, "e": 29722, "s": 29523, "text": "Image as List Marker: This property specifies the image as a list item marker. The list-style-image property is used to sets an image to be used as the list item marker. Its default value is “none”." }, { "code": null, "e": 29730, "s": 29722, "text": "Syntax:" }, { "code": null, "e": 29753, "s": 29730, "text": "list-style-image: url;" }, { "code": null, "e": 29878, "s": 29753, "text": "Example: This example describes the CSS List with the various list-style-image where the values are set to url of the image." }, { "code": null, "e": 29883, "s": 29878, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS list-style-image Property </title> <style> ul { list-style-image: url(\"https://contribute.geeksforgeeks.org/wp-content/uploads/listitem-1.png\"); } </style></head> <body> <h1> GeeksforGeeks </h1> <p> Unordered lists </p> <ul> <li>1</li> <li>2</li> <li>3</li> </ul></body> </html>", "e": 30283, "s": 29883, "text": null }, { "code": null, "e": 30291, "s": 30283, "text": "Output:" }, { "code": null, "e": 30508, "s": 30291, "text": "List Marker Position: This property specifies the position of the list item marker. The list-style-position property is used to sets the position of the marker relative to a list item. Its default value is “outside”." }, { "code": null, "e": 30548, "s": 30508, "text": "There are 2 types of position markers: " }, { "code": null, "e": 30699, "s": 30548, "text": "list-style-position: outside; In this, the bullet points will be outside the list item. The start of each line of the list will be aligned vertically." }, { "code": null, "e": 30707, "s": 30699, "text": "Syntax:" }, { "code": null, "e": 30737, "s": 30707, "text": "list-style-position: outside;" }, { "code": null, "e": 30855, "s": 30737, "text": "Example: This example describes the CSS List with the various list-style-position where the value is set to outside. " }, { "code": null, "e": 30860, "s": 30855, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> ul.a { list-style-position: outside; } </style></head> <body> <h2> GeeksforGeeks </h2> <p> Unordered lists </p> <ul class=\"a\"> <li>one <br> In this the bullet points will be outside the list item.</li> <li>two <br> The start of each line of the list will be aligned vertically. </li> <li>three</li> </ul></body> </html>", "e": 31329, "s": 30860, "text": null }, { "code": null, "e": 31337, "s": 31329, "text": "Output:" }, { "code": null, "e": 31484, "s": 31337, "text": "list-style-position: inside; In this, the bullet points will be inside the list. The line along with the bullet points will be aligned vertically." }, { "code": null, "e": 31492, "s": 31484, "text": "Syntax:" }, { "code": null, "e": 31521, "s": 31492, "text": "list-style-position: inside;" }, { "code": null, "e": 31638, "s": 31521, "text": "Example: This example describes the CSS List with the various list-style-position where the value is set to inside. " }, { "code": null, "e": 31643, "s": 31638, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> ul.a { list-style-position: inside; } </style></head> <body> <h2> GeeksforGeeks </h2> <p> Unordered lists </p> <ul class=\"a\"> <li>one <br> In this the bullet points will be inside the list item.</li> <li>two <br> The line along with the bullet points will be aligned vertically.. </li> <li>three</li> </ul></body> </html>", "e": 32116, "s": 31643, "text": null }, { "code": null, "e": 32124, "s": 32116, "text": "Output:" }, { "code": null, "e": 32338, "s": 32124, "text": "Shorthand Property: This property allows us to set all the list properties in one command. The order of property is a type, position, and image. If any of the properties is missing, the default value is inserted. " }, { "code": null, "e": 32413, "s": 32338, "text": "Example: This example describes the CSS List using the shorthand property." }, { "code": null, "e": 32418, "s": 32413, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> ul.a { list-style: square inside; } </style></head> <body> <h2> GeeksforGeeks </h2> <p> Unordered lists </p> <ul class=\"a\"> <li>one</li> <li>two</li> <li>three</li> </ul></body> </html>", "e": 32713, "s": 32418, "text": null }, { "code": null, "e": 32721, "s": 32713, "text": "Output:" }, { "code": null, "e": 32850, "s": 32721, "text": "Styling Lists: The list can be formatted in CSS. Different colors, borders, backgrounds, and paddings can be set for the lists. " }, { "code": null, "e": 32960, "s": 32850, "text": "Example: This example describes the CSS List where the various styling properties are applied to the element." }, { "code": null, "e": 32965, "s": 32960, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> ul.a { list-style: square; background: pink; padding: 20px; } </style></head> <body> <h2> GeeksforGeeks </h2> <p> Unordered lists </p> <ul class=\"a\"> <li>one</li> <li>two</li> <li>three</li> </ul></body> </html>", "e": 33300, "s": 32965, "text": null }, { "code": null, "e": 33308, "s": 33300, "text": "Output:" }, { "code": null, "e": 33416, "s": 33308, "text": "Nested List: Lists can also be nested. We have sub-sections for sections, so we need the nesting of lists. " }, { "code": null, "e": 33505, "s": 33416, "text": "Example: This example describes the CSS List having a list declared inside another list." }, { "code": null, "e": 33510, "s": 33505, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head></head> <body> <h2> GeeksforGeeks </h2> <ul> <li> one <ul> <li>sub one</li> <li>sub two</li> </ul> </li> <li> two <ul> <li>sub one</li> <li>sub two</li> </ul> </li> <li> three <ul> <li>sub one</li> <li>sub two</li> </ul> </li> </ul></body> </html>", "e": 34010, "s": 33510, "text": null }, { "code": null, "e": 34018, "s": 34010, "text": "Output:" }, { "code": null, "e": 34038, "s": 34018, "text": "Supported Browsers:" }, { "code": null, "e": 34057, "s": 34038, "text": "Google Chrome 95.0" }, { "code": null, "e": 34077, "s": 34057, "text": "Microsoft Edge 95.0" }, { "code": null, "e": 34090, "s": 34077, "text": "Firefox 93.0" }, { "code": null, "e": 34113, "s": 34090, "text": "Internet Explorer 11.0" }, { "code": null, "e": 34124, "s": 34113, "text": "Opera 80.0" }, { "code": null, "e": 34136, "s": 34124, "text": "Safari 15.0" }, { "code": null, "e": 34273, "s": 34136, "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": 34294, "s": 34273, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 34305, "s": 34294, "text": "CSS-Basics" }, { "code": null, "e": 34309, "s": 34305, "text": "CSS" }, { "code": null, "e": 34314, "s": 34309, "text": "HTML" }, { "code": null, "e": 34331, "s": 34314, "text": "Web Technologies" }, { "code": null, "e": 34336, "s": 34331, "text": "HTML" }, { "code": null, "e": 34434, "s": 34336, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34443, "s": 34434, "text": "Comments" }, { "code": null, "e": 34456, "s": 34443, "text": "Old Comments" }, { "code": null, "e": 34518, "s": 34456, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 34568, "s": 34518, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 34626, "s": 34568, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 34674, "s": 34626, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 34711, "s": 34674, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 34773, "s": 34711, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 34823, "s": 34773, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 34883, "s": 34823, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 34931, "s": 34883, "text": "How to update Node.js and NPM to next version ?" } ]
Training Tensorflow Object Detection API with custom dataset for working in Javascript and Vue.js | by Adrià Gil | Towards Data Science
This article is a re-work of the amazing tutorial from Gilbert Tanner on how to create your own object detector with Tensorflow Object Detection API.I’m following exactly the same steps but with some differences and adding some things I’ve faced during setup and training. I want to thank the author for the original content and of course give credit to him. In this article we are going to use OS X + Anaconda environment so then can be easily portable to Google Cloud Platform for example if you wish...with the addition of using GPUs instead of CPUs for computing 🚀 Also I have to say that I have developed this experiment in my research time working at Manifiesto where I perform as a frontend/online developer 🤗. Download and install Anaconda (Python 3.7 for OS X in my case) from:https://www.anaconda.com/distribution/ I will use the same version of Python that the actual Anaconda installation ships with for the new environment that we are going to create in a minute.To know which version simply run: conda info Then create and activate the environment: conda create --name tf-object-detection python=3.7.4conda activate tf-object-detection Install Tensorflow models and dependenciesChoose a folder you want to work at and create a directory named tensorflow.I will be working at the following location: /Users/<username>/projects/tensorflow Then just clone the Tensorflow models repository running: git clone https://github.com/tensorflow/models Now you need to install all the dependencies: conda install Cythonconda install contextlib2conda install pillowconda install lxmlconda install jupyterconda install matplotlibconda install tensorflow=1 Install the COCO APIFor this go back to your projects folder and clone the Github project repository and execute the commands below: git clone https://github.com/cocodataset/cocoapi.gitcd cocoapi/PythonAPImakecp -r pycocotools <path_to_tensorflow>/models/research Protobuf Installation/CompilationThis is because Tensorflow Object Detection API use .proto files and these files need to be compiled into .py files in order for the Object Detection API to work properly. Protobuf can compile these files. Protobuf can be downloaded from:https://github.com/protocolbuffers/protobuf/releasesPlace the downloaded file anywhere you want, for example in the projects folder. After extracting you need to go to models/research and use protobuf to extract python files from the proto files in the object_detection/protos directory.For this purpose we are going to use a little script.Save it inside the research folder and name it use_protobuf.py import osimport sysargs = sys.argvdirectory = args[1]protoc_path = args[2]for file in os.listdir(directory): if file.endswith(".proto"): os.system(protoc_path+" "+directory+"/"+file+" --python_out=.") And then you can use it: python use_protobuf.py <path_to_directory> <path_to_protoc_file># for example in our particular casepython use_protobuf.py object_detection/protos /Users/<username>/projects/protoc/bin/protoc Add necessary environment variablesWe need to add the research and research/slim folder to our environment variables and run the setup.py file. export PYTHONPATH=$PYTHONPATH:<PATH_TO_TF>/TensorFlow/models/researchexport PYTHONPATH=$PYTHONPATH:<PATH_TO_TF>/TensorFlow/models/research/object_detectionexport PYTHONPATH=$PYTHONPATH:<PATH_TO_TF>/TensorFlow/models/research/slim Note: the $PYTHONPATH environment variables needs to be added every time the shell session is closed or the Anaconda environment is deactivated. Now navigate to tensorflow/models/research and run: python setup.py buildpython setup.py install Testing Tensorflow Object Detection APIAfter the installation is complete we can test everything is working correctly by running the object_detection_tutorial.ipynb from the object_detection folder. Note: is important to have in consideration that this tutorial works for Tensorflow 2.0 and you must have Tensorflow installed in your environment — if not just run conda install tensorflow=2 jupyter notebook Then select the object_detection_tutorial.ipynb from the browser window and just follow the instructions. You can also check everything is working by simply importing object_detection inside a python shell: import object_detection And if no errors then you can assume everything is working properly. For our purpose we are going to use a bunch of images representing Jagermeister bottles.To do that as fast as possible we are going to scrap google images with a python script to automate the process. Scripts can be downloaded from:https://github.com/hardikvasa/google-images-downloadand, for example, place the downloaded files in projects folder named as google-images-download. Then just navigate to the folder where the python script is and execute: python google_images_download.py --keywords "jagermeister bottle" --limit 100 --format jpg Because the images resolution may be very different and some can be quite big we want to scale them to do the training process faster.Here is a little script: from PIL import Imageimport osimport argparsedef rescale_images(directory, size): for img in os.listdir(directory): im = Image.open(directory+img) im_resized = im.resize(size, Image.ANTIALIAS) im_resized.save(directory+img)if __name__ == '__main__': parser = argparse.ArgumentParser(description="Rescale images") parser.add_argument('-d', '--directory', type=str, required=True, help='Directory containing the images') parser.add_argument('-s', '--size', type=int, nargs=2, required=True, metavar=('width', 'height'), help='Image size') args = parser.parse_args() rescale_images(args.directory, args.size) To use the script we need to save it, for example, with the name transform_image_resolution.py and then go into the command line and type: python transform_image_resolution.py -d <image_dir>/ -s 800 600 Note: images in the image_dir folder will be overwritten so do a backup if needed. Note: important to check the downloaded images folder in order to avoid duplicates and delete corrupted files if any. Now we have to have to move about 80% of images into object_detection/images/train directory and the other 20% into object_detection/images/test directory. In order to label our data, we need some kind of labeling software.In this particular case we are going to use LabelImg. As far as we are using Anaconda we only need to follow these instructions: # install pyqt (version 5)conda install pyqt# download LabelImg and place it in 'projects' foldergit clone https://github.com/tzutalin/labelImg.git# navigate to labelImg directorycd labelImg# execute labelImg.pymake qt5py3;./labelImg.py Open each train and test folders and then use the “Create RectBox” button for labeling each image and click save.We are going to use “jagermeister bottle” label for each box.After saving you will see an XML file appearing in the same directory with the same name for the image we have just labeled. In order to create the TFRecords we will use two scripts from Dat Tran’s raccoon detector; xml_to_csv.py and generate_tfrecord.py files.Download and place them in object_detection folder.You can go to References section below to see from where I downloaded them. We need now to modify xml_to_csv.py script so we can transform the created xml files to csv correctly. # Old:def main(): image_path = os.path.join(os.getcwd(), 'annotations') xml_df = xml_to_csv(image_path) xml_df.to_csv('raccoon_labels.csv', index=None) print('Successfully converted xml to csv.')# New:def main(): for folder in ['train', 'test']: image_path = os.path.join(os.getcwd(), ('images/' + folder)) xml_df = xml_to_csv(image_path) xml_df.to_csv(('images/'+folder+'_labels.csv'), index=None) print('Successfully converted xml to csv.') Then we can use the script opening the command line and typing: python xml_to_csv.py As you can observe, two files have been created in the images directory. One called test_labels.csv and another one called train_labels.csv Note: if you get “No module named ‘pandas’” error just do a conda install pandas. Before we can transform these csv files to TFRecords we need to change the generate_tfrecords.py script. From: # TO-DO replace this with label mapdef class_text_to_int(row_label): if row_label == 'raccoon': return 1 else: None To: def class_text_to_int(row_label): if row_label == 'jagermeister bottle': return 1 else: None Now the TFRecords can be generated by typing: # train tfrecordpython generate_tfrecord.py --csv_input=images/train_labels.csv --image_dir=images/train --output_path=train.record# test tfrecordpython generate_tfrecord.py --csv_input=images/test_labels.csv --image_dir=images/test --output_path=test.record These two command generate a train.record and a test.record file which can be used to train our object detector. Note: if getting an error like “module tensorflow has no attribute app” is because you are using Tensorflow 2.0 so we need to change a line in generate_tfrecord.py file. From: # line 17import tensorflow as tf To: # line 17import tensorflow.compat.v1 as tf Or if you prefer you can rollback to Tensorflow 1.0 instead doing: conda remove tensorflowconda install tensorflow=1 Before we start training we need to create a label map and a training configuration file. Creating a label mapThe label map maps an id to name. We will put it in a folder called training located in the object_detection directory with the name labelmap.pbtxt item { id: 1 name: 'jagermeister bottle'} The id number of each item should match the id of specified item in the generate_tfrecord.py file. Creating a training configurationNow we need to create a training configuration file.We are going to use faster_rcnn_inception_v2_coco model which can be downloaded from:https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md Download it uncompress the file and place it into object_detection folder.Folder name will look like faster_rcnn_inception_v2_coco_2018_01_28 And we are going to start with a sample config file named faster_rcnn_inception_v2_pets.config which can be found in the sample folder.You can download it from:https://github.com/tensorflow/models/tree/master/research/object_detection/samples/configs Keep the same name and save it into the training folder and open it with a text editor in order to change a few lines of code. Line 9: change the number of classes to number of objects you want to detect (1 in our case). Line 106: change fine_tune_checkpoint to the path of the model.ckpt file fine_tune_checkpoint:"/Users/<username>/projects/tensorflow/models/research/object_detection/faster_rcnn_inception_v2_coco_2018_01_28/model.ckpt" Line 123: change input_path to the path of the train.record file: input_path:"/Users/<username>/projects/tensorflow/models/research/object_detection/train.record Line 135: change input_path to the path of the test.records file: input_path:"/Users/<username>/projects/tensorflow/models/research/object_detection/test.record Line 125-137: change label_map_path to the path of label map file: label_map_path:"/Users/<username>/projects/tensorflow/models/research/object_detection/training/labelmap.pbtxt Line 130: change num_example to the number of images in your test folder. num_examples: 10 We are going to use the train.py file which is located in the object_detection/legacy folder. We will copy it into the object_detection folder and then we will type the following into the command line: Update: or we can use the model_main.py file in the object_detection folder instead. python model_main.py --logtostderr --model_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_pets.config If everything was setup correctly the training should begin shortly. Note: if you are getting an error like “module tensorflow has no attribute contrib” is because you are using Tensorflow 2.0.There are two ways of solving this: update scripts for being used with Tensorflow 2.0rollback to Tensorflow 1.0 update scripts for being used with Tensorflow 2.0 rollback to Tensorflow 1.0 The easy way is doing a rollback so do the following # uninstall Tensorflow 2.0conda remove tensorflow# install Tensorflow 1.Xconda install tensorflow=1 Once the training is running you will see every 5 minutes or so (depending on your hardware) the current loss gets logged to Tensorboard. We can open Tensorboard by opening a second command line, navigating to object_detection folder and typing: tensorboard --logdir=training A web page is now opened at localhost:6006 You should train the model until it reaches a satisfying loss.The training process can be then terminated by pressing Ctrl+C. Once the model is trained we need to generate an inference graph, which can be used to run the model. For doing so we need to first find out the highest saved step number.For this, we need to navigate to the training directory and look for the model.ckpt file with the biggest index. Then we can create the inference graph by typing the following in the command line: python export_inference_graph.py --input_type image_tensor --pipeline_config_path training/faster_rcnn_inception_v2_pets.config --trained_checkpoint_prefix training/model.ckpt-XXXX --output_directory inference_graph where XXXX represents the highest number. First we need to install TensorflowJS in our environment.Usually we would use conda to install the package but unfortunately is not available in the repository sources.So we are going to use it via python pip: pip install tensorflowjs Once the installation finishes we can execute the following command in order to convert our saved model to something tensorfowjs understands: tensorflowjs_converter --input_format=tf_saved_model <input_dir> <output_dir> For example if we are in the directory /Users/<username>/projects/tensorflow/models/research/object_detection we can run something like: tensorflowjs_converter --input_format=tf_saved_model --output_node_names='detection_boxes,detection_classes,detection_features,detection_multiclass_scores,detection_scores,num_detections,raw_detection_boxes,raw_detection_scores' --saved_model_tags=serve --output_format=tfjs_graph_model inference_graph/saved_model inference_graph/web_model Note that the conversion options are specifically set for converting an object detection SavedModel and the output_node_names configuration have been retrieved with thesaved_model_cli command: saved_model_cli show --dir inference_graph/saved_model --tag_set serve --signature_def serving_default#output will print something like this:#detection_boxes#detection_classes#detection_features#detection_multiclass_scores#detection_scores#num_detections#raw_detection_boxes#raw_detection_scores Full explanation on gist in References section below. Now that we have our model properly converted we can use it in a web application environment that runs Javascript.For making things smoother we can head to the demo application listed in References section below.The repository you are looking for is the adriagil/tfjs-vue-example I have to stop for a moment and thank to freshsomebody for sharing this great Vue.js demo application which uses a pre-trained coco-ssd model to be used with a webcam in a browser.I’ve just adapted the code to work with my trained model consisting basically in how model serving and loading is done and how to retrieve the needed tensors to analyze data.Here the original app in case you are interested https://github.com/freshsomebody/tfjs-coco-ssd-vue-example Just navigate there and clone or download at your preferred location.Then copy the converted model in the previous step into the root directory of the downloaded project, the web_model folder. Then navigate to the application root directory and run: npm install Once finished open the App.vue file in your text editor of choice.You can see now the source code of the web application, great! 🍺 In order to load the converted model properly we need to do it via a web server.We’re going to use a Node package to do so called http-server.All we need to do is activate the web server with the command: node_modules/http-server/bin/http-server -c1 --cors . and the model will be accesible via http at http://localhost:8081/web_model/model.json to be loaded in the browser. Last but not least, we need to compile or serve the frontend application to test everything with the following command: npm run serve In http://localhost:8080 you should now see the webcam stream and the corresponding bounding boxes wrapping the Jaggermeister bottle in red.Awesome, we are done! 👏👏👏 Despite the results of this experience are OK there are 2 important things to have in consideration. The first one is that working in OS X is not the best choice.I would recommend you to switch to a Linux or Windows environment but only if you are going to use GPU, if not is the same piece of crap 😅A better solution (we know proper GPU cards are very expensive) is to do it on Google Cloud Plaform.They offer a very good environment and free credits for you to spend in any of your training experiments. The second thing that sucks is that the inception model we have chosen is precise but is very slow on computer browsers and even worse in mobile.So I’m just now training another model based on MobileNet which should perform a lot better 🤞 hopefully.Also my model is not optimized and maybe that could help, but I need to do some research on how to achieve it. We’ll see. If you liked, want more like this or have any questions please don’t hesitate to contact me...if you arrived here, you deserve it!And again many thanks to the authors that have motivated me to write this article. That’s all folks! [Update 24/02/2020]As I commented before, the performance for a web browser was not acceptable for a real-time video analysis so I decided to do a bit of research. Thanks to stackoverflow community ❤️ I found many suggestions like optimizing the model or going back to the training process again with another model. I decided to try with another model because the rcnn-inception model I trained was very precise but not really thought for the application I needed. I picked ssd_mobilenet_v2_coco this time.After a weekend training the model and almost 30k steps — I know is not necessary for development but worth to try like in a real situation— was time for testing. Results were far better than in my first attempt so now prediction rate is almost fluid with an acceptable frame rate. So lesson learned; choose the right model before training to suit your needs.
[ { "code": null, "e": 320, "s": 47, "text": "This article is a re-work of the amazing tutorial from Gilbert Tanner on how to create your own object detector with Tensorflow Object Detection API.I’m following exactly the same steps but with some differences and adding some things I’ve faced during setup and training." }, { "code": null, "e": 406, "s": 320, "text": "I want to thank the author for the original content and of course give credit to him." }, { "code": null, "e": 616, "s": 406, "text": "In this article we are going to use OS X + Anaconda environment so then can be easily portable to Google Cloud Platform for example if you wish...with the addition of using GPUs instead of CPUs for computing 🚀" }, { "code": null, "e": 765, "s": 616, "text": "Also I have to say that I have developed this experiment in my research time working at Manifiesto where I perform as a frontend/online developer 🤗." }, { "code": null, "e": 872, "s": 765, "text": "Download and install Anaconda (Python 3.7 for OS X in my case) from:https://www.anaconda.com/distribution/" }, { "code": null, "e": 1057, "s": 872, "text": "I will use the same version of Python that the actual Anaconda installation ships with for the new environment that we are going to create in a minute.To know which version simply run:" }, { "code": null, "e": 1068, "s": 1057, "text": "conda info" }, { "code": null, "e": 1110, "s": 1068, "text": "Then create and activate the environment:" }, { "code": null, "e": 1197, "s": 1110, "text": "conda create --name tf-object-detection python=3.7.4conda activate tf-object-detection" }, { "code": null, "e": 1360, "s": 1197, "text": "Install Tensorflow models and dependenciesChoose a folder you want to work at and create a directory named tensorflow.I will be working at the following location:" }, { "code": null, "e": 1398, "s": 1360, "text": "/Users/<username>/projects/tensorflow" }, { "code": null, "e": 1456, "s": 1398, "text": "Then just clone the Tensorflow models repository running:" }, { "code": null, "e": 1503, "s": 1456, "text": "git clone https://github.com/tensorflow/models" }, { "code": null, "e": 1549, "s": 1503, "text": "Now you need to install all the dependencies:" }, { "code": null, "e": 1704, "s": 1549, "text": "conda install Cythonconda install contextlib2conda install pillowconda install lxmlconda install jupyterconda install matplotlibconda install tensorflow=1" }, { "code": null, "e": 1837, "s": 1704, "text": "Install the COCO APIFor this go back to your projects folder and clone the Github project repository and execute the commands below:" }, { "code": null, "e": 1968, "s": 1837, "text": "git clone https://github.com/cocodataset/cocoapi.gitcd cocoapi/PythonAPImakecp -r pycocotools <path_to_tensorflow>/models/research" }, { "code": null, "e": 2207, "s": 1968, "text": "Protobuf Installation/CompilationThis is because Tensorflow Object Detection API use .proto files and these files need to be compiled into .py files in order for the Object Detection API to work properly. Protobuf can compile these files." }, { "code": null, "e": 2372, "s": 2207, "text": "Protobuf can be downloaded from:https://github.com/protocolbuffers/protobuf/releasesPlace the downloaded file anywhere you want, for example in the projects folder." }, { "code": null, "e": 2642, "s": 2372, "text": "After extracting you need to go to models/research and use protobuf to extract python files from the proto files in the object_detection/protos directory.For this purpose we are going to use a little script.Save it inside the research folder and name it use_protobuf.py" }, { "code": null, "e": 2853, "s": 2642, "text": "import osimport sysargs = sys.argvdirectory = args[1]protoc_path = args[2]for file in os.listdir(directory): if file.endswith(\".proto\"): os.system(protoc_path+\" \"+directory+\"/\"+file+\" --python_out=.\")" }, { "code": null, "e": 2878, "s": 2853, "text": "And then you can use it:" }, { "code": null, "e": 3070, "s": 2878, "text": "python use_protobuf.py <path_to_directory> <path_to_protoc_file># for example in our particular casepython use_protobuf.py object_detection/protos /Users/<username>/projects/protoc/bin/protoc" }, { "code": null, "e": 3214, "s": 3070, "text": "Add necessary environment variablesWe need to add the research and research/slim folder to our environment variables and run the setup.py file." }, { "code": null, "e": 3444, "s": 3214, "text": "export PYTHONPATH=$PYTHONPATH:<PATH_TO_TF>/TensorFlow/models/researchexport PYTHONPATH=$PYTHONPATH:<PATH_TO_TF>/TensorFlow/models/research/object_detectionexport PYTHONPATH=$PYTHONPATH:<PATH_TO_TF>/TensorFlow/models/research/slim" }, { "code": null, "e": 3589, "s": 3444, "text": "Note: the $PYTHONPATH environment variables needs to be added every time the shell session is closed or the Anaconda environment is deactivated." }, { "code": null, "e": 3641, "s": 3589, "text": "Now navigate to tensorflow/models/research and run:" }, { "code": null, "e": 3686, "s": 3641, "text": "python setup.py buildpython setup.py install" }, { "code": null, "e": 3885, "s": 3686, "text": "Testing Tensorflow Object Detection APIAfter the installation is complete we can test everything is working correctly by running the object_detection_tutorial.ipynb from the object_detection folder." }, { "code": null, "e": 4077, "s": 3885, "text": "Note: is important to have in consideration that this tutorial works for Tensorflow 2.0 and you must have Tensorflow installed in your environment — if not just run conda install tensorflow=2" }, { "code": null, "e": 4094, "s": 4077, "text": "jupyter notebook" }, { "code": null, "e": 4200, "s": 4094, "text": "Then select the object_detection_tutorial.ipynb from the browser window and just follow the instructions." }, { "code": null, "e": 4301, "s": 4200, "text": "You can also check everything is working by simply importing object_detection inside a python shell:" }, { "code": null, "e": 4325, "s": 4301, "text": "import object_detection" }, { "code": null, "e": 4394, "s": 4325, "text": "And if no errors then you can assume everything is working properly." }, { "code": null, "e": 4595, "s": 4394, "text": "For our purpose we are going to use a bunch of images representing Jagermeister bottles.To do that as fast as possible we are going to scrap google images with a python script to automate the process." }, { "code": null, "e": 4775, "s": 4595, "text": "Scripts can be downloaded from:https://github.com/hardikvasa/google-images-downloadand, for example, place the downloaded files in projects folder named as google-images-download." }, { "code": null, "e": 4848, "s": 4775, "text": "Then just navigate to the folder where the python script is and execute:" }, { "code": null, "e": 4939, "s": 4848, "text": "python google_images_download.py --keywords \"jagermeister bottle\" --limit 100 --format jpg" }, { "code": null, "e": 5098, "s": 4939, "text": "Because the images resolution may be very different and some can be quite big we want to scale them to do the training process faster.Here is a little script:" }, { "code": null, "e": 5743, "s": 5098, "text": "from PIL import Imageimport osimport argparsedef rescale_images(directory, size): for img in os.listdir(directory): im = Image.open(directory+img) im_resized = im.resize(size, Image.ANTIALIAS) im_resized.save(directory+img)if __name__ == '__main__': parser = argparse.ArgumentParser(description=\"Rescale images\") parser.add_argument('-d', '--directory', type=str, required=True, help='Directory containing the images') parser.add_argument('-s', '--size', type=int, nargs=2, required=True, metavar=('width', 'height'), help='Image size') args = parser.parse_args() rescale_images(args.directory, args.size)" }, { "code": null, "e": 5882, "s": 5743, "text": "To use the script we need to save it, for example, with the name transform_image_resolution.py and then go into the command line and type:" }, { "code": null, "e": 5946, "s": 5882, "text": "python transform_image_resolution.py -d <image_dir>/ -s 800 600" }, { "code": null, "e": 6029, "s": 5946, "text": "Note: images in the image_dir folder will be overwritten so do a backup if needed." }, { "code": null, "e": 6147, "s": 6029, "text": "Note: important to check the downloaded images folder in order to avoid duplicates and delete corrupted files if any." }, { "code": null, "e": 6303, "s": 6147, "text": "Now we have to have to move about 80% of images into object_detection/images/train directory and the other 20% into object_detection/images/test directory." }, { "code": null, "e": 6424, "s": 6303, "text": "In order to label our data, we need some kind of labeling software.In this particular case we are going to use LabelImg." }, { "code": null, "e": 6499, "s": 6424, "text": "As far as we are using Anaconda we only need to follow these instructions:" }, { "code": null, "e": 6736, "s": 6499, "text": "# install pyqt (version 5)conda install pyqt# download LabelImg and place it in 'projects' foldergit clone https://github.com/tzutalin/labelImg.git# navigate to labelImg directorycd labelImg# execute labelImg.pymake qt5py3;./labelImg.py" }, { "code": null, "e": 7035, "s": 6736, "text": "Open each train and test folders and then use the “Create RectBox” button for labeling each image and click save.We are going to use “jagermeister bottle” label for each box.After saving you will see an XML file appearing in the same directory with the same name for the image we have just labeled." }, { "code": null, "e": 7298, "s": 7035, "text": "In order to create the TFRecords we will use two scripts from Dat Tran’s raccoon detector; xml_to_csv.py and generate_tfrecord.py files.Download and place them in object_detection folder.You can go to References section below to see from where I downloaded them." }, { "code": null, "e": 7401, "s": 7298, "text": "We need now to modify xml_to_csv.py script so we can transform the created xml files to csv correctly." }, { "code": null, "e": 7887, "s": 7401, "text": "# Old:def main(): image_path = os.path.join(os.getcwd(), 'annotations') xml_df = xml_to_csv(image_path) xml_df.to_csv('raccoon_labels.csv', index=None) print('Successfully converted xml to csv.')# New:def main(): for folder in ['train', 'test']: image_path = os.path.join(os.getcwd(), ('images/' + folder)) xml_df = xml_to_csv(image_path) xml_df.to_csv(('images/'+folder+'_labels.csv'), index=None) print('Successfully converted xml to csv.')" }, { "code": null, "e": 7951, "s": 7887, "text": "Then we can use the script opening the command line and typing:" }, { "code": null, "e": 7972, "s": 7951, "text": "python xml_to_csv.py" }, { "code": null, "e": 8112, "s": 7972, "text": "As you can observe, two files have been created in the images directory. One called test_labels.csv and another one called train_labels.csv" }, { "code": null, "e": 8194, "s": 8112, "text": "Note: if you get “No module named ‘pandas’” error just do a conda install pandas." }, { "code": null, "e": 8299, "s": 8194, "text": "Before we can transform these csv files to TFRecords we need to change the generate_tfrecords.py script." }, { "code": null, "e": 8305, "s": 8299, "text": "From:" }, { "code": null, "e": 8441, "s": 8305, "text": "# TO-DO replace this with label mapdef class_text_to_int(row_label): if row_label == 'raccoon': return 1 else: None" }, { "code": null, "e": 8445, "s": 8441, "text": "To:" }, { "code": null, "e": 8558, "s": 8445, "text": "def class_text_to_int(row_label): if row_label == 'jagermeister bottle': return 1 else: None" }, { "code": null, "e": 8604, "s": 8558, "text": "Now the TFRecords can be generated by typing:" }, { "code": null, "e": 8863, "s": 8604, "text": "# train tfrecordpython generate_tfrecord.py --csv_input=images/train_labels.csv --image_dir=images/train --output_path=train.record# test tfrecordpython generate_tfrecord.py --csv_input=images/test_labels.csv --image_dir=images/test --output_path=test.record" }, { "code": null, "e": 8976, "s": 8863, "text": "These two command generate a train.record and a test.record file which can be used to train our object detector." }, { "code": null, "e": 9146, "s": 8976, "text": "Note: if getting an error like “module tensorflow has no attribute app” is because you are using Tensorflow 2.0 so we need to change a line in generate_tfrecord.py file." }, { "code": null, "e": 9152, "s": 9146, "text": "From:" }, { "code": null, "e": 9185, "s": 9152, "text": "# line 17import tensorflow as tf" }, { "code": null, "e": 9189, "s": 9185, "text": "To:" }, { "code": null, "e": 9232, "s": 9189, "text": "# line 17import tensorflow.compat.v1 as tf" }, { "code": null, "e": 9299, "s": 9232, "text": "Or if you prefer you can rollback to Tensorflow 1.0 instead doing:" }, { "code": null, "e": 9349, "s": 9299, "text": "conda remove tensorflowconda install tensorflow=1" }, { "code": null, "e": 9439, "s": 9349, "text": "Before we start training we need to create a label map and a training configuration file." }, { "code": null, "e": 9607, "s": 9439, "text": "Creating a label mapThe label map maps an id to name. We will put it in a folder called training located in the object_detection directory with the name labelmap.pbtxt" }, { "code": null, "e": 9655, "s": 9607, "text": "item { id: 1 name: 'jagermeister bottle'}" }, { "code": null, "e": 9754, "s": 9655, "text": "The id number of each item should match the id of specified item in the generate_tfrecord.py file." }, { "code": null, "e": 10028, "s": 9754, "text": "Creating a training configurationNow we need to create a training configuration file.We are going to use faster_rcnn_inception_v2_coco model which can be downloaded from:https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md" }, { "code": null, "e": 10170, "s": 10028, "text": "Download it uncompress the file and place it into object_detection folder.Folder name will look like faster_rcnn_inception_v2_coco_2018_01_28" }, { "code": null, "e": 10421, "s": 10170, "text": "And we are going to start with a sample config file named faster_rcnn_inception_v2_pets.config which can be found in the sample folder.You can download it from:https://github.com/tensorflow/models/tree/master/research/object_detection/samples/configs" }, { "code": null, "e": 10548, "s": 10421, "text": "Keep the same name and save it into the training folder and open it with a text editor in order to change a few lines of code." }, { "code": null, "e": 10642, "s": 10548, "text": "Line 9: change the number of classes to number of objects you want to detect (1 in our case)." }, { "code": null, "e": 10715, "s": 10642, "text": "Line 106: change fine_tune_checkpoint to the path of the model.ckpt file" }, { "code": null, "e": 10861, "s": 10715, "text": "fine_tune_checkpoint:\"/Users/<username>/projects/tensorflow/models/research/object_detection/faster_rcnn_inception_v2_coco_2018_01_28/model.ckpt\"" }, { "code": null, "e": 10927, "s": 10861, "text": "Line 123: change input_path to the path of the train.record file:" }, { "code": null, "e": 11023, "s": 10927, "text": "input_path:\"/Users/<username>/projects/tensorflow/models/research/object_detection/train.record" }, { "code": null, "e": 11089, "s": 11023, "text": "Line 135: change input_path to the path of the test.records file:" }, { "code": null, "e": 11184, "s": 11089, "text": "input_path:\"/Users/<username>/projects/tensorflow/models/research/object_detection/test.record" }, { "code": null, "e": 11251, "s": 11184, "text": "Line 125-137: change label_map_path to the path of label map file:" }, { "code": null, "e": 11362, "s": 11251, "text": "label_map_path:\"/Users/<username>/projects/tensorflow/models/research/object_detection/training/labelmap.pbtxt" }, { "code": null, "e": 11436, "s": 11362, "text": "Line 130: change num_example to the number of images in your test folder." }, { "code": null, "e": 11453, "s": 11436, "text": "num_examples: 10" }, { "code": null, "e": 11655, "s": 11453, "text": "We are going to use the train.py file which is located in the object_detection/legacy folder. We will copy it into the object_detection folder and then we will type the following into the command line:" }, { "code": null, "e": 11740, "s": 11655, "text": "Update: or we can use the model_main.py file in the object_detection folder instead." }, { "code": null, "e": 11866, "s": 11740, "text": "python model_main.py --logtostderr --model_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_pets.config" }, { "code": null, "e": 11935, "s": 11866, "text": "If everything was setup correctly the training should begin shortly." }, { "code": null, "e": 12095, "s": 11935, "text": "Note: if you are getting an error like “module tensorflow has no attribute contrib” is because you are using Tensorflow 2.0.There are two ways of solving this:" }, { "code": null, "e": 12171, "s": 12095, "text": "update scripts for being used with Tensorflow 2.0rollback to Tensorflow 1.0" }, { "code": null, "e": 12221, "s": 12171, "text": "update scripts for being used with Tensorflow 2.0" }, { "code": null, "e": 12248, "s": 12221, "text": "rollback to Tensorflow 1.0" }, { "code": null, "e": 12301, "s": 12248, "text": "The easy way is doing a rollback so do the following" }, { "code": null, "e": 12401, "s": 12301, "text": "# uninstall Tensorflow 2.0conda remove tensorflow# install Tensorflow 1.Xconda install tensorflow=1" }, { "code": null, "e": 12647, "s": 12401, "text": "Once the training is running you will see every 5 minutes or so (depending on your hardware) the current loss gets logged to Tensorboard. We can open Tensorboard by opening a second command line, navigating to object_detection folder and typing:" }, { "code": null, "e": 12677, "s": 12647, "text": "tensorboard --logdir=training" }, { "code": null, "e": 12720, "s": 12677, "text": "A web page is now opened at localhost:6006" }, { "code": null, "e": 12846, "s": 12720, "text": "You should train the model until it reaches a satisfying loss.The training process can be then terminated by pressing Ctrl+C." }, { "code": null, "e": 13130, "s": 12846, "text": "Once the model is trained we need to generate an inference graph, which can be used to run the model. For doing so we need to first find out the highest saved step number.For this, we need to navigate to the training directory and look for the model.ckpt file with the biggest index." }, { "code": null, "e": 13214, "s": 13130, "text": "Then we can create the inference graph by typing the following in the command line:" }, { "code": null, "e": 13430, "s": 13214, "text": "python export_inference_graph.py --input_type image_tensor --pipeline_config_path training/faster_rcnn_inception_v2_pets.config --trained_checkpoint_prefix training/model.ckpt-XXXX --output_directory inference_graph" }, { "code": null, "e": 13472, "s": 13430, "text": "where XXXX represents the highest number." }, { "code": null, "e": 13682, "s": 13472, "text": "First we need to install TensorflowJS in our environment.Usually we would use conda to install the package but unfortunately is not available in the repository sources.So we are going to use it via python pip:" }, { "code": null, "e": 13707, "s": 13682, "text": "pip install tensorflowjs" }, { "code": null, "e": 13849, "s": 13707, "text": "Once the installation finishes we can execute the following command in order to convert our saved model to something tensorfowjs understands:" }, { "code": null, "e": 13927, "s": 13849, "text": "tensorflowjs_converter --input_format=tf_saved_model <input_dir> <output_dir>" }, { "code": null, "e": 14064, "s": 13927, "text": "For example if we are in the directory /Users/<username>/projects/tensorflow/models/research/object_detection we can run something like:" }, { "code": null, "e": 14405, "s": 14064, "text": "tensorflowjs_converter --input_format=tf_saved_model --output_node_names='detection_boxes,detection_classes,detection_features,detection_multiclass_scores,detection_scores,num_detections,raw_detection_boxes,raw_detection_scores' --saved_model_tags=serve --output_format=tfjs_graph_model inference_graph/saved_model inference_graph/web_model" }, { "code": null, "e": 14598, "s": 14405, "text": "Note that the conversion options are specifically set for converting an object detection SavedModel and the output_node_names configuration have been retrieved with thesaved_model_cli command:" }, { "code": null, "e": 14894, "s": 14598, "text": "saved_model_cli show --dir inference_graph/saved_model --tag_set serve --signature_def serving_default#output will print something like this:#detection_boxes#detection_classes#detection_features#detection_multiclass_scores#detection_scores#num_detections#raw_detection_boxes#raw_detection_scores" }, { "code": null, "e": 14948, "s": 14894, "text": "Full explanation on gist in References section below." }, { "code": null, "e": 15228, "s": 14948, "text": "Now that we have our model properly converted we can use it in a web application environment that runs Javascript.For making things smoother we can head to the demo application listed in References section below.The repository you are looking for is the adriagil/tfjs-vue-example" }, { "code": null, "e": 15690, "s": 15228, "text": "I have to stop for a moment and thank to freshsomebody for sharing this great Vue.js demo application which uses a pre-trained coco-ssd model to be used with a webcam in a browser.I’ve just adapted the code to work with my trained model consisting basically in how model serving and loading is done and how to retrieve the needed tensors to analyze data.Here the original app in case you are interested https://github.com/freshsomebody/tfjs-coco-ssd-vue-example" }, { "code": null, "e": 15883, "s": 15690, "text": "Just navigate there and clone or download at your preferred location.Then copy the converted model in the previous step into the root directory of the downloaded project, the web_model folder." }, { "code": null, "e": 15940, "s": 15883, "text": "Then navigate to the application root directory and run:" }, { "code": null, "e": 15952, "s": 15940, "text": "npm install" }, { "code": null, "e": 16083, "s": 15952, "text": "Once finished open the App.vue file in your text editor of choice.You can see now the source code of the web application, great! 🍺" }, { "code": null, "e": 16288, "s": 16083, "text": "In order to load the converted model properly we need to do it via a web server.We’re going to use a Node package to do so called http-server.All we need to do is activate the web server with the command:" }, { "code": null, "e": 16342, "s": 16288, "text": "node_modules/http-server/bin/http-server -c1 --cors ." }, { "code": null, "e": 16458, "s": 16342, "text": "and the model will be accesible via http at http://localhost:8081/web_model/model.json to be loaded in the browser." }, { "code": null, "e": 16578, "s": 16458, "text": "Last but not least, we need to compile or serve the frontend application to test everything with the following command:" }, { "code": null, "e": 16592, "s": 16578, "text": "npm run serve" }, { "code": null, "e": 16758, "s": 16592, "text": "In http://localhost:8080 you should now see the webcam stream and the corresponding bounding boxes wrapping the Jaggermeister bottle in red.Awesome, we are done! 👏👏👏" }, { "code": null, "e": 16859, "s": 16758, "text": "Despite the results of this experience are OK there are 2 important things to have in consideration." }, { "code": null, "e": 17264, "s": 16859, "text": "The first one is that working in OS X is not the best choice.I would recommend you to switch to a Linux or Windows environment but only if you are going to use GPU, if not is the same piece of crap 😅A better solution (we know proper GPU cards are very expensive) is to do it on Google Cloud Plaform.They offer a very good environment and free credits for you to spend in any of your training experiments." }, { "code": null, "e": 17635, "s": 17264, "text": "The second thing that sucks is that the inception model we have chosen is precise but is very slow on computer browsers and even worse in mobile.So I’m just now training another model based on MobileNet which should perform a lot better 🤞 hopefully.Also my model is not optimized and maybe that could help, but I need to do some research on how to achieve it. We’ll see." }, { "code": null, "e": 17848, "s": 17635, "text": "If you liked, want more like this or have any questions please don’t hesitate to contact me...if you arrived here, you deserve it!And again many thanks to the authors that have motivated me to write this article." }, { "code": null, "e": 17866, "s": 17848, "text": "That’s all folks!" }, { "code": null, "e": 18030, "s": 17866, "text": "[Update 24/02/2020]As I commented before, the performance for a web browser was not acceptable for a real-time video analysis so I decided to do a bit of research." }, { "code": null, "e": 18331, "s": 18030, "text": "Thanks to stackoverflow community ❤️ I found many suggestions like optimizing the model or going back to the training process again with another model. I decided to try with another model because the rcnn-inception model I trained was very precise but not really thought for the application I needed." }, { "code": null, "e": 18654, "s": 18331, "text": "I picked ssd_mobilenet_v2_coco this time.After a weekend training the model and almost 30k steps — I know is not necessary for development but worth to try like in a real situation— was time for testing. Results were far better than in my first attempt so now prediction rate is almost fluid with an acceptable frame rate." } ]
Building a web scraper tool to analyze condo prices in Toronto | by Karan Singh | Towards Data Science
Condos have always fascinated me and in the city, I live, they are perhaps the first (or realistic) option that comes to the mind of many first-time home-buyers. Unless you have been living under a rock, you would be aware that house prices in Toronto have jumped manyfold over the last decade, and more so in the last 5 years. More recently, it has been the condo market that is on fire. So if you, like me, are looking for a condo to buy, you are in the right place. Being a highly data-driven person, I built a web-scraper tool that helps me analyze the condo prices in Toronto. My go-to website is Condos.ca. It has a good user interface and provides market intelligence (which I thought would be useful in validating my results). At the time of writing this article, it has listings spanning over 80 web pages, and I shall extract data from the first 50 pages as described later in the article. The objective of this undertaking was 2-fold: To scrape essential data on relevant parameters from the website to build a benchmark database To conduct market research by performing some exploratory EDA on the database such as average price per bedroom, average maintenance costs, average condo size, etc. I extracted the information displayed on every listing such as the price, the street address, the number of bedrooms, bathrooms, whether it has parking or not, the size range and, the maintenance fees. (Note: Many other parameters affect condo prices such as the age of the building, property tax, Floor number, images, etc., but I have left these for simplicity) It’s worth mentioning here that I had limited to no experience with HTML before performing this exercise. But here lies the beauty of web scraping. You don’t need an advanced understanding of HTML. I simply learned how to extract the required value from the waterfall of tags within the HTML code. And the rest is all python! Here is a useful resource on how to scrape websites. So let’s get started! We begin by importing the necessary modules. from bs4 import BeautifulSoup # For HTML parsingfrom time import sleep # To prevent overwhelming the server between connectionsimport pandas as pd # For converting results to a dataframe and bar chart plots# For Visualizationsimport matplotlib.pyplot as pltimport plotly.offline as pyimport plotly.graph_objs as go%matplotlib inline As soon as I made the request to scrape the website, I ran into an error. This is because many websites try to block users from scraping any data and it may be illegal depending on what one plans to do with the data (I had however obtained permission from condos.ca). To navigate through this issue, I used an API called Selenium. It’s an API that allows you to programmatically interact with a browser the way a real user would. Although Selenium is primarily used to help test a web application, it can be used for any task where you need browser automation. from selenium import webdriverfrom selenium.webdriver.common.keys import Keysdriver.get(“https://condos.ca") Working with filters Running the previous code opens up a new browser and loads the website, and helps you interact with the website as if a real user would. For example, instead of manually clicking on the website to select filters such as the no. of bedrooms, or home type, or provide a price range, Selenium does that easily by passing in a couple of lines of command. The model gives the user the ability to select multiple filters.For example, to get 2 bedroom options, I use the following code to click on the button: two_bed = driver.find_element_by_css_selector( ‘insert_css_path’)two_bed.click() Similarly, to get all the results with Gym, I simply use the following code: Gym = driver.find_element_by_css_selector('insert_css_path')Gym.click() Defining a function to iterate over multiple pages Because I want to be able to do this analysis for other cities, I define a function that creates a beautiful soup object using parameters of ‘city’, ‘mode’, and ‘page no’. Here, the ‘mode’ parameter takes in ‘Sale’ or ‘Rent’ as values, giving the user the ability to analyze rental prices as well! def get_page(city, mode, page): url= f'https://condos.ca/{city}/condos-for-{mode}?mode= {mode}&page={page}' driver.get(url) page_source = driver.page_source soup = BeautifulSoup(page_source, 'lxml') return soup The function utilizes the module called BeautifulSoup and returns an object called soup for a given webpage. It also loads up the requested webpage. (Later I shall iterate over all the webpages to extract the soup object for all pages) Now that we have the soup object, we can extract some useful information such as the total number of listings, total listings per page, etc., by parsing through the webpage HTML. It’s not as difficult as it sounds! We use soup.find() to obtain the relevant tags. A useful approach is to start by extracting the data on the first page. If you can do that successfully, rest is simply iterating the process over all the pages! #Defining soup object for page 1soup = get_page('toronto', 'Sale',1) Extracting some relevant information on listings from the first page. Total listings in Toronto : #The total number of Condo Listings in Torontosoup.find(‘div’,class_ = ‘sc-AxjAm dWkXrE’).find(‘span’,class_ = _5FYo1’).get_text() #no. of listings : 3560 The number of listings on the first page : len(soup.find_all(‘div’,class_ = ‘_3O0GU’)) #43 Now that we are a little comfortable with this, we can be a bit more ambitious and extract all the prices on page 1. prices=[]for tag in soup.find_all(‘div’,class_ = ‘_2PKdn’):prices.append(tag.get_text())prices[:5]['$450,000','$649,900','$399,999','$599,900','$780,000'] To make things simpler, I defined a variable called condo_container that would hold all the relevant data (price, location, size, etc.) of all the listings on a page condo_container = soup.find_all('div','_3SMhd') Now, all we have to do is extract price and other data from this condo_container. See the example below: #Obtaining Location of all listings on page 1Location_list=[]for i in range(len(condo_container)):for tag in condo_container[i].find('span',class_='_1Gfb3'):Location_list.append(tag)Location_list[:5]['1001 - 19 Four Winds Dr','306 - 2 Aberfoyle Cres','911 - 100 Echo Pt','524 - 120 Dallimore Circ','1121 - 386 Yonge St'] Rinse and repeat the above process for all variables and we got all the lists that we would need to construct a data-frame (see sample code below). The process gets a little bit tricky while trying to extract parameters such as bathrooms, size, and parking, etc owing to the HTML structure but with a little bit of effort, it can be done! (I am not sharing the complete code on purpose so as to avoid the reproduction of code). Now that we have all the lists, we simply append them onto a dictionary called data defined below. Some of the tags get a little confusing but that’s because they have been formatted from string type to integer wherever required. data = {'Prices':[],'Location':[],'Date_listed':[],'Bedrooms':[],'Bathrooms':[],'Maint_Fees':[],'Size':[],'Parking':[]}final_list=[]for page in range(50): soup = get_page('toronto', 'Sale',page) condo_container = soup.find_all('div','_3SMhd') sleep(random()) print(page) for i in range(len(condo_container)): listing = [] price_tag = condo_container[i].find('div',class_= '_2PKdn').get_text() formatted_tag = int(price_tag.split('$')[1].replace(',','')) data['Prices'].append(formatted_tag) location_tag = condo_container[i].find('span',class_='_1Gfb3').get_text() data['Location'].append(location_tag) if maint_tag != '': Maintenance_Fees = int(maint_tag.split('$') [1].replace(',','')) data['Maint_Fees'].append(Maintenance_Fees) else: data['Maint_Fees'].append('error') for info_tag in condo_container[i].find('div',class_='_3FIJA'): listing.append(info_tag) final_list.append(listing) Once we have the dictionary ready, we convert it into a pandas data-frame for further processing and EDA. The resulting data-frame has 2031 rows. A quick look at the dataset tells us that Bedrooms, Bathrooms, Maintenance fees, and Size are object type variables because they had been stored as string type in the HTML. These variables were cleaned and converted into an integer or float type. Moreover, I created a variable, Avg_Size from the Size variable. Through further data inspection, I found error values which I replaced with the mean of the respective columns. I also engineered a Street Address variable from the Location variable in case I want to perform some kind of location analysis later on. The dataset was treated for outliers, which were skewing my averages (expensive condos can get well expensive! ). The missing values were imputed with average or most occurring values in their respective columns. Now, that our dataset looks nice and clean, we can go ahead with some basic exploratory analysis! I was curious, how the average price and size varied by the number of bedrooms, which I think would be the first thing on the mind of any buyer! So I created some plots using Plotly (see sample code below). price_by_bed = condos.groupby(['Bedrooms']['Prices'].mean()data = go.Bar( x=price_by_bed.index, y=price_by_bed.values, )layout = go.Layout( title='Average Condo Price', xaxis_title="No. of Beds", yaxis_title="Value in $M" )fig = go.Figure(data=data, layout=layout)py.iplot(fig) The average price per square foot (taking in only 1,2 and 3 bedrooms in the subset) was calculated at $ 897, a little higher than the quoted average of $827/sq. ft on the day of my analysis (Note: There has been a gradual decline in average prices since the onset of COVID so the values shown here may be different from the current values). I was also able to analyze average maintenance values by the number of bedrooms. An interesting insight was that maintenance fees can make or break your investment in a condo since it could account for almost 25% of your monthly mortgage value! (something to keep in mind and not just focus on that hefty price tag) Below, I analyzed the number of listings by average sizes and found that most condos on sale fall in the 600–699 sq. ft category. These were some of the interesting insights I derived from this web scraping exercise. I am sure that armed with this knowledge now, I would fall into the category of an ‘informed buyer’’. If you have any interesting points to share, I would love to hear your comments down below. Thanks to the team at condos.ca for giving me permission to carry out this interesting and valuable exercise! Disclaimer: Please note that the views, thoughts, and opinions expressed in the text belong solely to the author, and not necessarily to the author’s employer, organization, committee, or other group or individual. This is not investment advice and the author does not intend to use the data for any commercial purposes but for personal reasons only.
[ { "code": null, "e": 641, "s": 172, "text": "Condos have always fascinated me and in the city, I live, they are perhaps the first (or realistic) option that comes to the mind of many first-time home-buyers. Unless you have been living under a rock, you would be aware that house prices in Toronto have jumped manyfold over the last decade, and more so in the last 5 years. More recently, it has been the condo market that is on fire. So if you, like me, are looking for a condo to buy, you are in the right place." }, { "code": null, "e": 1072, "s": 641, "text": "Being a highly data-driven person, I built a web-scraper tool that helps me analyze the condo prices in Toronto. My go-to website is Condos.ca. It has a good user interface and provides market intelligence (which I thought would be useful in validating my results). At the time of writing this article, it has listings spanning over 80 web pages, and I shall extract data from the first 50 pages as described later in the article." }, { "code": null, "e": 1118, "s": 1072, "text": "The objective of this undertaking was 2-fold:" }, { "code": null, "e": 1213, "s": 1118, "text": "To scrape essential data on relevant parameters from the website to build a benchmark database" }, { "code": null, "e": 1378, "s": 1213, "text": "To conduct market research by performing some exploratory EDA on the database such as average price per bedroom, average maintenance costs, average condo size, etc." }, { "code": null, "e": 1742, "s": 1378, "text": "I extracted the information displayed on every listing such as the price, the street address, the number of bedrooms, bathrooms, whether it has parking or not, the size range and, the maintenance fees. (Note: Many other parameters affect condo prices such as the age of the building, property tax, Floor number, images, etc., but I have left these for simplicity)" }, { "code": null, "e": 2121, "s": 1742, "text": "It’s worth mentioning here that I had limited to no experience with HTML before performing this exercise. But here lies the beauty of web scraping. You don’t need an advanced understanding of HTML. I simply learned how to extract the required value from the waterfall of tags within the HTML code. And the rest is all python! Here is a useful resource on how to scrape websites." }, { "code": null, "e": 2143, "s": 2121, "text": "So let’s get started!" }, { "code": null, "e": 2188, "s": 2143, "text": "We begin by importing the necessary modules." }, { "code": null, "e": 2521, "s": 2188, "text": "from bs4 import BeautifulSoup # For HTML parsingfrom time import sleep # To prevent overwhelming the server between connectionsimport pandas as pd # For converting results to a dataframe and bar chart plots# For Visualizationsimport matplotlib.pyplot as pltimport plotly.offline as pyimport plotly.graph_objs as go%matplotlib inline" }, { "code": null, "e": 3082, "s": 2521, "text": "As soon as I made the request to scrape the website, I ran into an error. This is because many websites try to block users from scraping any data and it may be illegal depending on what one plans to do with the data (I had however obtained permission from condos.ca). To navigate through this issue, I used an API called Selenium. It’s an API that allows you to programmatically interact with a browser the way a real user would. Although Selenium is primarily used to help test a web application, it can be used for any task where you need browser automation." }, { "code": null, "e": 3191, "s": 3082, "text": "from selenium import webdriverfrom selenium.webdriver.common.keys import Keysdriver.get(“https://condos.ca\")" }, { "code": null, "e": 3212, "s": 3191, "text": "Working with filters" }, { "code": null, "e": 3715, "s": 3212, "text": "Running the previous code opens up a new browser and loads the website, and helps you interact with the website as if a real user would. For example, instead of manually clicking on the website to select filters such as the no. of bedrooms, or home type, or provide a price range, Selenium does that easily by passing in a couple of lines of command. The model gives the user the ability to select multiple filters.For example, to get 2 bedroom options, I use the following code to click on the button:" }, { "code": null, "e": 3796, "s": 3715, "text": "two_bed = driver.find_element_by_css_selector( ‘insert_css_path’)two_bed.click()" }, { "code": null, "e": 3873, "s": 3796, "text": "Similarly, to get all the results with Gym, I simply use the following code:" }, { "code": null, "e": 3945, "s": 3873, "text": "Gym = driver.find_element_by_css_selector('insert_css_path')Gym.click()" }, { "code": null, "e": 3996, "s": 3945, "text": "Defining a function to iterate over multiple pages" }, { "code": null, "e": 4294, "s": 3996, "text": "Because I want to be able to do this analysis for other cities, I define a function that creates a beautiful soup object using parameters of ‘city’, ‘mode’, and ‘page no’. Here, the ‘mode’ parameter takes in ‘Sale’ or ‘Rent’ as values, giving the user the ability to analyze rental prices as well!" }, { "code": null, "e": 4537, "s": 4294, "text": "def get_page(city, mode, page): url= f'https://condos.ca/{city}/condos-for-{mode}?mode= {mode}&page={page}' driver.get(url) page_source = driver.page_source soup = BeautifulSoup(page_source, 'lxml') return soup" }, { "code": null, "e": 4773, "s": 4537, "text": "The function utilizes the module called BeautifulSoup and returns an object called soup for a given webpage. It also loads up the requested webpage. (Later I shall iterate over all the webpages to extract the soup object for all pages)" }, { "code": null, "e": 5198, "s": 4773, "text": "Now that we have the soup object, we can extract some useful information such as the total number of listings, total listings per page, etc., by parsing through the webpage HTML. It’s not as difficult as it sounds! We use soup.find() to obtain the relevant tags. A useful approach is to start by extracting the data on the first page. If you can do that successfully, rest is simply iterating the process over all the pages!" }, { "code": null, "e": 5267, "s": 5198, "text": "#Defining soup object for page 1soup = get_page('toronto', 'Sale',1)" }, { "code": null, "e": 5337, "s": 5267, "text": "Extracting some relevant information on listings from the first page." }, { "code": null, "e": 5365, "s": 5337, "text": "Total listings in Toronto :" }, { "code": null, "e": 5520, "s": 5365, "text": "#The total number of Condo Listings in Torontosoup.find(‘div’,class_ = ‘sc-AxjAm dWkXrE’).find(‘span’,class_ = _5FYo1’).get_text() #no. of listings : 3560" }, { "code": null, "e": 5563, "s": 5520, "text": "The number of listings on the first page :" }, { "code": null, "e": 5611, "s": 5563, "text": "len(soup.find_all(‘div’,class_ = ‘_3O0GU’)) #43" }, { "code": null, "e": 5728, "s": 5611, "text": "Now that we are a little comfortable with this, we can be a bit more ambitious and extract all the prices on page 1." }, { "code": null, "e": 5883, "s": 5728, "text": "prices=[]for tag in soup.find_all(‘div’,class_ = ‘_2PKdn’):prices.append(tag.get_text())prices[:5]['$450,000','$649,900','$399,999','$599,900','$780,000']" }, { "code": null, "e": 6049, "s": 5883, "text": "To make things simpler, I defined a variable called condo_container that would hold all the relevant data (price, location, size, etc.) of all the listings on a page" }, { "code": null, "e": 6097, "s": 6049, "text": "condo_container = soup.find_all('div','_3SMhd')" }, { "code": null, "e": 6202, "s": 6097, "text": "Now, all we have to do is extract price and other data from this condo_container. See the example below:" }, { "code": null, "e": 6523, "s": 6202, "text": "#Obtaining Location of all listings on page 1Location_list=[]for i in range(len(condo_container)):for tag in condo_container[i].find('span',class_='_1Gfb3'):Location_list.append(tag)Location_list[:5]['1001 - 19 Four Winds Dr','306 - 2 Aberfoyle Cres','911 - 100 Echo Pt','524 - 120 Dallimore Circ','1121 - 386 Yonge St']" }, { "code": null, "e": 6951, "s": 6523, "text": "Rinse and repeat the above process for all variables and we got all the lists that we would need to construct a data-frame (see sample code below). The process gets a little bit tricky while trying to extract parameters such as bathrooms, size, and parking, etc owing to the HTML structure but with a little bit of effort, it can be done! (I am not sharing the complete code on purpose so as to avoid the reproduction of code)." }, { "code": null, "e": 7181, "s": 6951, "text": "Now that we have all the lists, we simply append them onto a dictionary called data defined below. Some of the tags get a little confusing but that’s because they have been formatted from string type to integer wherever required." }, { "code": null, "e": 8172, "s": 7181, "text": "data = {'Prices':[],'Location':[],'Date_listed':[],'Bedrooms':[],'Bathrooms':[],'Maint_Fees':[],'Size':[],'Parking':[]}final_list=[]for page in range(50): soup = get_page('toronto', 'Sale',page) condo_container = soup.find_all('div','_3SMhd') sleep(random()) print(page) for i in range(len(condo_container)): listing = [] price_tag = condo_container[i].find('div',class_= '_2PKdn').get_text() formatted_tag = int(price_tag.split('$')[1].replace(',','')) data['Prices'].append(formatted_tag) location_tag = condo_container[i].find('span',class_='_1Gfb3').get_text() data['Location'].append(location_tag) if maint_tag != '': Maintenance_Fees = int(maint_tag.split('$') [1].replace(',','')) data['Maint_Fees'].append(Maintenance_Fees) else: data['Maint_Fees'].append('error') for info_tag in condo_container[i].find('div',class_='_3FIJA'): listing.append(info_tag) final_list.append(listing)" }, { "code": null, "e": 8318, "s": 8172, "text": "Once we have the dictionary ready, we convert it into a pandas data-frame for further processing and EDA. The resulting data-frame has 2031 rows." }, { "code": null, "e": 8491, "s": 8318, "text": "A quick look at the dataset tells us that Bedrooms, Bathrooms, Maintenance fees, and Size are object type variables because they had been stored as string type in the HTML." }, { "code": null, "e": 9093, "s": 8491, "text": "These variables were cleaned and converted into an integer or float type. Moreover, I created a variable, Avg_Size from the Size variable. Through further data inspection, I found error values which I replaced with the mean of the respective columns. I also engineered a Street Address variable from the Location variable in case I want to perform some kind of location analysis later on. The dataset was treated for outliers, which were skewing my averages (expensive condos can get well expensive! ). The missing values were imputed with average or most occurring values in their respective columns." }, { "code": null, "e": 9191, "s": 9093, "text": "Now, that our dataset looks nice and clean, we can go ahead with some basic exploratory analysis!" }, { "code": null, "e": 9398, "s": 9191, "text": "I was curious, how the average price and size varied by the number of bedrooms, which I think would be the first thing on the mind of any buyer! So I created some plots using Plotly (see sample code below)." }, { "code": null, "e": 9720, "s": 9398, "text": "price_by_bed = condos.groupby(['Bedrooms']['Prices'].mean()data = go.Bar( x=price_by_bed.index, y=price_by_bed.values, )layout = go.Layout( title='Average Condo Price', xaxis_title=\"No. of Beds\", yaxis_title=\"Value in $M\" )fig = go.Figure(data=data, layout=layout)py.iplot(fig)" }, { "code": null, "e": 10061, "s": 9720, "text": "The average price per square foot (taking in only 1,2 and 3 bedrooms in the subset) was calculated at $ 897, a little higher than the quoted average of $827/sq. ft on the day of my analysis (Note: There has been a gradual decline in average prices since the onset of COVID so the values shown here may be different from the current values)." }, { "code": null, "e": 10377, "s": 10061, "text": "I was also able to analyze average maintenance values by the number of bedrooms. An interesting insight was that maintenance fees can make or break your investment in a condo since it could account for almost 25% of your monthly mortgage value! (something to keep in mind and not just focus on that hefty price tag)" }, { "code": null, "e": 10507, "s": 10377, "text": "Below, I analyzed the number of listings by average sizes and found that most condos on sale fall in the 600–699 sq. ft category." }, { "code": null, "e": 10696, "s": 10507, "text": "These were some of the interesting insights I derived from this web scraping exercise. I am sure that armed with this knowledge now, I would fall into the category of an ‘informed buyer’’." }, { "code": null, "e": 10788, "s": 10696, "text": "If you have any interesting points to share, I would love to hear your comments down below." }, { "code": null, "e": 10898, "s": 10788, "text": "Thanks to the team at condos.ca for giving me permission to carry out this interesting and valuable exercise!" } ]
Git Branch Merge
We have the emergency fix ready, and so let's merge the master and emergency-fix branches. First, we need to change to the master branch: git checkout master Switched to branch 'master' Now we merge the current branch (master) with emergency-fix: git merge emergency-fix Updating 09f4acd..dfa79db Fast-forward index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) Since the emergency-fix branch came directly from master, and no other changes had been made to master while we were working, Git sees this as a continuation of master. So it can "Fast-forward", just pointing both master and emergency-fix to the same commit. As master and emergency-fix are essentially the same now, we can delete emergency-fix, as it is no longer needed: git branch -d emergency-fix Deleted branch emergency-fix (was dfa79db). Now we can move over to hello-world-images and keep working. Add another image file (img_hello_git.jpg) and change index.html, so it shows it: git checkout hello-world-images Switched to branch 'hello-world-images' Now, we are done with our work here and can stage and commit for this branch: git add --all git commit -m "added new image" [hello-world-images 1f1584e] added new image 2 files changed, 1 insertion(+) create mode 100644 img_hello_git.jpg We see that index.html has been changed in both branches. Now we are ready to merge hello-world-images into master. But what will happen to the changes we recently made in master? git checkout master git merge hello-world-images Auto-merging index.html CONFLICT (content): Merge conflict in index.html Automatic merge failed; fix conflicts and then commit the result. The merge failed, as there is conflict between the versions for index.html. Let us check the status: git status On branch master You have unmerged paths. (fix conflicts and run "git commit") (use "git merge --abort" to abort the merge) Changes to be committed: new file: img_hello_git.jpg new file: img_hello_world.jpg Unmerged paths: (use "git add ..." to mark resolution) both modified: index.html This confirms there is a conflict in index.html, but the image files are ready and stagedto be committed. So we need to fix that conflict. Open the file in our editor: We can see the differences between the versions and edit it like we want: Now we can stage index.html and check the status: git add index.html git status On branch master All conflicts fixed but you are still merging. (use "git commit" to conclude merge) Changes to be committed: new file: img_hello_git.jpg new file: img_hello_world.jpg modified: index.html The conflict has been fixed, and we can use commit to conclude the merge: git commit -m "merged with hello-world-images after fixing conflicts" [master e0b6038] merged with hello-world-images after fixing conflicts And delete the hello-world-images branch: git branch -d hello-world-images Deleted branch hello-world-images (was 1f1584e). Now you have a better understanding of how branches and merging works. Time to start working with a remote repository! Merge the hello-you branch with the current branch: git hello-you 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": 91, "s": 0, "text": "We have the emergency fix ready, and so let's merge the master and emergency-fix branches." }, { "code": null, "e": 138, "s": 91, "text": "First, we need to change to the master branch:" }, { "code": null, "e": 186, "s": 138, "text": "git checkout master\nSwitched to branch 'master'" }, { "code": null, "e": 247, "s": 186, "text": "Now we merge the current branch (master) with emergency-fix:" }, { "code": null, "e": 376, "s": 247, "text": "git merge emergency-fix\nUpdating 09f4acd..dfa79db\nFast-forward\n index.html | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)" }, { "code": null, "e": 635, "s": 376, "text": "Since the emergency-fix branch came directly from master, and no other changes had been made to master while we were working, Git sees this as a continuation of master. So it can \"Fast-forward\", just pointing both master and emergency-fix to the same commit." }, { "code": null, "e": 749, "s": 635, "text": "As master and emergency-fix are essentially the same now, we can delete emergency-fix, as it is no longer needed:" }, { "code": null, "e": 821, "s": 749, "text": "git branch -d emergency-fix\nDeleted branch emergency-fix (was dfa79db)." }, { "code": null, "e": 964, "s": 821, "text": "Now we can move over to hello-world-images and keep working. Add another image file (img_hello_git.jpg) and change index.html, so it shows it:" }, { "code": null, "e": 1036, "s": 964, "text": "git checkout hello-world-images\nSwitched to branch 'hello-world-images'" }, { "code": null, "e": 1114, "s": 1036, "text": "Now, we are done with our work here and can stage and commit for this branch:" }, { "code": null, "e": 1276, "s": 1114, "text": "git add --all\ngit commit -m \"added new image\"\n[hello-world-images 1f1584e] added new image\n 2 files changed, 1 insertion(+)\n create mode 100644 img_hello_git.jpg" }, { "code": null, "e": 1457, "s": 1276, "text": "We see that index.html has been changed in both branches. Now we are ready to merge hello-world-images into master. But what will \nhappen to the changes we recently made in master?" }, { "code": null, "e": 1645, "s": 1457, "text": "git checkout master\ngit merge hello-world-images\nAuto-merging index.html\nCONFLICT (content): Merge conflict in index.html\nAutomatic merge failed; fix conflicts and then commit the result." }, { "code": null, "e": 1746, "s": 1645, "text": "The merge failed, as there is conflict between the versions for index.html. Let us check the status:" }, { "code": null, "e": 2083, "s": 1746, "text": "git status\nOn branch master\nYou have unmerged paths.\n (fix conflicts and run \"git commit\")\n (use \"git merge --abort\" to abort the merge)\n\nChanges to be committed:\n new file: img_hello_git.jpg\n new file: img_hello_world.jpg\n\nUnmerged paths:\n (use \"git add ...\" to mark resolution)\n both modified: index.html" }, { "code": null, "e": 2189, "s": 2083, "text": "This confirms there is a conflict in index.html, but the image files are ready and stagedto be committed." }, { "code": null, "e": 2251, "s": 2189, "text": "So we need to fix that conflict. Open the file in our editor:" }, { "code": null, "e": 2325, "s": 2251, "text": "We can see the differences between the versions and edit it like we want:" }, { "code": null, "e": 2375, "s": 2325, "text": "Now we can stage index.html and check the status:" }, { "code": null, "e": 2643, "s": 2375, "text": "git add index.html\ngit status\nOn branch master\nAll conflicts fixed but you are still merging.\n (use \"git commit\" to conclude merge)\n\nChanges to be committed:\n new file: img_hello_git.jpg\n new file: img_hello_world.jpg\n modified: index.html" }, { "code": null, "e": 2717, "s": 2643, "text": "The conflict has been fixed, and we can use commit to conclude the merge:" }, { "code": null, "e": 2858, "s": 2717, "text": "git commit -m \"merged with hello-world-images after fixing conflicts\"\n[master e0b6038] merged with hello-world-images after fixing conflicts" }, { "code": null, "e": 2900, "s": 2858, "text": "And delete the hello-world-images branch:" }, { "code": null, "e": 2982, "s": 2900, "text": "git branch -d hello-world-images\nDeleted branch hello-world-images (was 1f1584e)." }, { "code": null, "e": 3101, "s": 2982, "text": "Now you have a better understanding of how branches and merging works. Time to start working with a remote repository!" }, { "code": null, "e": 3153, "s": 3101, "text": "Merge the hello-you branch with the current branch:" }, { "code": null, "e": 3168, "s": 3153, "text": "git hello-you" }, { "code": null, "e": 3188, "s": 3168, "text": "\nStart the Exercise" }, { "code": null, "e": 3221, "s": 3188, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 3263, "s": 3221, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 3370, "s": 3263, "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": 3389, "s": 3370, "text": "help@w3schools.com" } ]
Grouping objects based on key property in JavaScript
We have a parentArray that contains many sub arrays each of the same size, each sub array is an array of objects containing two properties: key and value. Within a subarray it is confirmed that two objects cannot have the same key but all subarrays have the same pair of n keys where n is the size of the sub array. Our job is to prepare an object with key as key of objects and value being an array that contains all the values for that particular key. Here is a sample parent array − const parentArray = [[ { key: 123, value: 'India' }, { key: 124, value: 'USA' }, { key: 125, value: 'Japan' }, { key: 126, value: 'Denmark' }, { key: 127, value: 'Austria' }, ], [ { key: 124, value: 'Kenya' }, { key: 126, value: 'UK' }, { key: 123, value: 'Germany' }, { key: 127, value: 'Spain' }, { key: 125, value: 'Portugal' }, ]]; We will iterate over the parent array and then all of the sub arrays one by one and if we find a matching key, we push it into the value array otherwise we create a new value array. The full code for this will be − const parentArray = [[ { key: 123, value: 'India' }, { key: 124, value: 'USA' }, { key: 125, value: 'Japan' }, { key: 126, value: 'Denmark' }, { key: 127, value: 'Austria' }, ], [ { key: 124, value: 'Kenya' }, { key: 126, value: 'UK' }, { key: 123, value: 'Germany' }, { key: 127, value: 'Spain' }, { key: 125, value: 'Portugal' }, ]]; const map = {}; parentArray.forEach(arr => { arr.forEach(obj => { const { key, value } = obj; if(map[key]){ map[key].push(value); }else{ map[key] = [value] } }) }); console.log(map); The output in the console will be − { '123': [ 'India', 'Germany' ], '124': [ 'USA', 'Kenya' ], '125': [ 'Japan', 'Portugal' ], '126': [ 'Denmark', 'UK' ], '127': [ 'Austria', 'Spain' ] }
[ { "code": null, "e": 1378, "s": 1062, "text": "We have a parentArray that contains many sub arrays each of the same size, each sub array is\nan array of objects containing two properties: key and value. Within a subarray it is confirmed\nthat two objects cannot have the same key but all subarrays have the same pair of n keys\nwhere n is the size of the sub array." }, { "code": null, "e": 1516, "s": 1378, "text": "Our job is to prepare an object with key as key of objects and value being an array that contains all the values for that particular key." }, { "code": null, "e": 1548, "s": 1516, "text": "Here is a sample parent array −" }, { "code": null, "e": 1944, "s": 1548, "text": "const parentArray = [[\n{\n key: 123,\n value: 'India'\n}, {\n key: 124,\n value: 'USA'\n}, {\n key: 125,\n value: 'Japan'\n}, {\n key: 126,\n value: 'Denmark'\n}, {\n key: 127,\n value: 'Austria'\n},\n], [\n{\n key: 124,\n value: 'Kenya'\n}, {\n key: 126,\n value: 'UK'\n}, {\n key: 123,\n value: 'Germany'\n}, {\n key: 127,\n value: 'Spain'\n}, {\n key: 125,\n value: 'Portugal'\n},\n]];" }, { "code": null, "e": 2126, "s": 1944, "text": "We will iterate over the parent array and then all of the sub arrays one by one and if we find a matching key, we push it into the value array otherwise we create a new value array." }, { "code": null, "e": 2159, "s": 2126, "text": "The full code for this will be −" }, { "code": null, "e": 2786, "s": 2159, "text": "const parentArray = [[\n{\n key: 123,\n value: 'India'\n}, {\n key: 124,\n value: 'USA'\n}, {\n key: 125,\n value: 'Japan'\n}, {\n key: 126,\n value: 'Denmark'\n}, {\n key: 127,\n value: 'Austria'\n},\n], [\n{\n key: 124,\n value: 'Kenya'\n}, {\n key: 126,\n value: 'UK'\n}, {\n key: 123,\n value: 'Germany'\n}, {\n key: 127,\n value: 'Spain'\n}, {\n key: 125,\n value: 'Portugal'\n},\n]];\nconst map = {};\nparentArray.forEach(arr => {\n arr.forEach(obj => {\n const { key, value } = obj;\n if(map[key]){\n map[key].push(value);\n }else{\n map[key] = [value]\n }\n })\n});\nconsole.log(map);" }, { "code": null, "e": 2822, "s": 2786, "text": "The output in the console will be −" }, { "code": null, "e": 2989, "s": 2822, "text": "{\n '123': [ 'India', 'Germany' ],\n '124': [ 'USA', 'Kenya' ],\n '125': [ 'Japan', 'Portugal' ],\n '126': [ 'Denmark', 'UK' ],\n '127': [ 'Austria', 'Spain' ]\n}" } ]
Count rows in a matrix that consist of same element in C++
We are given a matrix consisting of integers. The goal is to find the number of rows in the matrix that have all identical elements in it. If there is 5X4 matrix as shown − The answer would be 2, row 1 (having all 1’s) and row 3 (having all 7’s) contain the same element. Let us understand with examples. Input matrix = [ 1 1 1 1 ] [ 2 3 2 7 ] [ 3 3 3 3 ] Output − Count of rows in a matrix that consist of same element are − 2 Explanation − Row 0 contains all 1’s and row 2 contains all 3s. Input − matrix = [ 1 2 3 4 ] [ 1 2 3 4 ] [ 1 2 3 4 ] Output − Count of rows in a matrix that consist of same element are − 0 Explanation − All rows have different elements. We are taking the matrix in the form of a vector of vectors<int>. We will traverse each vector and create a set<int> for each row. Keep on inserting row elements to this set. In the end if this set has only 1 element (take set size). Then the current row has all the same elements. Take the matrix as a vector < vector <int> > matrix and initialize it Take the matrix as a vector < vector <int> > matrix and initialize it Calculate size using matrix.size(). Calculate size using matrix.size(). Function same_rows(vector<vector<int>> matrix, int size) takes the matrix and it’s size and returns the count of rows that have the same elements. Function same_rows(vector<vector<int>> matrix, int size) takes the matrix and it’s size and returns the count of rows that have the same elements. Take the initial count as 0. Take the initial count as 0. Traverse the matrix using for loop. i=0 to i=size. Traverse the matrix using for loop. i=0 to i=size. For each row traverse from j=0 to j<matrix[i].size(). For each row traverse from j=0 to j<matrix[i].size(). Take a set<int> set_row for storing elements of current row. Take a set<int> set_row for storing elements of current row. Add elements to this set for current row using set_row.insert(matrix[i][j]). Add elements to this set for current row using set_row.insert(matrix[i][j]). At the end check the size of set_row. If it is 1 then this row has all the same elements. Increment count. At the end check the size of set_row. If it is 1 then this row has all the same elements. Increment count. At the end of all iterations for all rows, return count as the final result. At the end of all iterations for all rows, return count as the final result. Live Demo #include <bits/stdc++.h> using namespace std; int same_rows(vector> matrix, int size){ int count = 0; for (int i = 0; i < size; i++){ set set_row; for (int j = 0; j < matrix[i].size(); j++){ set_row.insert(matrix[i][j]); } int set_size = set_row.size(); if (set_size == 1){ count++; } } return count; } int main(){ vector<vector<int>> matrix = { { 2, 2, 2, 2}, { 5, 5, 5, 5 }, { 2, 2, 2, 2 }, {5, 5, 5, 5} }; int size = matrix.size(); cout<<"Count of rows in a matrix that consist of same element are: "<<same_rows(matrix, size); return 0; } If we run the above code it will generate the following output − Count of rows in a matrix that consist of same element are: 4
[ { "code": null, "e": 1201, "s": 1062, "text": "We are given a matrix consisting of integers. The goal is to find the number of rows in the matrix that have all identical elements in it." }, { "code": null, "e": 1235, "s": 1201, "text": "If there is 5X4 matrix as shown −" }, { "code": null, "e": 1334, "s": 1235, "text": "The answer would be 2, row 1 (having all 1’s) and row 3 (having all 7’s) contain the same element." }, { "code": null, "e": 1367, "s": 1334, "text": "Let us understand with examples." }, { "code": null, "e": 1374, "s": 1367, "text": "Input " }, { "code": null, "e": 1428, "s": 1374, "text": "matrix =\n [ 1 1 1 1 ]\n [ 2 3 2 7 ]\n [ 3 3 3 3 ]" }, { "code": null, "e": 1500, "s": 1428, "text": "Output − Count of rows in a matrix that consist of same element are − 2" }, { "code": null, "e": 1564, "s": 1500, "text": "Explanation − Row 0 contains all 1’s and row 2 contains all 3s." }, { "code": null, "e": 1572, "s": 1564, "text": "Input −" }, { "code": null, "e": 1626, "s": 1572, "text": "matrix =\n [ 1 2 3 4 ]\n [ 1 2 3 4 ]\n [ 1 2 3 4 ]" }, { "code": null, "e": 1699, "s": 1626, "text": " Output − Count of rows in a matrix that consist of same element are − 0" }, { "code": null, "e": 1747, "s": 1699, "text": "Explanation − All rows have different elements." }, { "code": null, "e": 2029, "s": 1747, "text": "We are taking the matrix in the form of a vector of vectors<int>. We will traverse each vector and create a set<int> for each row. Keep on inserting row elements to this set. In the end if this set has only 1 element (take set size). Then the current row has all the same elements." }, { "code": null, "e": 2099, "s": 2029, "text": "Take the matrix as a vector < vector <int> > matrix and initialize it" }, { "code": null, "e": 2169, "s": 2099, "text": "Take the matrix as a vector < vector <int> > matrix and initialize it" }, { "code": null, "e": 2205, "s": 2169, "text": "Calculate size using matrix.size()." }, { "code": null, "e": 2241, "s": 2205, "text": "Calculate size using matrix.size()." }, { "code": null, "e": 2388, "s": 2241, "text": "Function same_rows(vector<vector<int>> matrix, int size) takes the matrix and it’s size and returns the count of rows that have the same elements." }, { "code": null, "e": 2535, "s": 2388, "text": "Function same_rows(vector<vector<int>> matrix, int size) takes the matrix and it’s size and returns the count of rows that have the same elements." }, { "code": null, "e": 2564, "s": 2535, "text": "Take the initial count as 0." }, { "code": null, "e": 2593, "s": 2564, "text": "Take the initial count as 0." }, { "code": null, "e": 2644, "s": 2593, "text": "Traverse the matrix using for loop. i=0 to i=size." }, { "code": null, "e": 2695, "s": 2644, "text": "Traverse the matrix using for loop. i=0 to i=size." }, { "code": null, "e": 2749, "s": 2695, "text": "For each row traverse from j=0 to j<matrix[i].size()." }, { "code": null, "e": 2803, "s": 2749, "text": "For each row traverse from j=0 to j<matrix[i].size()." }, { "code": null, "e": 2864, "s": 2803, "text": "Take a set<int> set_row for storing elements of current row." }, { "code": null, "e": 2925, "s": 2864, "text": "Take a set<int> set_row for storing elements of current row." }, { "code": null, "e": 3002, "s": 2925, "text": "Add elements to this set for current row using set_row.insert(matrix[i][j])." }, { "code": null, "e": 3079, "s": 3002, "text": "Add elements to this set for current row using set_row.insert(matrix[i][j])." }, { "code": null, "e": 3186, "s": 3079, "text": "At the end check the size of set_row. If it is 1 then this row has all the same elements. Increment count." }, { "code": null, "e": 3293, "s": 3186, "text": "At the end check the size of set_row. If it is 1 then this row has all the same elements. Increment count." }, { "code": null, "e": 3370, "s": 3293, "text": "At the end of all iterations for all rows, return count as the final result." }, { "code": null, "e": 3447, "s": 3370, "text": "At the end of all iterations for all rows, return count as the final result." }, { "code": null, "e": 3458, "s": 3447, "text": " Live Demo" }, { "code": null, "e": 4105, "s": 3458, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint same_rows(vector> matrix, int size){\n int count = 0;\n for (int i = 0; i < size; i++){\n set set_row;\n for (int j = 0; j < matrix[i].size(); j++){\n set_row.insert(matrix[i][j]);\n }\n int set_size = set_row.size();\n if (set_size == 1){\n count++;\n }\n }\n return count;\n}\nint main(){\n vector<vector<int>> matrix = {\n { 2, 2, 2, 2},\n { 5, 5, 5, 5 },\n { 2, 2, 2, 2 },\n {5, 5, 5, 5}\n };\n int size = matrix.size();\n cout<<\"Count of rows in a matrix that consist of same element are: \"<<same_rows(matrix, size);\n return 0;\n}" }, { "code": null, "e": 4171, "s": 4105, "text": "If we run the above code it will generate the following output − " }, { "code": null, "e": 4233, "s": 4171, "text": "Count of rows in a matrix that consist of same element are: 4" } ]
IntStream range() method in Java
The range() method in the IntStream class in Java is used to return a sequential ordered IntStream from startInclusive to endExclusive by an incremental step of 1. This includes the startInclusive as well. The syntax is as follows − static IntStream range(int startInclusive, int endExclusive) Here, the parameter startInclusive includes the starting value, whereas endExclusive excludes the last value To work with the IntStream class in Java, import the following package − import java.util.stream.IntStream; Create an IntStream and add stream elements in a range using range() method. This returns a sequential ordered IntStream by an incremental step of 1 within the range − intStream.forEach(System.out::println); The following is an example to implement IntStream range() method in Java − Live Demo import java.util.*; import java.util.stream.IntStream; public class Demo { public static void main(String[] args) { IntStream intStream = IntStream.range(20, 30); intStream.forEach(System.out::println); } } 20 21 22 23 24 25 26 27 28 29
[ { "code": null, "e": 1268, "s": 1062, "text": "The range() method in the IntStream class in Java is used to return a sequential ordered IntStream from startInclusive to endExclusive by an incremental step of 1. This includes the startInclusive as well." }, { "code": null, "e": 1295, "s": 1268, "text": "The syntax is as follows −" }, { "code": null, "e": 1356, "s": 1295, "text": "static IntStream range(int startInclusive, int endExclusive)" }, { "code": null, "e": 1465, "s": 1356, "text": "Here, the parameter startInclusive includes the starting value, whereas endExclusive excludes the last value" }, { "code": null, "e": 1538, "s": 1465, "text": "To work with the IntStream class in Java, import the following package −" }, { "code": null, "e": 1573, "s": 1538, "text": "import java.util.stream.IntStream;" }, { "code": null, "e": 1741, "s": 1573, "text": "Create an IntStream and add stream elements in a range using range() method. This returns a sequential ordered IntStream by an incremental step of 1 within the range −" }, { "code": null, "e": 1781, "s": 1741, "text": "intStream.forEach(System.out::println);" }, { "code": null, "e": 1857, "s": 1781, "text": "The following is an example to implement IntStream range() method in Java −" }, { "code": null, "e": 1868, "s": 1857, "text": " Live Demo" }, { "code": null, "e": 2094, "s": 1868, "text": "import java.util.*;\nimport java.util.stream.IntStream;\n\npublic class Demo {\n public static void main(String[] args) {\n IntStream intStream = IntStream.range(20, 30);\n intStream.forEach(System.out::println);\n }\n}" }, { "code": null, "e": 2124, "s": 2094, "text": "20\n21\n22\n23\n24\n25\n26\n27\n28\n29" } ]
Anomaly Detection in Manufacturing, Part 1: An Introduction | by Tim von Hahn | Towards Data Science
A critical motor failed. Millions of dollars in lost revenue. Worst of all, it happened on my watch. In reality, the failure wasn’t attributed to any one person — it was a system failure. But there were missed “signals” along the way, like the temperature probe with “spikes” weeks before. Unfortunately, I was not equipped with the tools to identify these problems. Reams of data was constantly collected, but to identify a single deviation was like finding a needle in a haystack.... You may have a similar story of equipment failure that has cost your business immense grief, both in terms of money and effort. Condition monitoring is the process of measuring the parameters of machines — such as temperatures, vibrations, pressures, etc. — in order to detect and prevent failures. However, yesterday’s implementation of condition monitoring is ill equipped to manage the deluge of data in today’s world. To find those “needles in the haystack,” and improve productivity, traditional condition monitoring must be combined with data science and machine learning. Fortunately, the sheer availability of data, and the clear line from theory to application, makes a compelling case for using data science and machine learning techniques in industrial environments. [1] A McKinsey study estimated that the appropriate use of data-driven techniques by process manufacturers “typically reduces machine downtime by 30 to 50 percent and increases machine life by 20 to 40 percent”. Ultimately, it is here, at the intersection of traditional industry, data science, and machine learning, that we unlock incredible value. This three part series will explore this application of data science and machine learning to a problem in manufacturing. In particular, we’ll learn to detect anomalies, during metal machining, using a variational autoencoder (VAE). Although this application is manufacturing specific, the principals can be used wherever anomaly detection is useful. In Part 1 (this post), we’ll review what anomaly detection is. We’ll also be introduced to the UC Berkeley milling data set and do some exploratory data analysis — an important first step. In Part 2, we’ll cover the theory of variational autoencoders. We’ll then build and train VAEs using TensorFlow — all the code is provided so you can easily follow along. Finally, in Part 3, we’ll use the trained VAEs for anomaly detection. You’ll come to understand how the latent space can be used in anomaly detection. In addition, we’ll make some unique data visualizations to better understand the results. By the end of this series, I hope you have a newfound appreciation for anomaly detection and how it can be used in a manufacturing environment. Maybe you’ll be inspired to exercise your data science skills in this fascinating domain? Let’s start by understanding what anomaly detection is, and seeing how autoencoders can be used for anomaly detection. The classic definition of an anomaly was given by Douglas Hawkins: “an [anomaly] is an observation which deviates so much from other observations as to arouse suspicions that it was generated by a different mechanism.” [2] Sometimes, anomalies are clearly identified, and a data scientist can pick them out using straightforward methods. In reality, though, noise in the data makes anomaly detection difficult. Discriminating between the noise and the anomalies becomes the central challenge, as shown below. There are many ways to perform anomaly detection. I highly recommend the book Outlier Analysis by Aggarwal for an excellent overview. One method of anomaly detection uses an autoencoder. Autoencoders, as shown in the figure below, learn to reconstruct their inputs. However, the reconstruction will never be perfect. Feeding data into an autoencoder that is very different from what the autoencoder was trained on will produce large reconstruction errors. Feeding similar data will produce lower reconstruction errors. The size of the reconstruction error can be used as a proxy for how abnormal the data is. A threshold can then be set, whereby data producing a reconstruction error above the threshold is considered an anomaly. This is called input space anomaly detection. Inherently, the power of the autoencoder lies in its ability to learn in a self-supervised way. Yann Lecun described the strength of self-supervised learning in his Turing Award address: self-supervised learning allows models to “learn about the world without training it for a particular task.” This allows large swaths of data to be used in the training of the model — data that would not be available in supervised learning techniques. The power of self-supervised learning makes it attractive for use in manufacturing and industrial environments where much of the data is not properly labeled, and/or it would be too costly to label. The use of an autoencoder for anomaly detection is one such instantiation of self-supervised learning. We’ll further explore the concept of self-supervised learning, anomaly detection, and autoencoders as we build a variational autoencoder to detect abnormalities on tools during metal machining. The metal machining data set, or milling data set, we’ll be using is from UC Berkeley. The data is hosted on the NASA Prognostics Center of Excellence web page and is freely available. In the following sections we’ll review what milling is and then explore the data. In milling, a rotary cutter, like that in the picture above, removes material as it moves along a work piece. Most often, milling is performed on metal — it’s metal machining. The picture below demonstrates a face milling procedure. The cutter is progressed forward while rotating. As the cutter rotates, the tool inserts “bite” into the metal and remove it. Over time, the tool inserts wear. Specifically, the flank of the tool wears, as shown below. In the UC Berkeley milling data set the flank wear (VB) is measured from cut to cut. This VB value will be used for labeling purposes. Note: I won’t cover all the code for the data exploration — follow along in the Colab notebook to see it all. Data exploration is an important step when tackling any new data science problem. As such, we need to familiarize ourselves with the UC Berkeley milling data set before we start any sort of model building. Where to begin? The first step is understanding how the data is structured. How is the data stored? In a database? In an array? Where is the meta-data (things like labels and time-stamps)? The UC Berkeley milling data set is contained in a structured MATLAB array. We can load the .mat files using the scipy.io module and the loadmat function. # load the data from the matlab filem = sio.loadmat(folder_raw_data / 'mill.mat',struct_as_record=True) The data is stored in a dictionary. Only the 'mill' key contains useful information. # store the 'mill' data in a separate np arraydata = m['mill'] We can see what the data array is made up of. # store the field names in the data np array in a tuple, ll = data.dtype.namesprint('List of the field names:\n', l)>>> List of the field names:>>> ('case', 'run', 'VB', 'time', 'DOC', 'feed', 'material', 'smcAC', 'smcDC', 'vib_table', 'vib_spindle', 'AE_table', 'AE_spindle') The documentation included with the UC Berkeley milling data set highlights important meta-data. The data set is made of 16 cases of milling tools performing cuts in metal. Six cutting parameters were used in the creation of the data: the metal type (either cast iron or steel, labelled as 1 or 2 in the data set, respectively) the depth of cut (either 0.75 mm or 1.5 mm) the feed rate (either 0.25 mm/rev or 0.5 mm/rev) Each of the 16 cases is a combination of the cutting parameters (for example, case one has a depth of cut of 1.5 mm, a feed rate of 0.5 mm/rev, and is performed on cast iron). The cases are made up of individual cuts from when the tool is new to degraded or worn. There are 167 cuts (called ‘runs’ in the documentation) amongst all 16 cases. Many of the cuts are accompanied by a measure of flank wear (VB). We’ll use this later to label the cuts as either healthy, degraded, or worn. Finally, six signals were collected during each cut: Acoustic emission (AE) signals from the spindle and table. Vibration from the spindle and table. AC/DC current from the spindle motor. The signals were collected at 250 Hz and each cut had 9000 sampling points, for a total signal length of 36 seconds. We will extract the meta-data and labels from the numpy array and store it as a pandas dataframe — we’ll call this dataframe df_labels since it contains the label information we’ll be interested in. This is how we create the dataframe: In the above table, from df_labels.head(), you can see that not all cuts are labelled with a flank wear (VB) value. Later, we’ll be setting categories for the tool health — either healthy, degraded, or worn (failed). We can reasonably estimate the tool health categories, based on nearby cuts that have wear values, for cuts without a flank wear (VB) value. Visualizing a new data set is a great way to grasp what is going on, and to detect any problems. I also love data visualization, so we’ll create a beautiful graphic using seaborn and Matplotlib. There are only 167 cuts in this data set, which isn’t a huge amount. We can visually inspect each cut to find abnormalities. Fortunately, I’ve already done that for you.... Below is a highlight. First, we’ll look at a fairly “normal” cut — cut number 167. However, if you look at all the cuts, you’ll find that cuts 18 and 95 (index 17 and 94) are strange — they will need to be discarded before we start building our anomaly detection model. Here is cut number 18: Here is cut number 95: Finally, we’ll create a plot that cleanly visualizes all six signals together (acoustic emissions, vibrations, and currents). Data science and machine learning are a strong fit for manufacturing environments. To that end, we’ve reviewed the concept of anomaly detection using autoencoders. This self-supervised learning method can be useful in a manufacturing environment to help detect, and prevent, machinery failures. In this post we also explained what metal machining is — in the context of milling — and we explored the UC Berkely milling data set. In Part 2, we will build a variational autoencoder and train it on the milling data. [1] Economist. (2020). Businesses are finding ai hard to adopt. The Economist, ISSN 0013–0613. [2] Hawkins, D. M. (1980). Identification of outliers (Vol. 11). London: Chapman and Hall. This article originally appeared on tvhahn.com. In addition, the work is complimentary to research published in IJHM. The official GitHub repo is here. Except where otherwise noted, this post and its contents is licensed under CC BY-SA 4.0 by the author. Some rights reserved
[ { "code": null, "e": 272, "s": 171, "text": "A critical motor failed. Millions of dollars in lost revenue. Worst of all, it happened on my watch." }, { "code": null, "e": 657, "s": 272, "text": "In reality, the failure wasn’t attributed to any one person — it was a system failure. But there were missed “signals” along the way, like the temperature probe with “spikes” weeks before. Unfortunately, I was not equipped with the tools to identify these problems. Reams of data was constantly collected, but to identify a single deviation was like finding a needle in a haystack...." }, { "code": null, "e": 1079, "s": 657, "text": "You may have a similar story of equipment failure that has cost your business immense grief, both in terms of money and effort. Condition monitoring is the process of measuring the parameters of machines — such as temperatures, vibrations, pressures, etc. — in order to detect and prevent failures. However, yesterday’s implementation of condition monitoring is ill equipped to manage the deluge of data in today’s world." }, { "code": null, "e": 1236, "s": 1079, "text": "To find those “needles in the haystack,” and improve productivity, traditional condition monitoring must be combined with data science and machine learning." }, { "code": null, "e": 1647, "s": 1236, "text": "Fortunately, the sheer availability of data, and the clear line from theory to application, makes a compelling case for using data science and machine learning techniques in industrial environments. [1] A McKinsey study estimated that the appropriate use of data-driven techniques by process manufacturers “typically reduces machine downtime by 30 to 50 percent and increases machine life by 20 to 40 percent”." }, { "code": null, "e": 1785, "s": 1647, "text": "Ultimately, it is here, at the intersection of traditional industry, data science, and machine learning, that we unlock incredible value." }, { "code": null, "e": 2135, "s": 1785, "text": "This three part series will explore this application of data science and machine learning to a problem in manufacturing. In particular, we’ll learn to detect anomalies, during metal machining, using a variational autoencoder (VAE). Although this application is manufacturing specific, the principals can be used wherever anomaly detection is useful." }, { "code": null, "e": 2324, "s": 2135, "text": "In Part 1 (this post), we’ll review what anomaly detection is. We’ll also be introduced to the UC Berkeley milling data set and do some exploratory data analysis — an important first step." }, { "code": null, "e": 2495, "s": 2324, "text": "In Part 2, we’ll cover the theory of variational autoencoders. We’ll then build and train VAEs using TensorFlow — all the code is provided so you can easily follow along." }, { "code": null, "e": 2736, "s": 2495, "text": "Finally, in Part 3, we’ll use the trained VAEs for anomaly detection. You’ll come to understand how the latent space can be used in anomaly detection. In addition, we’ll make some unique data visualizations to better understand the results." }, { "code": null, "e": 2970, "s": 2736, "text": "By the end of this series, I hope you have a newfound appreciation for anomaly detection and how it can be used in a manufacturing environment. Maybe you’ll be inspired to exercise your data science skills in this fascinating domain?" }, { "code": null, "e": 3089, "s": 2970, "text": "Let’s start by understanding what anomaly detection is, and seeing how autoencoders can be used for anomaly detection." }, { "code": null, "e": 3598, "s": 3089, "text": "The classic definition of an anomaly was given by Douglas Hawkins: “an [anomaly] is an observation which deviates so much from other observations as to arouse suspicions that it was generated by a different mechanism.” [2] Sometimes, anomalies are clearly identified, and a data scientist can pick them out using straightforward methods. In reality, though, noise in the data makes anomaly detection difficult. Discriminating between the noise and the anomalies becomes the central challenge, as shown below." }, { "code": null, "e": 3732, "s": 3598, "text": "There are many ways to perform anomaly detection. I highly recommend the book Outlier Analysis by Aggarwal for an excellent overview." }, { "code": null, "e": 4117, "s": 3732, "text": "One method of anomaly detection uses an autoencoder. Autoencoders, as shown in the figure below, learn to reconstruct their inputs. However, the reconstruction will never be perfect. Feeding data into an autoencoder that is very different from what the autoencoder was trained on will produce large reconstruction errors. Feeding similar data will produce lower reconstruction errors." }, { "code": null, "e": 4374, "s": 4117, "text": "The size of the reconstruction error can be used as a proxy for how abnormal the data is. A threshold can then be set, whereby data producing a reconstruction error above the threshold is considered an anomaly. This is called input space anomaly detection." }, { "code": null, "e": 4813, "s": 4374, "text": "Inherently, the power of the autoencoder lies in its ability to learn in a self-supervised way. Yann Lecun described the strength of self-supervised learning in his Turing Award address: self-supervised learning allows models to “learn about the world without training it for a particular task.” This allows large swaths of data to be used in the training of the model — data that would not be available in supervised learning techniques." }, { "code": null, "e": 5115, "s": 4813, "text": "The power of self-supervised learning makes it attractive for use in manufacturing and industrial environments where much of the data is not properly labeled, and/or it would be too costly to label. The use of an autoencoder for anomaly detection is one such instantiation of self-supervised learning." }, { "code": null, "e": 5309, "s": 5115, "text": "We’ll further explore the concept of self-supervised learning, anomaly detection, and autoencoders as we build a variational autoencoder to detect abnormalities on tools during metal machining." }, { "code": null, "e": 5576, "s": 5309, "text": "The metal machining data set, or milling data set, we’ll be using is from UC Berkeley. The data is hosted on the NASA Prognostics Center of Excellence web page and is freely available. In the following sections we’ll review what milling is and then explore the data." }, { "code": null, "e": 5752, "s": 5576, "text": "In milling, a rotary cutter, like that in the picture above, removes material as it moves along a work piece. Most often, milling is performed on metal — it’s metal machining." }, { "code": null, "e": 5935, "s": 5752, "text": "The picture below demonstrates a face milling procedure. The cutter is progressed forward while rotating. As the cutter rotates, the tool inserts “bite” into the metal and remove it." }, { "code": null, "e": 6163, "s": 5935, "text": "Over time, the tool inserts wear. Specifically, the flank of the tool wears, as shown below. In the UC Berkeley milling data set the flank wear (VB) is measured from cut to cut. This VB value will be used for labeling purposes." }, { "code": null, "e": 6273, "s": 6163, "text": "Note: I won’t cover all the code for the data exploration — follow along in the Colab notebook to see it all." }, { "code": null, "e": 6479, "s": 6273, "text": "Data exploration is an important step when tackling any new data science problem. As such, we need to familiarize ourselves with the UC Berkeley milling data set before we start any sort of model building." }, { "code": null, "e": 6668, "s": 6479, "text": "Where to begin? The first step is understanding how the data is structured. How is the data stored? In a database? In an array? Where is the meta-data (things like labels and time-stamps)?" }, { "code": null, "e": 6823, "s": 6668, "text": "The UC Berkeley milling data set is contained in a structured MATLAB array. We can load the .mat files using the scipy.io module and the loadmat function." }, { "code": null, "e": 6927, "s": 6823, "text": "# load the data from the matlab filem = sio.loadmat(folder_raw_data / 'mill.mat',struct_as_record=True)" }, { "code": null, "e": 7012, "s": 6927, "text": "The data is stored in a dictionary. Only the 'mill' key contains useful information." }, { "code": null, "e": 7075, "s": 7012, "text": "# store the 'mill' data in a separate np arraydata = m['mill']" }, { "code": null, "e": 7121, "s": 7075, "text": "We can see what the data array is made up of." }, { "code": null, "e": 7398, "s": 7121, "text": "# store the field names in the data np array in a tuple, ll = data.dtype.namesprint('List of the field names:\\n', l)>>> List of the field names:>>> ('case', 'run', 'VB', 'time', 'DOC', 'feed', 'material', 'smcAC', 'smcDC', 'vib_table', 'vib_spindle', 'AE_table', 'AE_spindle')" }, { "code": null, "e": 7633, "s": 7398, "text": "The documentation included with the UC Berkeley milling data set highlights important meta-data. The data set is made of 16 cases of milling tools performing cuts in metal. Six cutting parameters were used in the creation of the data:" }, { "code": null, "e": 7726, "s": 7633, "text": "the metal type (either cast iron or steel, labelled as 1 or 2 in the data set, respectively)" }, { "code": null, "e": 7770, "s": 7726, "text": "the depth of cut (either 0.75 mm or 1.5 mm)" }, { "code": null, "e": 7819, "s": 7770, "text": "the feed rate (either 0.25 mm/rev or 0.5 mm/rev)" }, { "code": null, "e": 7995, "s": 7819, "text": "Each of the 16 cases is a combination of the cutting parameters (for example, case one has a depth of cut of 1.5 mm, a feed rate of 0.5 mm/rev, and is performed on cast iron)." }, { "code": null, "e": 8304, "s": 7995, "text": "The cases are made up of individual cuts from when the tool is new to degraded or worn. There are 167 cuts (called ‘runs’ in the documentation) amongst all 16 cases. Many of the cuts are accompanied by a measure of flank wear (VB). We’ll use this later to label the cuts as either healthy, degraded, or worn." }, { "code": null, "e": 8357, "s": 8304, "text": "Finally, six signals were collected during each cut:" }, { "code": null, "e": 8416, "s": 8357, "text": "Acoustic emission (AE) signals from the spindle and table." }, { "code": null, "e": 8454, "s": 8416, "text": "Vibration from the spindle and table." }, { "code": null, "e": 8492, "s": 8454, "text": "AC/DC current from the spindle motor." }, { "code": null, "e": 8609, "s": 8492, "text": "The signals were collected at 250 Hz and each cut had 9000 sampling points, for a total signal length of 36 seconds." }, { "code": null, "e": 8845, "s": 8609, "text": "We will extract the meta-data and labels from the numpy array and store it as a pandas dataframe — we’ll call this dataframe df_labels since it contains the label information we’ll be interested in. This is how we create the dataframe:" }, { "code": null, "e": 9203, "s": 8845, "text": "In the above table, from df_labels.head(), you can see that not all cuts are labelled with a flank wear (VB) value. Later, we’ll be setting categories for the tool health — either healthy, degraded, or worn (failed). We can reasonably estimate the tool health categories, based on nearby cuts that have wear values, for cuts without a flank wear (VB) value." }, { "code": null, "e": 9398, "s": 9203, "text": "Visualizing a new data set is a great way to grasp what is going on, and to detect any problems. I also love data visualization, so we’ll create a beautiful graphic using seaborn and Matplotlib." }, { "code": null, "e": 9593, "s": 9398, "text": "There are only 167 cuts in this data set, which isn’t a huge amount. We can visually inspect each cut to find abnormalities. Fortunately, I’ve already done that for you.... Below is a highlight." }, { "code": null, "e": 9654, "s": 9593, "text": "First, we’ll look at a fairly “normal” cut — cut number 167." }, { "code": null, "e": 9841, "s": 9654, "text": "However, if you look at all the cuts, you’ll find that cuts 18 and 95 (index 17 and 94) are strange — they will need to be discarded before we start building our anomaly detection model." }, { "code": null, "e": 9864, "s": 9841, "text": "Here is cut number 18:" }, { "code": null, "e": 9887, "s": 9864, "text": "Here is cut number 95:" }, { "code": null, "e": 10013, "s": 9887, "text": "Finally, we’ll create a plot that cleanly visualizes all six signals together (acoustic emissions, vibrations, and currents)." }, { "code": null, "e": 10308, "s": 10013, "text": "Data science and machine learning are a strong fit for manufacturing environments. To that end, we’ve reviewed the concept of anomaly detection using autoencoders. This self-supervised learning method can be useful in a manufacturing environment to help detect, and prevent, machinery failures." }, { "code": null, "e": 10527, "s": 10308, "text": "In this post we also explained what metal machining is — in the context of milling — and we explored the UC Berkely milling data set. In Part 2, we will build a variational autoencoder and train it on the milling data." }, { "code": null, "e": 10622, "s": 10527, "text": "[1] Economist. (2020). Businesses are finding ai hard to adopt. The Economist, ISSN 0013–0613." }, { "code": null, "e": 10713, "s": 10622, "text": "[2] Hawkins, D. M. (1980). Identification of outliers (Vol. 11). London: Chapman and Hall." }, { "code": null, "e": 10865, "s": 10713, "text": "This article originally appeared on tvhahn.com. In addition, the work is complimentary to research published in IJHM. The official GitHub repo is here." }, { "code": null, "e": 10968, "s": 10865, "text": "Except where otherwise noted, this post and its contents is licensed under CC BY-SA 4.0 by the author." } ]
Python Pandas - Indicate all duplicate index values as True
To indicate all duplicate index values as True, use the index.duplicated(). Use the keep parameter with the value False. At first, import the required libraries − import pandas as pd Creating the index with some duplicates − index = pd.Index(['Car','Bike','Airplane','Ship','Airplane']) Display the index − print("Pandas Index with duplicates...\n",index) Indicate all duplicate index values as True. Set the "keep" parameter as "False" − print("\nIndicating all duplicate index values True...\n", index.duplicated(keep=False)) Following is the code − import pandas as pd # Creating the index with some duplicates index = pd.Index(['Car','Bike','Airplane','Ship','Airplane']) # Display the index print("Pandas Index with duplicates...\n",index) # Return the dtype of the data print("\nThe dtype object...\n",index.dtype) # get the dimensions of the data print("\nGet the dimensions...\n",index.ndim) # Indicate all duplicate index values as True # Set the "keep" parameter as "False" print("\nIndicating all duplicate index values True...\n", index.duplicated(keep=False)) This will produce the following code − Pandas Index with duplicates... Index(['Car', 'Bike', 'Airplane', 'Ship', 'Airplane'], dtype='object') The dtype object... object Get the dimensions... 1 Indicating all duplicate index values True... [False False True False True]
[ { "code": null, "e": 1183, "s": 1062, "text": "To indicate all duplicate index values as True, use the index.duplicated(). Use the keep parameter with the value False." }, { "code": null, "e": 1225, "s": 1183, "text": "At first, import the required libraries −" }, { "code": null, "e": 1245, "s": 1225, "text": "import pandas as pd" }, { "code": null, "e": 1287, "s": 1245, "text": "Creating the index with some duplicates −" }, { "code": null, "e": 1349, "s": 1287, "text": "index = pd.Index(['Car','Bike','Airplane','Ship','Airplane'])" }, { "code": null, "e": 1369, "s": 1349, "text": "Display the index −" }, { "code": null, "e": 1418, "s": 1369, "text": "print(\"Pandas Index with duplicates...\\n\",index)" }, { "code": null, "e": 1501, "s": 1418, "text": "Indicate all duplicate index values as True. Set the \"keep\" parameter as \"False\" −" }, { "code": null, "e": 1590, "s": 1501, "text": "print(\"\\nIndicating all duplicate index values True...\\n\", index.duplicated(keep=False))" }, { "code": null, "e": 1614, "s": 1590, "text": "Following is the code −" }, { "code": null, "e": 2140, "s": 1614, "text": "import pandas as pd\n\n# Creating the index with some duplicates\nindex = pd.Index(['Car','Bike','Airplane','Ship','Airplane'])\n\n# Display the index\nprint(\"Pandas Index with duplicates...\\n\",index)\n\n# Return the dtype of the data\nprint(\"\\nThe dtype object...\\n\",index.dtype)\n\n# get the dimensions of the data\nprint(\"\\nGet the dimensions...\\n\",index.ndim)\n\n# Indicate all duplicate index values as True\n# Set the \"keep\" parameter as \"False\"\nprint(\"\\nIndicating all duplicate index values True...\\n\", index.duplicated(keep=False))" }, { "code": null, "e": 2179, "s": 2140, "text": "This will produce the following code −" }, { "code": null, "e": 2412, "s": 2179, "text": "Pandas Index with duplicates...\nIndex(['Car', 'Bike', 'Airplane', 'Ship', 'Airplane'], dtype='object')\n\nThe dtype object...\nobject\n\nGet the dimensions...\n1\n\nIndicating all duplicate index values True...\n[False False True False True]" } ]
NHibernate - Relationships
In this chapter, we will look at relationships in NHibernate. Let's turn our attention to how we can understand relationships in NHibernate. The easiest way is to think about the relationships from the database perspective. We will first create a new application in which we will create some relationships among the customer and order entities. We will first create a new application in which we will create some relationships among the customer and order entities. The first relationship we're going to look at is a classic collection relationship. The first relationship we're going to look at is a classic collection relationship. We have a customer with a collection of orders. We have a customer with a collection of orders. This is a one-to-many relationship and it's represented in the database by 2 tables and there is a customer ID on the orders table and we have a foreign key relationship back to the customer. This is a one-to-many relationship and it's represented in the database by 2 tables and there is a customer ID on the orders table and we have a foreign key relationship back to the customer. First we need to create a database and two tables Customer and Order. You can create this by specifying the following query in SQL Server Explorer. USE [master] GO CREATE DATABASE [NHibernateDemo] GO USE [NHibernateDemo] GO CREATE TABLE [dbo].[Customer]( [Id] [uniqueidentifier] NOT NULL, [FirstName] [nvarchar](100) NOT NULL, [LastName] [nvarchar](100) NOT NULL, [Points] [int] NULL, [HasGoldStatus] [bit] NULL, [MemberSince] [date] NULL, [CreditRating] [nchar](20) NULL, [AverageRating] [decimal](18, 4) NULL, [Street] [nvarchar](100) NULL, [City] [nvarchar](100) NULL, [Province] [nvarchar](100) NULL, [Country] [nvarchar](100) NULL, PRIMARY KEY CLUSTERED ([Id] ASC) ) GO CREATE TABLE [dbo].[Order]( [Id] [uniqueidentifier] NOT NULL, [CustomerId] [uniqueidentifier] NULL, [Ordered] [datetime] NULL, [Shipped] [datetime] NULL, [Street] [nvarchar](100) NULL, [City] [nvarchar](100) NULL, [Province] [nvarchar](100) NULL, [Country] [nvarchar](100) NULL, PRIMARY KEY CLUSTERED ([Id] ASC) ) GO It will create two tables in the database. The following image shows the Customer Table. The following image shows the Order Table in which you can see the foreign key relationship back to the customer. We need to define the connection string in the app.config file, here is the implementation of the app.config file. <?xml version = "1.0" encoding = "utf-8" ?> <configuration> <connectionStrings> <add name = "default" connectionString = "Data Source = (localdb)\MSSQLLocalDB;Initial Catalog = NHibernateDemo;Integrated Security = True;Connect Timeout = 30;Encrypt = False;TrustServerCertificate = False; ApplicationIntent = ReadWrite;MultiSubnetFailover = False"/> </connectionStrings> </configuration> To install the NHibernate in your application, run the following command in NuGet Manager Console window. install-package NHibernate To configure the NHibernate configuration, we need to define the configuration in hibernate.cfg.xml file as shown in the following code. <xml version = "1.0" encoding = "utf-8" ?> <hibernate-configuration xmlns = "urn:nhibernate-configuration-2.2"> <session-factory> <property name = "connection.connection_string_name">default</property> <property name = "connection.driver_class"> NHibernate.Driver.SqlClientDriver </property> <property name = "dialect"> NHibernate.Dialect.MsSql2008Dialect </property> <property name = "show_sql">true</property> </session-factory> </hibernate-configuration> In this example, we will be working two domain classes, Customer and Order. Here is the Customer.cs file implementation in which we have two classes, one is the Customer class and another is the Location class in which object is used as an address in the Customer class. using System; using System.Text; using Iesi.Collections.Generic; namespace NHibernateDemo { public class Customer { public Customer() { MemberSince = DateTime.UtcNow; Orders = new HashedSet<Order>(); } public virtual Guid Id { get; set; } public virtual string FirstName { get; set; } public virtual string LastName { get; set; } public virtual double AverageRating { get; set; } public virtual int Points { get; set; } public virtual bool HasGoldStatus { get; set; } public virtual DateTime MemberSince { get; set; } public virtual CustomerCreditRating CreditRating { get; set; } public virtual Location Address { get; set; } public virtual ISet<Order> Orders { get; set; } public virtual void AddOrder(Order order) { Orders.Add(order); order.Customer = this; } public override string ToString() { var result = new StringBuilder(); result.AppendFormat("{1} {2} ({0})\r\n\tPoints: {3}\r\n\tHasGoldStatus: {4}\r\n\tMemberSince: {5} ({7})\r\n\tCreditRating: {6}\r\n\tAverageRating: {8}\r\n", Id, FirstName, LastName, Points, HasGoldStatus, MemberSince, CreditRating, MemberSince.Kind, AverageRating); result.AppendLine("\tOrders:"); foreach(var order in Orders) { result.AppendLine("\t\t" + order); } return result.ToString(); } } public class Location { public virtual string Street { get; set; } public virtual string City { get; set; } public virtual string Province { get; set; } public virtual string Country { get; set; } } public enum CustomerCreditRating { Excellent, VeryVeryGood, VeryGood, Good, Neutral, Poor, Terrible } } Here is the mapping file Customer.hbm.xml in which Customer class is mapped to the Customer table. <?xml version = "1.0" encoding = "utf-8" ?> <hibernate-mapping xmlns = "urn:nhibernate-mapping-2.2" assembly = "NHibernateDemo" namespace = "NHibernateDemo"> <class name = "Customer"> <id name = "Id"> <generator class = "guid.comb"/> </id> <property name = "FirstName"/> <property name = "LastName"/> <property name = "AverageRating"/> <property name = "Points"/> <property name = "HasGoldStatus"/> <property name = "MemberSince" type = "UtcDateTime"/> <property name = "CreditRating" type = "CustomerCreditRatingType"/> <component name = "Address"> <property name = "Street"/> <property name = "City"/> <property name = "Province"/> <property name = "Country"/> </component> </class> </hibernate-mapping> We also have an Order Class and here is the implementation of Order.cs file. using System; using Iesi.Collections.Generic; namespace NHibernateDemo { public class Order { public virtual Guid Id { get; set; } public virtual DateTime Ordered { get; set; } public virtual DateTime? Shipped { get; set; } public virtual Location ShipTo { get; set; } public virtual Customer Customer { get; set; } public override string ToString() { return string.Format("Order Id: {0}", Id); } } } We also need to map the Order class to the Order table in the database, so here is the implementation of the Order.hbm.xml file. <?xml version = "1.0" encoding = "utf-8" ?> <hibernate-mapping xmlns = "urn:nhibernate-mapping-2.2" assembly = "NHibernateDemo" namespace = "NHibernateDemo"> <class name = "Order" table = "`Order`"> <id name = "Id"> <generator class = "guid.comb"/> </id> <property name = "Ordered"/> <property name = "Shipped"/> <component name = "ShipTo"> <property name = "Street"/> <property name = "City"/> <property name = "Province"/> <property name = "Country"/> </component> <!--<many-to-one name = "Customer" column = "CustomerId" cascade = "save-update"/>--> </class> </hibernate-mapping> Here, we are going to take a look at a one-to-many relationship, in this case, between customer and orders. We've got our customer here, we're creating a new one, and you can see that the collection is initialized with the following pair of orders. private static Customer CreateCustomer() { var customer = new Customer { FirstName = "John", LastName = "Doe", Points = 100, HasGoldStatus = true, MemberSince = new DateTime(2012, 1, 1), CreditRating = CustomerCreditRating.Good, AverageRating = 42.42424242, Address = CreateLocation() }; var order1 = new Order { Ordered = DateTime.Now }; customer.AddOrder(order1); var order2 = new Order { Ordered = DateTime.Now.AddDays(-1), Shipped = DateTime.Now, ShipTo = CreateLocation() }; customer.AddOrder(order2); return customer; } So we will create a new customer and then save it, after saving it, we will find the ID and then reload it in another session in the Main method as shown in the following program. private static void Main() { var cfg = ConfigureNHibernate(); var sessionFactory = cfg.BuildSessionFactory(); Guid id; using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var newCustomer = CreateCustomer(); Console.WriteLine("New Customer:"); Console.WriteLine(newCustomer); session.Save(newCustomer); id = newCustomer.Id; tx.Commit(); } using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var reloaded = session.Load<Customer>(id); Console.WriteLine("Reloaded:"); Console.WriteLine(reloaded); tx.Commit(); } Console.WriteLine("Press <ENTER> to exit..."); Console.ReadLine(); } Here is the complete Program.cs file implementation. using System; using System.Data; using System.Linq; using System.Reflection; using HibernatingRhinos.Profiler.Appender.NHibernate; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Linq; namespace NHibernateDemo { internal class Program { private static void Main() { var cfg = ConfigureNHibernate(); var sessionFactory = cfg.BuildSessionFactory(); Guid id; using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var newCustomer = CreateCustomer(); Console.WriteLine("New Customer:"); Console.WriteLine(newCustomer); session.Save(newCustomer); id = newCustomer.Id; tx.Commit(); } using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var reloaded = session.Load<Customer>(id); Console.WriteLine("Reloaded:"); Console.WriteLine(reloaded); tx.Commit(); } Console.WriteLine("Press <ENTER> to exit..."); Console.ReadLine(); } private static Customer CreateCustomer() { var customer = new Customer { FirstName = "John", LastName = "Doe", Points = 100, HasGoldStatus = true, MemberSince = new DateTime(2012, 1, 1), CreditRating = CustomerCreditRating.Good, AverageRating = 42.42424242, Address = CreateLocation() }; var order1 = new Order { Ordered = DateTime.Now }; customer.AddOrder(order1); var order2 = new Order { Ordered = DateTime.Now.AddDays(-1), Shipped = DateTime.Now, ShipTo = CreateLocation() }; customer.AddOrder(order2); return customer; } private static Location CreateLocation() { return new Location { Street = "123 Somewhere Avenue", City = "Nowhere", Province = "Alberta", Country = "Canada" }; } private static Configuration ConfigureNHibernate() { NHibernateProfiler.Initialize(); var cfg = new Configuration(); cfg.DataBaseIntegration(x =&ht; { x.ConnectionStringName = "default"; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); x.IsolationLevel = IsolationLevel.RepeatableRead; x.Timeout = 10; x.BatchSize = 10; }); cfg.SessionFactory().GenerateStatistics(); cfg.AddAssembly(Assembly.GetExecutingAssembly()); return cfg; } } } When you run this application, you will see the following output. New Customer: John Doe (00000000-0000-0000-0000-000000000000) Points: 100 HasGoldStatus: True MemberSince: 1/1/2012 12:00:00 AM (Unspecified) CreditRating: Good AverageRating: 42.42424242 Orders: Order Id: 00000000-0000-0000-0000-000000000000 Order Id: 00000000-0000-0000-0000-000000000000 Reloaded: John Doe (9b0fcf10-83f6-4f39-bda5-a5b800ede2ba) Points: 100 HasGoldStatus: True MemberSince: 1/1/2012 12:00:00 AM (Utc) CreditRating: Good AverageRating: 42.4242 Orders: Press <ENTER> to exit... As you can see that initially the customer has 2 orders, but when we reload it, there are no orders to be seen. If you look at customer.hbm.xml file, you can see here that we do not map actual orders collection. So NHibernate knows nothing about it. Let's go ahead and add it. <?xml version = "1.0" encoding = "utf-8" ?> <hibernate-mapping xmlns = "urn:nhibernate-mapping-2.2" assembly = "NHibernateDemo" namespace = "NHibernateDemo"> <class name = "Customer"> <id name = "Id"> <generator class = "guid.comb"/> </id> <property name = "FirstName"/> <property name = "LastName"/> <property name = "AverageRating"/> <property name = "Points"/> <property name = "HasGoldStatus"/> <property name = "MemberSince" type = "UtcDateTime"/> <property name = "CreditRating" type = "CustomerCreditRatingType"/> <component name = "Address"> <property name = "Street"/> <property name = "City"/> <property name = "Province"/> <property name = "Country"/> </component> <set name = "Orders" table = "`Order`"> <key column = "CustomerId"/> <one-to-many class = "Order"/> </set> </class> </hibernate-mapping> This is a set and the name of this collection is ‘Orders’, which is stored in a table called order. We need to specify a key which is the name of the foreign key or to find orders. These orders are identified or belong to a customer through the customer ID. And then I have to note that this is a one-to-many relationship and it is with the order class. We also need to slightly change the Main method by saving the new customer orders to the database as well as shown in the following program. private static void Main() { var cfg = ConfigureNHibernate(); var sessionFactory = cfg.BuildSessionFactory(); Guid id; using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var newCustomer = CreateCustomer(); Console.WriteLine("New Customer:"); Console.WriteLine(newCustomer); session.Save(newCustomer); foreach (var order in newCustomer.Orders) { session.Save(order); } id = newCustomer.Id; tx.Commit(); } using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var reloaded = session.Load<Customer>(id); Console.WriteLine("The orders were ordered by: "); foreach (var order in reloaded.Orders) { Console.WriteLine(order.Customer); } tx.Commit(); } Console.WriteLine("Press <ENTER> to exit..."); Console.ReadLine(); } We have also specified which customer ordered that particular product. So we need to create a many-to-one relationship to relate that order back to that customer. So let's go into the Order.hbm.xml file and add a many-to-one, and then name the customer field and the column with the customer ID. <?xml version = "1.0" encoding = "utf-8" ?> <hibernate-mapping xmlns = "urn:nhibernate-mapping-2.2" assembly = "NHibernateDemo" namespace = "NHibernateDemo"> <class name = "Order" table = "`Order`"> <id name = "Id"> <generator class = "guid.comb"/> </id> <property name = "Ordered"/> <property name = "Shipped"/> <component name = "ShipTo"> <property name = "Street"/> <property name = "City"/> <property name = "Province"/> <property name = "Country"/> </component> <many-to-one name = "Customer" column = "CustomerId"/> </class> </hibernate-mapping> Let’s run this application again and now you will see the following output. New Customer: John Doe (00000000-0000-0000-0000-000000000000) Points: 100 HasGoldStatus: True MemberSince: 1/1/2012 12:00:00 AM (Unspecified) CreditRating: Good AverageRating: 42.42424242 Orders: Order Id: 00000000-0000-0000-0000-000000000000 Order Id: 00000000-0000-0000-0000-000000000000 Reloaded: John Doe (660a6f29-650e-4380-99e0-a5b800febbde) Points: 100 HasGoldStatus: True MemberSince: 1/1/2012 12:00:00 AM (Utc) CreditRating: Good AverageRating: 42.4242 Orders: Order Id: 57314deb-e023-4e55-ac1e-a5b800febbe3 Order Id: fc065683-d5f5-484b-ae42-a5b800febbe3 The orders were ordered by: John Doe (660a6f29-650e-4380-99e0-a5b800febbde) Points: 100 HasGoldStatus: True MemberSince: 1/1/2012 12:00:00 AM (Utc) CreditRating: Good AverageRating: 42.4242 Orders: Order Id: 57314deb-e023-4e55-ac1e-a5b800febbe3 Order Id: fc065683-d5f5-484b-ae42-a5b800febbe3 John Doe (660a6f29-650e-4380-99e0-a5b800febbde) Points: 100 HasGoldStatus: True MemberSince: 1/1/2012 12:00:00 AM (Utc) CreditRating: Good AverageRating: 42.4242 Orders: Order Id: 57314deb-e023-4e55-ac1e-a5b800febbe3 Order Id: fc065683-d5f5-484b-ae42-a5b800febbe3 Press <ENTER> to exit... Print Add Notes Bookmark this page
[ { "code": null, "e": 2557, "s": 2333, "text": "In this chapter, we will look at relationships in NHibernate. Let's turn our attention to how we can understand relationships in NHibernate. The easiest way is to think about the relationships from the database perspective." }, { "code": null, "e": 2678, "s": 2557, "text": "We will first create a new application in which we will create some relationships among the customer and order entities." }, { "code": null, "e": 2799, "s": 2678, "text": "We will first create a new application in which we will create some relationships among the customer and order entities." }, { "code": null, "e": 2883, "s": 2799, "text": "The first relationship we're going to look at is a classic collection relationship." }, { "code": null, "e": 2967, "s": 2883, "text": "The first relationship we're going to look at is a classic collection relationship." }, { "code": null, "e": 3015, "s": 2967, "text": "We have a customer with a collection of orders." }, { "code": null, "e": 3063, "s": 3015, "text": "We have a customer with a collection of orders." }, { "code": null, "e": 3255, "s": 3063, "text": "This is a one-to-many relationship and it's represented in the database by 2 tables and there is a customer ID on the orders table and we have a foreign key relationship back to the customer." }, { "code": null, "e": 3447, "s": 3255, "text": "This is a one-to-many relationship and it's represented in the database by 2 tables and there is a customer ID on the orders table and we have a foreign key relationship back to the customer." }, { "code": null, "e": 3595, "s": 3447, "text": "First we need to create a database and two tables Customer and Order. You can create this by specifying the following query in SQL Server Explorer." }, { "code": null, "e": 4534, "s": 3595, "text": "USE [master] \nGO \nCREATE DATABASE [NHibernateDemo] \nGO \nUSE [NHibernateDemo] \nGO\n\nCREATE TABLE [dbo].[Customer]( \n [Id] [uniqueidentifier] NOT NULL, \n [FirstName] [nvarchar](100) NOT NULL, \n [LastName] [nvarchar](100) NOT NULL, \n [Points] [int] NULL, [HasGoldStatus] [bit] NULL, \n [MemberSince] [date] NULL, \n [CreditRating] [nchar](20) NULL, \n [AverageRating] [decimal](18, 4) NULL, \n [Street] [nvarchar](100) NULL, \n [City] [nvarchar](100) NULL, \n [Province] [nvarchar](100) NULL, \n [Country] [nvarchar](100) NULL,\n PRIMARY KEY CLUSTERED ([Id] ASC) \n) \n\nGO \nCREATE TABLE [dbo].[Order]( \n [Id] [uniqueidentifier] NOT NULL, \n [CustomerId] [uniqueidentifier] NULL, \n [Ordered] [datetime] NULL, \n [Shipped] [datetime] NULL, \n [Street] [nvarchar](100) NULL, \n [City] [nvarchar](100) NULL, \n [Province] [nvarchar](100) NULL, \n [Country] [nvarchar](100) NULL, \n PRIMARY KEY CLUSTERED ([Id] ASC) \n) \nGO" }, { "code": null, "e": 4623, "s": 4534, "text": "It will create two tables in the database. The following image shows the Customer Table." }, { "code": null, "e": 4737, "s": 4623, "text": "The following image shows the Order Table in which you can see the foreign key relationship back to the customer." }, { "code": null, "e": 4852, "s": 4737, "text": "We need to define the connection string in the app.config file, here is the implementation of the app.config file." }, { "code": null, "e": 5288, "s": 4852, "text": "<?xml version = \"1.0\" encoding = \"utf-8\" ?> \n<configuration> \n \n <connectionStrings> \n <add name = \"default\" connectionString = \"Data Source =\n (localdb)\\MSSQLLocalDB;Initial Catalog = NHibernateDemo;Integrated Security =\n True;Connect Timeout = 30;Encrypt = False;TrustServerCertificate = False;\n ApplicationIntent = ReadWrite;MultiSubnetFailover = False\"/> \n </connectionStrings> \n\n</configuration>" }, { "code": null, "e": 5394, "s": 5288, "text": "To install the NHibernate in your application, run the following command in NuGet Manager Console window." }, { "code": null, "e": 5422, "s": 5394, "text": "install-package NHibernate\n" }, { "code": null, "e": 5559, "s": 5422, "text": "To configure the NHibernate configuration, we need to define the configuration in hibernate.cfg.xml file as shown in the following code." }, { "code": null, "e": 6099, "s": 5559, "text": "<xml version = \"1.0\" encoding = \"utf-8\" ?> \n<hibernate-configuration xmlns = \"urn:nhibernate-configuration-2.2\"> \n \n <session-factory> \n <property name = \"connection.connection_string_name\">default</property>\n\t\t\n <property name = \"connection.driver_class\">\n NHibernate.Driver.SqlClientDriver \n </property> \n\t\t\n <property name = \"dialect\">\n NHibernate.Dialect.MsSql2008Dialect\n </property> \n\t\t\n <property name = \"show_sql\">true</property> \n </session-factory> \n\n</hibernate-configuration>" }, { "code": null, "e": 6175, "s": 6099, "text": "In this example, we will be working two domain classes, Customer and Order." }, { "code": null, "e": 6370, "s": 6175, "text": "Here is the Customer.cs file implementation in which we have two classes, one is the Customer class and another is the Location class in which object is used as an address in the Customer class." }, { "code": null, "e": 8289, "s": 6370, "text": "using System; \nusing System.Text; \nusing Iesi.Collections.Generic;\n\nnamespace NHibernateDemo {\n \n public class Customer { \n \n public Customer() { \n MemberSince = DateTime.UtcNow; \n Orders = new HashedSet<Order>(); \n } \n \n public virtual Guid Id { get; set; } \n public virtual string FirstName { get; set; } \n public virtual string LastName { get; set; } \n public virtual double AverageRating { get; set; } \n public virtual int Points { get; set; } \n\t\t\n public virtual bool HasGoldStatus { get; set; }\n public virtual DateTime MemberSince { get; set; } \n public virtual CustomerCreditRating CreditRating { get; set; } \n public virtual Location Address { get; set; }\n\t\t\n public virtual ISet<Order> Orders { get; set; }\n public virtual void AddOrder(Order order) { Orders.Add(order); order.Customer = this; }\n \n public override string ToString() { \n var result = new StringBuilder();\n\t\t\t\n result.AppendFormat(\"{1} {2} ({0})\\r\\n\\tPoints: {3}\\r\\n\\tHasGoldStatus:\n {4}\\r\\n\\tMemberSince: {5} ({7})\\r\\n\\tCreditRating: {6}\\r\\n\\tAverageRating:\n {8}\\r\\n\", Id, FirstName, LastName, Points, HasGoldStatus, MemberSince,\n CreditRating, MemberSince.Kind, AverageRating);\n result.AppendLine(\"\\tOrders:\"); \n \n foreach(var order in Orders) { \n result.AppendLine(\"\\t\\t\" + order); \n } \n\t\t\t\n return result.ToString(); \n } \n }\n \n public class Location { \n public virtual string Street { get; set; } \n public virtual string City { get; set; } \n public virtual string Province { get; set; } \n public virtual string Country { get; set; } \n }\n \n public enum CustomerCreditRating { \n Excellent,\n VeryVeryGood, \n VeryGood, \n Good, \n Neutral, \n Poor, \n Terrible \n } \n}" }, { "code": null, "e": 8388, "s": 8289, "text": "Here is the mapping file Customer.hbm.xml in which Customer class is mapped to the Customer table." }, { "code": null, "e": 9249, "s": 8388, "text": "<?xml version = \"1.0\" encoding = \"utf-8\" ?> \n<hibernate-mapping xmlns = \"urn:nhibernate-mapping-2.2\" assembly = \"NHibernateDemo\" \n namespace = \"NHibernateDemo\"> \n\t\n <class name = \"Customer\"> \n \n <id name = \"Id\"> \n <generator class = \"guid.comb\"/> \n </id> \n\n <property name = \"FirstName\"/> \n <property name = \"LastName\"/> \n <property name = \"AverageRating\"/> \n <property name = \"Points\"/> \n <property name = \"HasGoldStatus\"/> \n <property name = \"MemberSince\" type = \"UtcDateTime\"/> \n <property name = \"CreditRating\" type = \"CustomerCreditRatingType\"/>\n \n <component name = \"Address\"> \n <property name = \"Street\"/> \n <property name = \"City\"/> \n <property name = \"Province\"/> \n <property name = \"Country\"/> \n </component> \n\n </class> \n</hibernate-mapping>" }, { "code": null, "e": 9326, "s": 9249, "text": "We also have an Order Class and here is the implementation of Order.cs file." }, { "code": null, "e": 9809, "s": 9326, "text": "using System; using Iesi.Collections.Generic;\n\nnamespace NHibernateDemo { \n\n public class Order { \n \n public virtual Guid Id { get; set; } \n public virtual DateTime Ordered { get; set; } \n public virtual DateTime? Shipped { get; set; }\n public virtual Location ShipTo { get; set; } \n public virtual Customer Customer { get; set; }\n \n public override string ToString() { \n return string.Format(\"Order Id: {0}\", Id); \n } \n } \n}" }, { "code": null, "e": 9938, "s": 9809, "text": "We also need to map the Order class to the Order table in the database, so here is the implementation of the Order.hbm.xml file." }, { "code": null, "e": 10660, "s": 9938, "text": "<?xml version = \"1.0\" encoding = \"utf-8\" ?> \n<hibernate-mapping xmlns = \"urn:nhibernate-mapping-2.2\" assembly = \"NHibernateDemo\" \n namespace = \"NHibernateDemo\"> \n\n <class name = \"Order\" table = \"`Order`\"> \n \n <id name = \"Id\"> \n <generator class = \"guid.comb\"/> \n </id> \n\t\t\n <property name = \"Ordered\"/> \n <property name = \"Shipped\"/> \n \n <component name = \"ShipTo\"> \n <property name = \"Street\"/> \n <property name = \"City\"/> \n <property name = \"Province\"/> \n <property name = \"Country\"/> \n </component> \n\n <!--<many-to-one name = \"Customer\" column = \"CustomerId\" cascade =\n \"save-update\"/>--> \n\t\t\t\n </class> \n</hibernate-mapping>" }, { "code": null, "e": 10909, "s": 10660, "text": "Here, we are going to take a look at a one-to-many relationship, in this case, between customer and orders. We've got our customer here, we're creating a new one, and you can see that the collection is initialized with the following pair of orders." }, { "code": null, "e": 11572, "s": 10909, "text": "private static Customer CreateCustomer() { \n \n var customer = new Customer { \n FirstName = \"John\", \n LastName = \"Doe\", \n Points = 100, \n HasGoldStatus = true, \n MemberSince = new DateTime(2012, 1, 1), \n CreditRating = CustomerCreditRating.Good, \n AverageRating = 42.42424242, \n Address = CreateLocation() \n }; \n \n var order1 = new Order { \n Ordered = DateTime.Now \n }; \n \n customer.AddOrder(order1); \n var order2 = new Order { \n Ordered = DateTime.Now.AddDays(-1), \n Shipped = DateTime.Now, \n ShipTo = CreateLocation() \n }; \n \n customer.AddOrder(order2); \n return customer; \n}" }, { "code": null, "e": 11752, "s": 11572, "text": "So we will create a new customer and then save it, after saving it, we will find the ID and then reload it in another session in the Main method as shown in the following program." }, { "code": null, "e": 12544, "s": 11752, "text": "private static void Main() { \n\n var cfg = ConfigureNHibernate(); \n var sessionFactory = cfg.BuildSessionFactory();\n \n Guid id; \n using(var session = sessionFactory.OpenSession()) \n\t\n using(var tx = session.BeginTransaction()) { \n var newCustomer = CreateCustomer(); \n Console.WriteLine(\"New Customer:\"); \n Console.WriteLine(newCustomer);\n session.Save(newCustomer); \n id = newCustomer.Id; \n tx.Commit(); \n }\n \n using(var session = sessionFactory.OpenSession()) \n\t\n using(var tx = session.BeginTransaction()) { \n var reloaded = session.Load<Customer>(id); \n Console.WriteLine(\"Reloaded:\"); \n Console.WriteLine(reloaded); \n tx.Commit(); \n }\n \n Console.WriteLine(\"Press <ENTER> to exit...\"); \n Console.ReadLine(); \n}" }, { "code": null, "e": 12597, "s": 12544, "text": "Here is the complete Program.cs file implementation." }, { "code": null, "e": 15559, "s": 12597, "text": "using System; \nusing System.Data; \nusing System.Linq; \nusing System.Reflection; \n\nusing HibernatingRhinos.Profiler.Appender.NHibernate; \nusing NHibernate.Cfg; \nusing NHibernate.Dialect; \nusing NHibernate.Driver; \nusing NHibernate.Linq;\n\nnamespace NHibernateDemo {\n \n internal class Program { \n\t\n private static void Main() { \n\t\t\n var cfg = ConfigureNHibernate(); \n var sessionFactory = cfg.BuildSessionFactory();\n \n Guid id; \n using(var session = sessionFactory.OpenSession())\n\t\t\t\n using(var tx = session.BeginTransaction()) { \n var newCustomer = CreateCustomer(); \n Console.WriteLine(\"New Customer:\"); \n Console.WriteLine(newCustomer); \n session.Save(newCustomer); \n id = newCustomer.Id; \n tx.Commit(); \n } \n \n using(var session = sessionFactory.OpenSession()) \n\t\t\t\n using(var tx = session.BeginTransaction()) { \n var reloaded = session.Load<Customer>(id); \n Console.WriteLine(\"Reloaded:\"); \n Console.WriteLine(reloaded); \n tx.Commit();\n }\n \n Console.WriteLine(\"Press <ENTER> to exit...\"); \n Console.ReadLine();\n }\n \n private static Customer CreateCustomer() { \n\t\t\n var customer = new Customer { \n FirstName = \"John\", \n LastName = \"Doe\", \n Points = 100, \n HasGoldStatus = true, \n MemberSince = new DateTime(2012, 1, 1), \n CreditRating = CustomerCreditRating.Good, \n AverageRating = 42.42424242, \n Address = CreateLocation() \n }; \n \n var order1 = new Order { \n Ordered = DateTime.Now\n }; \n \n customer.AddOrder(order1); \n\t\t\t\n var order2 = new Order { \n Ordered = DateTime.Now.AddDays(-1), \n Shipped = DateTime.Now, \n ShipTo = CreateLocation() \n }; \n \n customer.AddOrder(order2); \n return customer; \n } \n \n private static Location CreateLocation() { \n\t\t\n return new Location { \n Street = \"123 Somewhere Avenue\", \n City = \"Nowhere\", \n Province = \"Alberta\", \n Country = \"Canada\" \n }; \n } \n \n private static Configuration ConfigureNHibernate() { \n NHibernateProfiler.Initialize(); \n var cfg = new Configuration(); \n \n cfg.DataBaseIntegration(x =&ht; { \n x.ConnectionStringName = \"default\"; \n x.Driver<SqlClientDriver>(); \n x.Dialect<MsSql2008Dialect>(); \n x.IsolationLevel = IsolationLevel.RepeatableRead; \n x.Timeout = 10; x.BatchSize = 10; \n }); \n \n cfg.SessionFactory().GenerateStatistics();\n cfg.AddAssembly(Assembly.GetExecutingAssembly()); \n return cfg; \n } \n } \n}" }, { "code": null, "e": 15625, "s": 15559, "text": "When you run this application, you will see the following output." }, { "code": null, "e": 16173, "s": 15625, "text": "New Customer:\n\nJohn Doe (00000000-0000-0000-0000-000000000000)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Unspecified)\n CreditRating: Good\n AverageRating: 42.42424242\n\n Orders:\n Order Id: 00000000-0000-0000-0000-000000000000\n Order Id: 00000000-0000-0000-0000-000000000000\n\nReloaded:\nJohn Doe (9b0fcf10-83f6-4f39-bda5-a5b800ede2ba)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Utc)\n CreditRating: Good\n AverageRating: 42.4242\n\n Orders:\nPress <ENTER> to exit...\n" }, { "code": null, "e": 16450, "s": 16173, "text": "As you can see that initially the customer has 2 orders, but when we reload it, there are no orders to be seen. If you look at customer.hbm.xml file, you can see here that we do not map actual orders collection. So NHibernate knows nothing about it. Let's go ahead and add it." }, { "code": null, "e": 17467, "s": 16450, "text": "<?xml version = \"1.0\" encoding = \"utf-8\" ?> \n<hibernate-mapping xmlns = \"urn:nhibernate-mapping-2.2\" \n assembly = \"NHibernateDemo\" namespace = \"NHibernateDemo\">\n\t\n <class name = \"Customer\"> \n \n <id name = \"Id\">\n <generator class = \"guid.comb\"/> \n </id> \n \n <property name = \"FirstName\"/>\n <property name = \"LastName\"/> \n <property name = \"AverageRating\"/> \n <property name = \"Points\"/> \n <property name = \"HasGoldStatus\"/> \n <property name = \"MemberSince\" type = \"UtcDateTime\"/> \n <property name = \"CreditRating\" type = \"CustomerCreditRatingType\"/>\n \n <component name = \"Address\"> \n <property name = \"Street\"/> \n <property name = \"City\"/> \n <property name = \"Province\"/> \n <property name = \"Country\"/> \n </component>\n \n <set name = \"Orders\" table = \"`Order`\"> \n <key column = \"CustomerId\"/> \n <one-to-many class = \"Order\"/> \n </set> \n \n </class> \n</hibernate-mapping>" }, { "code": null, "e": 17821, "s": 17467, "text": "This is a set and the name of this collection is ‘Orders’, which is stored in a table called order. We need to specify a key which is the name of the foreign key or to find orders. These orders are identified or belong to a customer through the customer ID. And then I have to note that this is a one-to-many relationship and it is with the order class." }, { "code": null, "e": 17962, "s": 17821, "text": "We also need to slightly change the Main method by saving the new customer orders to the database as well as shown in the following program." }, { "code": null, "e": 18940, "s": 17962, "text": "private static void Main() { \n\n var cfg = ConfigureNHibernate(); \n var sessionFactory = cfg.BuildSessionFactory();\n \n Guid id; \n using(var session = sessionFactory.OpenSession()) \n\t\n using(var tx = session.BeginTransaction()) {\n var newCustomer = CreateCustomer(); \n Console.WriteLine(\"New Customer:\"); \n Console.WriteLine(newCustomer);\n session.Save(newCustomer); \n \n foreach (var order in newCustomer.Orders) { \n session.Save(order); \n } \n\t\t\n id = newCustomer.Id; \n tx.Commit(); \n }\n \n using(var session = sessionFactory.OpenSession()) \n\t\n using(var tx = session.BeginTransaction()) { \n var reloaded = session.Load<Customer>(id); \n Console.WriteLine(\"The orders were ordered by: \"); \n \n foreach (var order in reloaded.Orders) { \n Console.WriteLine(order.Customer); \n } \n\t\t\n tx.Commit(); \n }\n Console.WriteLine(\"Press <ENTER> to exit...\"); Console.ReadLine();\n}" }, { "code": null, "e": 19103, "s": 18940, "text": "We have also specified which customer ordered that particular product. So we need to create a many-to-one relationship to relate that order back to that customer." }, { "code": null, "e": 19236, "s": 19103, "text": "So let's go into the Order.hbm.xml file and add a many-to-one, and then name the customer field and the column with the customer ID." }, { "code": null, "e": 19925, "s": 19236, "text": "<?xml version = \"1.0\" encoding = \"utf-8\" ?> \n<hibernate-mapping xmlns = \"urn:nhibernate-mapping-2.2\" assembly = \"NHibernateDemo\"\n namespace = \"NHibernateDemo\"> \n\t\n <class name = \"Order\" table = \"`Order`\">\n \n <id name = \"Id\"> \n <generator class = \"guid.comb\"/> \n </id>\n \n <property name = \"Ordered\"/> \n <property name = \"Shipped\"/> \n \n <component name = \"ShipTo\"> \n <property name = \"Street\"/> \n <property name = \"City\"/> \n <property name = \"Province\"/> \n <property name = \"Country\"/> \n </component> \n\n <many-to-one name = \"Customer\" column = \"CustomerId\"/> \n\t\t\n </class> \n</hibernate-mapping>" }, { "code": null, "e": 20001, "s": 19925, "text": "Let’s run this application again and now you will see the following output." }, { "code": null, "e": 21277, "s": 20001, "text": "New Customer:\nJohn Doe (00000000-0000-0000-0000-000000000000)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Unspecified)\n CreditRating: Good\n AverageRating: 42.42424242\n\n Orders:\n Order Id: 00000000-0000-0000-0000-000000000000\n Order Id: 00000000-0000-0000-0000-000000000000\n\nReloaded:\nJohn Doe (660a6f29-650e-4380-99e0-a5b800febbde)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Utc)\n CreditRating: Good\n AverageRating: 42.4242\n\n Orders:\n Order Id: 57314deb-e023-4e55-ac1e-a5b800febbe3\n Order Id: fc065683-d5f5-484b-ae42-a5b800febbe3\n\nThe orders were ordered by:\nJohn Doe (660a6f29-650e-4380-99e0-a5b800febbde)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Utc)\n CreditRating: Good\n AverageRating: 42.4242\n\n Orders:\n Order Id: 57314deb-e023-4e55-ac1e-a5b800febbe3\n Order Id: fc065683-d5f5-484b-ae42-a5b800febbe3\n\nJohn Doe (660a6f29-650e-4380-99e0-a5b800febbde)\n Points: 100\n HasGoldStatus: True\n MemberSince: 1/1/2012 12:00:00 AM (Utc)\n CreditRating: Good\n AverageRating: 42.4242\n\n Orders:\n Order Id: 57314deb-e023-4e55-ac1e-a5b800febbe3\n Order Id: fc065683-d5f5-484b-ae42-a5b800febbe3\n\t\t\nPress <ENTER> to exit...\n" }, { "code": null, "e": 21284, "s": 21277, "text": " Print" }, { "code": null, "e": 21295, "s": 21284, "text": " Add Notes" } ]
Write a program to find the first non-repeating number in an integer array using Java?
To find the first non-repeating number in an array − Construct count array to store count of each element in the given array with same length and with initial value 0 for all elements. Compare each element in the array with all other elements, except itself. If match occurs increment its value in the count array. Get the index of the first 0 in the count array and print the element in the input array at this index. import java.util.Arrays; public class NonRpeatingArray { public static void main(String args[]) { int array[] = {114, 225, 669, 996, 336, 6547, 669, 225, 336, 669, 996, 669, 225 }; System.out.println(""); //Creating the count array int countArray[] = new int[array.length]; for(int i=0; i<array.length; i++) { countArray[i] = 0; } for(int i=0; i<array.length; i++) { for(int j=0; j<array.length;j++) { if(i!=j && array[i]==array[j]) { countArray[i]++; } } } System.out.println(Arrays.toString(countArray)); //First non-repeating element in the array for(int i=0; i<array.length; i++) { if(countArray[i]==0) { System.out.println(array[i]); break; } } } } [0, 2, 3, 1, 1, 0, 3, 2, 1, 3, 1, 3, 2] 114
[ { "code": null, "e": 1115, "s": 1062, "text": "To find the first non-repeating number in an array −" }, { "code": null, "e": 1247, "s": 1115, "text": "Construct count array to store count of each element in the given array with same length and with initial value 0 for all elements." }, { "code": null, "e": 1321, "s": 1247, "text": "Compare each element in the array with all other elements, except itself." }, { "code": null, "e": 1377, "s": 1321, "text": "If match occurs increment its value in the count array." }, { "code": null, "e": 1481, "s": 1377, "text": "Get the index of the first 0 in the count array and print the element in the input array at this index." }, { "code": null, "e": 2321, "s": 1481, "text": "import java.util.Arrays;\npublic class NonRpeatingArray {\n public static void main(String args[]) {\n int array[] = {114, 225, 669, 996, 336, 6547, 669, 225, 336, 669, 996, 669, 225 };\n System.out.println(\"\");\n //Creating the count array\n int countArray[] = new int[array.length];\n for(int i=0; i<array.length; i++) {\n countArray[i] = 0;\n }\n for(int i=0; i<array.length; i++) {\n for(int j=0; j<array.length;j++) {\n if(i!=j && array[i]==array[j]) {\n countArray[i]++;\n }\n }\n }\n System.out.println(Arrays.toString(countArray));\n //First non-repeating element in the array\n for(int i=0; i<array.length; i++) {\n if(countArray[i]==0) {\n System.out.println(array[i]);\n break;\n }\n }\n }\n}" }, { "code": null, "e": 2365, "s": 2321, "text": "[0, 2, 3, 1, 1, 0, 3, 2, 1, 3, 1, 3, 2]\n114" } ]
How to Add a Boolean Datatype Column to an Existing Table in SQL? - GeeksforGeeks
21 Nov, 2021 In SQL Server, a Boolean Datatype can be created by means of keeping BIT datatype. Though it is a numeric datatype, it can accept either 0 or 1 or NULL values only. Hence easily we can assign FALSE values to 0 and TRUE values to 1. This will provide the boolean nature for a data type. Regarding the storage, if there are less than 9 columns of the bit data are present in the table, they are stored as 1 byte. And for 9 to 16 BIT columns, their consumption is 2 bytes and so on it will hold. In this article, let us how we can add a Boolean i.e. BIT datatype to an existing table in SQL SERVER. Let us assume there is a database “GEEKSFORGEEKS” is available and there is a table called “Authors” available with the following data. Query: USE GEEKSFORGEEKS SELECT * FROM Authors; Output: Let us add a BIT data type to the “Authors” table. Bit datatype is helpful to represent Boolean nature either True(1) or False(0) and they are the only allowed values for BIT datatype. -- Add a column named "isActiveAuthor" with BIT datatype for "Authors" table ALTER TABLE Authors ADD isActiveAuthor BIT; As there are already few rows available in the table, we can add a new column “isActiveAuthor” as a NULL pattern only. After that, we can update the data. After adding the column, Query: SELECT * FROM Authors; Output: So, when a BIT datatype column is added to an existing table, its value will be populated with “NULL” values. Now let us try to update the column with a condition that if “NumberOfPosts” > 5, set “isActiveAuthor” to have the value 1 or else 0. -- Let us assume that if "NumberOfPosts" is more than 5, author is active enough to write articles -- Hence for this condition , set "isActiveAuthor" column to have value 1 UPDATE Authors SET isActiveAuthor = 1 WHERE NumberOfPosts > 5; -- On the other hand, if "NumberOfPosts" is less than and equal to 5, -- author is not active in the recent days and hence set "isActiveAuthor" column to have value 0 UPDATE Authors SET isActiveAuthor = 0 WHERE NumberOfPosts <= 5; SELECT * FROM Authors; Output: As the BIT column supports only 0 or 1 as values, we have populated like above. Let us try to update the value other than 0 or 1 -- Trying to update the "isActiveAuthor" with value 2, though errors are not produced, output is different UPDATE Authors SET isActiveAuthor = 2 WHERE NumberOfPosts = 5; SELECT * FROM Authors; Output: Reason for the updated value of 1 in the 3rd row : Though an update is given to get the value of 2, because of the “BIT” datatype for “isActiveAuthor” column, its value is converted to 1 only as the “BIT” datatype supports either 0 or 1 only. i.e. values other than 0 are converted to 1 and updated in the table. We can check the same here with different examples DECLARE @isValid BIT -- Initially it will have "NULL" value SELECT @isValid AS BitType --Assigning any nonzero value converts it to 1 -- i.e. other than 0, if any value is provided , it is converted to 1 SET @isValid=9 SELECT @isValid AS BitType --Assigning any nonzero value converts it to 1 SET @isValid=-100 SELECT @isValid AS BitType Output: This proves the “BIT” datatype accepts only the “Boolean” value i.e. either 0 or 1 only. If a nonzero value is given, it is converted to 1 only. Advantages : Always if the expected values are either 0 or 1 plus NULL, it is a good approach in keeping the column as “BIT” datatype as the code becomes logical Regarding storage, it is economic to use as it takes a little space while comparing to other data types. By considering the advantages, BIT datatype is the right approach for storing boolean data rs1686740 Picked SQL-Query SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Update Multiple Columns in Single Update Statement in SQL? What is Temporary Table in SQL? SQL Query for Matching Multiple Values in the Same Column SQL using Python SQL Query to Insert Multiple Rows SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL | Subquery SQL | SEQUENCES SQL | DROP, TRUNCATE SQL Query to Convert VARCHAR to INT
[ { "code": null, "e": 24188, "s": 24160, "text": "\n21 Nov, 2021" }, { "code": null, "e": 24475, "s": 24188, "text": "In SQL Server, a Boolean Datatype can be created by means of keeping BIT datatype. Though it is a numeric datatype, it can accept either 0 or 1 or NULL values only. Hence easily we can assign FALSE values to 0 and TRUE values to 1. This will provide the boolean nature for a data type. " }, { "code": null, "e": 24787, "s": 24475, "text": "Regarding the storage, if there are less than 9 columns of the bit data are present in the table, they are stored as 1 byte. And for 9 to 16 BIT columns, their consumption is 2 bytes and so on it will hold. In this article, let us how we can add a Boolean i.e. BIT datatype to an existing table in SQL SERVER." }, { "code": null, "e": 24923, "s": 24787, "text": "Let us assume there is a database “GEEKSFORGEEKS” is available and there is a table called “Authors” available with the following data." }, { "code": null, "e": 24930, "s": 24923, "text": "Query:" }, { "code": null, "e": 24971, "s": 24930, "text": "USE GEEKSFORGEEKS\nSELECT * FROM Authors;" }, { "code": null, "e": 24979, "s": 24971, "text": "Output:" }, { "code": null, "e": 25164, "s": 24979, "text": "Let us add a BIT data type to the “Authors” table. Bit datatype is helpful to represent Boolean nature either True(1) or False(0) and they are the only allowed values for BIT datatype." }, { "code": null, "e": 25287, "s": 25164, "text": "-- Add a column named \"isActiveAuthor\" \nwith BIT datatype for \"Authors\" table\nALTER TABLE Authors ADD isActiveAuthor BIT;" }, { "code": null, "e": 25468, "s": 25287, "text": "As there are already few rows available in the table, we can add a new column “isActiveAuthor” as a NULL pattern only. After that, we can update the data. After adding the column, " }, { "code": null, "e": 25475, "s": 25468, "text": "Query:" }, { "code": null, "e": 25498, "s": 25475, "text": "SELECT * FROM Authors;" }, { "code": null, "e": 25506, "s": 25498, "text": "Output:" }, { "code": null, "e": 25616, "s": 25506, "text": "So, when a BIT datatype column is added to an existing table, its value will be populated with “NULL” values." }, { "code": null, "e": 25751, "s": 25616, "text": "Now let us try to update the column with a condition that if “NumberOfPosts” > 5, set “isActiveAuthor” to have the value 1 or else 0. " }, { "code": null, "e": 26258, "s": 25751, "text": "-- Let us assume that if \"NumberOfPosts\" \n is more than 5, author is active enough to write articles\n-- Hence for this condition , set \"isActiveAuthor\"\n column to have value 1\nUPDATE Authors SET isActiveAuthor = 1 WHERE NumberOfPosts > 5;\n\n-- On the other hand, if \"NumberOfPosts\"\n is less than and equal to 5, \n-- author is not active in the recent days\n and hence set \"isActiveAuthor\" column to have value 0\nUPDATE Authors SET isActiveAuthor = 0 WHERE NumberOfPosts <= 5;\n\nSELECT * FROM Authors;" }, { "code": null, "e": 26266, "s": 26258, "text": "Output:" }, { "code": null, "e": 26346, "s": 26266, "text": "As the BIT column supports only 0 or 1 as values, we have populated like above." }, { "code": null, "e": 26396, "s": 26346, "text": "Let us try to update the value other than 0 or 1 " }, { "code": null, "e": 26598, "s": 26396, "text": "-- Trying to update the \"isActiveAuthor\"\n with value 2, though errors are not \n produced, output is different\nUPDATE Authors SET isActiveAuthor = \n2 WHERE NumberOfPosts = 5;\n\nSELECT * FROM Authors;" }, { "code": null, "e": 26606, "s": 26598, "text": "Output:" }, { "code": null, "e": 26657, "s": 26606, "text": "Reason for the updated value of 1 in the 3rd row :" }, { "code": null, "e": 26919, "s": 26657, "text": "Though an update is given to get the value of 2, because of the “BIT” datatype for “isActiveAuthor” column, its value is converted to 1 only as the “BIT” datatype supports either 0 or 1 only. i.e. values other than 0 are converted to 1 and updated in the table." }, { "code": null, "e": 26970, "s": 26919, "text": "We can check the same here with different examples" }, { "code": null, "e": 27321, "s": 26970, "text": "DECLARE @isValid BIT\n\n-- Initially it will have \"NULL\" value \nSELECT @isValid AS BitType\n \n--Assigning any nonzero value converts it to 1\n-- i.e. other than 0, if any\n value is provided , it is converted to 1\nSET @isValid=9\n \nSELECT @isValid AS BitType\n \n--Assigning any nonzero value converts it to 1\nSET @isValid=-100\n \nSELECT @isValid AS BitType" }, { "code": null, "e": 27329, "s": 27321, "text": "Output:" }, { "code": null, "e": 27474, "s": 27329, "text": "This proves the “BIT” datatype accepts only the “Boolean” value i.e. either 0 or 1 only. If a nonzero value is given, it is converted to 1 only." }, { "code": null, "e": 27487, "s": 27474, "text": "Advantages :" }, { "code": null, "e": 27636, "s": 27487, "text": "Always if the expected values are either 0 or 1 plus NULL, it is a good approach in keeping the column as “BIT” datatype as the code becomes logical" }, { "code": null, "e": 27741, "s": 27636, "text": "Regarding storage, it is economic to use as it takes a little space while comparing to other data types." }, { "code": null, "e": 27832, "s": 27741, "text": "By considering the advantages, BIT datatype is the right approach for storing boolean data" }, { "code": null, "e": 27842, "s": 27832, "text": "rs1686740" }, { "code": null, "e": 27849, "s": 27842, "text": "Picked" }, { "code": null, "e": 27859, "s": 27849, "text": "SQL-Query" }, { "code": null, "e": 27870, "s": 27859, "text": "SQL-Server" }, { "code": null, "e": 27874, "s": 27870, "text": "SQL" }, { "code": null, "e": 27878, "s": 27874, "text": "SQL" }, { "code": null, "e": 27976, "s": 27878, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27985, "s": 27976, "text": "Comments" }, { "code": null, "e": 27998, "s": 27985, "text": "Old Comments" }, { "code": null, "e": 28064, "s": 27998, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 28096, "s": 28064, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 28154, "s": 28096, "text": "SQL Query for Matching Multiple Values in the Same Column" }, { "code": null, "e": 28171, "s": 28154, "text": "SQL using Python" }, { "code": null, "e": 28205, "s": 28171, "text": "SQL Query to Insert Multiple Rows" }, { "code": null, "e": 28283, "s": 28205, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 28298, "s": 28283, "text": "SQL | Subquery" }, { "code": null, "e": 28314, "s": 28298, "text": "SQL | SEQUENCES" }, { "code": null, "e": 28335, "s": 28314, "text": "SQL | DROP, TRUNCATE" } ]
All You Need to Know to Secure Apps with CloudFront Functions And S3 | by Stefan Nastic | Towards Data Science
Currently Amazon S3 and CloudFront are some of the best cloud services for delivering production-ready SPAs, such as Angular apps, Vue apps or React apps. Unfortunately, by default, S3 and CloudFront don’t have all security features enabled, needed to run such SPA frontend apps in production. Recently, we have launched a platform with a frontend (Angular apps) hosted on Amazon S3 and CloudFront. In this article, I want to share main security best practices and how we implemented them for our platform. Having these security best practices in place, helped us pass a very stringent security audit with flying colors! Both S3 and CloudFront are very mature cloud services and are also relatively straightforward to start with. However, there is much more than what first meets the eye, in particular if the services are used together. Additionally, if combined with other cloud services such as Route 53 (AWS DNS service) and Amazon Certificates Manager, they become a powerful, must-have tool suite for any web developer. Unfortunately, their flexibility and seeming simplicity can be a security pitfall. Most of us have probably heard of at least one instance of S3 data leaks in the past few months (whenever you are reading this). Figure below shows an example infrastructure for a typical SPA, hosted on S3 and CloudFront1. Naturally, such a frontend app would depend on a set of backend services and APIs. As the article already grew beyond what I initially expected, we will not discuss the platform's backend in this article. In this article, I will mainly focus on the security best practices, which help address the following questions: How to secure an S3 buckets, which store sensitive user data and the application code? How to securely configure a CloudFront distribution? How to protect frontend apps against common OWASP threats with CloudFront Functions? So let’s first see what we can do to protect our Angular, Vue or React frontend apps with S3 and CloudFront. Note: I decided to structure the article based on the AWS services, as I want to make this hands on as much as possible. Over the years, S3 has evolved into an extremely feature-rich cloud service. There are many use cases which can be implemented with Amazon S3. Therefore, securing S3 buckets and objects will largely depend on how they are being used. Probably, the most common use case and the one I want to examine in more detail is: hosting web apps and providing storage for users’ binary object data, such as: images, videos and documents. Securing the S3 bucket mainly requires: locking down the access to the bucket, blocking all public access, securing data at rest, and securing data at transit. Let’s start with configuring bucket access permissions. Firstly, we need to understand that there are several ways to control access to S3 buckets and objects: Using S3 bucket policies, S3 ACLs, S3 Access Point policies or IAM policies. If you are interested in the distinctions, you should check out: “IAM Policies and Bucket Policies and ACLs! Oh, My!”. I will focus on configuring access controls with S3 bucket policies, as in my opinion they are most suitable for the task at hand. The following policy does a great job securing an S3 bucket. Our example S3 bucket policy contains two statements. First statement is used to lock down read access to the bucket’s objects, i.e., only allow accessing them via a specific CloudFront distribution. The distribution is specified by using its Origin Access Identity, which can be easily created with CloudFront console. This is very simple to set up, but it already improves the security, because S3 bucket policies will Deny an action unless there is an explicit Allow2. In our policy there is only explicit Allow for GetObject action and it only allows our CloudFront distribution to read the bucket’s objects. Note, that this policy does not prevent accessing the data through the CloudFront distribution. Anyone who knows the CloudFront URL will be able to read all the data in our S3 bucket. Later we will discus how to further limit read access to our data. Unpacking the second statement in our policy is a little bit more involved. It is used to block adding objects to the S3 bucket, unless the write request is made by a backend service which has a BACKEND_ROLE_ID role. More formal way of reading the statement would be: Deny PutObject Action for any Principle, unless its userId starts with a BACKEND_ROLE_ID. Or conversely, allow writing to this bucket only if the Principal has assumed the role with BACKEND_ROLE_ID. It is important to notice that in our condition we are not using role’s ARN, but rather its unique Role Id to specify the desired role. To retrieve the Role Id, we can run aws iam get-role --role-name ROLE_NAME. If for some reason you cannot use the AWS CLI, an alternative solution is to use the condition key aws:PrincipalArn instead of aws:userId, as it is also always included in the request. For example, you could change the above policy to specify the following condition statement, without changing the policy’s semantics. A keen-eyed reader will notice that we also have AIDA* specified in our statement’ condition. By adding it to our condition expression, we also allow all IAM users to write objects to the S3 bucket. The reason is that AWS IAM assigns unique IDs to all users and all of those IDs have the same prefix, which is, well AIDA. While adding this condition is not desired for production (remember to always keep people away form data), it can be quite useful during development. In addition, we can use similar approach to set permissions for CI/CD pipeline, lambda functions, EC2 instances within an Auto Scaling group, and so fort3. Note: Activating IAM Access Analyzer can be very helpful in practice, both during policy creation (where it acts as a “grammar checker”) and during system’s runtime (where continuously monitors changes to security policies). Also it is free of charge. This approach is a great way to allow backend services and external server-to-server callbacks to upload data to our S3 bucket. However, many applications will also want to enable end users to upload their own data, such as profile images. To enable uploading files directly from a frontend application to an S3 bucket, we need S3 presigned URLs. The way this process works (roughly) is to have the backend services send an upload request to S3. It then generates an encrypted upload URL, e.g., with a POST or PUT method and returns it to the calling service. Finally, the backend service sends this signed URL to the frontend client, who can then upload directly to S3. Cost reduction and better performance (especially with S3 transfer acceleration) are just some of the benefits of using the presigned URLs. Check out the following article for more details. aws.amazon.com Securing data at rest is a very broad topic, involving techniques, such as: data encryption, tokenization (anonymizing data) and masking (redacting data). S3 offers a number of useful features that can add additional layer of security to the data residing in S3. Although, securing data at rest can be a very involved process, most web applications should be fine by putting the following measures in place: Enabling default bucket encryption4. Amazon S3 supports server-side encryption of user data and it is fully transparent to the end user. Also it can be enabled with one click in S3 console. I recommend using Amazon S3-managed keys (SSE-S3), as that will reduce costs, but also since SSE-S3 are not subject to any rate limits. Activating bucket versioning. This makes S3 store a new version for every modified or deleted object from which we can restore (accidentally) compromised objects if necessary. Additionally, I find it very useful to enable MFA delete on the bucket, but it must be done by the root account. Activating versioning is very simple and similar to enabling server side encryption it doesn’t require us change application’s business logic. Enabling CloudTrail Logging for S34. This is the bare minimum, which I would recommend. It enables logging S3 API calls, including calls from the console and code calls (e.g., from the backend services) to Amazon S3 APIs. Finally, as additional security layer, make sure to block all public access to your S3 bucket. At its core, CloudFront is a Content Delivery Network (CDN) which (apart from a caching layer) does not store any data. Therefore, in the context of securing our frontend’s CloudFront distribution, it makes sense to mainly talk about: securing data in transit and managing access control. Our CloudFront distribution is the only entry point to our application. This means that all user requests will need to go through that CloudFront distribution. CloudFront also enables putting multiple origins behind a single distribution. This enables us to expose multiple S3 buckets through a single distribution, i.e., single (sub-)domain. All this makes securing our CloudFront distribution a very important issue. By restricting the access to our S3 bucket to CloudFront only, we have already significantly restricted the access controls. However, some data might require an additional layer of security. Enter CloudFront signed URLs. Signed URLs are a very useful feature, which probably deserves an article in itself. Here I briefly discuss when and how to use them, as our security best practices would be incomplete without the signed URLs. We usually decide to additionally protect S3 objects, when we don’t want them readable by everyone on the Web. This can be since the data is sensitive (e.g., user’s purchase invoices) or it should be only accessible to the paying users (e.g., course videos). For example, private user files should be accessible only to that specific user and not to everyone on the Web. Below an example of a signed URL, which can be used to access user_invoice.pdf. https://example.com/user_invoice.pdf?Expires=1622924658&Signature=9MwQEvSlsWvNfv9GrW71WMiG4X...&Key-Pair-Id=APKAJXX2ABBXX6HIX We notice that it is just a regular URL, which has three parameters appended at the end. Expires, which determines for how long the URL is valid, the (hashed and signed)Signature itself and Key-Pair-Id of a public key used to generate the Signature. If any of the parameters is omitted or incorrect CloudFront will return Forbidden, with HTTP 403 status code. Note also that in our example the signature is shortened for readability. Now how do we generate such URLs? The most frequent usage pattern, that I have seen, is to have a backend signing service, which acts as a trusted signer and signs URLs when requested by users (see figure above). The URLs are typically stored “raw” (base URL, without signature) and the signing service is used to generate signed URLs on demand as they are requested. These can then be embedded in fronted pages and shown to the user, e.g., on a user dashboard. Note: Recently, generating signed URLs got much more convenient, since now the public keys used for signed URLs (see Key-Pair-Id in the above example) can be managed through Key Groups by IAM users, without requiring AWS root account. An alternative to signed URLs are signed cookies. They both have their purpose, but generally we can achieve similar effects with both signed URLs and cookies. CloudFront offers a number of configuration knobs, which can easily be “turned” to improve overall security of data in transit. Here we consider data in transit to be all data flows between the viewer (user) and the origin (our S3 buckets), which go through CloudFront distribution (edge locations). Most important CloudFront config knobs include5: Ensure that security policy is properly configured with secure TLS and cypher. This guarantees that CloudFront is using secure version of TLS protocol for HTTPS communication between CloudFront’s edge locations and your users (viewers). As a rule of thumb, I recommend using TLSv1.0 or later (ideally use only TLSv1.2_2019 if you browser compatibility allows it) and strictly avoid using the SSLv3 protocol altogether. Note: see security policy setting for a CloudFront distribution. Ensure that the communication between the CloudFront distribution and the viewer is happening over HTTPS. Note: simply set viewer protocol policy to always require the viewers to use only the HTTPS protocol4. Ensure that the communication between the CloudFront edge location and their custom origins is using HTTPS in order to fulfill compliance requirements for data in transit encryption. Note: enabled automatically by setting the viewer protocol policy as previously described. Finally, there is also a useful S3 feature for addionally securing data in transit — VPC Endpoints, in particular Gateway Endpoints for S3. A Gateway endpoint is like a gateway to AWS public zone services. It is commonly used to enable an EC2 instance in a private subnet to access S3 (or DynamoDB), without leaving private VPC network. They work based on routing tables i.e. they add new routing rules. Security is done via VPC Endpoint policies. However, I will not discuss VPC Endpoint in more detail, as I believe that most applications work with data, which don’t necessarily require this level of isolation. Many of the top ten OWASP threats are not easy (or even possible) to address with only S3 and CloudFront features. Until recently, we had to use Lambda@Edge6, but since a couple of weeks ago we can use CloudFront Functions to achieve the same as with Lambda@Edge function, at a fraction of the cost. Below is the function, which we use to inject most common security HTTP response headers and enforce some of the best security practices. We want this function to fire before we return an response to the user. Therefore, it should be associated with a CloudFront Functions event type: viewer response. Our CloudFront function injects several common HTTP security headers to user/viewer responses from CloudFront: HTTP Strict-Transport-Security (HSTS) is an HTTP response header, which instructs the browser to always access the website using HTTPS. We add this header to protect our users from man-in-the-middle attack. Content Security Policy (CSP) is an HTTP response header, which tells the browser how and where it should load the page content. For example, CSP can be used to limit loading JS scripts only from trusted sources (such as own domain, Stripe and Google). CSP plays an important role in detecting and mitigating Cross Site Scripting (XSS) and data injection attacks. X-XSS-Protection is an HTTP response header, which instructs a browser to block pages from loading when it detects reflected Cross Site Scripting (XSS) attacks. This is very useful for older browsers that don’t support CSP. X-Content-Type-Options is an HTTP response header, which instructs a browsers to used MIME types as-is and disables browser’s content sniffing heuristics. By adding this header to the responses we can prevent MIME Confusion attacks. X-Frame-Options is an HTTP response header that indicates whether or not a browser is allowed to render a page in a <frame>, <iframe>, <embed> or <object> elements. We can use this header to prevent clickjacking attacks. Referrer-Policy is an HTTP response header, which controls how much referrer information should be included with requests to external links. Referrer policy is used to ensure that there is no Cross-domain Referrer leakage. Expect-CT is and HTTP response header, which enforces using Certificate Transparency policy, i.e., requires that the certificate is present in public logs and that client response has a valid signature attached to it. Note: This function was initially implemented with Lambda@Edge. That version of the function is available as a GitHub gist here. Amazons Well Architected Framework specifies 6 security best practices, which are broken down into 10 security questions. In this article we mainly focused on implementing data protection best practices for frontend applications, which use S3 and CloudFront for data storage and delivery. In particular, we addressed the SEC 9 (protecting data at rest) and SEC 10 (protecting data in transit) security questions. Additionally, we have seen how to protect against common OWASP threats, by using CloudFront Functions (or Lambda@Edge Functions). My initial goal was share my experiences about securing frontend applications on AWS and some lessons learned from the last security audit. However, this turned out to be (what I think) a comprehensive guide to securing frontend apps with S3 and CloudFront functions. Anyway, there are many tutorials explaining how to deploy SPAs such as Angular or React. However, the same is not true for comprehensive, end-to-end guide that focuses on implementing security best practices. Thanks for reading to the end! Hope you enjoyed this one! Here is an actual pattern how to deploy such an application by using AWS Cloud Development Kit (CDK).Note that in AWS terminology bucket owner is actually an AWS account, not an IAM user, which created the bucket or object. Please also see the endnote 3 below.Note that all services (and users), which want to access an S3 bucket need an explicit permission to do so. The permission can be granted via an S3 bucket policy or via an IAM policy. I prefer using the later. Therefore, in this article I assume that the BACKEND_ROLE has an associated IAM policy, which allows it to talk to S3.This can incur additional costs.In addition to these points, we can use field-level encryption s for particularly sensitive data, such as credit card information. It is additional layer of encryption on top of HTTPS and it guarantees that only your application can decrypt those fields. For example, this can prevent information leakage through system logs or diagnostic tools.AWS does offer additional service such as WAF and Shield, but one should not rely solely on them. Rather, we should always strive for defense in depth approach i.e., securing all layers of our application. Here is an actual pattern how to deploy such an application by using AWS Cloud Development Kit (CDK). Note that in AWS terminology bucket owner is actually an AWS account, not an IAM user, which created the bucket or object. Please also see the endnote 3 below. Note that all services (and users), which want to access an S3 bucket need an explicit permission to do so. The permission can be granted via an S3 bucket policy or via an IAM policy. I prefer using the later. Therefore, in this article I assume that the BACKEND_ROLE has an associated IAM policy, which allows it to talk to S3. This can incur additional costs. In addition to these points, we can use field-level encryption s for particularly sensitive data, such as credit card information. It is additional layer of encryption on top of HTTPS and it guarantees that only your application can decrypt those fields. For example, this can prevent information leakage through system logs or diagnostic tools. AWS does offer additional service such as WAF and Shield, but one should not rely solely on them. Rather, we should always strive for defense in depth approach i.e., securing all layers of our application.
[ { "code": null, "e": 465, "s": 171, "text": "Currently Amazon S3 and CloudFront are some of the best cloud services for delivering production-ready SPAs, such as Angular apps, Vue apps or React apps. Unfortunately, by default, S3 and CloudFront don’t have all security features enabled, needed to run such SPA frontend apps in production." }, { "code": null, "e": 792, "s": 465, "text": "Recently, we have launched a platform with a frontend (Angular apps) hosted on Amazon S3 and CloudFront. In this article, I want to share main security best practices and how we implemented them for our platform. Having these security best practices in place, helped us pass a very stringent security audit with flying colors!" }, { "code": null, "e": 1409, "s": 792, "text": "Both S3 and CloudFront are very mature cloud services and are also relatively straightforward to start with. However, there is much more than what first meets the eye, in particular if the services are used together. Additionally, if combined with other cloud services such as Route 53 (AWS DNS service) and Amazon Certificates Manager, they become a powerful, must-have tool suite for any web developer. Unfortunately, their flexibility and seeming simplicity can be a security pitfall. Most of us have probably heard of at least one instance of S3 data leaks in the past few months (whenever you are reading this)." }, { "code": null, "e": 1708, "s": 1409, "text": "Figure below shows an example infrastructure for a typical SPA, hosted on S3 and CloudFront1. Naturally, such a frontend app would depend on a set of backend services and APIs. As the article already grew beyond what I initially expected, we will not discuss the platform's backend in this article." }, { "code": null, "e": 1821, "s": 1708, "text": "In this article, I will mainly focus on the security best practices, which help address the following questions:" }, { "code": null, "e": 1908, "s": 1821, "text": "How to secure an S3 buckets, which store sensitive user data and the application code?" }, { "code": null, "e": 1961, "s": 1908, "text": "How to securely configure a CloudFront distribution?" }, { "code": null, "e": 2046, "s": 1961, "text": "How to protect frontend apps against common OWASP threats with CloudFront Functions?" }, { "code": null, "e": 2155, "s": 2046, "text": "So let’s first see what we can do to protect our Angular, Vue or React frontend apps with S3 and CloudFront." }, { "code": null, "e": 2276, "s": 2155, "text": "Note: I decided to structure the article based on the AWS services, as I want to make this hands on as much as possible." }, { "code": null, "e": 2703, "s": 2276, "text": "Over the years, S3 has evolved into an extremely feature-rich cloud service. There are many use cases which can be implemented with Amazon S3. Therefore, securing S3 buckets and objects will largely depend on how they are being used. Probably, the most common use case and the one I want to examine in more detail is: hosting web apps and providing storage for users’ binary object data, such as: images, videos and documents." }, { "code": null, "e": 2863, "s": 2703, "text": "Securing the S3 bucket mainly requires: locking down the access to the bucket, blocking all public access, securing data at rest, and securing data at transit." }, { "code": null, "e": 3219, "s": 2863, "text": "Let’s start with configuring bucket access permissions. Firstly, we need to understand that there are several ways to control access to S3 buckets and objects: Using S3 bucket policies, S3 ACLs, S3 Access Point policies or IAM policies. If you are interested in the distinctions, you should check out: “IAM Policies and Bucket Policies and ACLs! Oh, My!”." }, { "code": null, "e": 3411, "s": 3219, "text": "I will focus on configuring access controls with S3 bucket policies, as in my opinion they are most suitable for the task at hand. The following policy does a great job securing an S3 bucket." }, { "code": null, "e": 4275, "s": 3411, "text": "Our example S3 bucket policy contains two statements. First statement is used to lock down read access to the bucket’s objects, i.e., only allow accessing them via a specific CloudFront distribution. The distribution is specified by using its Origin Access Identity, which can be easily created with CloudFront console. This is very simple to set up, but it already improves the security, because S3 bucket policies will Deny an action unless there is an explicit Allow2. In our policy there is only explicit Allow for GetObject action and it only allows our CloudFront distribution to read the bucket’s objects. Note, that this policy does not prevent accessing the data through the CloudFront distribution. Anyone who knows the CloudFront URL will be able to read all the data in our S3 bucket. Later we will discus how to further limit read access to our data." }, { "code": null, "e": 4742, "s": 4275, "text": "Unpacking the second statement in our policy is a little bit more involved. It is used to block adding objects to the S3 bucket, unless the write request is made by a backend service which has a BACKEND_ROLE_ID role. More formal way of reading the statement would be: Deny PutObject Action for any Principle, unless its userId starts with a BACKEND_ROLE_ID. Or conversely, allow writing to this bucket only if the Principal has assumed the role with BACKEND_ROLE_ID." }, { "code": null, "e": 5273, "s": 4742, "text": "It is important to notice that in our condition we are not using role’s ARN, but rather its unique Role Id to specify the desired role. To retrieve the Role Id, we can run aws iam get-role --role-name ROLE_NAME. If for some reason you cannot use the AWS CLI, an alternative solution is to use the condition key aws:PrincipalArn instead of aws:userId, as it is also always included in the request. For example, you could change the above policy to specify the following condition statement, without changing the policy’s semantics." }, { "code": null, "e": 5901, "s": 5273, "text": "A keen-eyed reader will notice that we also have AIDA* specified in our statement’ condition. By adding it to our condition expression, we also allow all IAM users to write objects to the S3 bucket. The reason is that AWS IAM assigns unique IDs to all users and all of those IDs have the same prefix, which is, well AIDA. While adding this condition is not desired for production (remember to always keep people away form data), it can be quite useful during development. In addition, we can use similar approach to set permissions for CI/CD pipeline, lambda functions, EC2 instances within an Auto Scaling group, and so fort3." }, { "code": null, "e": 6153, "s": 5901, "text": "Note: Activating IAM Access Analyzer can be very helpful in practice, both during policy creation (where it acts as a “grammar checker”) and during system’s runtime (where continuously monitors changes to security policies). Also it is free of charge." }, { "code": null, "e": 7014, "s": 6153, "text": "This approach is a great way to allow backend services and external server-to-server callbacks to upload data to our S3 bucket. However, many applications will also want to enable end users to upload their own data, such as profile images. To enable uploading files directly from a frontend application to an S3 bucket, we need S3 presigned URLs. The way this process works (roughly) is to have the backend services send an upload request to S3. It then generates an encrypted upload URL, e.g., with a POST or PUT method and returns it to the calling service. Finally, the backend service sends this signed URL to the frontend client, who can then upload directly to S3. Cost reduction and better performance (especially with S3 transfer acceleration) are just some of the benefits of using the presigned URLs. Check out the following article for more details." }, { "code": null, "e": 7029, "s": 7014, "text": "aws.amazon.com" }, { "code": null, "e": 7437, "s": 7029, "text": "Securing data at rest is a very broad topic, involving techniques, such as: data encryption, tokenization (anonymizing data) and masking (redacting data). S3 offers a number of useful features that can add additional layer of security to the data residing in S3. Although, securing data at rest can be a very involved process, most web applications should be fine by putting the following measures in place:" }, { "code": null, "e": 7763, "s": 7437, "text": "Enabling default bucket encryption4. Amazon S3 supports server-side encryption of user data and it is fully transparent to the end user. Also it can be enabled with one click in S3 console. I recommend using Amazon S3-managed keys (SSE-S3), as that will reduce costs, but also since SSE-S3 are not subject to any rate limits." }, { "code": null, "e": 8195, "s": 7763, "text": "Activating bucket versioning. This makes S3 store a new version for every modified or deleted object from which we can restore (accidentally) compromised objects if necessary. Additionally, I find it very useful to enable MFA delete on the bucket, but it must be done by the root account. Activating versioning is very simple and similar to enabling server side encryption it doesn’t require us change application’s business logic." }, { "code": null, "e": 8417, "s": 8195, "text": "Enabling CloudTrail Logging for S34. This is the bare minimum, which I would recommend. It enables logging S3 API calls, including calls from the console and code calls (e.g., from the backend services) to Amazon S3 APIs." }, { "code": null, "e": 8512, "s": 8417, "text": "Finally, as additional security layer, make sure to block all public access to your S3 bucket." }, { "code": null, "e": 8801, "s": 8512, "text": "At its core, CloudFront is a Content Delivery Network (CDN) which (apart from a caching layer) does not store any data. Therefore, in the context of securing our frontend’s CloudFront distribution, it makes sense to mainly talk about: securing data in transit and managing access control." }, { "code": null, "e": 9220, "s": 8801, "text": "Our CloudFront distribution is the only entry point to our application. This means that all user requests will need to go through that CloudFront distribution. CloudFront also enables putting multiple origins behind a single distribution. This enables us to expose multiple S3 buckets through a single distribution, i.e., single (sub-)domain. All this makes securing our CloudFront distribution a very important issue." }, { "code": null, "e": 9441, "s": 9220, "text": "By restricting the access to our S3 bucket to CloudFront only, we have already significantly restricted the access controls. However, some data might require an additional layer of security. Enter CloudFront signed URLs." }, { "code": null, "e": 9651, "s": 9441, "text": "Signed URLs are a very useful feature, which probably deserves an article in itself. Here I briefly discuss when and how to use them, as our security best practices would be incomplete without the signed URLs." }, { "code": null, "e": 10102, "s": 9651, "text": "We usually decide to additionally protect S3 objects, when we don’t want them readable by everyone on the Web. This can be since the data is sensitive (e.g., user’s purchase invoices) or it should be only accessible to the paying users (e.g., course videos). For example, private user files should be accessible only to that specific user and not to everyone on the Web. Below an example of a signed URL, which can be used to access user_invoice.pdf." }, { "code": null, "e": 10228, "s": 10102, "text": "https://example.com/user_invoice.pdf?Expires=1622924658&Signature=9MwQEvSlsWvNfv9GrW71WMiG4X...&Key-Pair-Id=APKAJXX2ABBXX6HIX" }, { "code": null, "e": 10662, "s": 10228, "text": "We notice that it is just a regular URL, which has three parameters appended at the end. Expires, which determines for how long the URL is valid, the (hashed and signed)Signature itself and Key-Pair-Id of a public key used to generate the Signature. If any of the parameters is omitted or incorrect CloudFront will return Forbidden, with HTTP 403 status code. Note also that in our example the signature is shortened for readability." }, { "code": null, "e": 11124, "s": 10662, "text": "Now how do we generate such URLs? The most frequent usage pattern, that I have seen, is to have a backend signing service, which acts as a trusted signer and signs URLs when requested by users (see figure above). The URLs are typically stored “raw” (base URL, without signature) and the signing service is used to generate signed URLs on demand as they are requested. These can then be embedded in fronted pages and shown to the user, e.g., on a user dashboard." }, { "code": null, "e": 11519, "s": 11124, "text": "Note: Recently, generating signed URLs got much more convenient, since now the public keys used for signed URLs (see Key-Pair-Id in the above example) can be managed through Key Groups by IAM users, without requiring AWS root account. An alternative to signed URLs are signed cookies. They both have their purpose, but generally we can achieve similar effects with both signed URLs and cookies." }, { "code": null, "e": 11868, "s": 11519, "text": "CloudFront offers a number of configuration knobs, which can easily be “turned” to improve overall security of data in transit. Here we consider data in transit to be all data flows between the viewer (user) and the origin (our S3 buckets), which go through CloudFront distribution (edge locations). Most important CloudFront config knobs include5:" }, { "code": null, "e": 12352, "s": 11868, "text": "Ensure that security policy is properly configured with secure TLS and cypher. This guarantees that CloudFront is using secure version of TLS protocol for HTTPS communication between CloudFront’s edge locations and your users (viewers). As a rule of thumb, I recommend using TLSv1.0 or later (ideally use only TLSv1.2_2019 if you browser compatibility allows it) and strictly avoid using the SSLv3 protocol altogether. Note: see security policy setting for a CloudFront distribution." }, { "code": null, "e": 12561, "s": 12352, "text": "Ensure that the communication between the CloudFront distribution and the viewer is happening over HTTPS. Note: simply set viewer protocol policy to always require the viewers to use only the HTTPS protocol4." }, { "code": null, "e": 12835, "s": 12561, "text": "Ensure that the communication between the CloudFront edge location and their custom origins is using HTTPS in order to fulfill compliance requirements for data in transit encryption. Note: enabled automatically by setting the viewer protocol policy as previously described." }, { "code": null, "e": 13449, "s": 12835, "text": "Finally, there is also a useful S3 feature for addionally securing data in transit — VPC Endpoints, in particular Gateway Endpoints for S3. A Gateway endpoint is like a gateway to AWS public zone services. It is commonly used to enable an EC2 instance in a private subnet to access S3 (or DynamoDB), without leaving private VPC network. They work based on routing tables i.e. they add new routing rules. Security is done via VPC Endpoint policies. However, I will not discuss VPC Endpoint in more detail, as I believe that most applications work with data, which don’t necessarily require this level of isolation." }, { "code": null, "e": 14051, "s": 13449, "text": "Many of the top ten OWASP threats are not easy (or even possible) to address with only S3 and CloudFront features. Until recently, we had to use Lambda@Edge6, but since a couple of weeks ago we can use CloudFront Functions to achieve the same as with Lambda@Edge function, at a fraction of the cost. Below is the function, which we use to inject most common security HTTP response headers and enforce some of the best security practices. We want this function to fire before we return an response to the user. Therefore, it should be associated with a CloudFront Functions event type: viewer response." }, { "code": null, "e": 14162, "s": 14051, "text": "Our CloudFront function injects several common HTTP security headers to user/viewer responses from CloudFront:" }, { "code": null, "e": 14369, "s": 14162, "text": "HTTP Strict-Transport-Security (HSTS) is an HTTP response header, which instructs the browser to always access the website using HTTPS. We add this header to protect our users from man-in-the-middle attack." }, { "code": null, "e": 14733, "s": 14369, "text": "Content Security Policy (CSP) is an HTTP response header, which tells the browser how and where it should load the page content. For example, CSP can be used to limit loading JS scripts only from trusted sources (such as own domain, Stripe and Google). CSP plays an important role in detecting and mitigating Cross Site Scripting (XSS) and data injection attacks." }, { "code": null, "e": 14957, "s": 14733, "text": "X-XSS-Protection is an HTTP response header, which instructs a browser to block pages from loading when it detects reflected Cross Site Scripting (XSS) attacks. This is very useful for older browsers that don’t support CSP." }, { "code": null, "e": 15190, "s": 14957, "text": "X-Content-Type-Options is an HTTP response header, which instructs a browsers to used MIME types as-is and disables browser’s content sniffing heuristics. By adding this header to the responses we can prevent MIME Confusion attacks." }, { "code": null, "e": 15411, "s": 15190, "text": "X-Frame-Options is an HTTP response header that indicates whether or not a browser is allowed to render a page in a <frame>, <iframe>, <embed> or <object> elements. We can use this header to prevent clickjacking attacks." }, { "code": null, "e": 15634, "s": 15411, "text": "Referrer-Policy is an HTTP response header, which controls how much referrer information should be included with requests to external links. Referrer policy is used to ensure that there is no Cross-domain Referrer leakage." }, { "code": null, "e": 15852, "s": 15634, "text": "Expect-CT is and HTTP response header, which enforces using Certificate Transparency policy, i.e., requires that the certificate is present in public logs and that client response has a valid signature attached to it." }, { "code": null, "e": 15981, "s": 15852, "text": "Note: This function was initially implemented with Lambda@Edge. That version of the function is available as a GitHub gist here." }, { "code": null, "e": 16524, "s": 15981, "text": "Amazons Well Architected Framework specifies 6 security best practices, which are broken down into 10 security questions. In this article we mainly focused on implementing data protection best practices for frontend applications, which use S3 and CloudFront for data storage and delivery. In particular, we addressed the SEC 9 (protecting data at rest) and SEC 10 (protecting data in transit) security questions. Additionally, we have seen how to protect against common OWASP threats, by using CloudFront Functions (or Lambda@Edge Functions)." }, { "code": null, "e": 16792, "s": 16524, "text": "My initial goal was share my experiences about securing frontend applications on AWS and some lessons learned from the last security audit. However, this turned out to be (what I think) a comprehensive guide to securing frontend apps with S3 and CloudFront functions." }, { "code": null, "e": 17001, "s": 16792, "text": "Anyway, there are many tutorials explaining how to deploy SPAs such as Angular or React. However, the same is not true for comprehensive, end-to-end guide that focuses on implementing security best practices." }, { "code": null, "e": 17059, "s": 17001, "text": "Thanks for reading to the end! Hope you enjoyed this one!" }, { "code": null, "e": 18230, "s": 17059, "text": "Here is an actual pattern how to deploy such an application by using AWS Cloud Development Kit (CDK).Note that in AWS terminology bucket owner is actually an AWS account, not an IAM user, which created the bucket or object. Please also see the endnote 3 below.Note that all services (and users), which want to access an S3 bucket need an explicit permission to do so. The permission can be granted via an S3 bucket policy or via an IAM policy. I prefer using the later. Therefore, in this article I assume that the BACKEND_ROLE has an associated IAM policy, which allows it to talk to S3.This can incur additional costs.In addition to these points, we can use field-level encryption s for particularly sensitive data, such as credit card information. It is additional layer of encryption on top of HTTPS and it guarantees that only your application can decrypt those fields. For example, this can prevent information leakage through system logs or diagnostic tools.AWS does offer additional service such as WAF and Shield, but one should not rely solely on them. Rather, we should always strive for defense in depth approach i.e., securing all layers of our application." }, { "code": null, "e": 18332, "s": 18230, "text": "Here is an actual pattern how to deploy such an application by using AWS Cloud Development Kit (CDK)." }, { "code": null, "e": 18492, "s": 18332, "text": "Note that in AWS terminology bucket owner is actually an AWS account, not an IAM user, which created the bucket or object. Please also see the endnote 3 below." }, { "code": null, "e": 18821, "s": 18492, "text": "Note that all services (and users), which want to access an S3 bucket need an explicit permission to do so. The permission can be granted via an S3 bucket policy or via an IAM policy. I prefer using the later. Therefore, in this article I assume that the BACKEND_ROLE has an associated IAM policy, which allows it to talk to S3." }, { "code": null, "e": 18854, "s": 18821, "text": "This can incur additional costs." }, { "code": null, "e": 19200, "s": 18854, "text": "In addition to these points, we can use field-level encryption s for particularly sensitive data, such as credit card information. It is additional layer of encryption on top of HTTPS and it guarantees that only your application can decrypt those fields. For example, this can prevent information leakage through system logs or diagnostic tools." } ]
Apache Commons Collections - Quick Guide
Commons Collections augments Java Collections Framework. It provides several features to make collection handling easy. It provides many new interfaces, implementations and utilities. The main features of Commons Collections are as follows − Bag − Bag interfaces simplifies the collections, which have multiple number of copies of each object. Bag − Bag interfaces simplifies the collections, which have multiple number of copies of each object. BidiMap − BidiMap interfaces provide Bi-Directional maps, which can be used to lookup values using keys or keys using values. BidiMap − BidiMap interfaces provide Bi-Directional maps, which can be used to lookup values using keys or keys using values. MapIterator − MapIterator interface provide simple and easy iteration over maps. MapIterator − MapIterator interface provide simple and easy iteration over maps. Transforming Decorators − Transforming decorators can alter every object of a collection as and when it is added to the collection. Transforming Decorators − Transforming decorators can alter every object of a collection as and when it is added to the collection. Composite Collections − Composite collections are used, where multiple collections are required to be handled uniformly. Composite Collections − Composite collections are used, where multiple collections are required to be handled uniformly. Ordered Map − Ordered Maps retain the order, in which elements are added in. Ordered Map − Ordered Maps retain the order, in which elements are added in. Ordered Set − Ordered Sets retain the order, in which elements are added in. Ordered Set − Ordered Sets retain the order, in which elements are added in. Reference map − Reference map allows key/values to be garbage collected under close control. Reference map − Reference map allows key/values to be garbage collected under close control. Comparator implementations − Many Comparator implementations are available. Comparator implementations − Many Comparator implementations are available. Iterator implementations − Many Iterator implementations are available. Iterator implementations − Many Iterator implementations are available. Adapter Classes − Adapter classes are available to convert array and enumerations to collections. Adapter Classes − Adapter classes are available to convert array and enumerations to collections. Utilities − Utilities are available to test or create typical set-theory properties of collections such as union, intersection. Supports Closure. Utilities − Utilities are available to test or create typical set-theory properties of collections such as union, intersection. Supports Closure. If you are still willing to set up your environment for Java programming language, then this section guides you on how to download and set up Java on your machine. Please follow the steps mentioned below to set up the environment. Java SE is freely available from the link www.oracle.com/technetwork/java/archive-139210.html So, you download a version based on your operating system. Follow the instructions to download Java and run the .exe to install Java on your machine. Once, you have installed Java on your machine, you would need to set environment variables to point to correct installation directories. We are assuming that you have installed Java in c:\Program Files\java\jdk directory Right-click on 'My Computer' and select 'Properties'. Right-click on 'My Computer' and select 'Properties'. Click on the 'Environment variables' button under the 'Advanced' tab. Click on the 'Environment variables' button under the 'Advanced' tab. Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'. Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'. We are assuming that you have installed Java in c:\Program Files\java\jdk directory. Edit the 'C:\autoexec.bat' file and add the following line at the end − 'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'. Edit the 'C:\autoexec.bat' file and add the following line at the end − 'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'. Environment variable PATH should be set to point to where, the Java binaries have been installed. Refer to your shell documentation, if you have trouble doing this. Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH' To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following − Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad. Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad. Netbeans − It is a Java IDE that is open-source and free, which can be downloaded from www.netbeans.org/index.html. Netbeans − It is a Java IDE that is open-source and free, which can be downloaded from www.netbeans.org/index.html. Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org. Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org. Download the latest version of Apache Common Collections jar file from commons-collections4-4.1-bin.zip. At the time of writing this tutorial, we have downloaded commons-collections4-4.1-bin.zip and copied it into C:\>Apache folder. Set the APACHE_HOME environment variable to point to the base directory location where Apache jar is stored on your machine. Assuming, we've extracted commons-collections4-4.1-bin.zip in Apache folder on various Operating Systems as follows − Set the CLASSPATH environment variable to point to the Common Collections jar location. Assuming, you have stored commons-collections4-4.1-bin.zip in Apache folder on various Operating Systems as follows − New Interfaces are added to supports bags. A Bag defines a collection which, counts the number of times an object appears in the collection. For example, if a Bag contains {a, a, b, c} then getCount("a") will return 2 while uniqueSet() returns the unique values. Following is the declaration for org.apache.commons.collections4.Bag<E> interface − public interface Bag<E> extends Collection<E> The methods for bag inference are as follows − boolean add(E object) (Violation) Adds one copy of the specified object to the Bag. boolean add(E object, int nCopies) Adds nCopies copies of the specified object to the Bag. boolean containsAll(Collection<?> coll) (Violation) Returns true if the bag contains all elements in the given collection, respecting cardinality. int getCount(Object object) Returns the number of occurrences (cardinality) of the given object currently in the bag. Iterator<E> iterator() Returns an Iterator over the entire set of members, including copies due to cardinality. boolean remove(Object object) (Violation) Removes all occurrences of the given object from the bag. boolean remove(Object object, int nCopies) Removes nCopies copies of the specified object from the Bag. boolean removeAll(Collection<?> coll) (Violation) Remove all elements represented in the given collection, respecting cardinality. boolean retainAll(Collection<?> coll) (Violation) Remove any members of the bag that are not in the given collection, respecting cardinality. int size() Returns the total number of items in the bag across all types. Set<E> uniqueSet() Returns a Set of unique elements in the Bag. This interface inherits methods from the following interface − java.util.Collectio. An example of BagTester.java is as follows − import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.bag.HashBag; public class BagTester { public static void main(String[] args) { Bag<String> bag = new HashBag<>(); //add "a" two times to the bag. bag.add("a" , 2); //add "b" one time to the bag. bag.add("b"); //add "c" one time to the bag. bag.add("c"); //add "d" three times to the bag. bag.add("d",3 //get the count of "d" present in bag. System.out.println("d is present " + bag.getCount("d") + " times."); System.out.println("bag: " +bag); //get the set of unique values from the bag System.out.println("Unique Set: " +bag.uniqueSet()); //remove 2 occurrences of "d" from the bag bag.remove("d",2); System.out.println("2 occurences of d removed from bag: " +bag); System.out.println("d is present " + bag.getCount("d") + " times."); System.out.println("bag: " +bag); System.out.println("Unique Set: " +bag.uniqueSet()); } } You will see the following output − d is present 3 times. bag: [2:a,1:b,1:c,3:d] Unique Set: [a, b, c, d] 2 occurences of d removed from bag: [2:a,1:b,1:c,1:d] d is present 1 times. bag: [2:a,1:b,1:c,1:d] Unique Set: [a, b, c, d] New Interfaces are added to supports bidirectional Map. Using bidirectional map, a key can be lookup using value and value can be lookup using key easily. Following is the declaration for org.apache.commons.collections4.BidiMap<K,V> interface − public interface BidiMap<K,V> extends IterableMap<K,V> The methods for the BidiMap Interface are as follows − K getKey(Object value) Gets the key that is currently mapped to the specified value. BidiMap<V,K> inverseBidiMap() Gets a view of this map where the keys and values are reversed. V put(K key, V value) Puts the key-value pair into the map, replacing any previous pair. K removeValue(Object value) Removes the key-value pair that is currently mapped to the specified value (optional operation). Set<V> values() Returns a Set view of the values contained in this map. This interface inherits methods from the following interfaces − org.apache.commons.collections4.Ge. org.apache.commons.collections4.Ge. org.apache.commons.collections4.IterableGe. org.apache.commons.collections4.IterableGe. org.apache.commons.collections4.Pu. org.apache.commons.collections4.Pu. java.util.Ma. java.util.Ma. An example of BidiMapTester.java is as follows − import org.apache.commons.collections4.BidiMap; import org.apache.commons.collections4.bidimap.TreeBidiMap; public class BidiMapTester { public static void main(String[] args) { BidiMap>String, String< bidi = new TreeBidiMap<>(); bidi.put("One", "1"); bidi.put("Two", "2"); bidi.put("Three", "3"); System.out.println(bidi.get("One")); System.out.println(bidi.getKey("1")); System.out.println("Original Map: " + bidi); bidi.removeValue("1"); System.out.println("Modified Map: " + bidi); BidiMap<String, String> inversedMap = bidi.inverseBidiMap(); System.out.println("Inversed Map: " + inversedMap); } } When you run the code, you will see the following output − 1 One Original Map: {One=1, Three=3, Two=2} Modified Map: {Three=3, Two=2} Inversed Map: {2=Two, 3=Three} The JDK Map interface is pretty difficult to iterate as Iteration to be done on EntrySet or over the KeySet objects. MapIterator provides simple iteration over Map. Following example illustrates the same. An example for MapIteratorTester.java is as follows − import org.apache.commons.collections4.IterableMap; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.map.HashedMap; public class MapIteratorTester { public static void main(String[] args) { IterableMap<String, String> map = new HashedMap<>(); map.put("1", "One"); map.put("2", "Two"); map.put("3", "Three"); map.put("4", "Four"); map.put("5", "Five"); MapIterator<String, String> iterator = map.mapIterator(); while (iterator.hasNext()) { Object key = iterator.next(); Object value = iterator.getValue(); System.out.println("key: " + key); System.out.println("Value: " + value); iterator.setValue(value + "_"); } System.out.println(map); } } The output is stated below − key: 3 Value: Three key: 5 Value: Five key: 2 Value: Two key: 4 Value: Four key: 1 Value: One {3=Three_, 5=Five_, 2=Two_, 4=Four_, 1=One_} OrderedMap is a new interface for maps to retain the order in which elements are added. LinkedMap and ListOrderedMap are two available implementations. This interfaces supports iterator that of Map and allows iteration in both directions either forwards or backwards in a Map. Following example illustrates the same. An example of OrderedMapTester.java is as given below − import org.apache.commons.collections4.OrderedMap; import org.apache.commons.collections4.map.LinkedMap; public class OrderedMapTester { public static void main(String[] args) { OrderedMap<String, String> map = new LinkedMap<String, String>(); map.put("One", "1"); map.put("Two", "2"); map.put("Three", "3"); System.out.println(map.firstKey()); System.out.println(map.nextKey("One")); System.out.println(map.nextKey("Two")); } } The result will be as follows − One Two Three CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API. addIgnoreNull() method of CollectionUtils can be used to ensure that only non-null values are getting added to the collection. Following is the declaration for org.apache.commons.collections4.CollectionUtils.addIgnoreNull() method − public static <T> boolean addIgnoreNull(Collection<T> collection, T object) collection − The collection to add to, must not be null. collection − The collection to add to, must not be null. object − The object to add, if null it will not be added. object − The object to add, if null it will not be added. True if the collection changed. NullPointerException − If the collection is null. NullPointerException − If the collection is null. The following example shows the usage of org.apache.commons.collections4.CollectionUtils.addIgnoreNull() method. We are trying to add a null value and a sample non-null value. import java.util.LinkedList; import java.util.List; import org.apache.commons.collections4.CollectionUtils; public class CollectionUtilsTester { public static void main(String[] args) { List<String> list = new LinkedList<String>(); CollectionUtils.addIgnoreNull(list, null); CollectionUtils.addIgnoreNull(list, "a"); System.out.println(list); if(list.contains(null)) { System.out.println("Null value is present"); } else { System.out.println("Null value is not present"); } } } The output is mentioned below − [a] Null value is not present CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API. collate() method of CollectionUtils can be used to merge two already sorted lists. Following is the declaration for org.apache.commons.collections4.CollectionUtils.collate() method − public static <O extends Comparable<? super O>> List<O> collate(Iterable<? extends O> a, Iterable<? extends O> b) a − The first collection, must not be null. a − The first collection, must not be null. b − The second collection, must not be null. b − The second collection, must not be null. A new sorted List, containing the elements of Collection a and b. NullPointerException − If either collection is null. NullPointerException − If either collection is null. The following example shows the usage of org.apache.commons.collections4.CollectionUtils.collate() method. We'll merge two sorted lists and then print the merged and sorted list. import java.util.Arrays; import java.util.List; import org.apache.commons.collections4.CollectionUtils; public class CollectionUtilsTester { 8. Apache Commons Collections — Merge & Sort public static void main(String[] args) { List<String> sortedList1 = Arrays.asList("A","C","E"); List<String> sortedList2 = Arrays.asList("B","D","F"); List<String> mergedList = CollectionUtils.collate(sortedList1, sortedList2); System.out.println(mergedList); } } The output is as follows − [A, B, C, D, E, F] CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API. collect() method of CollectionUtils can be used to transform a list of one type of objects to list of different type of objects. Following is the declaration for org.apache.commons.collections4.CollectionUtils.collect() method − public static <I,O> Collection<O> collect(Iterable<I> inputCollection, Transformer<? super I,? extends O> transformer) inputCollection − The collection to get the input from, may not be null. inputCollection − The collection to get the input from, may not be null. Transformer − The transformer to use, may be null. Transformer − The transformer to use, may be null. The transformed result (new list). NullPointerException − If the input collection is null. NullPointerException − If the input collection is null. The following example shows the usage of org.apache.commons.collections4.CollectionUtils.collect() method. We'll transform a list of string to list of integer by parsing the integer value from String. import java.util.Arrays; import java.util.List; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.Transformer; public class CollectionUtilsTester { public static void main(String[] args) { List<String> stringList = Arrays.asList("1","2","3"); List<Integer> integerList = (List<Integer>) CollectionUtils.collect(stringList, new Transformer<String, Integer>() { @Override public Integer transform(String input) { return Integer.parseInt(input); } }); System.out.println(integerList); } } When you use the code, you will get the following code − [1, 2, 3] CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API. filter() method of CollectionUtils can be used to filter a list to remove objects which do not satisfy condition provided by predicate passed. Following is the declaration for org.apache.commons.collections4.CollectionUtils.filter() method − public static <T> boolean filter(Iterable<T> collection, Predicate<? super T> predicate) collection − The collection to get the input from, may not be null. collection − The collection to get the input from, may not be null. predicate − The predicate to use as a filter, may be null. predicate − The predicate to use as a filter, may be null. True if the collection is modified by this call, false otherwise. The following example shows the usage of org.apache.commons.collections4.CollectionUtils.filter() method. We'll filter a list of integer to get even numbers only. import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.Predicate; public class CollectionUtilsTester { public static void main(String[] args) { List<Integer> integerList = new ArrayList<Integer>(); integerList.addAll(Arrays.asList(1,2,3,4,5,6,7,8)); System.out.println("Original List: " + integerList); CollectionUtils.filter(integerList, new Predicate<Integer>() { @Override public boolean evaluate(Integer input) { if(input.intValue() % 2 == 0) { return true; } return false; } }); System.out.println("Filtered List (Even numbers): " + integerList); } } It will produce the following result − Original List: [1, 2, 3, 4, 5, 6, 7, 8] Filtered List (Even numbers): [2, 4, 6, 8] filterInverse() method of CollectionUtils can be used to filter a list to remove objects, which satisfy condition provided by predicate passed. Following is the declaration for org.apache.commons.collections4.CollectionUtils.filterInverse() method − public static <T> boolean filterInverse(Iterable<T> collection, Predicate<? super T> predicate) collection − The collection to get the input from, may not be null. collection − The collection to get the input from, may not be null. predicate − The predicate to use as a filter, may be null. predicate − The predicate to use as a filter, may be null. True if the collection is modified by this call, false otherwise. The following example shows the usage of org.apache.commons.collections4.CollectionUtils.filterInverse() method. We'll filter a list of integer to get odd numbers only. import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.Predicate; public class CollectionUtilsTester { public static void main(String[] args) { List<Integer> integerList = new ArrayList<Integer>(); integerList.addAll(Arrays.asList(1,2,3,4,5,6,7,8)); System.out.println("Original List: " + integerList); CollectionUtils.filterInverse(integerList, new Predicate<Integer>() { @Override public boolean evaluate(Integer input) { if(input.intValue() % 2 == 0) { return true; } return false; } }); System.out.println("Filtered List (Odd numbers): " + integerList); } } The result is as stated below − Original List: [1, 2, 3, 4, 5, 6, 7, 8] Filtered List (Odd numbers): [1, 3, 5, 7] CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API. isNotEmpty() method of CollectionUtils can be used to check if a list is not empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list. Following is the declaration for org.apache.commons.collections4.CollectionUtils.isNotEmpty() method − public static boolean isNotEmpty(Collection<?> coll) coll − The collection to check, may be null. coll − The collection to check, may be null. True if non-null and non-empty. The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isNotEmpty() method. We'll check a list is empty or not. import java.util.List; import org.apache.commons.collections4.CollectionUtils; public class CollectionUtilsTester { public static void main(String[] args) { List<String> list = getList(); System.out.println("Non-Empty List Check: " + checkNotEmpty1(list)); System.out.println("Non-Empty List Check: " + checkNotEmpty1(list)); } static List<String> getList() { return null; } static boolean checkNotEmpty1(List<String> list) { return !(list == null || list.isEmpty()); } static boolean checkNotEmpty2(List<String> list) { return CollectionUtils.isNotEmpty(list); } } The output is given below − Non-Empty List Check: false Non-Empty List Check: false isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list. Following is the declaration for org.apache.commons.collections4.CollectionUtils.isEmpty() method − public static boolean isEmpty(Collection<?> coll) coll − The collection to check, may be null. coll − The collection to check, may be null. True if empty or null. The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isEmpty() method. We'll check a list is empty or not. import java.util.List; import org.apache.commons.collections4.CollectionUtils; public class CollectionUtilsTester { public static void main(String[] args) { List<String> list = getList(); System.out.println("Empty List Check: " + checkEmpty1(list)); System.out.println("Empty List Check: " + checkEmpty1(list)); } static List<String> getList() { return null; } static boolean checkEmpty1(List<String> list) { return (list == null || list.isEmpty()); } static boolean checkEmpty2(List<String> list) { return CollectionUtils.isEmpty(list); } } Given below is the output of the code − Empty List Check: true Empty List Check: true CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API. isSubCollection() method of CollectionUtils can be used to check if a collection contains the given collection or not. Following is the declaration for org.apache.commons.collections4.CollectionUtils.isSubCollection() method − public static boolean isSubCollection(Collection<?> a, Collection<?> b) a − The first (sub) collection, must not be null. a − The first (sub) collection, must not be null. b − The second (super) collection, must not be null. b − The second (super) collection, must not be null. True if and only if a is a sub-collection of b. The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isSubCollection() method. We'll check a list is part of another list or not. import java.util.Arrays; import java.util.List; import org.apache.commons.collections4.CollectionUtils; public class CollectionUtilsTester { public static void main(String[] args) { //checking inclusion List<String> list1 = Arrays.asList("A","A","A","C","B","B"); List<String> list2 = Arrays.asList("A","A","B","B"); System.out.println("List 1: " + list1); System.out.println("List 2: " + list2); System.out.println("Is List 2 contained in List 1: " + CollectionUtils.isSubCollection(list2, list1)); } } You will receive the following output − List 1: [A, A, A, C, B, B] List 2: [A, A, B, B] Is List 2 contained in List 1: true CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API. intersection() method of CollectionUtils can be used to get the common objects between two collections(intersection). Following is the declaration for org.apache.commons.collections4.CollectionUtils.intersection() method − public static <O> Collection<O> intersection(Iterable<? extends O> a, Iterable<? extends O> b) a − The first (sub) collection, must not be null. a − The first (sub) collection, must not be null. b − The second (super) collection, must not be null. b − The second (super) collection, must not be null. The intersection of the two collections. The following example shows the usage of org.apache.commons.collections4.CollectionUtils.intersection() method. We'll get the intersection of two lists. import java.util.Arrays; import java.util.List; import org.apache.commons.collections4.CollectionUtils; public class CollectionUtilsTester { public static void main(String[] args) { //checking inclusion List<String> list1 = Arrays.asList("A","A","A","C","B","B"); List<String> list2 = Arrays.asList("A","A","B","B"); System.out.println("List 1: " + list1); System.out.println("List 2: " + list2); System.out.println("Commons Objects of List 1 and List 2: " + CollectionUtils.intersection(list1, list2)); } } When you run the code, you will see the following output − List 1: [A, A, A, C, B, B] List 2: [A, A, B, B] Commons Objects of List 1 and List 2: [A, A, B, B] CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API. subtract() method of CollectionUtils can be used to get the new collection by subtracting objects of one collection from other. Following is the declaration for org.apache.commons.collections4.CollectionUtils.subtract() method − public static <O> Collection<O> subtract(Iterable<? extends O> a, Iterable<? extends O> b) a − The collection to subtract from, must not be null. a − The collection to subtract from, must not be null. b − The collection to subtract, must not be null. b − The collection to subtract, must not be null. A new collection with the results. The following example shows the usage of org.apache.commons.collections4.CollectionUtils.subtract() method. We'll get the subtraction of two lists. import java.util.Arrays; import java.util.List; import org.apache.commons.collections4.CollectionUtils; public class CollectionUtilsTester { public static void main(String[] args) { //checking inclusion List<String> list1 = Arrays.asList("A","A","A","C","B","B"); List<String> list2 = Arrays.asList("A","A","B","B"); System.out.println("List 1: " + list1); System.out.println("List 2: " + list2); System.out.println("List 1 - List 2: "+ CollectionUtils.subtract(list1, list2)); } } When you execute the above code, you should see the following output − List 1: [A, A, A, C, B, B] List 2: [A, A, B, B] List 1 - List 2: [A, C] CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API. union() method of CollectionUtils can be used to get the union of two collections. Following is the declaration for org.apache.commons.collections4.CollectionUtils.union() method − public static <O> Collection<O> union(Iterable<? extends O> a, Iterable<? extends O> b) a − The first collection, must not be null. a − The first collection, must not be null. b − The second collection, must not be null. b − The second collection, must not be null. The union of the two collections. The following example shows the usage of org.apache.commons.collections4.CollectionUtils.union() method. We'll get the union of two lists. import java.util.Arrays; import java.util.List; import org.apache.commons.collections4.CollectionUtils; public class CollectionUtilsTester { public static void main(String[] args) { //checking inclusion List<String> list1 = Arrays.asList("A","A","A","C","B","B"); List<String> list2 = Arrays.asList("A","A","B","B"); System.out.println("List 1: " + list1); System.out.println("List 2: " + list2); System.out.println("Union of List 1 and List 2: "+ CollectionUtils.union(list1, list2)); } } This produces the following output − List 1: [A, A, A, C, B, B] List 2: [A, A, B, B] Union of List 1 and List 2: [A, A, A, B, B, C] Print Add Notes Bookmark this page
[ { "code": null, "e": 2384, "s": 2200, "text": "Commons Collections augments Java Collections Framework. It provides several features to make collection handling easy. It provides many new interfaces, implementations and utilities." }, { "code": null, "e": 2442, "s": 2384, "text": "The main features of Commons Collections are as follows −" }, { "code": null, "e": 2544, "s": 2442, "text": "Bag − Bag interfaces simplifies the collections, which have multiple number of copies of each object." }, { "code": null, "e": 2646, "s": 2544, "text": "Bag − Bag interfaces simplifies the collections, which have multiple number of copies of each object." }, { "code": null, "e": 2772, "s": 2646, "text": "BidiMap − BidiMap interfaces provide Bi-Directional maps, which can be used to lookup values using keys or keys using values." }, { "code": null, "e": 2898, "s": 2772, "text": "BidiMap − BidiMap interfaces provide Bi-Directional maps, which can be used to lookup values using keys or keys using values." }, { "code": null, "e": 2979, "s": 2898, "text": "MapIterator − MapIterator interface provide simple and easy iteration over maps." }, { "code": null, "e": 3060, "s": 2979, "text": "MapIterator − MapIterator interface provide simple and easy iteration over maps." }, { "code": null, "e": 3192, "s": 3060, "text": "Transforming Decorators − Transforming decorators can alter every object of a collection as and when it is added to the collection." }, { "code": null, "e": 3324, "s": 3192, "text": "Transforming Decorators − Transforming decorators can alter every object of a collection as and when it is added to the collection." }, { "code": null, "e": 3445, "s": 3324, "text": "Composite Collections − Composite collections are used, where multiple collections are required to be handled uniformly." }, { "code": null, "e": 3566, "s": 3445, "text": "Composite Collections − Composite collections are used, where multiple collections are required to be handled uniformly." }, { "code": null, "e": 3643, "s": 3566, "text": "Ordered Map − Ordered Maps retain the order, in which elements are added in." }, { "code": null, "e": 3720, "s": 3643, "text": "Ordered Map − Ordered Maps retain the order, in which elements are added in." }, { "code": null, "e": 3797, "s": 3720, "text": "Ordered Set − Ordered Sets retain the order, in which elements are added in." }, { "code": null, "e": 3874, "s": 3797, "text": "Ordered Set − Ordered Sets retain the order, in which elements are added in." }, { "code": null, "e": 3967, "s": 3874, "text": "Reference map − Reference map allows key/values to be garbage collected under close control." }, { "code": null, "e": 4060, "s": 3967, "text": "Reference map − Reference map allows key/values to be garbage collected under close control." }, { "code": null, "e": 4136, "s": 4060, "text": "Comparator implementations − Many Comparator implementations are available." }, { "code": null, "e": 4212, "s": 4136, "text": "Comparator implementations − Many Comparator implementations are available." }, { "code": null, "e": 4284, "s": 4212, "text": "Iterator implementations − Many Iterator implementations are available." }, { "code": null, "e": 4356, "s": 4284, "text": "Iterator implementations − Many Iterator implementations are available." }, { "code": null, "e": 4454, "s": 4356, "text": "Adapter Classes − Adapter classes are available to convert array and enumerations to collections." }, { "code": null, "e": 4552, "s": 4454, "text": "Adapter Classes − Adapter classes are available to convert array and enumerations to collections." }, { "code": null, "e": 4698, "s": 4552, "text": "Utilities − Utilities are available to test or create typical set-theory properties of collections such as union, intersection. Supports Closure." }, { "code": null, "e": 4844, "s": 4698, "text": "Utilities − Utilities are available to test or create typical set-theory properties of collections such as union, intersection. Supports Closure." }, { "code": null, "e": 5075, "s": 4844, "text": "If you are still willing to set up your environment for Java programming language, then this section guides you on how to download and set up Java on your machine. Please follow the steps mentioned below to set up the environment." }, { "code": null, "e": 5228, "s": 5075, "text": "Java SE is freely available from the link www.oracle.com/technetwork/java/archive-139210.html So, you download a version based on your operating system." }, { "code": null, "e": 5456, "s": 5228, "text": "Follow the instructions to download Java and run the .exe to install Java on your machine. Once, you have installed Java on your machine, you would need to set environment variables to point to correct installation directories." }, { "code": null, "e": 5540, "s": 5456, "text": "We are assuming that you have installed Java in c:\\Program Files\\java\\jdk directory" }, { "code": null, "e": 5594, "s": 5540, "text": "Right-click on 'My Computer' and select 'Properties'." }, { "code": null, "e": 5648, "s": 5594, "text": "Right-click on 'My Computer' and select 'Properties'." }, { "code": null, "e": 5718, "s": 5648, "text": "Click on the 'Environment variables' button under the 'Advanced' tab." }, { "code": null, "e": 5788, "s": 5718, "text": "Click on the 'Environment variables' button under the 'Advanced' tab." }, { "code": null, "e": 6024, "s": 5788, "text": "Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\\WINDOWS\\SYSTEM32', then change your path to read 'C:\\WINDOWS\\SYSTEM32;c:\\Program Files\\java\\jdk\\bin'." }, { "code": null, "e": 6260, "s": 6024, "text": "Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\\WINDOWS\\SYSTEM32', then change your path to read 'C:\\WINDOWS\\SYSTEM32;c:\\Program Files\\java\\jdk\\bin'." }, { "code": null, "e": 6345, "s": 6260, "text": "We are assuming that you have installed Java in c:\\Program Files\\java\\jdk directory." }, { "code": null, "e": 6466, "s": 6345, "text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end − 'SET PATH=%PATH%;C:\\Program Files\\java\\jdk\\bin'." }, { "code": null, "e": 6587, "s": 6466, "text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end − 'SET PATH=%PATH%;C:\\Program Files\\java\\jdk\\bin'." }, { "code": null, "e": 6752, "s": 6587, "text": "Environment variable PATH should be set to point to where, the Java binaries have been installed. Refer to your shell documentation, if you have trouble doing this." }, { "code": null, "e": 6892, "s": 6752, "text": "Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH'" }, { "code": null, "e": 7057, "s": 6892, "text": "To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following −" }, { "code": null, "e": 7177, "s": 7057, "text": "Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad." }, { "code": null, "e": 7297, "s": 7177, "text": "Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad." }, { "code": null, "e": 7413, "s": 7297, "text": "Netbeans − It is a Java IDE that is open-source and free, which can be downloaded from www.netbeans.org/index.html." }, { "code": null, "e": 7529, "s": 7413, "text": "Netbeans − It is a Java IDE that is open-source and free, which can be downloaded from www.netbeans.org/index.html." }, { "code": null, "e": 7652, "s": 7529, "text": "Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org." }, { "code": null, "e": 7775, "s": 7652, "text": "Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org." }, { "code": null, "e": 8008, "s": 7775, "text": "Download the latest version of Apache Common Collections jar file from commons-collections4-4.1-bin.zip. At the time of writing this tutorial, we have downloaded commons-collections4-4.1-bin.zip and copied it into C:\\>Apache folder." }, { "code": null, "e": 8251, "s": 8008, "text": "Set the APACHE_HOME environment variable to point to the base directory location where Apache jar is stored on your machine. Assuming, we've extracted commons-collections4-4.1-bin.zip in Apache folder on various Operating Systems as follows −" }, { "code": null, "e": 8457, "s": 8251, "text": "Set the CLASSPATH environment variable to point to the Common Collections jar location. Assuming, you have stored commons-collections4-4.1-bin.zip in Apache folder on various Operating Systems as follows −" }, { "code": null, "e": 8720, "s": 8457, "text": "New Interfaces are added to supports bags. A Bag defines a collection which, counts the number of times an object appears in the collection. For example, if a Bag contains {a, a, b, c} then getCount(\"a\") will return 2 while uniqueSet() returns the unique values." }, { "code": null, "e": 8804, "s": 8720, "text": "Following is the declaration for org.apache.commons.collections4.Bag<E> interface −" }, { "code": null, "e": 8853, "s": 8804, "text": "public interface Bag<E>\n extends Collection<E>" }, { "code": null, "e": 8900, "s": 8853, "text": "The methods for bag inference are as follows −" }, { "code": null, "e": 8922, "s": 8900, "text": "boolean add(E object)" }, { "code": null, "e": 8984, "s": 8922, "text": "(Violation) Adds one copy of the specified object to the Bag." }, { "code": null, "e": 9019, "s": 8984, "text": "boolean add(E object, int nCopies)" }, { "code": null, "e": 9075, "s": 9019, "text": "Adds nCopies copies of the specified object to the Bag." }, { "code": null, "e": 9115, "s": 9075, "text": "boolean containsAll(Collection<?> coll)" }, { "code": null, "e": 9222, "s": 9115, "text": "(Violation) Returns true if the bag contains all elements in the given collection, respecting cardinality." }, { "code": null, "e": 9250, "s": 9222, "text": "int getCount(Object object)" }, { "code": null, "e": 9340, "s": 9250, "text": "Returns the number of occurrences (cardinality) of the given object currently in the bag." }, { "code": null, "e": 9363, "s": 9340, "text": "Iterator<E> iterator()" }, { "code": null, "e": 9452, "s": 9363, "text": "Returns an Iterator over the entire set of members, including copies due to cardinality." }, { "code": null, "e": 9482, "s": 9452, "text": "boolean remove(Object object)" }, { "code": null, "e": 9552, "s": 9482, "text": "(Violation) Removes all occurrences of the given object from the bag." }, { "code": null, "e": 9595, "s": 9552, "text": "boolean remove(Object object, int nCopies)" }, { "code": null, "e": 9656, "s": 9595, "text": "Removes nCopies copies of the specified object from the Bag." }, { "code": null, "e": 9694, "s": 9656, "text": "boolean removeAll(Collection<?> coll)" }, { "code": null, "e": 9787, "s": 9694, "text": "(Violation) Remove all elements represented in the given collection, respecting cardinality." }, { "code": null, "e": 9825, "s": 9787, "text": "boolean retainAll(Collection<?> coll)" }, { "code": null, "e": 9929, "s": 9825, "text": "(Violation) Remove any members of the bag that are not in the given collection, respecting cardinality." }, { "code": null, "e": 9940, "s": 9929, "text": "int size()" }, { "code": null, "e": 10003, "s": 9940, "text": "Returns the total number of items in the bag across all types." }, { "code": null, "e": 10022, "s": 10003, "text": "Set<E> uniqueSet()" }, { "code": null, "e": 10067, "s": 10022, "text": "Returns a Set of unique elements in the Bag." }, { "code": null, "e": 10130, "s": 10067, "text": "This interface inherits methods from the following interface −" }, { "code": null, "e": 10151, "s": 10130, "text": "java.util.Collectio." }, { "code": null, "e": 10196, "s": 10151, "text": "An example of BagTester.java is as follows −" }, { "code": null, "e": 11276, "s": 10196, "text": "import org.apache.commons.collections4.Bag;\nimport org.apache.commons.collections4.bag.HashBag;\n\npublic class BagTester {\n public static void main(String[] args) {\n Bag<String> bag = new HashBag<>();\n //add \"a\" two times to the bag.\n bag.add(\"a\" , 2);\n \n //add \"b\" one time to the bag.\n bag.add(\"b\");\n \n //add \"c\" one time to the bag.\n bag.add(\"c\");\n \n //add \"d\" three times to the bag.\n bag.add(\"d\",3\n \n //get the count of \"d\" present in bag.\n System.out.println(\"d is present \" + bag.getCount(\"d\") + \" times.\");\n System.out.println(\"bag: \" +bag);\n \n //get the set of unique values from the bag\n System.out.println(\"Unique Set: \" +bag.uniqueSet());\n \n //remove 2 occurrences of \"d\" from the bag\n bag.remove(\"d\",2);\n System.out.println(\"2 occurences of d removed from bag: \" +bag);\n System.out.println(\"d is present \" + bag.getCount(\"d\") + \" times.\");\n System.out.println(\"bag: \" +bag);\n System.out.println(\"Unique Set: \" +bag.uniqueSet());\n }\n}" }, { "code": null, "e": 11312, "s": 11276, "text": "You will see the following output −" }, { "code": null, "e": 11507, "s": 11312, "text": "d is present 3 times.\nbag: [2:a,1:b,1:c,3:d]\nUnique Set: [a, b, c, d]\n2 occurences of d removed from bag: [2:a,1:b,1:c,1:d]\nd is present 1 times.\nbag: [2:a,1:b,1:c,1:d]\nUnique Set: [a, b, c, d]\n" }, { "code": null, "e": 11662, "s": 11507, "text": "New Interfaces are added to supports bidirectional Map. Using bidirectional map, a key can be lookup using value and value can be lookup using key easily." }, { "code": null, "e": 11752, "s": 11662, "text": "Following is the declaration for org.apache.commons.collections4.BidiMap<K,V> interface −" }, { "code": null, "e": 11810, "s": 11752, "text": "public interface BidiMap<K,V>\n extends IterableMap<K,V>" }, { "code": null, "e": 11865, "s": 11810, "text": "The methods for the BidiMap Interface are as follows −" }, { "code": null, "e": 11888, "s": 11865, "text": "K getKey(Object value)" }, { "code": null, "e": 11950, "s": 11888, "text": "Gets the key that is currently mapped to the specified value." }, { "code": null, "e": 11980, "s": 11950, "text": "BidiMap<V,K> inverseBidiMap()" }, { "code": null, "e": 12044, "s": 11980, "text": "Gets a view of this map where the keys and values are reversed." }, { "code": null, "e": 12066, "s": 12044, "text": "V put(K key, V value)" }, { "code": null, "e": 12133, "s": 12066, "text": "Puts the key-value pair into the map, replacing any previous pair." }, { "code": null, "e": 12161, "s": 12133, "text": "K removeValue(Object value)" }, { "code": null, "e": 12258, "s": 12161, "text": "Removes the key-value pair that is currently mapped to the specified value (optional operation)." }, { "code": null, "e": 12274, "s": 12258, "text": "Set<V> values()" }, { "code": null, "e": 12330, "s": 12274, "text": "Returns a Set view of the values contained in this map." }, { "code": null, "e": 12394, "s": 12330, "text": "This interface inherits methods from the following interfaces −" }, { "code": null, "e": 12430, "s": 12394, "text": "org.apache.commons.collections4.Ge." }, { "code": null, "e": 12466, "s": 12430, "text": "org.apache.commons.collections4.Ge." }, { "code": null, "e": 12510, "s": 12466, "text": "org.apache.commons.collections4.IterableGe." }, { "code": null, "e": 12554, "s": 12510, "text": "org.apache.commons.collections4.IterableGe." }, { "code": null, "e": 12590, "s": 12554, "text": "org.apache.commons.collections4.Pu." }, { "code": null, "e": 12626, "s": 12590, "text": "org.apache.commons.collections4.Pu." }, { "code": null, "e": 12640, "s": 12626, "text": "java.util.Ma." }, { "code": null, "e": 12654, "s": 12640, "text": "java.util.Ma." }, { "code": null, "e": 12703, "s": 12654, "text": "An example of BidiMapTester.java is as follows −" }, { "code": null, "e": 13394, "s": 12703, "text": "import org.apache.commons.collections4.BidiMap;\nimport org.apache.commons.collections4.bidimap.TreeBidiMap;\n\npublic class BidiMapTester {\n public static void main(String[] args) {\n BidiMap>String, String< bidi = new TreeBidiMap<>();\n \n bidi.put(\"One\", \"1\");\n bidi.put(\"Two\", \"2\");\n bidi.put(\"Three\", \"3\");\n\n System.out.println(bidi.get(\"One\"));\n System.out.println(bidi.getKey(\"1\"));\n System.out.println(\"Original Map: \" + bidi);\n \n bidi.removeValue(\"1\");\n System.out.println(\"Modified Map: \" + bidi);\n BidiMap<String, String> inversedMap = bidi.inverseBidiMap();\n System.out.println(\"Inversed Map: \" + inversedMap);\n }\n}" }, { "code": null, "e": 13453, "s": 13394, "text": "When you run the code, you will see the following output −" }, { "code": null, "e": 13560, "s": 13453, "text": "1\nOne\nOriginal Map: {One=1, Three=3, Two=2}\nModified Map: {Three=3, Two=2}\nInversed Map: {2=Two, 3=Three}\n" }, { "code": null, "e": 13765, "s": 13560, "text": "The JDK Map interface is pretty difficult to iterate as Iteration to be done on EntrySet or over the KeySet objects. MapIterator provides simple iteration over Map. Following example illustrates the same." }, { "code": null, "e": 13819, "s": 13765, "text": "An example for MapIteratorTester.java is as follows −" }, { "code": null, "e": 14634, "s": 13819, "text": "import org.apache.commons.collections4.IterableMap;\nimport org.apache.commons.collections4.MapIterator;\nimport org.apache.commons.collections4.map.HashedMap;\n\npublic class MapIteratorTester {\n public static void main(String[] args) {\n IterableMap<String, String> map = new HashedMap<>();\n \n map.put(\"1\", \"One\");\n map.put(\"2\", \"Two\");\n map.put(\"3\", \"Three\");\n map.put(\"4\", \"Four\");\n map.put(\"5\", \"Five\");\n\n MapIterator<String, String> iterator = map.mapIterator();\n while (iterator.hasNext()) {\n Object key = iterator.next();\n Object value = iterator.getValue();\n\n System.out.println(\"key: \" + key);\n System.out.println(\"Value: \" + value);\n \n iterator.setValue(value + \"_\");\n }\n System.out.println(map);\n }\n}" }, { "code": null, "e": 14663, "s": 14634, "text": "The output is stated below −" }, { "code": null, "e": 14803, "s": 14663, "text": "key: 3\nValue: Three\nkey: 5\nValue: Five\nkey: 2\nValue: Two\nkey: 4\nValue: Four\nkey: 1\nValue: One\n{3=Three_, 5=Five_, 2=Two_, 4=Four_, 1=One_}\n" }, { "code": null, "e": 15120, "s": 14803, "text": "OrderedMap is a new interface for maps to retain the order in which elements are added. LinkedMap and ListOrderedMap are two available implementations. This interfaces supports iterator that of Map and allows iteration in both directions either forwards or backwards in a Map. Following example illustrates the same." }, { "code": null, "e": 15176, "s": 15120, "text": "An example of OrderedMapTester.java is as given below −" }, { "code": null, "e": 15661, "s": 15176, "text": "import org.apache.commons.collections4.OrderedMap;\nimport org.apache.commons.collections4.map.LinkedMap;\n\npublic class OrderedMapTester {\n public static void main(String[] args) {\n OrderedMap<String, String> map = new LinkedMap<String, String>();\n map.put(\"One\", \"1\");\n map.put(\"Two\", \"2\");\n map.put(\"Three\", \"3\");\n \n System.out.println(map.firstKey());\n System.out.println(map.nextKey(\"One\"));\n System.out.println(map.nextKey(\"Two\"));\n }\n}" }, { "code": null, "e": 15693, "s": 15661, "text": "The result will be as follows −" }, { "code": null, "e": 15708, "s": 15693, "text": "One\nTwo\nThree\n" }, { "code": null, "e": 16009, "s": 15708, "text": "CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API." }, { "code": null, "e": 16136, "s": 16009, "text": "addIgnoreNull() method of CollectionUtils can be used to ensure that only non-null values are getting added to the collection." }, { "code": null, "e": 16169, "s": 16136, "text": "Following is the declaration for" }, { "code": null, "e": 16242, "s": 16169, "text": "org.apache.commons.collections4.CollectionUtils.addIgnoreNull() method −" }, { "code": null, "e": 16319, "s": 16242, "text": "public static <T> boolean addIgnoreNull(Collection<T> collection, T object)\n" }, { "code": null, "e": 16376, "s": 16319, "text": "collection − The collection to add to, must not be null." }, { "code": null, "e": 16433, "s": 16376, "text": "collection − The collection to add to, must not be null." }, { "code": null, "e": 16491, "s": 16433, "text": "object − The object to add, if null it will not be added." }, { "code": null, "e": 16549, "s": 16491, "text": "object − The object to add, if null it will not be added." }, { "code": null, "e": 16581, "s": 16549, "text": "True if the collection changed." }, { "code": null, "e": 16631, "s": 16581, "text": "NullPointerException − If the collection is null." }, { "code": null, "e": 16681, "s": 16631, "text": "NullPointerException − If the collection is null." }, { "code": null, "e": 16857, "s": 16681, "text": "The following example shows the usage of org.apache.commons.collections4.CollectionUtils.addIgnoreNull() method. We are trying to add a null value and a sample non-null value." }, { "code": null, "e": 17404, "s": 16857, "text": "import java.util.LinkedList;\nimport java.util.List;\nimport org.apache.commons.collections4.CollectionUtils;\n\npublic class CollectionUtilsTester {\n public static void main(String[] args) {\n List<String> list = new LinkedList<String>();\n CollectionUtils.addIgnoreNull(list, null);\n CollectionUtils.addIgnoreNull(list, \"a\");\n\n System.out.println(list);\n\n if(list.contains(null)) {\n System.out.println(\"Null value is present\");\n } else {\n System.out.println(\"Null value is not present\");\n }\n }\n}" }, { "code": null, "e": 17436, "s": 17404, "text": "The output is mentioned below −" }, { "code": null, "e": 17467, "s": 17436, "text": "[a]\nNull value is not present\n" }, { "code": null, "e": 17768, "s": 17467, "text": "CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API." }, { "code": null, "e": 17851, "s": 17768, "text": "collate() method of CollectionUtils can be used to merge two already sorted lists." }, { "code": null, "e": 17884, "s": 17851, "text": "Following is the declaration for" }, { "code": null, "e": 17951, "s": 17884, "text": "org.apache.commons.collections4.CollectionUtils.collate() method −" }, { "code": null, "e": 18069, "s": 17951, "text": "public static <O extends Comparable<? super O>> List<O>\n collate(Iterable<? extends O> a, Iterable<? extends O> b)\n" }, { "code": null, "e": 18113, "s": 18069, "text": "a − The first collection, must not be null." }, { "code": null, "e": 18157, "s": 18113, "text": "a − The first collection, must not be null." }, { "code": null, "e": 18202, "s": 18157, "text": "b − The second collection, must not be null." }, { "code": null, "e": 18247, "s": 18202, "text": "b − The second collection, must not be null." }, { "code": null, "e": 18313, "s": 18247, "text": "A new sorted List, containing the elements of Collection a and b." }, { "code": null, "e": 18366, "s": 18313, "text": "NullPointerException − If either collection is null." }, { "code": null, "e": 18419, "s": 18366, "text": "NullPointerException − If either collection is null." }, { "code": null, "e": 18598, "s": 18419, "text": "The following example shows the usage of org.apache.commons.collections4.CollectionUtils.collate() method. We'll merge two sorted lists and then print the merged and sorted list." }, { "code": null, "e": 19079, "s": 18598, "text": "import java.util.Arrays;\nimport java.util.List;\nimport org.apache.commons.collections4.CollectionUtils;\n\npublic class CollectionUtilsTester { 8. Apache Commons Collections — Merge & Sort\n public static void main(String[] args) {\n List<String> sortedList1 = Arrays.asList(\"A\",\"C\",\"E\");\n List<String> sortedList2 = Arrays.asList(\"B\",\"D\",\"F\");\n List<String> mergedList = CollectionUtils.collate(sortedList1, sortedList2);\n System.out.println(mergedList);\n }\n}" }, { "code": null, "e": 19106, "s": 19079, "text": "The output is as follows −" }, { "code": null, "e": 19126, "s": 19106, "text": "[A, B, C, D, E, F]\n" }, { "code": null, "e": 19427, "s": 19126, "text": "CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API." }, { "code": null, "e": 19556, "s": 19427, "text": "collect() method of CollectionUtils can be used to transform a list of one type of objects to list of different type of objects." }, { "code": null, "e": 19589, "s": 19556, "text": "Following is the declaration for" }, { "code": null, "e": 19656, "s": 19589, "text": "org.apache.commons.collections4.CollectionUtils.collect() method −" }, { "code": null, "e": 19776, "s": 19656, "text": "public static <I,O> Collection<O> collect(Iterable<I> inputCollection, Transformer<? super I,? extends O> transformer)\n" }, { "code": null, "e": 19849, "s": 19776, "text": "inputCollection − The collection to get the input from, may not be null." }, { "code": null, "e": 19922, "s": 19849, "text": "inputCollection − The collection to get the input from, may not be null." }, { "code": null, "e": 19973, "s": 19922, "text": "Transformer − The transformer to use, may be null." }, { "code": null, "e": 20024, "s": 19973, "text": "Transformer − The transformer to use, may be null." }, { "code": null, "e": 20059, "s": 20024, "text": "The transformed result (new list)." }, { "code": null, "e": 20115, "s": 20059, "text": "NullPointerException − If the input collection is null." }, { "code": null, "e": 20171, "s": 20115, "text": "NullPointerException − If the input collection is null." }, { "code": null, "e": 20372, "s": 20171, "text": "The following example shows the usage of org.apache.commons.collections4.CollectionUtils.collect() method. We'll transform a list of string to list of integer by parsing the integer value from String." }, { "code": null, "e": 20989, "s": 20372, "text": "import java.util.Arrays;\nimport java.util.List;\nimport org.apache.commons.collections4.CollectionUtils;\nimport org.apache.commons.collections4.Transformer;\n\npublic class CollectionUtilsTester {\n public static void main(String[] args) {\n List<String> stringList = Arrays.asList(\"1\",\"2\",\"3\");\n List<Integer> integerList = (List<Integer>) CollectionUtils.collect(stringList,\n new Transformer<String, Integer>() {\n \n @Override\n public Integer transform(String input) {\n return Integer.parseInt(input);\n }\n });\n System.out.println(integerList);\n }\n}" }, { "code": null, "e": 21046, "s": 20989, "text": "When you use the code, you will get the following code −" }, { "code": null, "e": 21057, "s": 21046, "text": "[1, 2, 3]\n" }, { "code": null, "e": 21358, "s": 21057, "text": "CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API." }, { "code": null, "e": 21501, "s": 21358, "text": "filter() method of CollectionUtils can be used to filter a list to remove objects which do not satisfy condition provided by predicate passed." }, { "code": null, "e": 21534, "s": 21501, "text": "Following is the declaration for" }, { "code": null, "e": 21600, "s": 21534, "text": "org.apache.commons.collections4.CollectionUtils.filter() method −" }, { "code": null, "e": 21692, "s": 21600, "text": "public static <T> boolean filter(Iterable<T> collection,\n Predicate<? super T> predicate)" }, { "code": null, "e": 21760, "s": 21692, "text": "collection − The collection to get the input from, may not be null." }, { "code": null, "e": 21828, "s": 21760, "text": "collection − The collection to get the input from, may not be null." }, { "code": null, "e": 21887, "s": 21828, "text": "predicate − The predicate to use as a filter, may be null." }, { "code": null, "e": 21946, "s": 21887, "text": "predicate − The predicate to use as a filter, may be null." }, { "code": null, "e": 22012, "s": 21946, "text": "True if the collection is modified by this call, false otherwise." }, { "code": null, "e": 22175, "s": 22012, "text": "The following example shows the usage of org.apache.commons.collections4.CollectionUtils.filter() method. We'll filter a list of integer to get even numbers only." }, { "code": null, "e": 22970, "s": 22175, "text": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport org.apache.commons.collections4.CollectionUtils;\nimport org.apache.commons.collections4.Predicate;\n\npublic class CollectionUtilsTester {\n public static void main(String[] args) {\n List<Integer> integerList = new ArrayList<Integer>(); \n integerList.addAll(Arrays.asList(1,2,3,4,5,6,7,8));\n System.out.println(\"Original List: \" + integerList);\n CollectionUtils.filter(integerList, new Predicate<Integer>() {\n @Override\n public boolean evaluate(Integer input) {\n if(input.intValue() % 2 == 0) {\n return true;\n }\n return false;\n }\n });\n System.out.println(\"Filtered List (Even numbers): \" + integerList);\n }\n}" }, { "code": null, "e": 23009, "s": 22970, "text": "It will produce the following result −" }, { "code": null, "e": 23093, "s": 23009, "text": "Original List: [1, 2, 3, 4, 5, 6, 7, 8]\nFiltered List (Even numbers): [2, 4, 6, 8]\n" }, { "code": null, "e": 23237, "s": 23093, "text": "filterInverse() method of CollectionUtils can be used to filter a list to remove objects, which satisfy condition provided by predicate passed." }, { "code": null, "e": 23270, "s": 23237, "text": "Following is the declaration for" }, { "code": null, "e": 23343, "s": 23270, "text": "org.apache.commons.collections4.CollectionUtils.filterInverse() method −" }, { "code": null, "e": 23439, "s": 23343, "text": "public static <T> boolean filterInverse(Iterable<T> collection, Predicate<? super T> predicate)" }, { "code": null, "e": 23507, "s": 23439, "text": "collection − The collection to get the input from, may not be null." }, { "code": null, "e": 23575, "s": 23507, "text": "collection − The collection to get the input from, may not be null." }, { "code": null, "e": 23634, "s": 23575, "text": "predicate − The predicate to use as a filter, may be null." }, { "code": null, "e": 23693, "s": 23634, "text": "predicate − The predicate to use as a filter, may be null." }, { "code": null, "e": 23759, "s": 23693, "text": "True if the collection is modified by this call, false otherwise." }, { "code": null, "e": 23928, "s": 23759, "text": "The following example shows the usage of org.apache.commons.collections4.CollectionUtils.filterInverse() method. We'll filter a list of integer to get odd numbers only." }, { "code": null, "e": 24730, "s": 23928, "text": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport org.apache.commons.collections4.CollectionUtils;\nimport org.apache.commons.collections4.Predicate;\n\npublic class CollectionUtilsTester {\n public static void main(String[] args) {\n List<Integer> integerList = new ArrayList<Integer>(); \n integerList.addAll(Arrays.asList(1,2,3,4,5,6,7,8));\n System.out.println(\"Original List: \" + integerList); \n CollectionUtils.filterInverse(integerList, new Predicate<Integer>() {\n @Override\n public boolean evaluate(Integer input) {\n if(input.intValue() % 2 == 0) {\n return true;\n }\n return false;\n }\n });\n System.out.println(\"Filtered List (Odd numbers): \" + integerList);\n }\n}" }, { "code": null, "e": 24762, "s": 24730, "text": "The result is as stated below −" }, { "code": null, "e": 24845, "s": 24762, "text": "Original List: [1, 2, 3, 4, 5, 6, 7, 8]\nFiltered List (Odd numbers): [1, 3, 5, 7]\n" }, { "code": null, "e": 25146, "s": 24845, "text": "CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API." }, { "code": null, "e": 25355, "s": 25146, "text": "isNotEmpty() method of CollectionUtils can be used to check if a list is not empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list." }, { "code": null, "e": 25388, "s": 25355, "text": "Following is the declaration for" }, { "code": null, "e": 25458, "s": 25388, "text": "org.apache.commons.collections4.CollectionUtils.isNotEmpty() method −" }, { "code": null, "e": 25512, "s": 25458, "text": "public static boolean isNotEmpty(Collection<?> coll)\n" }, { "code": null, "e": 25557, "s": 25512, "text": "coll − The collection to check, may be null." }, { "code": null, "e": 25602, "s": 25557, "text": "coll − The collection to check, may be null." }, { "code": null, "e": 25634, "s": 25602, "text": "True if non-null and non-empty." }, { "code": null, "e": 25780, "s": 25634, "text": "The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isNotEmpty() method. We'll check a list is empty or not." }, { "code": null, "e": 26407, "s": 25780, "text": "import java.util.List;\nimport org.apache.commons.collections4.CollectionUtils;\n\npublic class CollectionUtilsTester {\n public static void main(String[] args) {\n List<String> list = getList();\n System.out.println(\"Non-Empty List Check: \" + checkNotEmpty1(list));\n System.out.println(\"Non-Empty List Check: \" + checkNotEmpty1(list));\n }\n static List<String> getList() {\n return null;\n }\n static boolean checkNotEmpty1(List<String> list) {\n return !(list == null || list.isEmpty());\n }\n static boolean checkNotEmpty2(List<String> list) {\n return CollectionUtils.isNotEmpty(list);\n }\n}" }, { "code": null, "e": 26435, "s": 26407, "text": "The output is given below −" }, { "code": null, "e": 26492, "s": 26435, "text": "Non-Empty List Check: false\nNon-Empty List Check: false\n" }, { "code": null, "e": 26694, "s": 26492, "text": "isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list." }, { "code": null, "e": 26727, "s": 26694, "text": "Following is the declaration for" }, { "code": null, "e": 26794, "s": 26727, "text": "org.apache.commons.collections4.CollectionUtils.isEmpty() method −" }, { "code": null, "e": 26845, "s": 26794, "text": "public static boolean isEmpty(Collection<?> coll)\n" }, { "code": null, "e": 26890, "s": 26845, "text": "coll − The collection to check, may be null." }, { "code": null, "e": 26935, "s": 26890, "text": "coll − The collection to check, may be null." }, { "code": null, "e": 26958, "s": 26935, "text": "True if empty or null." }, { "code": null, "e": 27101, "s": 26958, "text": "The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isEmpty() method. We'll check a list is empty or not." }, { "code": null, "e": 27704, "s": 27101, "text": "import java.util.List;\nimport org.apache.commons.collections4.CollectionUtils;\n\npublic class CollectionUtilsTester {\n public static void main(String[] args) {\n List<String> list = getList();\n System.out.println(\"Empty List Check: \" + checkEmpty1(list));\n System.out.println(\"Empty List Check: \" + checkEmpty1(list));\n }\n static List<String> getList() {\n return null;\n }\n static boolean checkEmpty1(List<String> list) {\n return (list == null || list.isEmpty());\n }\n static boolean checkEmpty2(List<String> list) {\n return CollectionUtils.isEmpty(list);\n }\n}" }, { "code": null, "e": 27744, "s": 27704, "text": "Given below is the output of the code −" }, { "code": null, "e": 27791, "s": 27744, "text": "Empty List Check: true\nEmpty List Check: true\n" }, { "code": null, "e": 28092, "s": 27791, "text": "CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API." }, { "code": null, "e": 28211, "s": 28092, "text": "isSubCollection() method of CollectionUtils can be used to check if a collection contains the given collection or not." }, { "code": null, "e": 28244, "s": 28211, "text": "Following is the declaration for" }, { "code": null, "e": 28319, "s": 28244, "text": "org.apache.commons.collections4.CollectionUtils.isSubCollection() method −" }, { "code": null, "e": 28392, "s": 28319, "text": "public static boolean isSubCollection(Collection<?> a, Collection<?> b)\n" }, { "code": null, "e": 28442, "s": 28392, "text": "a − The first (sub) collection, must not be null." }, { "code": null, "e": 28492, "s": 28442, "text": "a − The first (sub) collection, must not be null." }, { "code": null, "e": 28545, "s": 28492, "text": "b − The second (super) collection, must not be null." }, { "code": null, "e": 28598, "s": 28545, "text": "b − The second (super) collection, must not be null." }, { "code": null, "e": 28646, "s": 28598, "text": "True if and only if a is a sub-collection of b." }, { "code": null, "e": 28812, "s": 28646, "text": "The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isSubCollection() method. We'll check a list is part of another list or not." }, { "code": null, "e": 29359, "s": 28812, "text": "import java.util.Arrays;\nimport java.util.List;\nimport org.apache.commons.collections4.CollectionUtils;\n\npublic class CollectionUtilsTester {\n public static void main(String[] args) {\n //checking inclusion\n List<String> list1 = Arrays.asList(\"A\",\"A\",\"A\",\"C\",\"B\",\"B\");\n List<String> list2 = Arrays.asList(\"A\",\"A\",\"B\",\"B\");\n System.out.println(\"List 1: \" + list1);\n System.out.println(\"List 2: \" + list2);\n System.out.println(\"Is List 2 contained in List 1: \" + CollectionUtils.isSubCollection(list2, list1));\n }\n}" }, { "code": null, "e": 29399, "s": 29359, "text": "You will receive the following output −" }, { "code": null, "e": 29484, "s": 29399, "text": "List 1: [A, A, A, C, B, B]\nList 2: [A, A, B, B]\nIs List 2 contained in List 1: true\n" }, { "code": null, "e": 29785, "s": 29484, "text": "CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API." }, { "code": null, "e": 29903, "s": 29785, "text": "intersection() method of CollectionUtils can be used to get the common objects between two collections(intersection)." }, { "code": null, "e": 30008, "s": 29903, "text": "Following is the declaration for org.apache.commons.collections4.CollectionUtils.intersection() method −" }, { "code": null, "e": 30104, "s": 30008, "text": "public static <O> Collection<O> intersection(Iterable<? extends O> a, Iterable<? extends O> b)\n" }, { "code": null, "e": 30154, "s": 30104, "text": "a − The first (sub) collection, must not be null." }, { "code": null, "e": 30204, "s": 30154, "text": "a − The first (sub) collection, must not be null." }, { "code": null, "e": 30257, "s": 30204, "text": "b − The second (super) collection, must not be null." }, { "code": null, "e": 30310, "s": 30257, "text": "b − The second (super) collection, must not be null." }, { "code": null, "e": 30351, "s": 30310, "text": "The intersection of the two collections." }, { "code": null, "e": 30504, "s": 30351, "text": "The following example shows the usage of org.apache.commons.collections4.CollectionUtils.intersection() method. We'll get the intersection of two lists." }, { "code": null, "e": 31055, "s": 30504, "text": "import java.util.Arrays;\nimport java.util.List;\nimport org.apache.commons.collections4.CollectionUtils;\n\npublic class CollectionUtilsTester {\n public static void main(String[] args) {\n //checking inclusion\n List<String> list1 = Arrays.asList(\"A\",\"A\",\"A\",\"C\",\"B\",\"B\");\n List<String> list2 = Arrays.asList(\"A\",\"A\",\"B\",\"B\");\n System.out.println(\"List 1: \" + list1);\n System.out.println(\"List 2: \" + list2);\n System.out.println(\"Commons Objects of List 1 and List 2: \" + CollectionUtils.intersection(list1, list2));\n }\n}" }, { "code": null, "e": 31114, "s": 31055, "text": "When you run the code, you will see the following output −" }, { "code": null, "e": 31214, "s": 31114, "text": "List 1: [A, A, A, C, B, B]\nList 2: [A, A, B, B]\nCommons Objects of List 1 and List 2: [A, A, B, B]\n" }, { "code": null, "e": 31515, "s": 31214, "text": "CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API." }, { "code": null, "e": 31643, "s": 31515, "text": "subtract() method of CollectionUtils can be used to get the new collection by subtracting objects of one collection from other." }, { "code": null, "e": 31744, "s": 31643, "text": "Following is the declaration for org.apache.commons.collections4.CollectionUtils.subtract() method −" }, { "code": null, "e": 31836, "s": 31744, "text": "public static <O> Collection<O> subtract(Iterable<? extends O> a, Iterable<? extends O> b)\n" }, { "code": null, "e": 31891, "s": 31836, "text": "a − The collection to subtract from, must not be null." }, { "code": null, "e": 31946, "s": 31891, "text": "a − The collection to subtract from, must not be null." }, { "code": null, "e": 31996, "s": 31946, "text": "b − The collection to subtract, must not be null." }, { "code": null, "e": 32046, "s": 31996, "text": "b − The collection to subtract, must not be null." }, { "code": null, "e": 32081, "s": 32046, "text": "A new collection with the results." }, { "code": null, "e": 32229, "s": 32081, "text": "The following example shows the usage of org.apache.commons.collections4.CollectionUtils.subtract() method. We'll get the subtraction of two lists." }, { "code": null, "e": 32755, "s": 32229, "text": "import java.util.Arrays;\nimport java.util.List;\nimport org.apache.commons.collections4.CollectionUtils;\n\npublic class CollectionUtilsTester {\n public static void main(String[] args) {\n //checking inclusion\n List<String> list1 = Arrays.asList(\"A\",\"A\",\"A\",\"C\",\"B\",\"B\");\n List<String> list2 = Arrays.asList(\"A\",\"A\",\"B\",\"B\");\n\n System.out.println(\"List 1: \" + list1);\n System.out.println(\"List 2: \" + list2);\n System.out.println(\"List 1 - List 2: \"+ CollectionUtils.subtract(list1, list2));\n }\n}" }, { "code": null, "e": 32826, "s": 32755, "text": "When you execute the above code, you should see the following output −" }, { "code": null, "e": 32899, "s": 32826, "text": "List 1: [A, A, A, C, B, B]\nList 2: [A, A, B, B]\nList 1 - List 2: [A, C]\n" }, { "code": null, "e": 33200, "s": 32899, "text": "CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API." }, { "code": null, "e": 33283, "s": 33200, "text": "union() method of CollectionUtils can be used to get the union of two collections." }, { "code": null, "e": 33381, "s": 33283, "text": "Following is the declaration for org.apache.commons.collections4.CollectionUtils.union() method −" }, { "code": null, "e": 33470, "s": 33381, "text": "public static <O> Collection<O> union(Iterable<? extends O> a, Iterable<? extends O> b)\n" }, { "code": null, "e": 33514, "s": 33470, "text": "a − The first collection, must not be null." }, { "code": null, "e": 33558, "s": 33514, "text": "a − The first collection, must not be null." }, { "code": null, "e": 33603, "s": 33558, "text": "b − The second collection, must not be null." }, { "code": null, "e": 33648, "s": 33603, "text": "b − The second collection, must not be null." }, { "code": null, "e": 33682, "s": 33648, "text": "The union of the two collections." }, { "code": null, "e": 33821, "s": 33682, "text": "The following example shows the usage of org.apache.commons.collections4.CollectionUtils.union() method. We'll get the union of two lists." }, { "code": null, "e": 34361, "s": 33821, "text": "import java.util.Arrays;\nimport java.util.List;\nimport org.apache.commons.collections4.CollectionUtils;\n\npublic class CollectionUtilsTester {\n public static void main(String[] args) {\n //checking inclusion\n List<String> list1 = Arrays.asList(\"A\",\"A\",\"A\",\"C\",\"B\",\"B\");\n List<String> list2 = Arrays.asList(\"A\",\"A\",\"B\",\"B\");\n \n System.out.println(\"List 1: \" + list1);\n System.out.println(\"List 2: \" + list2);\n System.out.println(\"Union of List 1 and List 2: \"+ CollectionUtils.union(list1, list2));\n }\n}" }, { "code": null, "e": 34398, "s": 34361, "text": "This produces the following output −" }, { "code": null, "e": 34494, "s": 34398, "text": "List 1: [A, A, A, C, B, B]\nList 2: [A, A, B, B]\nUnion of List 1 and List 2: [A, A, A, B, B, C]\n" }, { "code": null, "e": 34501, "s": 34494, "text": " Print" }, { "code": null, "e": 34512, "s": 34501, "text": " Add Notes" } ]
How to add display:none in an HTML element using jQuery?
To workaround with display: none in an element in jQuery, use the hide() method. It will do the same work. You can try to run the following code to learn how to add display:none in an HTML element − Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").removeAttr("style").hide(); }); }); </script> </head> <body> <h1>Heading 1</h1> <p style="font-size:15px">This is demo text. This will hide on button click.</p> <p>This is another text. This will hide on button click</p> <button>Hide</button> </body> </html>
[ { "code": null, "e": 1169, "s": 1062, "text": "To workaround with display: none in an element in jQuery, use the hide() method. It will do the same work." }, { "code": null, "e": 1261, "s": 1169, "text": "You can try to run the following code to learn how to add display:none in an HTML element −" }, { "code": null, "e": 1271, "s": 1261, "text": "Live Demo" }, { "code": null, "e": 1737, "s": 1271, "text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $(\"button\").click(function(){\n $(\"p\").removeAttr(\"style\").hide();\n });\n});\n</script>\n</head>\n<body>\n\n<h1>Heading 1</h1>\n\n<p style=\"font-size:15px\">This is demo text. This will hide on button click.</p>\n<p>This is another text. This will hide on button click</p>\n\n<button>Hide</button>\n\n</body>\n</html>" } ]
How to upsample a matrix by repeating elements using NumPy in Python?
03 Jan, 2021 Prerequisites: Numpy Upsampling a matrix simply means expanding it and obviously upsampling can be done by adding more elements to the original matrix. It can be done in various ways like adding new elements and expanding the original matrix or it can be done by the matrix elements of original matrix itself. The later approach is discussed below along with 2 methods to do the same. We use the numpy.repeat() method to upsample the matrix by repeating the numbers of the matrix. We pass the matrix in repeat() method with the axis to upsample the matrix. This method is used to repeat elements of array. Syntax: numpy.repeat(array, repeats, axis=0) Parameters: array=Name of the array repeats= Numbers of repetitions of every element axis= The axis along which to repeat the values. By default, axis is set to None. For row-wise axis=0 and for column-wise axis=1. Approach Import module Create array Pass it to repeat method Print matrix Example: Python3 # importing required moduleimport numpy as np # declaring an arraya = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # use the repeat function to upsample the arrayprint(np.repeat(a, 5, axis=1).repeat(3, axis=0)) Output: In this approach we will see how np.kron is used to upsample a matrix. We pass the matrix along with an ones matrix which will multiply with each other using kron() method and the result will be an upsampled matrix. Syntax: np.kron(a ,b) where a and b are two arrays. It returns the Kronecker product of two arrays. Its parameters are two arrays whose product to be calculated Example: Python3 # import required librariesimport numpy as np # creating an array using numpya = np.array([[9, 8, 5], [11, 12, 14], [20, 21, 22]]) # using kron function upsampling the arrayupsampled_array = np.kron(a, np.ones((2, 2))) # printing the desired resultprint(upsampled_array) Output : Picked Python numpy-Matrix Function Python-numpy Technical Scripter 2020 Python Technical Scripter 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 Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jan, 2021" }, { "code": null, "e": 49, "s": 28, "text": "Prerequisites: Numpy" }, { "code": null, "e": 413, "s": 49, "text": "Upsampling a matrix simply means expanding it and obviously upsampling can be done by adding more elements to the original matrix. It can be done in various ways like adding new elements and expanding the original matrix or it can be done by the matrix elements of original matrix itself. The later approach is discussed below along with 2 methods to do the same." }, { "code": null, "e": 634, "s": 413, "text": "We use the numpy.repeat() method to upsample the matrix by repeating the numbers of the matrix. We pass the matrix in repeat() method with the axis to upsample the matrix. This method is used to repeat elements of array." }, { "code": null, "e": 645, "s": 634, "text": "Syntax: " }, { "code": null, "e": 682, "s": 645, "text": "numpy.repeat(array, repeats, axis=0)" }, { "code": null, "e": 694, "s": 682, "text": "Parameters:" }, { "code": null, "e": 718, "s": 694, "text": "array=Name of the array" }, { "code": null, "e": 767, "s": 718, "text": "repeats= Numbers of repetitions of every element" }, { "code": null, "e": 849, "s": 767, "text": "axis= The axis along which to repeat the values. By default, axis is set to None." }, { "code": null, "e": 897, "s": 849, "text": "For row-wise axis=0 and for column-wise axis=1." }, { "code": null, "e": 906, "s": 897, "text": "Approach" }, { "code": null, "e": 920, "s": 906, "text": "Import module" }, { "code": null, "e": 933, "s": 920, "text": "Create array" }, { "code": null, "e": 958, "s": 933, "text": "Pass it to repeat method" }, { "code": null, "e": 971, "s": 958, "text": "Print matrix" }, { "code": null, "e": 980, "s": 971, "text": "Example:" }, { "code": null, "e": 988, "s": 980, "text": "Python3" }, { "code": "# importing required moduleimport numpy as np # declaring an arraya = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # use the repeat function to upsample the arrayprint(np.repeat(a, 5, axis=1).repeat(3, axis=0))", "e": 1190, "s": 988, "text": null }, { "code": null, "e": 1198, "s": 1190, "text": "Output:" }, { "code": null, "e": 1414, "s": 1198, "text": "In this approach we will see how np.kron is used to upsample a matrix. We pass the matrix along with an ones matrix which will multiply with each other using kron() method and the result will be an upsampled matrix." }, { "code": null, "e": 1422, "s": 1414, "text": "Syntax:" }, { "code": null, "e": 1436, "s": 1422, "text": "np.kron(a ,b)" }, { "code": null, "e": 1466, "s": 1436, "text": "where a and b are two arrays." }, { "code": null, "e": 1514, "s": 1466, "text": "It returns the Kronecker product of two arrays." }, { "code": null, "e": 1575, "s": 1514, "text": "Its parameters are two arrays whose product to be calculated" }, { "code": null, "e": 1585, "s": 1575, "text": "Example: " }, { "code": null, "e": 1593, "s": 1585, "text": "Python3" }, { "code": "# import required librariesimport numpy as np # creating an array using numpya = np.array([[9, 8, 5], [11, 12, 14], [20, 21, 22]]) # using kron function upsampling the arrayupsampled_array = np.kron(a, np.ones((2, 2))) # printing the desired resultprint(upsampled_array)", "e": 1867, "s": 1593, "text": null }, { "code": null, "e": 1876, "s": 1867, "text": "Output :" }, { "code": null, "e": 1883, "s": 1876, "text": "Picked" }, { "code": null, "e": 1912, "s": 1883, "text": "Python numpy-Matrix Function" }, { "code": null, "e": 1925, "s": 1912, "text": "Python-numpy" }, { "code": null, "e": 1949, "s": 1925, "text": "Technical Scripter 2020" }, { "code": null, "e": 1956, "s": 1949, "text": "Python" }, { "code": null, "e": 1975, "s": 1956, "text": "Technical Scripter" }, { "code": null, "e": 2073, "s": 1975, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2105, "s": 2073, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2132, "s": 2105, "text": "Python Classes and Objects" }, { "code": null, "e": 2153, "s": 2132, "text": "Python OOPs Concepts" }, { "code": null, "e": 2176, "s": 2153, "text": "Introduction To PYTHON" }, { "code": null, "e": 2207, "s": 2176, "text": "Python | os.path.join() method" }, { "code": null, "e": 2263, "s": 2207, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2305, "s": 2263, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2347, "s": 2305, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2386, "s": 2347, "text": "Python | Get unique values from a list" } ]
Python Program to print all Possible Combinations from the three Digits
29 Aug, 2020 Given 3 digits a, b, and c. The task is to find all the possible combinations from these digits. Examples: Input: [1, 2, 3] Output: 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 Input: [0, 9, 5] Output: 0 9 5 0 5 9 9 0 5 9 5 0 5 0 9 5 9 0 Method 1: Brute force or Naive approach The naive approach is to run 3 loops from 0 to 3 and print all the numbers from the list if the indexes are not equal to each other. Example: Python3 # Python program to print all# the possible combinations def comb(L): for i in range(3): for j in range(3): for k in range(3): # check if the indexes are not # same if (i!=j and j!=k and i!=k): print(L[i], L[j], L[k]) # Driver Codecomb([1, 2, 3]) Output: 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 Method 2: Using itertools.permutations() This method takes a list as an input and returns an object list of tuples that contain all permutation in a list form. Example: Python3 # Python program to print all# the possible combinations from itertools import permutations # Get all combination of [1, 2, 3]# of length 3comb = permutations([1, 2, 3], 3) for i in comb: print(i) Output: (1, 2, 3) (1, 3, 2) (2, 1, 3) (2, 3, 1) (3, 1, 2) (3, 2, 1) Python list-programs Python-itertools Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Aug, 2020" }, { "code": null, "e": 151, "s": 54, "text": "Given 3 digits a, b, and c. The task is to find all the possible combinations from these digits." }, { "code": null, "e": 161, "s": 151, "text": "Examples:" }, { "code": null, "e": 285, "s": 161, "text": "Input: [1, 2, 3]\nOutput:\n1 2 3\n1 3 2\n2 1 3\n2 3 1\n3 1 2\n3 2 1\n\nInput: [0, 9, 5]\nOutput:\n0 9 5\n0 5 9\n9 0 5\n9 5 0\n5 0 9\n5 9 0\n" }, { "code": null, "e": 325, "s": 285, "text": "Method 1: Brute force or Naive approach" }, { "code": null, "e": 458, "s": 325, "text": "The naive approach is to run 3 loops from 0 to 3 and print all the numbers from the list if the indexes are not equal to each other." }, { "code": null, "e": 467, "s": 458, "text": "Example:" }, { "code": null, "e": 475, "s": 467, "text": "Python3" }, { "code": "# Python program to print all# the possible combinations def comb(L): for i in range(3): for j in range(3): for k in range(3): # check if the indexes are not # same if (i!=j and j!=k and i!=k): print(L[i], L[j], L[k]) # Driver Codecomb([1, 2, 3])", "e": 853, "s": 475, "text": null }, { "code": null, "e": 861, "s": 853, "text": "Output:" }, { "code": null, "e": 898, "s": 861, "text": "1 2 3\n1 3 2\n2 1 3\n2 3 1\n3 1 2\n3 2 1\n" }, { "code": null, "e": 939, "s": 898, "text": "Method 2: Using itertools.permutations()" }, { "code": null, "e": 1058, "s": 939, "text": "This method takes a list as an input and returns an object list of tuples that contain all permutation in a list form." }, { "code": null, "e": 1067, "s": 1058, "text": "Example:" }, { "code": null, "e": 1075, "s": 1067, "text": "Python3" }, { "code": "# Python program to print all# the possible combinations from itertools import permutations # Get all combination of [1, 2, 3]# of length 3comb = permutations([1, 2, 3], 3) for i in comb: print(i)", "e": 1278, "s": 1075, "text": null }, { "code": null, "e": 1286, "s": 1278, "text": "Output:" }, { "code": null, "e": 1347, "s": 1286, "text": "(1, 2, 3)\n(1, 3, 2)\n(2, 1, 3)\n(2, 3, 1)\n(3, 1, 2)\n(3, 2, 1)\n" }, { "code": null, "e": 1368, "s": 1347, "text": "Python list-programs" }, { "code": null, "e": 1385, "s": 1368, "text": "Python-itertools" }, { "code": null, "e": 1392, "s": 1385, "text": "Python" }, { "code": null, "e": 1408, "s": 1392, "text": "Python Programs" }, { "code": null, "e": 1506, "s": 1408, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1538, "s": 1506, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1565, "s": 1538, "text": "Python Classes and Objects" }, { "code": null, "e": 1596, "s": 1565, "text": "Python | os.path.join() method" }, { "code": null, "e": 1619, "s": 1596, "text": "Introduction To PYTHON" }, { "code": null, "e": 1640, "s": 1619, "text": "Python OOPs Concepts" }, { "code": null, "e": 1662, "s": 1640, "text": "Defaultdict in Python" }, { "code": null, "e": 1701, "s": 1662, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1739, "s": 1701, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 1788, "s": 1739, "text": "Python | Convert string dictionary to dictionary" } ]
GATE | GATE-CS-2016 (Set 2) | Question 61
28 Jun, 2021 Consider the following database schedule with two transactions, T1 and T2. S = r2(X); r1(X); r2(Y); w1(X); r1(Y); w2(X); a1; a2; where ri(Z) denotes a read operation by transaction Ti on a variable Z, wi(Z) denotes a write operation by Ti on a variable Z and ai denotes an abort by transaction Ti .Which one of the following statements about the above schedule is TRUE?(A) S is non-recoverable(B) S is recoverable, but has a cascading abort(C) S does not have a cascading abort (D) S is strictAnswer: (C)Explanation: As we can see in figure, T2 overwrites a value that T1 writes T1 aborts: its “remembered” values are restored. Cascading Abort could have arised if – > Abort of T1 required abort of T2 but as T2 is already aborted , its not a cascade abort. Therefore, Option C Option A – is not true because the given schedule is recoverable Option B – is not true as it is recoverable and avoid cascading aborts; Option D – is not true because T2 is also doing abort operation after T1 does, so NOT strict.Quiz of this Question GATE-CS-2016 (Set 2) GATE-GATE-CS-2016 (Set 2) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 127, "s": 52, "text": "Consider the following database schedule with two transactions, T1 and T2." }, { "code": null, "e": 181, "s": 127, "text": "S = r2(X); r1(X); r2(Y); w1(X); r1(Y); w2(X); a1; a2;" }, { "code": null, "e": 530, "s": 181, "text": "where ri(Z) denotes a read operation by transaction Ti on a variable Z, wi(Z) denotes a write operation by Ti on a variable Z and ai denotes an abort by transaction Ti .Which one of the following statements about the above schedule is TRUE?(A) S is non-recoverable(B) S is recoverable, but has a cascading abort(C) S does not have a cascading abort" }, { "code": null, "e": 594, "s": 530, "text": "(D) S is strictAnswer: (C)Explanation: As we can see in figure," }, { "code": null, "e": 631, "s": 594, "text": "T2 overwrites a value that T1 writes" }, { "code": null, "e": 680, "s": 631, "text": "T1 aborts: its “remembered” values are restored." }, { "code": null, "e": 830, "s": 680, "text": "Cascading Abort could have arised if – > Abort of T1 required abort of T2 but as T2 is already aborted , its not a cascade abort. Therefore, Option C" }, { "code": null, "e": 895, "s": 830, "text": "Option A – is not true because the given schedule is recoverable" }, { "code": null, "e": 967, "s": 895, "text": "Option B – is not true as it is recoverable and avoid cascading aborts;" }, { "code": null, "e": 1082, "s": 967, "text": "Option D – is not true because T2 is also doing abort operation after T1 does, so NOT strict.Quiz of this Question" }, { "code": null, "e": 1103, "s": 1082, "text": "GATE-CS-2016 (Set 2)" }, { "code": null, "e": 1129, "s": 1103, "text": "GATE-GATE-CS-2016 (Set 2)" }, { "code": null, "e": 1134, "s": 1129, "text": "GATE" } ]
Sum of LCM(1, n), LCM(2, n), LCM(3, n), ... , LCM(n, n)
21 Jun, 2022 Given an integer n, the task is to find the sum: LCM(1, n) + LCM(2, n) + LCM(3, n) + ... + LCM(n, n) where LCM(i, n) is the Least Common Multiple of i and n. Examples: Input: 3 Output: 10 LCM(1, 3) + LCM(2, 3) + LCM(3, 3) = 3 + 6 + 3 = 12 Input: 5 Output: 55 LCM(1, 5) + LCM(2, 5) + LCM(3, 5) + LCM(4, 5) + LCM(5, 5) = 55 Naive Approach: LCM of two numbers a and b = (a * b) / gcd(a, b) where gcd(a, b) is the Greatest Common Divisor of a and b. Calculate the values of individual LCM for all pairs starting from (1, n) to (n, n). Sum all the LCM results from the previous step. Print the sum in the end. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long int // Function to calculate the required LCM sumll lcmSum(long long n){ ll sum = 0; for (long long int i = 1; i <= n; i++) { // GCD of i and n long long int gcd = __gcd(i, n); // LCM of i and n i.e. (i * n) / gcd(i, n) long long int lcm = (i * n) / gcd; // Update sum sum = sum + lcm; } return sum;} // Driver codeint main(){ int n = 3; cout << lcmSum(n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // return gcd of two numbersstatic int gcd(int a,int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a); } // Function to calculate the required LCM sumstatic int lcmSum(int n){ int sum = 0; for (int i = 1; i <= n; i++) { // GCD of i and n int gcd = gcd(i, n); // LCM of i and n i.e. (i * n) / gcd(i, n) int lcm = (i * n) / gcd; // Update sum sum = sum + lcm; } return sum;} // Driver codepublic static void main(String args[]){ int n = 3; System.out.println(lcmSum(n));}} // This code is contributed by// Surendra _Gangwar # Python3 implementation of the approachimport math # Function to calculate the required LCM sumdef lcmSum(n): Sum = 0 for i in range(1, n + 1): # GCD of i and n gcd = math.gcd(i, n) # LCM of i and n i.e. (i * n) / gcd(i, n) lcm = (i * n) // gcd # Update sum Sum = Sum + lcm return Sum # Driver codeif __name__ == "__main__": n = 3 print(lcmSum(n)) # This code is contributed by Rituraj Jain // C# implementation of the approachclass GFG{ // return gcd of two numbersstatic int gcd1(int a,int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd1(a - b, b); return gcd1(a, b - a); } // Function to calculate the required LCM sumstatic int lcmSum(int n){ int sum = 0; for (int i = 1; i <= n; i++) { // GCD of i and n int gcd = gcd1(i, n); // LCM of i and n i.e. (i * n) / gcd(i, n) int lcm = (i * n) / gcd; // Update sum sum = sum + lcm; } return sum;} // Driver codestatic void Main(){ int n = 3; System.Console.WriteLine(lcmSum(n));}} // This code is contributed by chandan_jnu <?php// PHP implementation of the approach function __gcd($a, $b){ if($b == 0) return $a; return __gcd($b, $a % $b);} // Function to calculate the required LCM sumfunction lcmSum($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) { // GCD of i and n $gcd = __gcd($i, $n); // LCM of i and n i.e. (i * n) / gcd(i, n) $lcm = ($i * $n) / $gcd; // Update sum $sum = $sum + $lcm; } return $sum;} // Driver code$n = 3; echo lcmSum($n); // This code is contributed by chandan_jnu?> <script> // Javascript implementation of the approach // return gcd of two numbersfunction gcd(a, b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // Function to calculate the required LCM sumfunction lcmSum(n){ var sum = 0; for(var i = 1; i <= n; i++) { // GCD of i and n var _gcd = gcd(i, n); // LCM of i and n i.e. (i * n) / gcd(i, n) var lcm = (i * n) / _gcd; // Update sum sum = sum + lcm; } return sum;} // Driver codevar n = 3; document.write(lcmSum(n)); // This code is contributed by Ankita saini </script> 12 Time Complexity: O(n * logn), where n represents the given integer. Auxiliary Space: O(1), no extra space is required, so it is a constant. Efficient Approach: Using Euler Totient Function, ∑LCM(i, n) = ((∑(d * ETF(d)) + 1) * n) / 2 where ETF(d) is Euler totient function of d and d belongs to the set of divisors of n. Example: Let n be 5 then LCM(1, 5) + LCM(2, 5) + LCM(3, 5) + LCM(4, 5) + LCM(5, 5) = 5 + 10 + 15 + 20 + 5 = 55With Euler Totient Function: All divisors of 5 are {1, 5} Hence, ((1*ETF(1) + 5*ETF(5) + 1) * 5) / 2 = 55 Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define n 1000002#define ll long long int ll phi[n + 2], ans[n + 2]; // Euler totient Functionvoid ETF(){ for (int i = 1; i <= n; i++) { phi[i] = i; } for (int i = 2; i <= n; i++) { if (phi[i] == i) { phi[i] = i - 1; for (int j = 2 * i; j <= n; j += i) { phi[j] = (phi[j] * (i - 1)) / i; } } }} // Function to return the required LCM sumll LcmSum(int m){ ETF(); for (int i = 1; i <= n; i++) { // Summation of d * ETF(d) where // d belongs to set of divisors of n for (int j = i; j <= n; j += i) { ans[j] += (i * phi[i]); } } ll answer = ans[m]; answer = (answer + 1) * m; answer = answer / 2; return answer;} // Driver codeint main(){ int m = 5; cout << LcmSum(m); return 0;} // Java implementation of the approachclass GFG{ static int n = 1000002; static int[] phi = new int[n + 2];static int[] ans = new int[n + 2]; // Euler totient Functionstatic void ETF(){ for (int i = 1; i <= n; i++) { phi[i] = i; } for (int i = 2; i <= n; i++) { if (phi[i] == i) { phi[i] = i - 1; for (int j = 2 * i; j <= n; j += i) { phi[j] = (phi[j] * (i - 1)) / i; } } }} // Function to return the required LCM sumstatic int LcmSum(int m){ ETF(); for (int i = 1; i <= n; i++) { // Summation of d * ETF(d) where // d belongs to set of divisors of n for (int j = i; j <= n; j += i) { ans[j] += (i * phi[i]); } } int answer = ans[m]; answer = (answer + 1) * m; answer = answer / 2; return answer;} // Driver codepublic static void main (String[] args){ int m = 5; System.out.println(LcmSum(m));}} // This code is contributed by chandan_jnu # Python3 implementation of the approachn = 100002; phi = [0] * (n + 2);ans = [0] * (n + 2); # Euler totient Functiondef ETF(): for i in range(1, n + 1): phi[i] = i; for i in range(2, n + 1): if (phi[i] == i): phi[i] = i - 1; for j in range(2 * i, n + 1, i): phi[j] = (phi[j] * (i - 1)) // i; # Function to return the required LCM sumdef LcmSum(m): ETF(); for i in range(1, n + 1): # Summation of d * ETF(d) where # d belongs to set of divisors of n for j in range(i, n + 1, i): ans[j] += (i * phi[i]); answer = ans[m]; answer = (answer + 1) * m; answer = answer // 2; return answer; # Driver codem = 5;print(LcmSum(m)); # This code is contributed# by chandan_jnu // C# implementation of the approachusing System; class GFG{static int n = 1000002; static int[] phi = new int[n + 2];static int[] ans = new int[n + 2]; // Euler totient Functionstatic void ETF(){ for (int i = 1; i <= n; i++) { phi[i] = i; } for (int i = 2; i <= n; i++) { if (phi[i] == i) { phi[i] = i - 1; for (int j = 2 * i; j <= n; j += i) { phi[j] = (phi[j] * (i - 1)) / i; } } }} // Function to return the required LCM sumstatic int LcmSum(int m){ ETF(); for (int i = 1; i <= n; i++) { // Summation of d * ETF(d) where // d belongs to set of divisors of n for (int j = i; j <= n; j += i) { ans[j] += (i * phi[i]); } } int answer = ans[m]; answer = (answer + 1) * m; answer = answer / 2; return answer;} // Driver codestatic void Main(){ int m = 5; Console.WriteLine(LcmSum(m));}} // This code is contributed by chandan_jnu <?php// PHP implementation of the approach$n = 10002; $phi = array_fill(0, $n + 2, 0);$ans = array_fill(0, $n + 2, 0); // Euler totient Functionfunction ETF(){ global $phi, $n; for ($i = 1; $i <= $n; $i++) { $phi[$i] = $i; } for ($i = 2; $i <= $n; $i++) { if ($phi[$i] == $i) { $phi[$i] = $i - 1; for ($j = 2 * $i; $j <= $n; $j += $i) { $phi[$j] = (int)(($phi[$j] * ($i - 1)) / $i); } } }} // Function to return the required LCM sumfunction LcmSum($m){ ETF(); global $ans, $n, $phi; for ($i = 1; $i <= $n; $i++) { // Summation of d * ETF(d) where // d belongs to set of divisors of n for ($j = $i; $j <= $n; $j += $i) { $ans[$j] += ($i * $phi[$i]); } } $answer = $ans[$m]; $answer = ($answer + 1) * $m; $answer = (int)($answer / 2); return $answer;} // Driver code$m = 5; echo LcmSum($m); // This code is contributed by chandan_jnu?> <script> // javascript implementation of the approach var n = 1000002; var phi = Array(n + 2).fill(0); var ans = Array(n + 2).fill(0); // Euler totient Function function ETF() { for (i = 1; i <= n; i++) { phi[i] = i; } for (i = 2; i <= n; i++) { if (phi[i] == i) { phi[i] = i - 1; for (j = 2 * i; j <= n; j += i) { phi[j] = (phi[j] * (i - 1)) / i; } } } } // Function to return the required LCM sum function LcmSum(m) { ETF(); for (i = 1; i <= n; i++) { // Summation of d * ETF(d) where // d belongs to set of divisors of n for (j = i; j <= n; j += i) { ans[j] += (i * phi[i]); } } var answer = ans[m]; answer = (answer + 1) * m; answer = answer / 2; return answer; } // Driver code var m = 5; document.write(LcmSum(m)); // This code is contributed by aashish1995</script> 55 Time Complexity: O(N * logN)Auxiliary Space: O(N) Mostafijur Rahaman rituraj_jain SURENDRA_GANGWAR Chandan_Kumar maxitrucbonbec ankita_saini aashish1995 pankajsharmagfg samim2000 GCD-LCM Technical Scripter 2018 Algorithms Mathematical Technical Scripter Mathematical Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Find if there is a path between two vertices in an undirected graph How to Start Learning DSA? Complete Roadmap To Learn DSA From Scratch Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete 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": 52, "s": 24, "text": "\n21 Jun, 2022" }, { "code": null, "e": 102, "s": 52, "text": "Given an integer n, the task is to find the sum: " }, { "code": null, "e": 212, "s": 102, "text": "LCM(1, n) + LCM(2, n) + LCM(3, n) + ... + LCM(n, n) where LCM(i, n) is the Least Common Multiple of i and n. " }, { "code": null, "e": 224, "s": 212, "text": "Examples: " }, { "code": null, "e": 295, "s": 224, "text": "Input: 3 Output: 10 LCM(1, 3) + LCM(2, 3) + LCM(3, 3) = 3 + 6 + 3 = 12" }, { "code": null, "e": 379, "s": 295, "text": "Input: 5 Output: 55 LCM(1, 5) + LCM(2, 5) + LCM(3, 5) + LCM(4, 5) + LCM(5, 5) = 55 " }, { "code": null, "e": 505, "s": 379, "text": "Naive Approach: LCM of two numbers a and b = (a * b) / gcd(a, b) where gcd(a, b) is the Greatest Common Divisor of a and b. " }, { "code": null, "e": 590, "s": 505, "text": "Calculate the values of individual LCM for all pairs starting from (1, n) to (n, n)." }, { "code": null, "e": 638, "s": 590, "text": "Sum all the LCM results from the previous step." }, { "code": null, "e": 664, "s": 638, "text": "Print the sum in the end." }, { "code": null, "e": 716, "s": 664, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 720, "s": 716, "text": "C++" }, { "code": null, "e": 725, "s": 720, "text": "Java" }, { "code": null, "e": 733, "s": 725, "text": "Python3" }, { "code": null, "e": 736, "s": 733, "text": "C#" }, { "code": null, "e": 740, "s": 736, "text": "PHP" }, { "code": null, "e": 751, "s": 740, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long int // Function to calculate the required LCM sumll lcmSum(long long n){ ll sum = 0; for (long long int i = 1; i <= n; i++) { // GCD of i and n long long int gcd = __gcd(i, n); // LCM of i and n i.e. (i * n) / gcd(i, n) long long int lcm = (i * n) / gcd; // Update sum sum = sum + lcm; } return sum;} // Driver codeint main(){ int n = 3; cout << lcmSum(n); return 0;}", "e": 1291, "s": 751, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // return gcd of two numbersstatic int gcd(int a,int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a); } // Function to calculate the required LCM sumstatic int lcmSum(int n){ int sum = 0; for (int i = 1; i <= n; i++) { // GCD of i and n int gcd = gcd(i, n); // LCM of i and n i.e. (i * n) / gcd(i, n) int lcm = (i * n) / gcd; // Update sum sum = sum + lcm; } return sum;} // Driver codepublic static void main(String args[]){ int n = 3; System.out.println(lcmSum(n));}} // This code is contributed by// Surendra _Gangwar", "e": 2142, "s": 1291, "text": null }, { "code": "# Python3 implementation of the approachimport math # Function to calculate the required LCM sumdef lcmSum(n): Sum = 0 for i in range(1, n + 1): # GCD of i and n gcd = math.gcd(i, n) # LCM of i and n i.e. (i * n) / gcd(i, n) lcm = (i * n) // gcd # Update sum Sum = Sum + lcm return Sum # Driver codeif __name__ == \"__main__\": n = 3 print(lcmSum(n)) # This code is contributed by Rituraj Jain", "e": 2597, "s": 2142, "text": null }, { "code": "// C# implementation of the approachclass GFG{ // return gcd of two numbersstatic int gcd1(int a,int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd1(a - b, b); return gcd1(a, b - a); } // Function to calculate the required LCM sumstatic int lcmSum(int n){ int sum = 0; for (int i = 1; i <= n; i++) { // GCD of i and n int gcd = gcd1(i, n); // LCM of i and n i.e. (i * n) / gcd(i, n) int lcm = (i * n) / gcd; // Update sum sum = sum + lcm; } return sum;} // Driver codestatic void Main(){ int n = 3; System.Console.WriteLine(lcmSum(n));}} // This code is contributed by chandan_jnu", "e": 3408, "s": 2597, "text": null }, { "code": "<?php// PHP implementation of the approach function __gcd($a, $b){ if($b == 0) return $a; return __gcd($b, $a % $b);} // Function to calculate the required LCM sumfunction lcmSum($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) { // GCD of i and n $gcd = __gcd($i, $n); // LCM of i and n i.e. (i * n) / gcd(i, n) $lcm = ($i * $n) / $gcd; // Update sum $sum = $sum + $lcm; } return $sum;} // Driver code$n = 3; echo lcmSum($n); // This code is contributed by chandan_jnu?>", "e": 3946, "s": 3408, "text": null }, { "code": "<script> // Javascript implementation of the approach // return gcd of two numbersfunction gcd(a, b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // Function to calculate the required LCM sumfunction lcmSum(n){ var sum = 0; for(var i = 1; i <= n; i++) { // GCD of i and n var _gcd = gcd(i, n); // LCM of i and n i.e. (i * n) / gcd(i, n) var lcm = (i * n) / _gcd; // Update sum sum = sum + lcm; } return sum;} // Driver codevar n = 3; document.write(lcmSum(n)); // This code is contributed by Ankita saini </script>", "e": 4736, "s": 3946, "text": null }, { "code": null, "e": 4739, "s": 4736, "text": "12" }, { "code": null, "e": 4809, "s": 4741, "text": "Time Complexity: O(n * logn), where n represents the given integer." }, { "code": null, "e": 4882, "s": 4809, "text": "Auxiliary Space: O(1), no extra space is required, so it is a constant. " }, { "code": null, "e": 5062, "s": 4882, "text": "Efficient Approach: Using Euler Totient Function, ∑LCM(i, n) = ((∑(d * ETF(d)) + 1) * n) / 2 where ETF(d) is Euler totient function of d and d belongs to the set of divisors of n." }, { "code": null, "e": 5072, "s": 5062, "text": "Example: " }, { "code": null, "e": 5280, "s": 5072, "text": "Let n be 5 then LCM(1, 5) + LCM(2, 5) + LCM(3, 5) + LCM(4, 5) + LCM(5, 5) = 5 + 10 + 15 + 20 + 5 = 55With Euler Totient Function: All divisors of 5 are {1, 5} Hence, ((1*ETF(1) + 5*ETF(5) + 1) * 5) / 2 = 55 " }, { "code": null, "e": 5333, "s": 5280, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 5337, "s": 5333, "text": "C++" }, { "code": null, "e": 5342, "s": 5337, "text": "Java" }, { "code": null, "e": 5350, "s": 5342, "text": "Python3" }, { "code": null, "e": 5353, "s": 5350, "text": "C#" }, { "code": null, "e": 5357, "s": 5353, "text": "PHP" }, { "code": null, "e": 5368, "s": 5357, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define n 1000002#define ll long long int ll phi[n + 2], ans[n + 2]; // Euler totient Functionvoid ETF(){ for (int i = 1; i <= n; i++) { phi[i] = i; } for (int i = 2; i <= n; i++) { if (phi[i] == i) { phi[i] = i - 1; for (int j = 2 * i; j <= n; j += i) { phi[j] = (phi[j] * (i - 1)) / i; } } }} // Function to return the required LCM sumll LcmSum(int m){ ETF(); for (int i = 1; i <= n; i++) { // Summation of d * ETF(d) where // d belongs to set of divisors of n for (int j = i; j <= n; j += i) { ans[j] += (i * phi[i]); } } ll answer = ans[m]; answer = (answer + 1) * m; answer = answer / 2; return answer;} // Driver codeint main(){ int m = 5; cout << LcmSum(m); return 0;}", "e": 6282, "s": 5368, "text": null }, { "code": "// Java implementation of the approachclass GFG{ static int n = 1000002; static int[] phi = new int[n + 2];static int[] ans = new int[n + 2]; // Euler totient Functionstatic void ETF(){ for (int i = 1; i <= n; i++) { phi[i] = i; } for (int i = 2; i <= n; i++) { if (phi[i] == i) { phi[i] = i - 1; for (int j = 2 * i; j <= n; j += i) { phi[j] = (phi[j] * (i - 1)) / i; } } }} // Function to return the required LCM sumstatic int LcmSum(int m){ ETF(); for (int i = 1; i <= n; i++) { // Summation of d * ETF(d) where // d belongs to set of divisors of n for (int j = i; j <= n; j += i) { ans[j] += (i * phi[i]); } } int answer = ans[m]; answer = (answer + 1) * m; answer = answer / 2; return answer;} // Driver codepublic static void main (String[] args){ int m = 5; System.out.println(LcmSum(m));}} // This code is contributed by chandan_jnu", "e": 7311, "s": 6282, "text": null }, { "code": "# Python3 implementation of the approachn = 100002; phi = [0] * (n + 2);ans = [0] * (n + 2); # Euler totient Functiondef ETF(): for i in range(1, n + 1): phi[i] = i; for i in range(2, n + 1): if (phi[i] == i): phi[i] = i - 1; for j in range(2 * i, n + 1, i): phi[j] = (phi[j] * (i - 1)) // i; # Function to return the required LCM sumdef LcmSum(m): ETF(); for i in range(1, n + 1): # Summation of d * ETF(d) where # d belongs to set of divisors of n for j in range(i, n + 1, i): ans[j] += (i * phi[i]); answer = ans[m]; answer = (answer + 1) * m; answer = answer // 2; return answer; # Driver codem = 5;print(LcmSum(m)); # This code is contributed# by chandan_jnu", "e": 8087, "s": 7311, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{static int n = 1000002; static int[] phi = new int[n + 2];static int[] ans = new int[n + 2]; // Euler totient Functionstatic void ETF(){ for (int i = 1; i <= n; i++) { phi[i] = i; } for (int i = 2; i <= n; i++) { if (phi[i] == i) { phi[i] = i - 1; for (int j = 2 * i; j <= n; j += i) { phi[j] = (phi[j] * (i - 1)) / i; } } }} // Function to return the required LCM sumstatic int LcmSum(int m){ ETF(); for (int i = 1; i <= n; i++) { // Summation of d * ETF(d) where // d belongs to set of divisors of n for (int j = i; j <= n; j += i) { ans[j] += (i * phi[i]); } } int answer = ans[m]; answer = (answer + 1) * m; answer = answer / 2; return answer;} // Driver codestatic void Main(){ int m = 5; Console.WriteLine(LcmSum(m));}} // This code is contributed by chandan_jnu", "e": 9101, "s": 8087, "text": null }, { "code": "<?php// PHP implementation of the approach$n = 10002; $phi = array_fill(0, $n + 2, 0);$ans = array_fill(0, $n + 2, 0); // Euler totient Functionfunction ETF(){ global $phi, $n; for ($i = 1; $i <= $n; $i++) { $phi[$i] = $i; } for ($i = 2; $i <= $n; $i++) { if ($phi[$i] == $i) { $phi[$i] = $i - 1; for ($j = 2 * $i; $j <= $n; $j += $i) { $phi[$j] = (int)(($phi[$j] * ($i - 1)) / $i); } } }} // Function to return the required LCM sumfunction LcmSum($m){ ETF(); global $ans, $n, $phi; for ($i = 1; $i <= $n; $i++) { // Summation of d * ETF(d) where // d belongs to set of divisors of n for ($j = $i; $j <= $n; $j += $i) { $ans[$j] += ($i * $phi[$i]); } } $answer = $ans[$m]; $answer = ($answer + 1) * $m; $answer = (int)($answer / 2); return $answer;} // Driver code$m = 5; echo LcmSum($m); // This code is contributed by chandan_jnu?>", "e": 10156, "s": 9101, "text": null }, { "code": "<script> // javascript implementation of the approach var n = 1000002; var phi = Array(n + 2).fill(0); var ans = Array(n + 2).fill(0); // Euler totient Function function ETF() { for (i = 1; i <= n; i++) { phi[i] = i; } for (i = 2; i <= n; i++) { if (phi[i] == i) { phi[i] = i - 1; for (j = 2 * i; j <= n; j += i) { phi[j] = (phi[j] * (i - 1)) / i; } } } } // Function to return the required LCM sum function LcmSum(m) { ETF(); for (i = 1; i <= n; i++) { // Summation of d * ETF(d) where // d belongs to set of divisors of n for (j = i; j <= n; j += i) { ans[j] += (i * phi[i]); } } var answer = ans[m]; answer = (answer + 1) * m; answer = answer / 2; return answer; } // Driver code var m = 5; document.write(LcmSum(m)); // This code is contributed by aashish1995</script>", "e": 11213, "s": 10156, "text": null }, { "code": null, "e": 11216, "s": 11213, "text": "55" }, { "code": null, "e": 11268, "s": 11218, "text": "Time Complexity: O(N * logN)Auxiliary Space: O(N)" }, { "code": null, "e": 11287, "s": 11268, "text": "Mostafijur Rahaman" }, { "code": null, "e": 11300, "s": 11287, "text": "rituraj_jain" }, { "code": null, "e": 11317, "s": 11300, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 11331, "s": 11317, "text": "Chandan_Kumar" }, { "code": null, "e": 11346, "s": 11331, "text": "maxitrucbonbec" }, { "code": null, "e": 11359, "s": 11346, "text": "ankita_saini" }, { "code": null, "e": 11371, "s": 11359, "text": "aashish1995" }, { "code": null, "e": 11387, "s": 11371, "text": "pankajsharmagfg" }, { "code": null, "e": 11397, "s": 11387, "text": "samim2000" }, { "code": null, "e": 11405, "s": 11397, "text": "GCD-LCM" }, { "code": null, "e": 11429, "s": 11405, "text": "Technical Scripter 2018" }, { "code": null, "e": 11440, "s": 11429, "text": "Algorithms" }, { "code": null, "e": 11453, "s": 11440, "text": "Mathematical" }, { "code": null, "e": 11472, "s": 11453, "text": "Technical Scripter" }, { "code": null, "e": 11485, "s": 11472, "text": "Mathematical" }, { "code": null, "e": 11496, "s": 11485, "text": "Algorithms" }, { "code": null, "e": 11594, "s": 11496, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11632, "s": 11594, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 11700, "s": 11632, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 11727, "s": 11700, "text": "How to Start Learning DSA?" }, { "code": null, "e": 11770, "s": 11727, "text": "Complete Roadmap To Learn DSA From Scratch" }, { "code": null, "e": 11837, "s": 11770, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 11867, "s": 11837, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 11910, "s": 11867, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 11970, "s": 11910, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 11985, "s": 11970, "text": "C++ Data Types" } ]
proc file system in Linux
03 Dec, 2021 Proc file system (procfs) is virtual file system created on fly when system boots and is dissolved at time of system shut down. It contains useful information about the processes that are currently running, it is regarded as control and information center for kernel. The proc file system also provides communication medium between kernel space and user space. Below is snapshot of /proc from my PC. ls -l /proc total 0 dr-xr-xr-x 9 root root 0 Mar 31 21:34 1 dr-xr-xr-x 9 root root 0 Mar 31 21:34 10 dr-xr-xr-x 9 avahi avahi 0 Mar 31 21:34 1034 dr-xr-xr-x 9 root root 0 Mar 31 21:34 1036 dr-xr-xr-x 9 root root 0 Mar 31 21:34 1039 dr-xr-xr-x 9 root root 0 Mar 31 21:34 1041 dr-xr-xr-x 9 root root 0 Mar 31 21:34 1043 dr-xr-xr-x 9 root root 0 Mar 31 21:34 1044 dr-xr-xr-x 9 root root 0 Mar 31 21:34 1048 dr-xr-xr-x 9 root root 0 Mar 31 21:34 105 dr-xr-xr-x 9 root root 0 Mar 31 21:34 1078 dr-xr-xr-x 9 root root 0 Mar 31 21:34 11 dr-xr-xr-x 9 root root 0 Mar 31 21:34 1121 dr-xr-xr-x 9 lp lp 0 Mar 31 21:34 1146 dr-xr-xr-x 9 postgres postgres 0 Mar 31 21:34 1149 dr-xr-xr-x 9 mysql mysql 0 Mar 31 21:34 1169 dr-xr-xr-x 9 postgres postgres 0 Mar 31 21:34 1180 dr-xr-xr-x 9 postgres postgres 0 Mar 31 21:34 1181 dr-xr-xr-x 9 postgres postgres 0 Mar 31 21:34 1182 dr-xr-xr-x 9 postgres postgres 0 Mar 31 21:34 1183 dr-xr-xr-x 9 postgres postgres 0 Mar 31 21:34 1184 dr-xr-xr-x 9 root root 0 Mar 31 21:34 1186 dr-xr-xr-x 9 root root 0 Mar 31 21:34 12 ... If you list the directories, you will find that for each PID of a process there is dedicated directory.You can check directories only on terminal using ls -l /proc | grep '^d' Now let’s check for particular process of assigned PID, you can get the PID of any running process from ps command ps -aux Output: ps -aux command output Now check the highlighted process with PID=7494, you can check that there is entry for this process in /proc file system. ls -ltr /proc/7494 Output: total 0 -rw-r--r-- 1 mandeep mandeep 0 Apr 1 01:14 oom_score_adj dr-xr-xr-x 13 mandeep mandeep 0 Apr 1 01:14 task -r--r--r-- 1 mandeep mandeep 0 Apr 1 01:16 status -r--r--r-- 1 mandeep mandeep 0 Apr 1 01:16 stat -r--r--r-- 1 mandeep mandeep 0 Apr 1 01:16 cmdline -r--r--r-- 1 mandeep mandeep 0 Apr 1 01:17 wchan -rw-r--r-- 1 mandeep mandeep 0 Apr 1 01:17 uid_map -rw-rw-rw- 1 mandeep mandeep 0 Apr 1 01:17 timerslack_ns -r--r--r-- 1 mandeep mandeep 0 Apr 1 01:17 timers -r-------- 1 mandeep mandeep 0 Apr 1 01:17 syscall -r--r--r-- 1 mandeep mandeep 0 Apr 1 01:17 statm -r-------- 1 mandeep mandeep 0 Apr 1 01:17 stack -r--r--r-- 1 mandeep mandeep 0 Apr 1 01:17 smaps -rw-r--r-- 1 mandeep mandeep 0 Apr 1 01:17 setgroups -r--r--r-- 1 mandeep mandeep 0 Apr 1 01:17 sessionid -r--r--r-- 1 mandeep mandeep 0 Apr 1 01:17 schedstat -rw-r--r-- 1 mandeep mandeep 0 Apr 1 01:17 sched lrwxrwxrwx 1 mandeep mandeep 0 Apr 1 01:17 root -> /proc/2341/fdinfo -rw-r--r-- 1 mandeep mandeep 0 Apr 1 01:17 projid_map -r-------- 1 mandeep mandeep 0 Apr 1 01:17 personality ... In linux, /proc includes a directory for each running process, including kernel processes, in directories named /proc/PID, these are the directories present: Some other files in /proc file system are: For example, the contents of /proc/crypto are less /proc/crypto name : ccm(aes) driver : ccm_base(ctr(aes-aesni), cbcmac(aes-aesni)) module : ccm priority : 300 refcnt : 2 selftest : passed internal : no type : aead async : no blocksize : 1 ivsize : 16 maxauthsize : 16 geniv : name : ctr(aes) driver : ctr(aes-aesni) module : kernel priority : 300 refcnt : 3 selftest : passed internal : no type : blkcipher blocksize : 1 min keysize : 16 max keysize : 32 ivsize : 16 geniv : chainiv ... References :1) /wiki/Procfs2) /proc nnr223442 as5853535 Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Dec, 2021" }, { "code": null, "e": 180, "s": 52, "text": "Proc file system (procfs) is virtual file system created on fly when system boots and is dissolved at time of system shut down." }, { "code": null, "e": 320, "s": 180, "text": "It contains useful information about the processes that are currently running, it is regarded as control and information center for kernel." }, { "code": null, "e": 413, "s": 320, "text": "The proc file system also provides communication medium between kernel space and user space." }, { "code": null, "e": 452, "s": 413, "text": "Below is snapshot of /proc from my PC." }, { "code": null, "e": 1895, "s": 452, "text": "ls -l /proc\n\ntotal 0\ndr-xr-xr-x 9 root root 0 Mar 31 21:34 1\ndr-xr-xr-x 9 root root 0 Mar 31 21:34 10\ndr-xr-xr-x 9 avahi avahi 0 Mar 31 21:34 1034\ndr-xr-xr-x 9 root root 0 Mar 31 21:34 1036\ndr-xr-xr-x 9 root root 0 Mar 31 21:34 1039\ndr-xr-xr-x 9 root root 0 Mar 31 21:34 1041\ndr-xr-xr-x 9 root root 0 Mar 31 21:34 1043\ndr-xr-xr-x 9 root root 0 Mar 31 21:34 1044\ndr-xr-xr-x 9 root root 0 Mar 31 21:34 1048\ndr-xr-xr-x 9 root root 0 Mar 31 21:34 105\ndr-xr-xr-x 9 root root 0 Mar 31 21:34 1078\ndr-xr-xr-x 9 root root 0 Mar 31 21:34 11\ndr-xr-xr-x 9 root root 0 Mar 31 21:34 1121\ndr-xr-xr-x 9 lp lp 0 Mar 31 21:34 1146\ndr-xr-xr-x 9 postgres postgres 0 Mar 31 21:34 1149\ndr-xr-xr-x 9 mysql mysql 0 Mar 31 21:34 1169\ndr-xr-xr-x 9 postgres postgres 0 Mar 31 21:34 1180\ndr-xr-xr-x 9 postgres postgres 0 Mar 31 21:34 1181\ndr-xr-xr-x 9 postgres postgres 0 Mar 31 21:34 1182\ndr-xr-xr-x 9 postgres postgres 0 Mar 31 21:34 1183\ndr-xr-xr-x 9 postgres postgres 0 Mar 31 21:34 1184\ndr-xr-xr-x 9 root root 0 Mar 31 21:34 1186\ndr-xr-xr-x 9 root root 0 Mar 31 21:34 12\n\n...\n" }, { "code": null, "e": 2047, "s": 1895, "text": "If you list the directories, you will find that for each PID of a process there is dedicated directory.You can check directories only on terminal using" }, { "code": null, "e": 2072, "s": 2047, "text": "ls -l /proc | grep '^d'\n" }, { "code": null, "e": 2187, "s": 2072, "text": "Now let’s check for particular process of assigned PID, you can get the PID of any running process from ps command" }, { "code": null, "e": 2196, "s": 2187, "text": "ps -aux\n" }, { "code": null, "e": 2204, "s": 2196, "text": "Output:" }, { "code": null, "e": 2227, "s": 2204, "text": "ps -aux command output" }, { "code": null, "e": 2349, "s": 2227, "text": "Now check the highlighted process with PID=7494, you can check that there is entry for this process in /proc file system." }, { "code": null, "e": 2369, "s": 2349, "text": "ls -ltr /proc/7494\n" }, { "code": null, "e": 2377, "s": 2369, "text": "Output:" }, { "code": null, "e": 3476, "s": 2377, "text": "total 0\n-rw-r--r-- 1 mandeep mandeep 0 Apr 1 01:14 oom_score_adj\ndr-xr-xr-x 13 mandeep mandeep 0 Apr 1 01:14 task\n-r--r--r-- 1 mandeep mandeep 0 Apr 1 01:16 status\n-r--r--r-- 1 mandeep mandeep 0 Apr 1 01:16 stat\n-r--r--r-- 1 mandeep mandeep 0 Apr 1 01:16 cmdline\n-r--r--r-- 1 mandeep mandeep 0 Apr 1 01:17 wchan\n-rw-r--r-- 1 mandeep mandeep 0 Apr 1 01:17 uid_map\n-rw-rw-rw- 1 mandeep mandeep 0 Apr 1 01:17 timerslack_ns\n-r--r--r-- 1 mandeep mandeep 0 Apr 1 01:17 timers\n-r-------- 1 mandeep mandeep 0 Apr 1 01:17 syscall\n-r--r--r-- 1 mandeep mandeep 0 Apr 1 01:17 statm\n-r-------- 1 mandeep mandeep 0 Apr 1 01:17 stack\n-r--r--r-- 1 mandeep mandeep 0 Apr 1 01:17 smaps\n-rw-r--r-- 1 mandeep mandeep 0 Apr 1 01:17 setgroups\n-r--r--r-- 1 mandeep mandeep 0 Apr 1 01:17 sessionid\n-r--r--r-- 1 mandeep mandeep 0 Apr 1 01:17 schedstat\n-rw-r--r-- 1 mandeep mandeep 0 Apr 1 01:17 sched\nlrwxrwxrwx 1 mandeep mandeep 0 Apr 1 01:17 root -> /proc/2341/fdinfo\n-rw-r--r-- 1 mandeep mandeep 0 Apr 1 01:17 projid_map\n-r-------- 1 mandeep mandeep 0 Apr 1 01:17 personality\n\n...\n" }, { "code": null, "e": 3634, "s": 3476, "text": "In linux, /proc includes a directory for each running process, including kernel processes, in directories named /proc/PID, these are the directories present:" }, { "code": null, "e": 3677, "s": 3634, "text": "Some other files in /proc file system are:" }, { "code": null, "e": 3723, "s": 3677, "text": "For example, the contents of /proc/crypto are" }, { "code": null, "e": 4305, "s": 3723, "text": "less /proc/crypto\n\nname : ccm(aes)\ndriver : ccm_base(ctr(aes-aesni), cbcmac(aes-aesni))\nmodule : ccm\npriority : 300\nrefcnt : 2\nselftest : passed\ninternal : no\ntype : aead\nasync : no\nblocksize : 1\nivsize : 16\nmaxauthsize : 16\ngeniv : \n\nname : ctr(aes)\ndriver : ctr(aes-aesni)\nmodule : kernel\npriority : 300\nrefcnt : 3\nselftest : passed\ninternal : no\ntype : blkcipher\nblocksize : 1\nmin keysize : 16\nmax keysize : 32\nivsize : 16\ngeniv : chainiv\n\n...\n" }, { "code": null, "e": 4341, "s": 4305, "text": "References :1) /wiki/Procfs2) /proc" }, { "code": null, "e": 4351, "s": 4341, "text": "nnr223442" }, { "code": null, "e": 4361, "s": 4351, "text": "as5853535" }, { "code": null, "e": 4372, "s": 4361, "text": "Linux-Unix" } ]
Minimum insertions to form shortest palindrome
28 Jun, 2022 Given a string S, determine the least number of characters that should be added on to the left side of S so that the complete string becomes a palindrome. Examples: Input: S = "LOL" Output: 0 LOL is already a palindrome Input: S = "JAVA" Output: 3 We need to add 3 characters to form AVAJAVA. The idea is to find the longest palindromic prefix of given string. The count of characters after the prefix is our answer. The longest palindromic prefix can be found by looping from last char to first char. For example, in “JAVA”, the longest palindromic prefix is “J”, so we need to add remaining 3 at the beginning characters to form palindrome. C++ Java Python3 C# Javascript // C++ program to find minimum number of insertions// on left side to form a palindrome. #include <bits/stdc++.h>using namespace std; // Returns true if a string str[st..end] is palindromebool isPalin(char str[], int st, int end){ while (st < end) { if (str[st] != str[end]) return false; st++; end--; } return true;} // Returns count of insertions on left side to make// str[] a palindromeint findMinInsert(char str[], int n){ // Find the largest prefix of given string // that is palindrome. for (int i = n - 1; i >= 0; i--) { // Characters after the palindromic prefix // must be added at the beginning also to make // the complete string palindrome if (isPalin(str, 0, i)) return (n - i - 1); }} // Driver programint main(){ char Input[] = "JAVA"; printf("%d", findMinInsert(Input, strlen(Input))); return 0;} // Java program to find minimum number// of insertions on left side to form// a palindrome.import java.util.*; class GFG { // Returns true if a string // str[st..end] is palindrome static boolean isPalin(char[] str, int st, int end) { while (st < end) { if (str[st] != str[end]) return false; st++; end--; } return true; } // Returns count of insertions on // left side to make str[] a palindrome static int findMinInsert(char[] str, int n) { // Find the largest prefix of given // string that is palindrome. for (int i = n - 1; i >= 0; i--) { // Characters after the palindromic // prefix must be added at the // beginning also to make the // complete string palindrome if (isPalin(str, 0, i)) return (n - i - 1); } return 0; } // Driver Code public static void main(String[] args) { char[] Input = "JAVA".toCharArray(); System.out.println( findMinInsert(Input, Input.length)); }} // This code is contributed by pratham76 # Python3 program to find# minimum number of insertions# on left side to form a palindrome. # Returns true if a string# str[st..end] is palindrome def isPalin(str, st, end): while (st < end): if (str[st] != str[end]): return False st += 1 end--1 return True # Returns count of insertions# on left side to make# str[] a palindromedef findMinInsert(str, n): # Find the largest # prefix of given string # that is palindrome. for i in range(n-1, -1, -1): # Characters after the # palindromic prefix must # be added at the beginning # also to make the complete # string palindrome if (isPalin(str, 0, i)): return (n - i - 1) # Driver CodeInput = "JAVA"print(findMinInsert(Input, len(Input))) # This code is contributed# by Smitha // C# program to find minimum number// of insertions on left side to form// a palindrome.using System;using System.Text; class GFG { // Returns true if a string // str[st..end] is palindrome static bool isPalin(char[] str, int st, int end) { while (st < end) { if (str[st] != str[end]) return false; st++; end--; } return true; } // Returns count of insertions on // left side to make str[] a palindrome static int findMinInsert(char[] str, int n) { // Find the largest prefix of given string // that is palindrome. for (int i = n - 1; i >= 0; i--) { // Characters after the palindromic // prefix must be added at the // beginning also to make the // complete string palindrome if (isPalin(str, 0, i)) return (n - i - 1); } return 0; } // Driver Code public static void Main(string[] args) { char[] Input = "JAVA".ToCharArray(); Console.Write(findMinInsert(Input, Input.Length)); }} // This code is contributed by rutvik_56 <script>// javascript program to find minimum number of insertions// on left side to form a palindrome. // Returns true if a string str[st..end] is palindromefunction isPalin(str,st,end){ while (st < end) { if (str[st] != str[end]) return false; st++; end--; } return true;} // Returns count of insertions on left side to make// str[] a palindromefunction findMinInsert(str,n){ // Find the largest prefix of given string // that is palindrome. for (let i = n - 1; i >= 0; i--) { // Characters after the palindromic prefix // must be added at the beginning also to make // the complete string palindrome if (isPalin(str, 0, i)) return (n - i - 1); }} let Input = "JAVA"; document.write(findMinInsert(Input,Input.length)); // This code is contributed by vaibhavrabadiya07. </script> 3 Time Complexity: O(n2) Auxiliary Space: O(1) Thanks to Utkarsh Trivedi for suggesting this solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Here we’ll preprocess the string and use the lps[] to skip the characters and store the longest palindromic prefix. For example: s = "AABAACAABAA”, lps[] is [0, 1, 0, 1, 2, 0, 1, 2, 3, 4, 5] In the above example we clearly see that the lps[] can give the length of longest proper palindromic prefix. But here we need longest palindromic prefix not proper palindromic prefix. So, to handle this we can we can append the reverse of S in S. For Example: s = ABBC newS = "ABBC" + "#" + "CBBA" lps[] for newS is [0 0 0 0 0 0 0 0 1 1] As 1 is there at the end of lps[]. so our ans is 4 - 1 = 3 Using the above logic, we can get the solution in O(N) time only. C++ #include <bits/stdc++.h>using namespace std;// using kmp algorithmint find_lps(string str){ int n = str.length(); vector<int> lps(n, 0); // initialized with 0 int len = 0; // length of previous longest prefix suffix // the loop calculates lps[i] for i = 1 to M-1 int i = 1; while (i < n) { if (str[len] == str[i]) { lps[i++] = ++len; } else { if (len != 0) len = lps[len - 1]; else lps[i++] = 0; } } return lps[n - 1];}int main(){ string s = "AABAACAABAA"; string rev = s; reverse(rev.begin(), rev.end()); string newS = s + "#" + rev; int len = find_lps(newS); cout << s.length() - len << endl; return 0;} 0 Time Complexity: O(N),Auxiliary Space: O(N) where N is the length of newS. Smitha Dinesh Semwal rutvik_56 pratham76 vaibhavrabadiya117 manish_kr shivamanandrj9 hardikkoriintern Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Longest Palindromic Substring | Set 1 Length of the longest substring without repeating characters Top 50 String Coding Problems for Interviews What is Data Structure: Types, Classifications and Applications Convert string to char array in C++ Check whether two strings are anagram of each other Reverse words in a given string Print all the duplicates in the input string Reverse string in Python (6 different ways) Array of Strings in C++ - 5 Different Ways to Create
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2022" }, { "code": null, "e": 210, "s": 54, "text": "Given a string S, determine the least number of characters that should be added on to the left side of S so that the complete string becomes a palindrome. " }, { "code": null, "e": 221, "s": 210, "text": "Examples: " }, { "code": null, "e": 350, "s": 221, "text": "Input: S = \"LOL\"\nOutput: 0\nLOL is already a palindrome\n\nInput: S = \"JAVA\"\nOutput: 3\nWe need to add 3 characters to form AVAJAVA." }, { "code": null, "e": 701, "s": 350, "text": "The idea is to find the longest palindromic prefix of given string. The count of characters after the prefix is our answer. The longest palindromic prefix can be found by looping from last char to first char. For example, in “JAVA”, the longest palindromic prefix is “J”, so we need to add remaining 3 at the beginning characters to form palindrome. " }, { "code": null, "e": 705, "s": 701, "text": "C++" }, { "code": null, "e": 710, "s": 705, "text": "Java" }, { "code": null, "e": 718, "s": 710, "text": "Python3" }, { "code": null, "e": 721, "s": 718, "text": "C#" }, { "code": null, "e": 732, "s": 721, "text": "Javascript" }, { "code": "// C++ program to find minimum number of insertions// on left side to form a palindrome. #include <bits/stdc++.h>using namespace std; // Returns true if a string str[st..end] is palindromebool isPalin(char str[], int st, int end){ while (st < end) { if (str[st] != str[end]) return false; st++; end--; } return true;} // Returns count of insertions on left side to make// str[] a palindromeint findMinInsert(char str[], int n){ // Find the largest prefix of given string // that is palindrome. for (int i = n - 1; i >= 0; i--) { // Characters after the palindromic prefix // must be added at the beginning also to make // the complete string palindrome if (isPalin(str, 0, i)) return (n - i - 1); }} // Driver programint main(){ char Input[] = \"JAVA\"; printf(\"%d\", findMinInsert(Input, strlen(Input))); return 0;}", "e": 1647, "s": 732, "text": null }, { "code": "// Java program to find minimum number// of insertions on left side to form// a palindrome.import java.util.*; class GFG { // Returns true if a string // str[st..end] is palindrome static boolean isPalin(char[] str, int st, int end) { while (st < end) { if (str[st] != str[end]) return false; st++; end--; } return true; } // Returns count of insertions on // left side to make str[] a palindrome static int findMinInsert(char[] str, int n) { // Find the largest prefix of given // string that is palindrome. for (int i = n - 1; i >= 0; i--) { // Characters after the palindromic // prefix must be added at the // beginning also to make the // complete string palindrome if (isPalin(str, 0, i)) return (n - i - 1); } return 0; } // Driver Code public static void main(String[] args) { char[] Input = \"JAVA\".toCharArray(); System.out.println( findMinInsert(Input, Input.length)); }} // This code is contributed by pratham76", "e": 2818, "s": 1647, "text": null }, { "code": "# Python3 program to find# minimum number of insertions# on left side to form a palindrome. # Returns true if a string# str[st..end] is palindrome def isPalin(str, st, end): while (st < end): if (str[st] != str[end]): return False st += 1 end--1 return True # Returns count of insertions# on left side to make# str[] a palindromedef findMinInsert(str, n): # Find the largest # prefix of given string # that is palindrome. for i in range(n-1, -1, -1): # Characters after the # palindromic prefix must # be added at the beginning # also to make the complete # string palindrome if (isPalin(str, 0, i)): return (n - i - 1) # Driver CodeInput = \"JAVA\"print(findMinInsert(Input, len(Input))) # This code is contributed# by Smitha", "e": 3673, "s": 2818, "text": null }, { "code": "// C# program to find minimum number// of insertions on left side to form// a palindrome.using System;using System.Text; class GFG { // Returns true if a string // str[st..end] is palindrome static bool isPalin(char[] str, int st, int end) { while (st < end) { if (str[st] != str[end]) return false; st++; end--; } return true; } // Returns count of insertions on // left side to make str[] a palindrome static int findMinInsert(char[] str, int n) { // Find the largest prefix of given string // that is palindrome. for (int i = n - 1; i >= 0; i--) { // Characters after the palindromic // prefix must be added at the // beginning also to make the // complete string palindrome if (isPalin(str, 0, i)) return (n - i - 1); } return 0; } // Driver Code public static void Main(string[] args) { char[] Input = \"JAVA\".ToCharArray(); Console.Write(findMinInsert(Input, Input.Length)); }} // This code is contributed by rutvik_56", "e": 4834, "s": 3673, "text": null }, { "code": "<script>// javascript program to find minimum number of insertions// on left side to form a palindrome. // Returns true if a string str[st..end] is palindromefunction isPalin(str,st,end){ while (st < end) { if (str[st] != str[end]) return false; st++; end--; } return true;} // Returns count of insertions on left side to make// str[] a palindromefunction findMinInsert(str,n){ // Find the largest prefix of given string // that is palindrome. for (let i = n - 1; i >= 0; i--) { // Characters after the palindromic prefix // must be added at the beginning also to make // the complete string palindrome if (isPalin(str, 0, i)) return (n - i - 1); }} let Input = \"JAVA\"; document.write(findMinInsert(Input,Input.length)); // This code is contributed by vaibhavrabadiya07. </script>", "e": 5733, "s": 4834, "text": null }, { "code": null, "e": 5735, "s": 5733, "text": "3" }, { "code": null, "e": 5758, "s": 5735, "text": "Time Complexity: O(n2)" }, { "code": null, "e": 5780, "s": 5758, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 5959, "s": 5780, "text": "Thanks to Utkarsh Trivedi for suggesting this solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 6075, "s": 5959, "text": "Here we’ll preprocess the string and use the lps[] to skip the characters and store the longest palindromic prefix." }, { "code": null, "e": 6151, "s": 6075, "text": "For example: s = \"AABAACAABAA”, \nlps[] is [0, 1, 0, 1, 2, 0, 1, 2, 3, 4, 5]" }, { "code": null, "e": 6398, "s": 6151, "text": "In the above example we clearly see that the lps[] can give the length of longest proper palindromic prefix. But here we need longest palindromic prefix not proper palindromic prefix. So, to handle this we can we can append the reverse of S in S." }, { "code": null, "e": 6548, "s": 6398, "text": "For Example: s = ABBC\nnewS = \"ABBC\" + \"#\" + \"CBBA\"\nlps[] for newS is [0 0 0 0 0 0 0 0 1 1]\nAs 1 is there at the end of lps[]. so our ans is 4 - 1 = 3" }, { "code": null, "e": 6614, "s": 6548, "text": "Using the above logic, we can get the solution in O(N) time only." }, { "code": null, "e": 6618, "s": 6614, "text": "C++" }, { "code": "#include <bits/stdc++.h>using namespace std;// using kmp algorithmint find_lps(string str){ int n = str.length(); vector<int> lps(n, 0); // initialized with 0 int len = 0; // length of previous longest prefix suffix // the loop calculates lps[i] for i = 1 to M-1 int i = 1; while (i < n) { if (str[len] == str[i]) { lps[i++] = ++len; } else { if (len != 0) len = lps[len - 1]; else lps[i++] = 0; } } return lps[n - 1];}int main(){ string s = \"AABAACAABAA\"; string rev = s; reverse(rev.begin(), rev.end()); string newS = s + \"#\" + rev; int len = find_lps(newS); cout << s.length() - len << endl; return 0;}", "e": 7361, "s": 6618, "text": null }, { "code": null, "e": 7363, "s": 7361, "text": "0" }, { "code": null, "e": 7438, "s": 7363, "text": "Time Complexity: O(N),Auxiliary Space: O(N) where N is the length of newS." }, { "code": null, "e": 7459, "s": 7438, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 7469, "s": 7459, "text": "rutvik_56" }, { "code": null, "e": 7479, "s": 7469, "text": "pratham76" }, { "code": null, "e": 7498, "s": 7479, "text": "vaibhavrabadiya117" }, { "code": null, "e": 7508, "s": 7498, "text": "manish_kr" }, { "code": null, "e": 7523, "s": 7508, "text": "shivamanandrj9" }, { "code": null, "e": 7540, "s": 7523, "text": "hardikkoriintern" }, { "code": null, "e": 7548, "s": 7540, "text": "Strings" }, { "code": null, "e": 7556, "s": 7548, "text": "Strings" }, { "code": null, "e": 7654, "s": 7556, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7692, "s": 7654, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 7753, "s": 7692, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 7798, "s": 7753, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 7862, "s": 7798, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 7898, "s": 7862, "text": "Convert string to char array in C++" }, { "code": null, "e": 7950, "s": 7898, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 7982, "s": 7950, "text": "Reverse words in a given string" }, { "code": null, "e": 8027, "s": 7982, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 8071, "s": 8027, "text": "Reverse string in Python (6 different ways)" } ]
statsmodels.jarque_bera() in Python
26 Mar, 2020 With the help of statsmodels.jarque_bera() method, we can get the jarque bera test for normality and it’s a test based on skewness, and the kurtosis, and has an asymptotic distribution. Syntax : statsmodels.jarque_bera(residual, axis)Return : Return the jarque bera test statistics, pvalue, skewness, and the kurtosis. Example #1 :In this example we can see that by using statsmodels.jarque_bera() method, we are able to get the jarque bera test statistics, pvalue, skewness and kurtosis by using this method. # import numpy and statsmodelsimport numpy as npfrom statsmodels.stats.stattools import jarque_bera g = np.array([1, 2, 3])# Using statsmodels.jarque_bera() methodgfg = jarque_bera(g) print(gfg) Output : (0.28125, 0.8688150562628432, 0.0, 1.5) Example #2 : # import numpy and statsmodelsimport numpy as npfrom statsmodels.stats.stattools import jarque_bera g = np.array([1, 2, 3, -1, -2, -3])# Using statsmodels.jarque_bera() methodgfg = jarque_bera(g) print(gfg) Output : (0.5625000000000003, 0.7548396019890072, 0.0, 1.4999999999999996) Python-statsmodels 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 Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Introduction To PYTHON Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2020" }, { "code": null, "e": 214, "s": 28, "text": "With the help of statsmodels.jarque_bera() method, we can get the jarque bera test for normality and it’s a test based on skewness, and the kurtosis, and has an asymptotic distribution." }, { "code": null, "e": 347, "s": 214, "text": "Syntax : statsmodels.jarque_bera(residual, axis)Return : Return the jarque bera test statistics, pvalue, skewness, and the kurtosis." }, { "code": null, "e": 538, "s": 347, "text": "Example #1 :In this example we can see that by using statsmodels.jarque_bera() method, we are able to get the jarque bera test statistics, pvalue, skewness and kurtosis by using this method." }, { "code": "# import numpy and statsmodelsimport numpy as npfrom statsmodels.stats.stattools import jarque_bera g = np.array([1, 2, 3])# Using statsmodels.jarque_bera() methodgfg = jarque_bera(g) print(gfg)", "e": 735, "s": 538, "text": null }, { "code": null, "e": 744, "s": 735, "text": "Output :" }, { "code": null, "e": 784, "s": 744, "text": "(0.28125, 0.8688150562628432, 0.0, 1.5)" }, { "code": null, "e": 797, "s": 784, "text": "Example #2 :" }, { "code": "# import numpy and statsmodelsimport numpy as npfrom statsmodels.stats.stattools import jarque_bera g = np.array([1, 2, 3, -1, -2, -3])# Using statsmodels.jarque_bera() methodgfg = jarque_bera(g) print(gfg)", "e": 1006, "s": 797, "text": null }, { "code": null, "e": 1015, "s": 1006, "text": "Output :" }, { "code": null, "e": 1081, "s": 1015, "text": "(0.5625000000000003, 0.7548396019890072, 0.0, 1.4999999999999996)" }, { "code": null, "e": 1100, "s": 1081, "text": "Python-statsmodels" }, { "code": null, "e": 1107, "s": 1100, "text": "Python" }, { "code": null, "e": 1205, "s": 1107, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1223, "s": 1205, "text": "Python Dictionary" }, { "code": null, "e": 1265, "s": 1223, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1287, "s": 1265, "text": "Enumerate() in Python" }, { "code": null, "e": 1313, "s": 1287, "text": "Python String | replace()" }, { "code": null, "e": 1345, "s": 1313, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1374, "s": 1345, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1401, "s": 1374, "text": "Python Classes and Objects" }, { "code": null, "e": 1424, "s": 1401, "text": "Introduction To PYTHON" }, { "code": null, "e": 1445, "s": 1424, "text": "Python OOPs Concepts" } ]