title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How to make the web page height to fit screen height with HTML?
|
Many ways are available to make the web page height to fit the screen height β
Give relative heights β
html, body {
height: 100%;
}
You can also give fixed positioning β
#main
{
position:fixed;
top:0px;
bottom:0px;
left:0px;
right:0px;
}
You can also use Viewport height to fulfill your purpose β
height: 100vh;
|
[
{
"code": null,
"e": 1141,
"s": 1062,
"text": "Many ways are available to make the web page height to fit the screen height β"
},
{
"code": null,
"e": 1165,
"s": 1141,
"text": "Give relative heights β"
},
{
"code": null,
"e": 1197,
"s": 1165,
"text": "html, body {\n height: 100%;\n}"
},
{
"code": null,
"e": 1235,
"s": 1197,
"text": "You can also give fixed positioning β"
},
{
"code": null,
"e": 1318,
"s": 1235,
"text": "#main\n{\n position:fixed;\n top:0px;\n bottom:0px;\n left:0px;\n right:0px;\n}"
},
{
"code": null,
"e": 1377,
"s": 1318,
"text": "You can also use Viewport height to fulfill your purpose β"
},
{
"code": null,
"e": 1392,
"s": 1377,
"text": "height: 100vh;"
}
] |
Bulma | Tabs - GeeksforGeeks
|
01 Jul, 2020
Bulma is a free and open-source CSS framework based on Flexbox. It is component rich, compatible, and well documented. It is highly responsive in nature. It uses classes to implement its design.
Tabs in Bulma are simple responsive horizontal navigation tabs with different styles. They require the following structure:
A container for the tabs.
The HTML <ul> element for holding the tags.
A list of <li> elements for each tag.
HTML anchor elements <a> for each tag link.
Example 1: This example illustrates simple Bulma tabs.
html
<!DOCTYPE html><html lang="en"><head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <title>Bulma Tabs</title> <style> div.container { margin-top: 80px; } div h1 { margin-bottom: 20px; color: green !important } </style></head><body> <div class='container'> <div class="columns is-centered"> <div class="column is-10"> <div class='has-text-centered'> <h1 class='title'>Tabs</h1> </div> <div class="tabs"> <ul> <li class="is-active" ><a>Home</a> </li> <li><a>Articles</a></li> <li><a>Lectures</a></li> <li><a>Documentation</a></li> <li><a>Contact Us</a></li> </ul> </div> </div> </div> </div></body></html>
Output:
Example 2: This example illustrates tabs with different alignment.
html
<!DOCTYPE html><html lang="en"><head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <title>Bulma Tabs</title> <style> div.container { margin-top: 80px; } div h1 { margin-bottom: 20px; color: green !important } </style></head><body> <div class='container'> <div class='has-text-centered'> <h1 class='title'> Tabs </h1> </div> <div class="tabs"> <ul> <li class="is-active"> <a>Home</a> </li> <li><a>Articles</a></li> <li><a>Lectures</a></li> <li><a>Documentation</a></li> <li><a>Contact Us</a></li> </ul> </div> <!-- Tabs aligned to the center --> <div class="tabs is-centered"> <ul> <li class="is-active"> <a>Home</a> </li> <li><a>Articles</a></li> <li><a>Lectures</a></li> <li><a>Documentation</a></li> <li><a>Contact Us</a></li> </ul> </div> <!-- Tabs aligned to the right --> <div class="tabs is-right"> <ul> <li class="is-active"> <a>Home</a> </li> <li><a>Articles</a></li> <li><a>Lectures</a></li> <li><a>Documentation</a></li> <li><a>Contact Us</a></li> </ul> </div> </div></body></html>
Output:
Example 2: This example illustrates tabs with different sizes.
html
<!DOCTYPE html><html lang="en"><head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <title>Bulma Tabs</title> <style> div.container { margin-top: 80px; } div h1 { margin-bottom: 20px; color: green !important } </style></head><body> <div class='container'> <div class='has-text-centered'> <h1 class='title'> Tabs </h1> </div> <!-- Small sized tabs --> <div class="tabs is-small"> <ul> <li class="is-active"> <a>Home</a> </li> <li><a>Articles</a></li> <li><a>Lectures</a></li> <li><a>Documentation</a></li> <li><a>Contact Us</a></li> </ul> </div> <!-- Medium sized tabs --> <div class="tabs is-medium"> <ul> <li class="is-active"> <a>Home</a> </li> <li><a>Articles</a></li> <li><a>Lectures</a></li> <li><a>Documentation</a></li> <li><a>Contact Us</a></li> </ul> </div> <!-- Large sized tabs --> <div class="tabs is-large"> <ul> <li class="is-active"> <a>Home</a> </li> <li><a>Articles</a></li> <li><a>Lectures</a></li> <li><a>Documentation</a></li> <li><a>Contact Us</a></li> </ul> </div> </div></body></html>
Output:
Example 4: This example illustrates tabs with the use of font-awesome icons.
html
<!DOCTYPE html><html lang="en"> <head> <!-- Bulma CSS CDN --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- FontAwesome CDN --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <title>Bulma Tabs</title> <style> div.container { margin-top: 80px; } div h1 { margin-bottom: 20px; color: green !important } </style></head> <body> <div class='container'> <div class='has-text-centered'> <h1 class='title'>Tabs</h1> </div> <div class="tabs is-centered"> <ul> <li class="is-active"> <a> <!-- Using the home icon --> <span class="icon is-small"> <i class="fas fa-home" aria-hidden="true"> </i> </span> <span>Home</span> </a> </li> <li> <a> <!-- Using the newspaper icon --> <span class="icon is-small"> <i class="fas fa-newspaper" aria-hidden="true"> </i> </span> <span>Articles</span> </a> </li> <li> <a> <!-- Using the music icon --> <span class="icon is-small"> <i class="fas fa-music" aria-hidden="true"> </i> </span> <span>Music</span> </a> </li> <li> <a> <!-- Using the film icon --> <span class="icon is-small"> <i class="fas fa-film" aria-hidden="true"> </i> </span> <span>Videos</span> </a> </li> <li> <a> <!-- Using the file icon --> <span class="icon is-small"> <i class="far fa-file-alt" aria-hidden="true"> </i> </span> <span>Documents</span> </a> </li> </ul> </div> </div></body></html>
Output:
Example 5: This example illustrates boxed style tabs (the active tab will be boxed).
html
<!DOCTYPE html><html lang="en"><head> <!-- Bulma CSS CDN --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- FontAwesome CDN --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <title>Bulma Tabs</title> <style> div.container { margin-top: 80px; } div h1 { margin-bottom: 20px; color: green !important } </style></head><body> <div class='container'> <div class='has-text-centered'> <h1 class='title'>Tabs</h1> </div> <div class="tabs is-boxed"> <ul> <li class="is-active"> <a> <span class="icon is-small"> <i class="fas fa-home" aria-hidden="true"> </i> </span> <span>Home</span> </a> </li> <li> <a> <span class="icon is-small"> <i class="fas fa-newspaper" aria-hidden="true"> </i> </span> <span>Articles</span> </a> </li> <li> <a> <span class="icon is-small"> <i class="fas fa-music" aria-hidden="true"> </i> </span> <span>Music</span> </a> </li> <li> <a> <span class="icon is-small"> <i class="fas fa-film" aria-hidden="true"> </i> </span> <span>Videos</span> </a> </li> <li> <a> <span class="icon is-small"> <i class="far fa-file-alt" aria-hidden="true"> </i> </span> <span>Documents</span> </a> </li> </ul> </div> <div class="tabs is-boxed"> <ul> <li class="is-active"> <a> <span class="icon is-small"> <i class="fas fa-home" aria-hidden="true"> </i> </span> <span>Home</span> </a> </li> <li> <a> <span class="icon is-small"> <i class="fas fa-newspaper" aria-hidden="true"> </i> </span> <span>Articles</span> </a> </li> <li> <a> <span class="icon is-small"> <i class="fas fa-music" aria-hidden="true"> </i> </span> <span>Music</span> </a> </li> <li class='is-active'> <a> <span class="icon is-small"> <i class="fas fa-film" aria-hidden="true"> </i> </span> <span>Videos</span> </a> </li> <li> <a> <span class="icon is-small"> <i class="far fa-file-alt" aria-hidden="true"> </i> </span> <span>Documents</span> </a> </li> </ul> </div> </div></body></html>
Output:
Example 6: This example illustrates mutually exclusive tabs.
html
<!DOCTYPE html><html lang="en"><head> <!-- Bulma CSS CDN --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- FontAwesome CDN --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <title>Bulma Tabs</title> <style> div.container { margin-top: 80px; } div h1 { margin-bottom: 20px; color: green !important } </style></head> <body> <div class='container'> <div class='has-text-centered'> <h1 class='title'>Tabs</h1> </div> <div class="tabs is-toggle is-centered"> <ul> <li class="is-active"> <a> <span class="icon is-small"> <i class="fas fa-home" aria-hidden="true"> </i> </span> <span>Home</span> </a> </li> <li> <a> <span class="icon is-small"> <i class="fas fa-user-circle" aria-hidden="true"> </i> </span> <span>Profile</span> </a> </li> <li> <a> <span class="icon is-small"> <i class="fas fa-newspaper" aria-hidden="true"> </i> </span> <span>Articles</span> </a> </li> <li> <a> <span class="icon is-small"> <i class="fas fa-music" aria-hidden="true"> </i> </span> <span>Music</span> </a> </li> <li> <a> <span class="icon is-small"> <i class="fas fa-film" aria-hidden="true"> </i> </span> <span>Videos</span> </a> </li> <li> <a> <span class="icon is-small"> <i class="far fa-file-alt" aria-hidden="true"> </i> </span> <span>Documents</span> </a> </li> </ul> </div> </div></body></html>
Output:
Example 7: This example illustrates mutually exclusive rounded tabs.
html
<!DOCTYPE html><html lang="en"><head> <!-- Bulma CSS CDN --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- FontAwesome CDN --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <title>Bulma Tabs</title> <style> div.container { margin-top: 80px; } div h1 { margin-bottom: 20px; color: green !important } </style></head><body> <div class='container'> <div class='has-text-centered'> <h1 class='title'>Tabs</h1> </div> <div class="tabs is-toggle is-toggle-rounded is-centered"> <ul> <li class="is-active"> <a> <span class="icon is-small"> <i class="fas fa-home" aria-hidden="true"> </i> </span> <span>Home</span> </a> </li> <li> <a> <span class="icon is-small"> <i class="fas fa-user-circle" aria-hidden="true"> </i> </span> <span>Profile</span> </a> </li> <li> <a> <span class="icon is-small"> <i class="fas fa-newspaper" aria-hidden="true"> </i> </span> <span>Articles</span> </a> </li> <li> <a> <span class="icon is-small"> <i class="fas fa-music" aria-hidden="true"> </i> </span> <span>Music</span> </a> </li> <li> <a> <span class="icon is-small"> <i class="fas fa-film" aria-hidden="true"> </i> </span> <span>Videos</span> </a> </li> <li> <a> <span class="icon is-small"> <i class="far fa-file-alt" aria-hidden="true"> </i> </span> <span>Documents</span> </a> </li> </ul> </div> </div></body></html>
Output:
Bulma
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 27353,
"s": 27325,
"text": "\n01 Jul, 2020"
},
{
"code": null,
"e": 27548,
"s": 27353,
"text": "Bulma is a free and open-source CSS framework based on Flexbox. It is component rich, compatible, and well documented. It is highly responsive in nature. It uses classes to implement its design."
},
{
"code": null,
"e": 27672,
"s": 27548,
"text": "Tabs in Bulma are simple responsive horizontal navigation tabs with different styles. They require the following structure:"
},
{
"code": null,
"e": 27698,
"s": 27672,
"text": "A container for the tabs."
},
{
"code": null,
"e": 27742,
"s": 27698,
"text": "The HTML <ul> element for holding the tags."
},
{
"code": null,
"e": 27780,
"s": 27742,
"text": "A list of <li> elements for each tag."
},
{
"code": null,
"e": 27824,
"s": 27780,
"text": "HTML anchor elements <a> for each tag link."
},
{
"code": null,
"e": 27879,
"s": 27824,
"text": "Example 1: This example illustrates simple Bulma tabs."
},
{
"code": null,
"e": 27884,
"s": 27879,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <title>Bulma Tabs</title> <style> div.container { margin-top: 80px; } div h1 { margin-bottom: 20px; color: green !important } </style></head><body> <div class='container'> <div class=\"columns is-centered\"> <div class=\"column is-10\"> <div class='has-text-centered'> <h1 class='title'>Tabs</h1> </div> <div class=\"tabs\"> <ul> <li class=\"is-active\" ><a>Home</a> </li> <li><a>Articles</a></li> <li><a>Lectures</a></li> <li><a>Documentation</a></li> <li><a>Contact Us</a></li> </ul> </div> </div> </div> </div></body></html>",
"e": 28727,
"s": 27884,
"text": null
},
{
"code": null,
"e": 28736,
"s": 28727,
"text": "Output: "
},
{
"code": null,
"e": 28803,
"s": 28736,
"text": "Example 2: This example illustrates tabs with different alignment."
},
{
"code": null,
"e": 28808,
"s": 28803,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <title>Bulma Tabs</title> <style> div.container { margin-top: 80px; } div h1 { margin-bottom: 20px; color: green !important } </style></head><body> <div class='container'> <div class='has-text-centered'> <h1 class='title'> Tabs </h1> </div> <div class=\"tabs\"> <ul> <li class=\"is-active\"> <a>Home</a> </li> <li><a>Articles</a></li> <li><a>Lectures</a></li> <li><a>Documentation</a></li> <li><a>Contact Us</a></li> </ul> </div> <!-- Tabs aligned to the center --> <div class=\"tabs is-centered\"> <ul> <li class=\"is-active\"> <a>Home</a> </li> <li><a>Articles</a></li> <li><a>Lectures</a></li> <li><a>Documentation</a></li> <li><a>Contact Us</a></li> </ul> </div> <!-- Tabs aligned to the right --> <div class=\"tabs is-right\"> <ul> <li class=\"is-active\"> <a>Home</a> </li> <li><a>Articles</a></li> <li><a>Lectures</a></li> <li><a>Documentation</a></li> <li><a>Contact Us</a></li> </ul> </div> </div></body></html>",
"e": 30122,
"s": 28808,
"text": null
},
{
"code": null,
"e": 30131,
"s": 30122,
"text": "Output: "
},
{
"code": null,
"e": 30194,
"s": 30131,
"text": "Example 2: This example illustrates tabs with different sizes."
},
{
"code": null,
"e": 30199,
"s": 30194,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <title>Bulma Tabs</title> <style> div.container { margin-top: 80px; } div h1 { margin-bottom: 20px; color: green !important } </style></head><body> <div class='container'> <div class='has-text-centered'> <h1 class='title'> Tabs </h1> </div> <!-- Small sized tabs --> <div class=\"tabs is-small\"> <ul> <li class=\"is-active\"> <a>Home</a> </li> <li><a>Articles</a></li> <li><a>Lectures</a></li> <li><a>Documentation</a></li> <li><a>Contact Us</a></li> </ul> </div> <!-- Medium sized tabs --> <div class=\"tabs is-medium\"> <ul> <li class=\"is-active\"> <a>Home</a> </li> <li><a>Articles</a></li> <li><a>Lectures</a></li> <li><a>Documentation</a></li> <li><a>Contact Us</a></li> </ul> </div> <!-- Large sized tabs --> <div class=\"tabs is-large\"> <ul> <li class=\"is-active\"> <a>Home</a> </li> <li><a>Articles</a></li> <li><a>Lectures</a></li> <li><a>Documentation</a></li> <li><a>Contact Us</a></li> </ul> </div> </div></body></html>",
"e": 31533,
"s": 30199,
"text": null
},
{
"code": null,
"e": 31541,
"s": 31533,
"text": "Output:"
},
{
"code": null,
"e": 31618,
"s": 31541,
"text": "Example 4: This example illustrates tabs with the use of font-awesome icons."
},
{
"code": null,
"e": 31623,
"s": 31618,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Bulma CSS CDN --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- FontAwesome CDN --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <title>Bulma Tabs</title> <style> div.container { margin-top: 80px; } div h1 { margin-bottom: 20px; color: green !important } </style></head> <body> <div class='container'> <div class='has-text-centered'> <h1 class='title'>Tabs</h1> </div> <div class=\"tabs is-centered\"> <ul> <li class=\"is-active\"> <a> <!-- Using the home icon --> <span class=\"icon is-small\"> <i class=\"fas fa-home\" aria-hidden=\"true\"> </i> </span> <span>Home</span> </a> </li> <li> <a> <!-- Using the newspaper icon --> <span class=\"icon is-small\"> <i class=\"fas fa-newspaper\" aria-hidden=\"true\"> </i> </span> <span>Articles</span> </a> </li> <li> <a> <!-- Using the music icon --> <span class=\"icon is-small\"> <i class=\"fas fa-music\" aria-hidden=\"true\"> </i> </span> <span>Music</span> </a> </li> <li> <a> <!-- Using the film icon --> <span class=\"icon is-small\"> <i class=\"fas fa-film\" aria-hidden=\"true\"> </i> </span> <span>Videos</span> </a> </li> <li> <a> <!-- Using the file icon --> <span class=\"icon is-small\"> <i class=\"far fa-file-alt\" aria-hidden=\"true\"> </i> </span> <span>Documents</span> </a> </li> </ul> </div> </div></body></html>",
"e": 33758,
"s": 31623,
"text": null
},
{
"code": null,
"e": 33767,
"s": 33758,
"text": "Output: "
},
{
"code": null,
"e": 33852,
"s": 33767,
"text": "Example 5: This example illustrates boxed style tabs (the active tab will be boxed)."
},
{
"code": null,
"e": 33857,
"s": 33852,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <!-- Bulma CSS CDN --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- FontAwesome CDN --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <title>Bulma Tabs</title> <style> div.container { margin-top: 80px; } div h1 { margin-bottom: 20px; color: green !important } </style></head><body> <div class='container'> <div class='has-text-centered'> <h1 class='title'>Tabs</h1> </div> <div class=\"tabs is-boxed\"> <ul> <li class=\"is-active\"> <a> <span class=\"icon is-small\"> <i class=\"fas fa-home\" aria-hidden=\"true\"> </i> </span> <span>Home</span> </a> </li> <li> <a> <span class=\"icon is-small\"> <i class=\"fas fa-newspaper\" aria-hidden=\"true\"> </i> </span> <span>Articles</span> </a> </li> <li> <a> <span class=\"icon is-small\"> <i class=\"fas fa-music\" aria-hidden=\"true\"> </i> </span> <span>Music</span> </a> </li> <li> <a> <span class=\"icon is-small\"> <i class=\"fas fa-film\" aria-hidden=\"true\"> </i> </span> <span>Videos</span> </a> </li> <li> <a> <span class=\"icon is-small\"> <i class=\"far fa-file-alt\" aria-hidden=\"true\"> </i> </span> <span>Documents</span> </a> </li> </ul> </div> <div class=\"tabs is-boxed\"> <ul> <li class=\"is-active\"> <a> <span class=\"icon is-small\"> <i class=\"fas fa-home\" aria-hidden=\"true\"> </i> </span> <span>Home</span> </a> </li> <li> <a> <span class=\"icon is-small\"> <i class=\"fas fa-newspaper\" aria-hidden=\"true\"> </i> </span> <span>Articles</span> </a> </li> <li> <a> <span class=\"icon is-small\"> <i class=\"fas fa-music\" aria-hidden=\"true\"> </i> </span> <span>Music</span> </a> </li> <li class='is-active'> <a> <span class=\"icon is-small\"> <i class=\"fas fa-film\" aria-hidden=\"true\"> </i> </span> <span>Videos</span> </a> </li> <li> <a> <span class=\"icon is-small\"> <i class=\"far fa-file-alt\" aria-hidden=\"true\"> </i> </span> <span>Documents</span> </a> </li> </ul> </div> </div></body></html>",
"e": 36981,
"s": 33857,
"text": null
},
{
"code": null,
"e": 36990,
"s": 36981,
"text": "Output: "
},
{
"code": null,
"e": 37051,
"s": 36990,
"text": "Example 6: This example illustrates mutually exclusive tabs."
},
{
"code": null,
"e": 37056,
"s": 37051,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <!-- Bulma CSS CDN --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- FontAwesome CDN --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <title>Bulma Tabs</title> <style> div.container { margin-top: 80px; } div h1 { margin-bottom: 20px; color: green !important } </style></head> <body> <div class='container'> <div class='has-text-centered'> <h1 class='title'>Tabs</h1> </div> <div class=\"tabs is-toggle is-centered\"> <ul> <li class=\"is-active\"> <a> <span class=\"icon is-small\"> <i class=\"fas fa-home\" aria-hidden=\"true\"> </i> </span> <span>Home</span> </a> </li> <li> <a> <span class=\"icon is-small\"> <i class=\"fas fa-user-circle\" aria-hidden=\"true\"> </i> </span> <span>Profile</span> </a> </li> <li> <a> <span class=\"icon is-small\"> <i class=\"fas fa-newspaper\" aria-hidden=\"true\"> </i> </span> <span>Articles</span> </a> </li> <li> <a> <span class=\"icon is-small\"> <i class=\"fas fa-music\" aria-hidden=\"true\"> </i> </span> <span>Music</span> </a> </li> <li> <a> <span class=\"icon is-small\"> <i class=\"fas fa-film\" aria-hidden=\"true\"> </i> </span> <span>Videos</span> </a> </li> <li> <a> <span class=\"icon is-small\"> <i class=\"far fa-file-alt\" aria-hidden=\"true\"> </i> </span> <span>Documents</span> </a> </li> </ul> </div> </div></body></html>",
"e": 39163,
"s": 37056,
"text": null
},
{
"code": null,
"e": 39172,
"s": 39163,
"text": "Output: "
},
{
"code": null,
"e": 39241,
"s": 39172,
"text": "Example 7: This example illustrates mutually exclusive rounded tabs."
},
{
"code": null,
"e": 39246,
"s": 39241,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <!-- Bulma CSS CDN --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- FontAwesome CDN --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <title>Bulma Tabs</title> <style> div.container { margin-top: 80px; } div h1 { margin-bottom: 20px; color: green !important } </style></head><body> <div class='container'> <div class='has-text-centered'> <h1 class='title'>Tabs</h1> </div> <div class=\"tabs is-toggle is-toggle-rounded is-centered\"> <ul> <li class=\"is-active\"> <a> <span class=\"icon is-small\"> <i class=\"fas fa-home\" aria-hidden=\"true\"> </i> </span> <span>Home</span> </a> </li> <li> <a> <span class=\"icon is-small\"> <i class=\"fas fa-user-circle\" aria-hidden=\"true\"> </i> </span> <span>Profile</span> </a> </li> <li> <a> <span class=\"icon is-small\"> <i class=\"fas fa-newspaper\" aria-hidden=\"true\"> </i> </span> <span>Articles</span> </a> </li> <li> <a> <span class=\"icon is-small\"> <i class=\"fas fa-music\" aria-hidden=\"true\"> </i> </span> <span>Music</span> </a> </li> <li> <a> <span class=\"icon is-small\"> <i class=\"fas fa-film\" aria-hidden=\"true\"> </i> </span> <span>Videos</span> </a> </li> <li> <a> <span class=\"icon is-small\"> <i class=\"far fa-file-alt\" aria-hidden=\"true\"> </i> </span> <span>Documents</span> </a> </li> </ul> </div> </div></body></html>",
"e": 41385,
"s": 39246,
"text": null
},
{
"code": null,
"e": 41393,
"s": 41385,
"text": "Output:"
},
{
"code": null,
"e": 41399,
"s": 41393,
"text": "Bulma"
},
{
"code": null,
"e": 41403,
"s": 41399,
"text": "CSS"
},
{
"code": null,
"e": 41420,
"s": 41403,
"text": "Web Technologies"
},
{
"code": null,
"e": 41518,
"s": 41420,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41568,
"s": 41518,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 41630,
"s": 41568,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 41678,
"s": 41630,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 41736,
"s": 41678,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 41791,
"s": 41736,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 41831,
"s": 41791,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 41864,
"s": 41831,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 41909,
"s": 41864,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 41952,
"s": 41909,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to get the size of a string in Python?
|
Python has a method called len() that gives us the length of any composite object. To get the length of a string, just pass the string to the len() call.
print(len('Hello World!'))
12
If you want the size of the string in bytes, you can use the getsizeof() method from the sys module.
from sys import getsizeof
getsizeof('Hello World!')
33
You can read more about it at sys.getsizeof()
|
[
{
"code": null,
"e": 1217,
"s": 1062,
"text": "Python has a method called len() that gives us the length of any composite object. To get the length of a string, just pass the string to the len() call. "
},
{
"code": null,
"e": 1244,
"s": 1217,
"text": "print(len('Hello World!'))"
},
{
"code": null,
"e": 1247,
"s": 1244,
"text": "12"
},
{
"code": null,
"e": 1349,
"s": 1247,
"text": "If you want the size of the string in bytes, you can use the getsizeof() method from the sys module. "
},
{
"code": null,
"e": 1401,
"s": 1349,
"text": "from sys import getsizeof\ngetsizeof('Hello World!')"
},
{
"code": null,
"e": 1404,
"s": 1401,
"text": "33"
},
{
"code": null,
"e": 1450,
"s": 1404,
"text": "You can read more about it at sys.getsizeof()"
}
] |
Abstraction by Parameterization and Specification in Java - GeeksforGeeks
|
02 Nov, 2020
Abstraction by Parameterization and specification both are important methods in Java. We do this in hope of simplifying our analysis by separating attributes and details implementation for user requirements by showing the essential part to the user and hiding certain details for the various purposes like security, maintenance, etc.
Abstractions help us in many ways like an easy way to arrange code.
It also helps in decomposing big steps into smaller steps.
It is useful for suppresses details and simplifying interaction.
Abstraction plays an important role in improving the maintenance part of the project.
Example:
Basically abstraction is a method to provide simplicity by hiding all the mechanisms behind them. For example when someone calls you so you see on your screen that xyz is calling you with a green icon to receive and red icon with a reject option and some messaging option but, what you do not see is the all the backend mechanism that how someone is calling you how by tapping on-screen icon you can receive/reject or text someone how itβs going to connect to caller all the things. This way abstraction makes things simple.
Java
// A sample program to demonstrate// Abstraction program in Java // Consider a Student_Record class. abstract class Student_Record { // It's an Abstract method does // not contain body. public abstract void Student_Fee_Record(); // Student_Info is a normal method. public void Student_Info() { String name = "Ashish"; int roll_no = 12345; System.out.println("Hello! " + name + " your roll_no is :" + roll_no); }} // Student_marks is a subclass which// is extended from Student_Record.class Student_Fee extends Student_Record { public void Student_Fee_Record() { int Fee = 1000; // Here is provided body of // Student_Fee_Record(). System.out.println("Fee :" + Fee); }} class Student_Data { public static void main(String[] args) { // Create a Student_Fee object Student_Fee s1 = new Student_Fee(); s1.Student_Fee_Record(); s1.Student_Info(); }}
Output :
Fee :1000
Hello! Ashish your roll_no is :12345
Methods of Abstraction :
Abstraction by Parameterization.
Abstraction by Specification.
Abstraction by Parameterization :
It abstracts from the identity of the data by replacing them with parameters.
Example β
x % 2 = 0
It describes a computation that when we divide a number x to 2 then the remainder is equal to zero which we use for finding that given number x is even or not.
x : int(x % 2 == 0)(y)
It is identical in meaning to
y % 2==0
In more familiar notation, we might denote the previous expression by the following expression given below.
Java
class Abstraction { // Abstraction by parameterization int Even(int x) { if (x % 2 == 0) return x; }}
Abstraction by Specification:
It abstracts from the implementation details (how the module is implemented) to the behavior users can depend on (what the module does). It isolates modules from one anotherβs implementations.
It allows us to abstract from the computation described by the body of a procedure to the end that procedure was designed to accomplish. We do this by associating with each other procedure a specification of its intended effect and then considering the meaning of a procedure call to be based on this specification rather than on the procedureβs body.
Even-odd procedure:
Java
int Even(int x) { // REQUIRES: num x is only integer // MODIFIES: system.out // EFFECTS : is num x % 2==0 // then num x is even else it is odd. if (x % 2 == 0) { system.out.print(num + "is even ") else system.out .print(num + "is odd") }}
Example:
In this program, you will see how you can write the logic for a user like if the user wants only input any number and just to know whether a given number is odd or even the logic of the program is given below to check the even and odd for any user input number.
Input : 11
Output : Odd
Input : 52
Output : Even
Java
import java.util.Scanner; class CheckEvenOdd { // REQUIRES:num x is only integer // MODIFIES:System.out // EFFECT:is num x % 2 == 0 // then x is even else odd public static void main(String args[]) { int num; System.out.println("Enter an Integer number:"); Scanner input = new Scanner(System.in); num = input.nextInt(); if (num % 2 == 0) System.out.println("Entered number is even"); else System.out.println("Entered number is odd"); }}
Input:
78
Output :
Enter an Integer number:
78
Entered number is even
Java-Object Oriented
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
StringBuilder Class in Java with Examples
HashMap get() Method in Java
Functional Interfaces in Java
Strings in Java
|
[
{
"code": null,
"e": 23894,
"s": 23866,
"text": "\n02 Nov, 2020"
},
{
"code": null,
"e": 24228,
"s": 23894,
"text": "Abstraction by Parameterization and specification both are important methods in Java. We do this in hope of simplifying our analysis by separating attributes and details implementation for user requirements by showing the essential part to the user and hiding certain details for the various purposes like security, maintenance, etc."
},
{
"code": null,
"e": 24296,
"s": 24228,
"text": "Abstractions help us in many ways like an easy way to arrange code."
},
{
"code": null,
"e": 24355,
"s": 24296,
"text": "It also helps in decomposing big steps into smaller steps."
},
{
"code": null,
"e": 24420,
"s": 24355,
"text": "It is useful for suppresses details and simplifying interaction."
},
{
"code": null,
"e": 24506,
"s": 24420,
"text": "Abstraction plays an important role in improving the maintenance part of the project."
},
{
"code": null,
"e": 24515,
"s": 24506,
"text": "Example:"
},
{
"code": null,
"e": 25040,
"s": 24515,
"text": "Basically abstraction is a method to provide simplicity by hiding all the mechanisms behind them. For example when someone calls you so you see on your screen that xyz is calling you with a green icon to receive and red icon with a reject option and some messaging option but, what you do not see is the all the backend mechanism that how someone is calling you how by tapping on-screen icon you can receive/reject or text someone how itβs going to connect to caller all the things. This way abstraction makes things simple."
},
{
"code": null,
"e": 25045,
"s": 25040,
"text": "Java"
},
{
"code": "// A sample program to demonstrate// Abstraction program in Java // Consider a Student_Record class. abstract class Student_Record { // It's an Abstract method does // not contain body. public abstract void Student_Fee_Record(); // Student_Info is a normal method. public void Student_Info() { String name = \"Ashish\"; int roll_no = 12345; System.out.println(\"Hello! \" + name + \" your roll_no is :\" + roll_no); }} // Student_marks is a subclass which// is extended from Student_Record.class Student_Fee extends Student_Record { public void Student_Fee_Record() { int Fee = 1000; // Here is provided body of // Student_Fee_Record(). System.out.println(\"Fee :\" + Fee); }} class Student_Data { public static void main(String[] args) { // Create a Student_Fee object Student_Fee s1 = new Student_Fee(); s1.Student_Fee_Record(); s1.Student_Info(); }}",
"e": 26097,
"s": 25045,
"text": null
},
{
"code": null,
"e": 26106,
"s": 26097,
"text": "Output :"
},
{
"code": null,
"e": 26154,
"s": 26106,
"text": "Fee :1000\nHello! Ashish your roll_no is :12345\n"
},
{
"code": null,
"e": 26179,
"s": 26154,
"text": "Methods of Abstraction :"
},
{
"code": null,
"e": 26212,
"s": 26179,
"text": "Abstraction by Parameterization."
},
{
"code": null,
"e": 26242,
"s": 26212,
"text": "Abstraction by Specification."
},
{
"code": null,
"e": 26276,
"s": 26242,
"text": "Abstraction by Parameterization :"
},
{
"code": null,
"e": 26354,
"s": 26276,
"text": "It abstracts from the identity of the data by replacing them with parameters."
},
{
"code": null,
"e": 26364,
"s": 26354,
"text": "Example β"
},
{
"code": null,
"e": 26377,
"s": 26364,
"text": "x % 2 = 0\n"
},
{
"code": null,
"e": 26537,
"s": 26377,
"text": "It describes a computation that when we divide a number x to 2 then the remainder is equal to zero which we use for finding that given number x is even or not."
},
{
"code": null,
"e": 26561,
"s": 26537,
"text": "x : int(x % 2 == 0)(y)\n"
},
{
"code": null,
"e": 26592,
"s": 26561,
"text": "It is identical in meaning to "
},
{
"code": null,
"e": 26602,
"s": 26592,
"text": "y % 2==0\n"
},
{
"code": null,
"e": 26710,
"s": 26602,
"text": "In more familiar notation, we might denote the previous expression by the following expression given below."
},
{
"code": null,
"e": 26715,
"s": 26710,
"text": "Java"
},
{
"code": "class Abstraction { // Abstraction by parameterization int Even(int x) { if (x % 2 == 0) return x; }}",
"e": 26849,
"s": 26715,
"text": null
},
{
"code": null,
"e": 26879,
"s": 26849,
"text": "Abstraction by Specification:"
},
{
"code": null,
"e": 27072,
"s": 26879,
"text": "It abstracts from the implementation details (how the module is implemented) to the behavior users can depend on (what the module does). It isolates modules from one anotherβs implementations."
},
{
"code": null,
"e": 27424,
"s": 27072,
"text": "It allows us to abstract from the computation described by the body of a procedure to the end that procedure was designed to accomplish. We do this by associating with each other procedure a specification of its intended effect and then considering the meaning of a procedure call to be based on this specification rather than on the procedureβs body."
},
{
"code": null,
"e": 27444,
"s": 27424,
"text": "Even-odd procedure:"
},
{
"code": null,
"e": 27449,
"s": 27444,
"text": "Java"
},
{
"code": "int Even(int x) { // REQUIRES: num x is only integer // MODIFIES: system.out // EFFECTS : is num x % 2==0 // then num x is even else it is odd. if (x % 2 == 0) { system.out.print(num + \"is even \") else system.out .print(num + \"is odd\") }}",
"e": 27727,
"s": 27449,
"text": null
},
{
"code": null,
"e": 27736,
"s": 27727,
"text": "Example:"
},
{
"code": null,
"e": 27998,
"s": 27736,
"text": "In this program, you will see how you can write the logic for a user like if the user wants only input any number and just to know whether a given number is odd or even the logic of the program is given below to check the even and odd for any user input number."
},
{
"code": null,
"e": 28049,
"s": 27998,
"text": "Input : 11\nOutput : Odd\n\nInput : 52\nOutput : Even\n"
},
{
"code": null,
"e": 28054,
"s": 28049,
"text": "Java"
},
{
"code": "import java.util.Scanner; class CheckEvenOdd { // REQUIRES:num x is only integer // MODIFIES:System.out // EFFECT:is num x % 2 == 0 // then x is even else odd public static void main(String args[]) { int num; System.out.println(\"Enter an Integer number:\"); Scanner input = new Scanner(System.in); num = input.nextInt(); if (num % 2 == 0) System.out.println(\"Entered number is even\"); else System.out.println(\"Entered number is odd\"); }}",
"e": 28585,
"s": 28054,
"text": null
},
{
"code": null,
"e": 28592,
"s": 28585,
"text": "Input:"
},
{
"code": null,
"e": 28595,
"s": 28592,
"text": "78"
},
{
"code": null,
"e": 28604,
"s": 28595,
"text": "Output :"
},
{
"code": null,
"e": 28656,
"s": 28604,
"text": "Enter an Integer number:\n78\nEntered number is even\n"
},
{
"code": null,
"e": 28677,
"s": 28656,
"text": "Java-Object Oriented"
},
{
"code": null,
"e": 28682,
"s": 28677,
"text": "Java"
},
{
"code": null,
"e": 28687,
"s": 28682,
"text": "Java"
},
{
"code": null,
"e": 28785,
"s": 28687,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28794,
"s": 28785,
"text": "Comments"
},
{
"code": null,
"e": 28807,
"s": 28794,
"text": "Old Comments"
},
{
"code": null,
"e": 28853,
"s": 28807,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28874,
"s": 28853,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28889,
"s": 28874,
"text": "Stream In Java"
},
{
"code": null,
"e": 28908,
"s": 28889,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28925,
"s": 28908,
"text": "Generics in Java"
},
{
"code": null,
"e": 28968,
"s": 28925,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 29010,
"s": 28968,
"text": "StringBuilder Class in Java with Examples"
},
{
"code": null,
"e": 29039,
"s": 29010,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 29069,
"s": 29039,
"text": "Functional Interfaces in Java"
}
] |
How to trim down non printable characters from a string in Python?
|
If you have only ASCII characters and want to remove the non-printable characters, the easiest way is to filter out those characters using string.printable. For example,
>>> import string
>>> filter(lambda x: x in string.printable, '\x01string')
string
The 0x01 was not printed as it is not a printable character. If you need to support Unicode as well, then you need to use the Unicode data module and regexes to remove these characters.
import sys, unicodedata, re
# Get all unicode characters
all_chars = (unichr(i) for i in xrange(sys.maxunicode))
# Get all non printable characters
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) == 'Cc')
# Create regex of above characters
control_char_re = re.compile('[%s]' % re.escape(control_chars))
# Substitute these characters by empty string in the original string.
def remove_control_chars(s):
return control_char_re.sub('', s)
print (remove_control_chars('\x00\x01String'))
This will give the output:
String
|
[
{
"code": null,
"e": 1232,
"s": 1062,
"text": "If you have only ASCII characters and want to remove the non-printable characters, the easiest way is to filter out those characters using string.printable. For example,"
},
{
"code": null,
"e": 1315,
"s": 1232,
"text": ">>> import string\n>>> filter(lambda x: x in string.printable, '\\x01string')\nstring"
},
{
"code": null,
"e": 1501,
"s": 1315,
"text": "The 0x01 was not printed as it is not a printable character. If you need to support Unicode as well, then you need to use the Unicode data module and regexes to remove these characters."
},
{
"code": null,
"e": 2013,
"s": 1501,
"text": "import sys, unicodedata, re\n# Get all unicode characters\nall_chars = (unichr(i) for i in xrange(sys.maxunicode))\n# Get all non printable characters\ncontrol_chars = ''.join(c for c in all_chars if unicodedata.category(c) == 'Cc')\n# Create regex of above characters\ncontrol_char_re = re.compile('[%s]' % re.escape(control_chars))\n# Substitute these characters by empty string in the original string.\ndef remove_control_chars(s):\n return control_char_re.sub('', s)\nprint (remove_control_chars('\\x00\\x01String'))"
},
{
"code": null,
"e": 2040,
"s": 2013,
"text": "This will give the output:"
},
{
"code": null,
"e": 2047,
"s": 2040,
"text": "String"
}
] |
Angular PrimeNG Password Component - GeeksforGeeks
|
24 Aug, 2021
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Password component in Angular PrimeNG.
Password Component: It is used to represent the strength indicator for the password fields.
Properties:
promptLabel: It is used to show some text to prompt password entry. It is of string data type, the default value is null.
mediumRegex: It is the medium regular expression to be used for password checking. It is of string data type, the default value is the regex for a medium-level password.
strongRegex: It is the medium Regular expression to be used for password checking. It is of string data type, the default value is the regex for a strong level password.
weakLabel: It is used to show text for a weak password entry. It is of string data type, the default value is null.
mediumLabel: It is used to show text for a medium password entry. It is of string data type, the default value is null.
strongLabel: It is used to show text for a strong password entry. It is of string data type, the default value is null.
feedback: It is used to show the strength indicator or not. It is of the boolean datatype, the default value is true.
toggleMask: It is used to show an icon to display the password as plain text. It is of the boolean datatype, the default value is false.
appendTo: This property takes the ID of the element on which overlay is appended to. It is of string data type, the default value is null.
inputStyle: It is used to set the Inline style of the input field. It is of string data type, the default value is null.
inputStyleClass: It is used to set the Style class of the input field. It is of string data type, the default value is null.
inputId: It is an ID identifier of the underlying input element. It is of string data type, the default value is null.
style: It is used to set the Inline style of the element. It is of string data type, the default value is null.
styleClass: It is used to set the Style class of the element. It is of string data type, the default value is null.
placeholder: It is used to set the Placeholder text for the input. It is of string data type, the default value is null.
Templates:
header: It is the header part for the element.
content: It is the content part for the element.
footer: It is the footer part for the element.
Styling:
p-password-panel: It is a styling Container of password panel.
p-password-meter: It is a styling Meter element of password strength.
p-password-info: It is a Text to display strength.
Creating Angular application & module installation:
Step 1: Create an Angular application using the following command.ng new appname
Step 1: Create an Angular application using the following command.
ng new appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.
cd appname
Step 3: Install PrimeNG in your given directory.npm install primeng --save
npm install primeicons --save
Step 3: Install PrimeNG in your given directory.
npm install primeng --save
npm install primeicons --save
Project Structure: It will look like the following.
Example 1: This is the basic example that shows how to use the Password component.
app.component.html
<h2>GeeksforGeeks</h2><h5>PrimeNG Password Component</h5><p-password [feedback]="false"></p-password><p-password [disabled]="true" [feedback]="false"></p-password>
app.module.ts
import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { PasswordModule } from "primeng/password"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, PasswordModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}
Output:
Example 2: In this example, we will know how to use the toggleMask property in the password component.
app.component.html
<h2>GeeksforGeeks</h2><h5>PrimeNG password component</h5><p-password [toggleMask] ="true"></p-password>
app.module.ts
import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { PasswordModule } from "primeng/password"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, PasswordModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}
Output:
Reference: https://primefaces.org/primeng/showcase/#/password
Angular-PrimeNG
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular PrimeNG Messages Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 26354,
"s": 26326,
"text": "\n24 Aug, 2021"
},
{
"code": null,
"e": 26638,
"s": 26354,
"text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Password component in Angular PrimeNG."
},
{
"code": null,
"e": 26731,
"s": 26638,
"text": "Password Component: It is used to represent the strength indicator for the password fields. "
},
{
"code": null,
"e": 26743,
"s": 26731,
"text": "Properties:"
},
{
"code": null,
"e": 26865,
"s": 26743,
"text": "promptLabel: It is used to show some text to prompt password entry. It is of string data type, the default value is null."
},
{
"code": null,
"e": 27035,
"s": 26865,
"text": "mediumRegex: It is the medium regular expression to be used for password checking. It is of string data type, the default value is the regex for a medium-level password."
},
{
"code": null,
"e": 27205,
"s": 27035,
"text": "strongRegex: It is the medium Regular expression to be used for password checking. It is of string data type, the default value is the regex for a strong level password."
},
{
"code": null,
"e": 27321,
"s": 27205,
"text": "weakLabel: It is used to show text for a weak password entry. It is of string data type, the default value is null."
},
{
"code": null,
"e": 27441,
"s": 27321,
"text": "mediumLabel: It is used to show text for a medium password entry. It is of string data type, the default value is null."
},
{
"code": null,
"e": 27561,
"s": 27441,
"text": "strongLabel: It is used to show text for a strong password entry. It is of string data type, the default value is null."
},
{
"code": null,
"e": 27680,
"s": 27561,
"text": "feedback: It is used to show the strength indicator or not. It is of the boolean datatype, the default value is true."
},
{
"code": null,
"e": 27817,
"s": 27680,
"text": "toggleMask: It is used to show an icon to display the password as plain text. It is of the boolean datatype, the default value is false."
},
{
"code": null,
"e": 27956,
"s": 27817,
"text": "appendTo: This property takes the ID of the element on which overlay is appended to. It is of string data type, the default value is null."
},
{
"code": null,
"e": 28077,
"s": 27956,
"text": "inputStyle: It is used to set the Inline style of the input field. It is of string data type, the default value is null."
},
{
"code": null,
"e": 28202,
"s": 28077,
"text": "inputStyleClass: It is used to set the Style class of the input field. It is of string data type, the default value is null."
},
{
"code": null,
"e": 28321,
"s": 28202,
"text": "inputId: It is an ID identifier of the underlying input element. It is of string data type, the default value is null."
},
{
"code": null,
"e": 28433,
"s": 28321,
"text": "style: It is used to set the Inline style of the element. It is of string data type, the default value is null."
},
{
"code": null,
"e": 28549,
"s": 28433,
"text": "styleClass: It is used to set the Style class of the element. It is of string data type, the default value is null."
},
{
"code": null,
"e": 28670,
"s": 28549,
"text": "placeholder: It is used to set the Placeholder text for the input. It is of string data type, the default value is null."
},
{
"code": null,
"e": 28681,
"s": 28670,
"text": "Templates:"
},
{
"code": null,
"e": 28728,
"s": 28681,
"text": "header: It is the header part for the element."
},
{
"code": null,
"e": 28777,
"s": 28728,
"text": "content: It is the content part for the element."
},
{
"code": null,
"e": 28824,
"s": 28777,
"text": "footer: It is the footer part for the element."
},
{
"code": null,
"e": 28835,
"s": 28826,
"text": "Styling:"
},
{
"code": null,
"e": 28898,
"s": 28835,
"text": "p-password-panel: It is a styling Container of password panel."
},
{
"code": null,
"e": 28968,
"s": 28898,
"text": "p-password-meter: It is a styling Meter element of password strength."
},
{
"code": null,
"e": 29019,
"s": 28968,
"text": "p-password-info: It is a Text to display strength."
},
{
"code": null,
"e": 29071,
"s": 29019,
"text": "Creating Angular application & module installation:"
},
{
"code": null,
"e": 29152,
"s": 29071,
"text": "Step 1: Create an Angular application using the following command.ng new appname"
},
{
"code": null,
"e": 29219,
"s": 29152,
"text": "Step 1: Create an Angular application using the following command."
},
{
"code": null,
"e": 29234,
"s": 29219,
"text": "ng new appname"
},
{
"code": null,
"e": 29341,
"s": 29234,
"text": "Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname"
},
{
"code": null,
"e": 29438,
"s": 29341,
"text": "Step 2: After creating your project folder i.e. appname, move to it using the following command."
},
{
"code": null,
"e": 29449,
"s": 29438,
"text": "cd appname"
},
{
"code": null,
"e": 29554,
"s": 29449,
"text": "Step 3: Install PrimeNG in your given directory.npm install primeng --save\nnpm install primeicons --save"
},
{
"code": null,
"e": 29603,
"s": 29554,
"text": "Step 3: Install PrimeNG in your given directory."
},
{
"code": null,
"e": 29660,
"s": 29603,
"text": "npm install primeng --save\nnpm install primeicons --save"
},
{
"code": null,
"e": 29712,
"s": 29660,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 29798,
"s": 29714,
"text": "Example 1: This is the basic example that shows how to use the Password component. "
},
{
"code": null,
"e": 29817,
"s": 29798,
"text": "app.component.html"
},
{
"code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Password Component</h5><p-password [feedback]=\"false\"></p-password><p-password [disabled]=\"true\" [feedback]=\"false\"></p-password>",
"e": 29981,
"s": 29817,
"text": null
},
{
"code": null,
"e": 29995,
"s": 29981,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { PasswordModule } from \"primeng/password\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, PasswordModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}",
"e": 30517,
"s": 29995,
"text": null
},
{
"code": null,
"e": 30525,
"s": 30517,
"text": "Output:"
},
{
"code": null,
"e": 30629,
"s": 30525,
"text": "Example 2: In this example, we will know how to use the toggleMask property in the password component. "
},
{
"code": null,
"e": 30648,
"s": 30629,
"text": "app.component.html"
},
{
"code": "<h2>GeeksforGeeks</h2><h5>PrimeNG password component</h5><p-password [toggleMask] =\"true\"></p-password>",
"e": 30752,
"s": 30648,
"text": null
},
{
"code": null,
"e": 30766,
"s": 30752,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { PasswordModule } from \"primeng/password\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, PasswordModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}",
"e": 31289,
"s": 30766,
"text": null
},
{
"code": null,
"e": 31297,
"s": 31289,
"text": "Output:"
},
{
"code": null,
"e": 31359,
"s": 31297,
"text": "Reference: https://primefaces.org/primeng/showcase/#/password"
},
{
"code": null,
"e": 31375,
"s": 31359,
"text": "Angular-PrimeNG"
},
{
"code": null,
"e": 31385,
"s": 31375,
"text": "AngularJS"
},
{
"code": null,
"e": 31402,
"s": 31385,
"text": "Web Technologies"
},
{
"code": null,
"e": 31500,
"s": 31402,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31535,
"s": 31500,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 31570,
"s": 31535,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 31605,
"s": 31570,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 31629,
"s": 31605,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 31682,
"s": 31629,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 31722,
"s": 31682,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31755,
"s": 31722,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31800,
"s": 31755,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31843,
"s": 31800,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to get the value of the rel attribute of a link in JavaScript?
|
To get the value of the rel attribute of a link in JavaScript, use the rel property. The rel is used to set the following status of a page i.e. follow and nofollow.
You can try to run the following code to get the value of the rel attribute of a link.
Live Demo
<!DOCTYPE html>
<html>
<body>
<p><a id="anchorid" rel="nofollow" href="https://www.qries.com/">Qries</a></p>
<script>
var myVal = document.getElementById("anchorid").rel;
document.write("Value of rel attribute: "+myVal);
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1227,
"s": 1062,
"text": "To get the value of the rel attribute of a link in JavaScript, use the rel property. The rel is used to set the following status of a page i.e. follow and nofollow."
},
{
"code": null,
"e": 1314,
"s": 1227,
"text": "You can try to run the following code to get the value of the rel attribute of a link."
},
{
"code": null,
"e": 1324,
"s": 1314,
"text": "Live Demo"
},
{
"code": null,
"e": 1613,
"s": 1324,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <p><a id=\"anchorid\" rel=\"nofollow\" href=\"https://www.qries.com/\">Qries</a></p>\n <script>\n var myVal = document.getElementById(\"anchorid\").rel;\n document.write(\"Value of rel attribute: \"+myVal);\n </script>\n </body>\n</html>"
}
] |
Check if a given Binary Tree is SumTree - GeeksforGeeks
|
10 May, 2022
Write a function that returns true if the given Binary Tree is SumTree else false. A SumTree is a Binary Tree where the value of a node is equal to the sum of the nodes present in its left subtree and right subtree. An empty tree is SumTree and the sum of an empty tree can be considered as 0. A leaf node is also considered as SumTree.
Following is an example of SumTree.
26
/ \
10 3
/ \ \
4 6 3
Method 1 (Simple) Get the sum of nodes in the left subtree and right subtree. Check if the sum calculated is equal to the rootβs data. Also, recursively check if the left and right subtrees are SumTrees.
C++
C
Java
Python3
C#
Javascript
// C++ program to check if Binary tree// is sum tree or not#include <iostream>using namespace std; // A binary tree node has data,// left child and right childstruct node{ int data; struct node* left; struct node* right;}; // A utility function to get the sum// of values in tree with root as rootint sum(struct node *root){ if (root == NULL) return 0; return sum(root->left) + root->data + sum(root->right);} // Returns 1 if sum property holds for// the given node and both of its childrenint isSumTree(struct node* node){ int ls, rs; // If node is NULL or it's a leaf // node then return true if (node == NULL || (node->left == NULL && node->right == NULL)) return 1; // Get sum of nodes in left and // right subtrees ls = sum(node->left); rs = sum(node->right); // If the node and both of its // children satisfy the property // return 1 else 0 if ((node->data == ls + rs) && isSumTree(node->left) && isSumTree(node->right)) return 1; return 0;} // Helper function that allocates a new node// with the given data and NULL left and right// pointers.struct node* newNode(int data){ struct node* node = (struct node*)malloc( sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} // Driver codeint main(){ struct node *root = newNode(26); root->left = newNode(10); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(6); root->right->right = newNode(3); if (isSumTree(root)) cout << "The given tree is a SumTree "; else cout << "The given tree is not a SumTree "; getchar(); return 0;} // This code is contributed by khushboogoyal499
// C program to check if Binary tree// is sum tree or not#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, left child and right child */struct node{ int data; struct node* left; struct node* right;}; /* A utility function to get the sum of values in tree with root as root */int sum(struct node *root){ if(root == NULL) return 0; return sum(root->left) + root->data + sum(root->right);} /* returns 1 if sum property holds for the given node and both of its children */int isSumTree(struct node* node){ int ls, rs; /* If node is NULL or it's a leaf node then return true */ if(node == NULL || (node->left == NULL && node->right == NULL)) return 1; /* Get sum of nodes in left and right subtrees */ ls = sum(node->left); rs = sum(node->right); /* if the node and both of its children satisfy the property return 1 else 0*/ if((node->data == ls + rs)&& isSumTree(node->left) && isSumTree(node->right)) return 1; return 0;} /* Helper function that allocates a new node with the given data and NULL left and right pointers.*/struct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Driver program to test above function */int main(){ struct node *root = newNode(26); root->left = newNode(10); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(6); root->right->right = newNode(3); if(isSumTree(root)) printf("The given tree is a SumTree."); else printf("The given tree is not a SumTree."); getchar(); return 0;}
// Java program to check if Binary tree// is sum tree or notimport java.io.*; // A binary tree node has data,// left child and right childclass Node{ int data; Node left, right, nextRight; // Helper function that allocates a new node // with the given data and NULL left and right // pointers. Node(int item) { data = item; left = right = null; }}class BinaryTree { public static Node root; // A utility function to get the sum // of values in tree with root as root static int sum(Node node) { if(node == null) { return 0; } return (sum(node.left) + node.data+sum(node.right)); } // Returns 1 if sum property holds for // the given node and both of its children static int isSumTree(Node node) { int ls,rs; // If node is NULL or it's a leaf // node then return true if(node == null || (node.left == null && node.right == null)) { return 1; } // Get sum of nodes in left and // right subtrees ls = sum(node.left); rs = sum(node.right); // If the node and both of its // children satisfy the property // return 1 else 0 if((node.data == ls + rs) && isSumTree(node.left) != 0 && isSumTree(node.right) != 0) { return 1; } return 0; } // Driver code public static void main (String[] args) { BinaryTree tree=new BinaryTree(); tree.root=new Node(26); tree.root.left=new Node(10); tree.root.right=new Node(3); tree.root.left.left=new Node(4); tree.root.left.right=new Node(6); tree.root.right.right=new Node(3); if(isSumTree(root) != 0) { System.out.println("The given tree is a SumTree"); } else { System.out.println("The given tree is not a SumTree"); } }} // This code is contributed by rag2127
# Python3 program to implement# the above approach # A binary tree node has data,# left child and right childclass node: def __init__(self, x): self.data = x self.left = None self.right = None # A utility function to get the sum# of values in tree with root as rootdef sum(root): if(root == None): return 0 return (sum(root.left) + root.data + sum(root.right)) # returns 1 if sum property holds# for the given node and both of# its childrendef isSumTree(node): # ls, rs # If node is None or it's a leaf # node then return true if(node == None or (node.left == None and node.right == None)): return 1 # Get sum of nodes in left and # right subtrees ls = sum(node.left) rs = sum(node.right) # if the node and both of its children # satisfy the property return 1 else 0 if((node.data == ls + rs) and isSumTree(node.left) and isSumTree(node.right)): return 1 return 0 # Driver codeif __name__ == '__main__': root = node(26) root.left= node(10) root.right = node(3) root.left.left = node(4) root.left.right = node(6) root.right.right = node(3) if(isSumTree(root)): print("The given tree is a SumTree ") else: print("The given tree is not a SumTree ") # This code is contributed by Mohit Kumar 29
// C# program to check if Binary tree// is sum tree or notusing System; // A binary tree node has data,// left child and right childpublic class Node{ public int data; public Node left, right, nextRight; // Helper function that allocates a new node // with the given data and NULL left and right // pointers. public Node(int item) { data = item; left = right = null; }} class BinaryTree { public Node root; // A utility function to get the sum // of values in tree with root as root int sum(Node node) { if(node == null) { return 0; } return (sum(node.left) + node.data+sum(node.right)); } // Returns 1 if sum property holds for // the given node and both of its children int isSumTree(Node node) { int ls,rs; // If node is NULL or it's a leaf // node then return true if(node == null || (node.left == null && node.right == null)) { return 1; } // Get sum of nodes in left and // right subtrees ls = sum(node.left); rs = sum(node.right); // If the node and both of its // children satisfy the property // return 1 else 0 if((node.data == ls + rs) && isSumTree(node.left) != 0 && isSumTree(node.right) != 0) { return 1; } return 0; } // Driver code public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(26); tree.root.left = new Node(10); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(6); tree.root.right.right = new Node(3); if(tree.isSumTree(tree.root) != 0) { Console.WriteLine("The given tree is a SumTree"); } else { Console.WriteLine("The given tree is not a SumTree"); } }} // This code is contributed by Pratham76
<script>// Javascript program to check if Binary tree// is sum tree or not // A binary tree node has data, // left child and right child class Node { // Helper function that allocates a new node // with the given data and NULL left and right // pointers. constructor(x) { this.data = x; this.left = null; this.right = null; } } let root; // A utility function to get the sum // of values in tree with root as root function sum(node) { if(node == null) { return 0; } return (sum(node.left) + node.data+sum(node.right)); } // Returns 1 if sum property holds for // the given node and both of its children function isSumTree(node) { let ls,rs; // If node is NULL or it's a leaf // node then return true if(node == null || (node.left == null && node.right == null)) { return 1; } // Get sum of nodes in left and // right subtrees ls = sum(node.left); rs = sum(node.right); // If the node and both of its // children satisfy the property // return 1 else 0 if((node.data == ls + rs) && isSumTree(node.left) != 0 && isSumTree(node.right) != 0) { return 1; } return 0; } // Driver code root = new Node(26) root.left= new Node(10) root.right = new Node(3) root.left.left = new Node(4) root.left.right = new Node(6) root.right.right = new Node(3) if(isSumTree(root) != 0) { document.write("The given tree is a SumTree"); } else { document.write("The given tree is not a SumTree"); } // This code is contributed by unknown2108</script>
The given tree is a SumTree
Time Complexity: O(n^2) in the worst case. The worst-case occurs for a skewed tree.
Method 2 (Tricky) Method 1 uses sum() to get the sum of nodes in left and right subtrees. Method 2 uses the following rules to get the sum directly. 1) If the node is a leaf node then the sum of the subtree rooted with this node is equal to the value of this node. 2) If the node is not a leaf node then the sum of the subtree rooted with this node is twice the value of this node (Assuming that the tree rooted with this node is SumTree).
C++
C
Java
Python3
C#
Javascript
// C++ program to check if Binary tree// is sum tree or not#include<bits/stdc++.h>using namespace std; /* A binary tree node has data, left child and right child */struct node{ int data; node* left; node* right;}; /* Utility function to check ifthe given node is leaf or not */int isLeaf(node *node){ if(node == NULL) return 0; if(node->left == NULL && node->right == NULL) return 1; return 0;} /* returns 1 if SumTree property holds for the given tree */int isSumTree(node* node){ int ls; // for sum of nodes in left subtree int rs; // for sum of nodes in right subtree /* If node is NULL or it's a leaf node then return true */ if(node == NULL || isLeaf(node)) return 1; if( isSumTree(node->left) && isSumTree(node->right)) { // Get the sum of nodes in left subtree if(node->left == NULL) ls = 0; else if(isLeaf(node->left)) ls = node->left->data; else ls = 2 * (node->left->data); // Get the sum of nodes in right subtree if(node->right == NULL) rs = 0; else if(isLeaf(node->right)) rs = node->right->data; else rs = 2 * (node->right->data); /* If root's data is equal to sum of nodes in left and right subtrees then return 1 else return 0*/ return(node->data == ls + rs); } return 0;} /* Helper function that allocates a new node with the given data and NULL left and right pointers.*/node* newNode(int data){ node* node1 = new node(); node1->data = data; node1->left = NULL; node1->right = NULL; return(node1);} /* Driver code */int main(){ node *root = newNode(26); root->left = newNode(10); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(6); root->right->right = newNode(3); if(isSumTree(root)) cout << "The given tree is a SumTree "; else cout << "The given tree is not a SumTree "; return 0;} // This code is contributed by rutvik_56
// C program to check if Binary tree// is sum tree or not#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, left child and right child */struct node{ int data; struct node* left; struct node* right;}; /* Utility function to check if the given node is leaf or not */int isLeaf(struct node *node){ if(node == NULL) return 0; if(node->left == NULL && node->right == NULL) return 1; return 0;} /* returns 1 if SumTree property holds for the given tree */int isSumTree(struct node* node){ int ls; // for sum of nodes in left subtree int rs; // for sum of nodes in right subtree /* If node is NULL or it's a leaf node then return true */ if(node == NULL || isLeaf(node)) return 1; if( isSumTree(node->left) && isSumTree(node->right)) { // Get the sum of nodes in left subtree if(node->left == NULL) ls = 0; else if(isLeaf(node->left)) ls = node->left->data; else ls = 2*(node->left->data); // Get the sum of nodes in right subtree if(node->right == NULL) rs = 0; else if(isLeaf(node->right)) rs = node->right->data; else rs = 2*(node->right->data); /* If root's data is equal to sum of nodes in left and right subtrees then return 1 else return 0*/ return(node->data == ls + rs); } return 0;} /* Helper function that allocates a new node with the given data and NULL left and right pointers.*/struct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Driver program to test above function */int main(){ struct node *root = newNode(26); root->left = newNode(10); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(6); root->right->right = newNode(3); if(isSumTree(root)) printf("The given tree is a SumTree "); else printf("The given tree is not a SumTree "); getchar(); return 0;}
// Java program to check if Binary tree is sum tree or not /* A binary tree node has data, left child and right child */class Node{ int data; Node left, right, nextRight; Node(int item) { data = item; left = right = nextRight = null; }} class BinaryTree{ Node root; /* Utility function to check if the given node is leaf or not */ int isLeaf(Node node) { if (node == null) return 0; if (node.left == null && node.right == null) return 1; return 0; } /* returns 1 if SumTree property holds for the given tree */ int isSumTree(Node node) { int ls; // for sum of nodes in left subtree int rs; // for sum of nodes in right subtree /* If node is NULL or it's a leaf node then return true */ if (node == null || isLeaf(node) == 1) return 1; if (isSumTree(node.left) != 0 && isSumTree(node.right) != 0) { // Get the sum of nodes in left subtree if (node.left == null) ls = 0; else if (isLeaf(node.left) != 0) ls = node.left.data; else ls = 2 * (node.left.data); // Get the sum of nodes in right subtree if (node.right == null) rs = 0; else if (isLeaf(node.right) != 0) rs = node.right.data; else rs = 2 * (node.right.data); /* If root's data is equal to sum of nodes in left and right subtrees then return 1 else return 0*/ if ((node.data == rs + ls)) return 1; else return 0; } return 0; } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(26); tree.root.left = new Node(10); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(6); tree.root.right.right = new Node(3); if (tree.isSumTree(tree.root) != 0) System.out.println("The given tree is a SumTree"); else System.out.println("The given tree is not a SumTree"); }} // This code has been contributed by Mayank Jaiswal
# Python3 program to check if# Binary tree is sum tree or not # A binary tree node has data,# left child and right childclass node: def __init__(self, x): self.data = x self.left = None self.right = None def isLeaf(node): if(node == None): return 0 if(node.left == None and node.right == None): return 1 return 0 # A utility function to get the sum# of values in tree with root as rootdef sum(root): if(root == None): return 0 return (sum(root.left) + root.data + sum(root.right)) # returns 1 if SumTree property holds# for the given treedef isSumTree(node): # If node is None or # it's a leaf node then return true if(node == None or isLeaf(node)): return 1 if(isSumTree(node.left) and isSumTree(node.right)): # Get the sum of nodes in left subtree if(node.left == None): ls = 0 elif(isLeaf(node.left)): ls = node.left.data else: ls = 2 * (node.left.data) # Get the sum of nodes in right subtree if(node.right == None): rs = 0 elif(isLeaf(node.right)): rs = node.right.data else: rs = 2 * (node.right.data) # If root's data is equal to sum of nodes # in left and right subtrees then return 1 # else return 0 return(node.data == ls + rs) return 0 # Driver codeif __name__ == '__main__': root = node(26) root.left = node(10) root.right = node(3) root.left.left = node(4) root.left.right = node(6) root.right.right = node(3) if(isSumTree(root)): print("The given tree is a SumTree ") else: print("The given tree is not a SumTree ") # This code is contributed by kirtishsurangalikar
// C# program to check if Binary tree// is sum tree or notusing System; // A binary tree node has data, left// child and right childpublic class Node{ public int data; public Node left, right, nextRight; public Node(int d) { data = d; left = right = nextRight = null; }} public class BinaryTree{ public static Node root; // Utility function to check if// the given node is leaf or notpublic int isLeaf(Node node){ if (node == null) return 0; if (node.left == null && node.right == null) return 1; return 0;} // Returns 1 if SumTree property holds// for the given treepublic int isSumTree(Node node){ // For sum of nodes in left subtree int ls; // For sum of nodes in right subtree int rs; // If node is NULL or it's a leaf // node then return true if (node == null || isLeaf(node) == 1) return 1; if (isSumTree(node.left) != 0 && isSumTree(node.right) != 0) { // Get the sum of nodes in left subtree if (node.left == null) ls = 0; else if (isLeaf(node.left) != 0) ls = node.left.data; else ls = 2 * (node.left.data); // Get the sum of nodes in right subtree if (node.right == null) rs = 0; else if (isLeaf(node.right) != 0) rs = node.right.data; else rs = 2 * (node.right.data); // If root's data is equal to sum of // nodes in left and right subtrees // then return 1 else return 0 if ((node.data == rs + ls)) return 1; else return 0; } return 0;} // Driver codestatic public void Main(){ BinaryTree tree = new BinaryTree(); BinaryTree.root = new Node(26); BinaryTree.root.left = new Node(10); BinaryTree.root.right = new Node(3); BinaryTree.root.left.left = new Node(4); BinaryTree.root.left.right = new Node(6); BinaryTree.root.right.right = new Node(3); if (tree.isSumTree(BinaryTree.root) != 0) { Console.WriteLine("The given tree is a SumTree"); } else { Console.WriteLine("The given tree is " + "not a SumTree"); }}} // This code is contributed by avanitrachhadiya2155
<script> // JavaScript program to check // if Binary tree is sum tree or not class Node { constructor(item) { this.data = item; this.left = null; this.right = null; this.nextRight = null; } } let root; /* Utility function to check if the given node is leaf or not */ function isLeaf(node) { if (node == null) return 0; if (node.left == null && node.right == null) return 1; return 0; } /* returns 1 if SumTree property holds for the given tree */ function isSumTree(node) { let ls; // for sum of nodes in left subtree let rs; // for sum of nodes in right subtree /* If node is NULL or it's a leaf node then return true */ if (node == null || isLeaf(node) == 1) return 1; if (isSumTree(node.left) != 0 && isSumTree(node.right) != 0) { // Get the sum of nodes in left subtree if (node.left == null) ls = 0; else if (isLeaf(node.left) != 0) ls = node.left.data; else ls = 2 * (node.left.data); // Get the sum of nodes in right subtree if (node.right == null) rs = 0; else if (isLeaf(node.right) != 0) rs = node.right.data; else rs = 2 * (node.right.data); /* If root's data is equal to sum of nodes in left and right subtrees then return 1 else return 0*/ if ((node.data == rs + ls)) return 1; else return 0; } return 0; } root = new Node(26); root.left = new Node(10); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(6); root.right.right = new Node(3); if (isSumTree(root) != 0) document.write("The given tree is a SumTree"); else document.write("The given tree is not a SumTree"); </script>
Output:
The given tree is a SumTree
Time Complexity: O(n)
Method 3
Similar to postorder traversal iteratively find the sum in each stepReturn left + right + current data if left + right is equal to current node dataElse return -1
Similar to postorder traversal iteratively find the sum in each step
Return left + right + current data if left + right is equal to current node data
Else return -1
C++
C++14
Java
Python3
Javascript
// C++ program to check if Binary tree// is sum tree or not#include<bits/stdc++.h>using namespace std; /* A binary tree node has data,left child and right child */struct node{ int data; node* left; node* right;}; /* Utility function to check ifthe given node is leaf or not */int isLeaf(node *node){ if(node == NULL) return 0; if(node->left == NULL && node->right == NULL) return 1; return 0;} /* returns data if SumTree property holds for the given tree else return -1*/int isSumTree(node* node){ if(node == NULL) return 0; int ls; // for sum of nodes in left subtree int rs; // for sum of nodes in right subtree ls = isSumTree(node->left); if(ls == -1) // To stop for further traversal of tree if found not sumTree return -1; rs = isSumTree(node->right); if(rs == -1) // To stop for further traversal of tree if found not sumTree return -1; if(isLeaf(node) || ls + rs == node->data) return ls + rs + node->data; else return -1; } /* Helper function that allocates a new nodewith the given data and NULL left and rightpointers.*/node* newNode(int data){ node* node1 = new node(); node1->data = data; node1->left = NULL; node1->right = NULL; return(node1);} /* Driver code */int main(){ node *root = newNode(26); root->left = newNode(10); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(6); root->right->right = newNode(3); int total = isSumTree(root); if(total != -1 && total == 2*(root->data)) cout<<"Tree is a Sum Tree"; else cout<<"Given Tree is not sum Tree"; return 0;} // This code is contributed by Mugunthan
// C++ program to check if Binary tree// is sum tree or not#include<bits/stdc++.h>using namespace std; /* A binary tree node has data,left child and right child */struct node{ int data; node* left; node* right;}; /* Utility function to check ifthe given node is leaf or not */int isLeaf(node *node){ if(node == NULL) return 0; if(node->left == NULL && node->right == NULL) return 1; return 0;} /* returns data if SumTree property holds for the given tree else return -1*/int isSumTree(node* node){ if(node == NULL) return 0; int ls; // for sum of nodes in left subtree int rs; // for sum of nodes in right subtree ls = isSumTree(node->left); if(ls == -1) // To stop for further traversal of tree if found not sumTree return -1; rs = isSumTree(node->right); if(rs == -1) // To stop for further traversal of tree if found not sumTree return -1; if(isLeaf(node) || ls + rs == node->data) return ls + rs + node->data; else return -1; } /* Helper function that allocates a new nodewith the given data and NULL left and rightpointers.*/node* newNode(int data){ node* node1 = new node(); node1->data = data; node1->left = NULL; node1->right = NULL; return(node1);} /* Driver code */int main(){ node *root = newNode(26); root->left = newNode(10); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(6); root->right->right = newNode(3); int total = isSumTree(root); if(total != -1 && total == 2*(root->data)) cout<<"Sum Tree"; else cout<<"No sum Tree"; return 0;} // This code is contributed by Mugunthan
// Java program to check if Binary tree// is sum tree or not import java.util.*; class GFG{/* A binary tree node has data,left child and right child */ static class Node {int data;Node left, right; } /* Utility function to check ifthe given node is leaf or not */static int isLeaf(Node node){ if(node == null) return 0; if(node.left == null && node.right == null) return 1; return 0;} /* returns data if SumTree property holds for the given tree else return -1*/static int isSumTree(Node node){ if(node == null) return 0; int ls; // for sum of nodes in left subtree int rs; // for sum of nodes in right subtree ls = isSumTree(node.left); if(ls == -1) // To stop for further traversal of tree if found not sumTree return -1; rs = isSumTree(node.right); if(rs == -1) // To stop for further traversal of tree if found not sumTree return -1; if(isLeaf(node)==1 || ls + rs == node.data) return ls + rs + node.data; else return -1; } /* Helper function that allocates a new nodewith the given data and null left and rightpointers.*/static Node newNode(int data){ Node node1 = new Node(); node1.data = data; node1.left = null; node1.right = null; return(node1);} public static void main(String args[]){ Node root = newNode(26); root.left = newNode(10); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(6); root.right.right = newNode(3); int total = isSumTree(root); if(total != -1 && total == 2*(root.data)) System.out.print("Tree is a Sum Tree"); else System.out.print("Given Tree is not sum Tree");}} // This code is contributed by jana_sayantan.
# Python3 program to check if# Binary tree is sum tree or not # A binary tree node has data,# left child and right childclass node: def __init__(self, x): self.data = x self.left = None self.right = None def isLeaf(node): if(node == None): return 0 if(node.left == None and node.right == None): return 1 return 0 # returns data if SumTree property holds for the given# tree else return -1def isSumTree(node): if(node == None): return 0 ls = isSumTree(node.left) if(ls == -1): #To stop for further traversal of tree if found not sumTree return -1 rs = isSumTree(node.right) if(rs == -1): #To stop for further traversal of tree if found not sumTree return -1 if(isLeaf(node) or ls + rs == node.data): return ls + rs + node.data else: return -1 # Driver codeif __name__ == '__main__': root = node(26) root.left = node(10) root.right = node(3) root.left.left = node(4) root.left.right = node(6) root.right.right = node(3) if(isSumTree(root)): print("The given tree is a SumTree ") else: print("The given tree is not a SumTree ") # This code is contributed by Mugunthan
<script> // JavaScript program to check if// Binary tree is sum tree or not // A binary tree node has data,// left child and right childclass node{ constructor(x){ this.data = x this.left = null this.right = null } } function isLeaf(node){ if(node == null) return 0 if(node.left == null && node.right == null) return 1 return 0} // returns data if SumTree property holds for the given// tree else return -1function isSumTree(node){ if(node == null) return 0 let ls = isSumTree(node.left) if(ls == -1) // To stop for further traversal of tree if found not sumTree return -1 let rs = isSumTree(node.right) if(rs == -1) // To stop for further traversal of tree if found not sumTree return -1 if(isLeaf(node) || ls + rs == node.data) return ls + rs + node.data else return -1} // Driver codelet root = new node(26)root.left = new node(10)root.right = new node(3)root.left.left = new node(4)root.left.right = new node(6)root.right.right = new node(3) if(isSumTree(root)) document.write("The given tree is a SumTree ")else document.write("The given tree is not a SumTree ") // This code is contributed by shinjanpatra </script>
Time Complexity: O(n), since each element is traversed only once
mohit kumar 29
avanitrachhadiya2155
khushboogoyal499
rag2127
pratham76
rutvik_56
unknown2108
kirtishsurangalikar
decode2207
surinderdawra388
amartyaghoshgfg
mugunthanramesh
shinjanpatra
jana_sayantan
Adobe
Amazon
Goldman Sachs
Tree
Amazon
Goldman Sachs
Adobe
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Binary Tree | Set 3 (Types of Binary Tree)
Inorder Tree Traversal without Recursion
Binary Tree | Set 2 (Properties)
Decision Tree
A program to check if a binary tree is BST or not
Construct Tree from given Inorder and Preorder traversals
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
|
[
{
"code": null,
"e": 26571,
"s": 26543,
"text": "\n10 May, 2022"
},
{
"code": null,
"e": 26908,
"s": 26571,
"text": "Write a function that returns true if the given Binary Tree is SumTree else false. A SumTree is a Binary Tree where the value of a node is equal to the sum of the nodes present in its left subtree and right subtree. An empty tree is SumTree and the sum of an empty tree can be considered as 0. A leaf node is also considered as SumTree."
},
{
"code": null,
"e": 26945,
"s": 26908,
"text": "Following is an example of SumTree. "
},
{
"code": null,
"e": 27022,
"s": 26945,
"text": " 26\n / \\\n 10 3\n / \\ \\\n 4 6 3"
},
{
"code": null,
"e": 27226,
"s": 27022,
"text": "Method 1 (Simple) Get the sum of nodes in the left subtree and right subtree. Check if the sum calculated is equal to the rootβs data. Also, recursively check if the left and right subtrees are SumTrees."
},
{
"code": null,
"e": 27230,
"s": 27226,
"text": "C++"
},
{
"code": null,
"e": 27232,
"s": 27230,
"text": "C"
},
{
"code": null,
"e": 27237,
"s": 27232,
"text": "Java"
},
{
"code": null,
"e": 27245,
"s": 27237,
"text": "Python3"
},
{
"code": null,
"e": 27248,
"s": 27245,
"text": "C#"
},
{
"code": null,
"e": 27259,
"s": 27248,
"text": "Javascript"
},
{
"code": "// C++ program to check if Binary tree// is sum tree or not#include <iostream>using namespace std; // A binary tree node has data,// left child and right childstruct node{ int data; struct node* left; struct node* right;}; // A utility function to get the sum// of values in tree with root as rootint sum(struct node *root){ if (root == NULL) return 0; return sum(root->left) + root->data + sum(root->right);} // Returns 1 if sum property holds for// the given node and both of its childrenint isSumTree(struct node* node){ int ls, rs; // If node is NULL or it's a leaf // node then return true if (node == NULL || (node->left == NULL && node->right == NULL)) return 1; // Get sum of nodes in left and // right subtrees ls = sum(node->left); rs = sum(node->right); // If the node and both of its // children satisfy the property // return 1 else 0 if ((node->data == ls + rs) && isSumTree(node->left) && isSumTree(node->right)) return 1; return 0;} // Helper function that allocates a new node// with the given data and NULL left and right// pointers.struct node* newNode(int data){ struct node* node = (struct node*)malloc( sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} // Driver codeint main(){ struct node *root = newNode(26); root->left = newNode(10); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(6); root->right->right = newNode(3); if (isSumTree(root)) cout << \"The given tree is a SumTree \"; else cout << \"The given tree is not a SumTree \"; getchar(); return 0;} // This code is contributed by khushboogoyal499",
"e": 29055,
"s": 27259,
"text": null
},
{
"code": "// C program to check if Binary tree// is sum tree or not#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, left child and right child */struct node{ int data; struct node* left; struct node* right;}; /* A utility function to get the sum of values in tree with root as root */int sum(struct node *root){ if(root == NULL) return 0; return sum(root->left) + root->data + sum(root->right);} /* returns 1 if sum property holds for the given node and both of its children */int isSumTree(struct node* node){ int ls, rs; /* If node is NULL or it's a leaf node then return true */ if(node == NULL || (node->left == NULL && node->right == NULL)) return 1; /* Get sum of nodes in left and right subtrees */ ls = sum(node->left); rs = sum(node->right); /* if the node and both of its children satisfy the property return 1 else 0*/ if((node->data == ls + rs)&& isSumTree(node->left) && isSumTree(node->right)) return 1; return 0;} /* Helper function that allocates a new node with the given data and NULL left and right pointers.*/struct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Driver program to test above function */int main(){ struct node *root = newNode(26); root->left = newNode(10); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(6); root->right->right = newNode(3); if(isSumTree(root)) printf(\"The given tree is a SumTree.\"); else printf(\"The given tree is not a SumTree.\"); getchar(); return 0;}",
"e": 30822,
"s": 29055,
"text": null
},
{
"code": "// Java program to check if Binary tree// is sum tree or notimport java.io.*; // A binary tree node has data,// left child and right childclass Node{ int data; Node left, right, nextRight; // Helper function that allocates a new node // with the given data and NULL left and right // pointers. Node(int item) { data = item; left = right = null; }}class BinaryTree { public static Node root; // A utility function to get the sum // of values in tree with root as root static int sum(Node node) { if(node == null) { return 0; } return (sum(node.left) + node.data+sum(node.right)); } // Returns 1 if sum property holds for // the given node and both of its children static int isSumTree(Node node) { int ls,rs; // If node is NULL or it's a leaf // node then return true if(node == null || (node.left == null && node.right == null)) { return 1; } // Get sum of nodes in left and // right subtrees ls = sum(node.left); rs = sum(node.right); // If the node and both of its // children satisfy the property // return 1 else 0 if((node.data == ls + rs) && isSumTree(node.left) != 0 && isSumTree(node.right) != 0) { return 1; } return 0; } // Driver code public static void main (String[] args) { BinaryTree tree=new BinaryTree(); tree.root=new Node(26); tree.root.left=new Node(10); tree.root.right=new Node(3); tree.root.left.left=new Node(4); tree.root.left.right=new Node(6); tree.root.right.right=new Node(3); if(isSumTree(root) != 0) { System.out.println(\"The given tree is a SumTree\"); } else { System.out.println(\"The given tree is not a SumTree\"); } }} // This code is contributed by rag2127",
"e": 32823,
"s": 30822,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # A binary tree node has data,# left child and right childclass node: def __init__(self, x): self.data = x self.left = None self.right = None # A utility function to get the sum# of values in tree with root as rootdef sum(root): if(root == None): return 0 return (sum(root.left) + root.data + sum(root.right)) # returns 1 if sum property holds# for the given node and both of# its childrendef isSumTree(node): # ls, rs # If node is None or it's a leaf # node then return true if(node == None or (node.left == None and node.right == None)): return 1 # Get sum of nodes in left and # right subtrees ls = sum(node.left) rs = sum(node.right) # if the node and both of its children # satisfy the property return 1 else 0 if((node.data == ls + rs) and isSumTree(node.left) and isSumTree(node.right)): return 1 return 0 # Driver codeif __name__ == '__main__': root = node(26) root.left= node(10) root.right = node(3) root.left.left = node(4) root.left.right = node(6) root.right.right = node(3) if(isSumTree(root)): print(\"The given tree is a SumTree \") else: print(\"The given tree is not a SumTree \") # This code is contributed by Mohit Kumar 29",
"e": 34214,
"s": 32823,
"text": null
},
{
"code": "// C# program to check if Binary tree// is sum tree or notusing System; // A binary tree node has data,// left child and right childpublic class Node{ public int data; public Node left, right, nextRight; // Helper function that allocates a new node // with the given data and NULL left and right // pointers. public Node(int item) { data = item; left = right = null; }} class BinaryTree { public Node root; // A utility function to get the sum // of values in tree with root as root int sum(Node node) { if(node == null) { return 0; } return (sum(node.left) + node.data+sum(node.right)); } // Returns 1 if sum property holds for // the given node and both of its children int isSumTree(Node node) { int ls,rs; // If node is NULL or it's a leaf // node then return true if(node == null || (node.left == null && node.right == null)) { return 1; } // Get sum of nodes in left and // right subtrees ls = sum(node.left); rs = sum(node.right); // If the node and both of its // children satisfy the property // return 1 else 0 if((node.data == ls + rs) && isSumTree(node.left) != 0 && isSumTree(node.right) != 0) { return 1; } return 0; } // Driver code public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(26); tree.root.left = new Node(10); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(6); tree.root.right.right = new Node(3); if(tree.isSumTree(tree.root) != 0) { Console.WriteLine(\"The given tree is a SumTree\"); } else { Console.WriteLine(\"The given tree is not a SumTree\"); } }} // This code is contributed by Pratham76",
"e": 36254,
"s": 34214,
"text": null
},
{
"code": "<script>// Javascript program to check if Binary tree// is sum tree or not // A binary tree node has data, // left child and right child class Node { // Helper function that allocates a new node // with the given data and NULL left and right // pointers. constructor(x) { this.data = x; this.left = null; this.right = null; } } let root; // A utility function to get the sum // of values in tree with root as root function sum(node) { if(node == null) { return 0; } return (sum(node.left) + node.data+sum(node.right)); } // Returns 1 if sum property holds for // the given node and both of its children function isSumTree(node) { let ls,rs; // If node is NULL or it's a leaf // node then return true if(node == null || (node.left == null && node.right == null)) { return 1; } // Get sum of nodes in left and // right subtrees ls = sum(node.left); rs = sum(node.right); // If the node and both of its // children satisfy the property // return 1 else 0 if((node.data == ls + rs) && isSumTree(node.left) != 0 && isSumTree(node.right) != 0) { return 1; } return 0; } // Driver code root = new Node(26) root.left= new Node(10) root.right = new Node(3) root.left.left = new Node(4) root.left.right = new Node(6) root.right.right = new Node(3) if(isSumTree(root) != 0) { document.write(\"The given tree is a SumTree\"); } else { document.write(\"The given tree is not a SumTree\"); } // This code is contributed by unknown2108</script>",
"e": 38086,
"s": 36254,
"text": null
},
{
"code": null,
"e": 38114,
"s": 38086,
"text": "The given tree is a SumTree"
},
{
"code": null,
"e": 38198,
"s": 38114,
"text": "Time Complexity: O(n^2) in the worst case. The worst-case occurs for a skewed tree."
},
{
"code": null,
"e": 38638,
"s": 38198,
"text": "Method 2 (Tricky) Method 1 uses sum() to get the sum of nodes in left and right subtrees. Method 2 uses the following rules to get the sum directly. 1) If the node is a leaf node then the sum of the subtree rooted with this node is equal to the value of this node. 2) If the node is not a leaf node then the sum of the subtree rooted with this node is twice the value of this node (Assuming that the tree rooted with this node is SumTree)."
},
{
"code": null,
"e": 38642,
"s": 38638,
"text": "C++"
},
{
"code": null,
"e": 38644,
"s": 38642,
"text": "C"
},
{
"code": null,
"e": 38649,
"s": 38644,
"text": "Java"
},
{
"code": null,
"e": 38657,
"s": 38649,
"text": "Python3"
},
{
"code": null,
"e": 38660,
"s": 38657,
"text": "C#"
},
{
"code": null,
"e": 38671,
"s": 38660,
"text": "Javascript"
},
{
"code": "// C++ program to check if Binary tree// is sum tree or not#include<bits/stdc++.h>using namespace std; /* A binary tree node has data, left child and right child */struct node{ int data; node* left; node* right;}; /* Utility function to check ifthe given node is leaf or not */int isLeaf(node *node){ if(node == NULL) return 0; if(node->left == NULL && node->right == NULL) return 1; return 0;} /* returns 1 if SumTree property holds for the given tree */int isSumTree(node* node){ int ls; // for sum of nodes in left subtree int rs; // for sum of nodes in right subtree /* If node is NULL or it's a leaf node then return true */ if(node == NULL || isLeaf(node)) return 1; if( isSumTree(node->left) && isSumTree(node->right)) { // Get the sum of nodes in left subtree if(node->left == NULL) ls = 0; else if(isLeaf(node->left)) ls = node->left->data; else ls = 2 * (node->left->data); // Get the sum of nodes in right subtree if(node->right == NULL) rs = 0; else if(isLeaf(node->right)) rs = node->right->data; else rs = 2 * (node->right->data); /* If root's data is equal to sum of nodes in left and right subtrees then return 1 else return 0*/ return(node->data == ls + rs); } return 0;} /* Helper function that allocates a new node with the given data and NULL left and right pointers.*/node* newNode(int data){ node* node1 = new node(); node1->data = data; node1->left = NULL; node1->right = NULL; return(node1);} /* Driver code */int main(){ node *root = newNode(26); root->left = newNode(10); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(6); root->right->right = newNode(3); if(isSumTree(root)) cout << \"The given tree is a SumTree \"; else cout << \"The given tree is not a SumTree \"; return 0;} // This code is contributed by rutvik_56",
"e": 40740,
"s": 38671,
"text": null
},
{
"code": "// C program to check if Binary tree// is sum tree or not#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, left child and right child */struct node{ int data; struct node* left; struct node* right;}; /* Utility function to check if the given node is leaf or not */int isLeaf(struct node *node){ if(node == NULL) return 0; if(node->left == NULL && node->right == NULL) return 1; return 0;} /* returns 1 if SumTree property holds for the given tree */int isSumTree(struct node* node){ int ls; // for sum of nodes in left subtree int rs; // for sum of nodes in right subtree /* If node is NULL or it's a leaf node then return true */ if(node == NULL || isLeaf(node)) return 1; if( isSumTree(node->left) && isSumTree(node->right)) { // Get the sum of nodes in left subtree if(node->left == NULL) ls = 0; else if(isLeaf(node->left)) ls = node->left->data; else ls = 2*(node->left->data); // Get the sum of nodes in right subtree if(node->right == NULL) rs = 0; else if(isLeaf(node->right)) rs = node->right->data; else rs = 2*(node->right->data); /* If root's data is equal to sum of nodes in left and right subtrees then return 1 else return 0*/ return(node->data == ls + rs); } return 0;} /* Helper function that allocates a new node with the given data and NULL left and right pointers.*/struct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Driver program to test above function */int main(){ struct node *root = newNode(26); root->left = newNode(10); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(6); root->right->right = newNode(3); if(isSumTree(root)) printf(\"The given tree is a SumTree \"); else printf(\"The given tree is not a SumTree \"); getchar(); return 0;}",
"e": 42892,
"s": 40740,
"text": null
},
{
"code": "// Java program to check if Binary tree is sum tree or not /* A binary tree node has data, left child and right child */class Node{ int data; Node left, right, nextRight; Node(int item) { data = item; left = right = nextRight = null; }} class BinaryTree{ Node root; /* Utility function to check if the given node is leaf or not */ int isLeaf(Node node) { if (node == null) return 0; if (node.left == null && node.right == null) return 1; return 0; } /* returns 1 if SumTree property holds for the given tree */ int isSumTree(Node node) { int ls; // for sum of nodes in left subtree int rs; // for sum of nodes in right subtree /* If node is NULL or it's a leaf node then return true */ if (node == null || isLeaf(node) == 1) return 1; if (isSumTree(node.left) != 0 && isSumTree(node.right) != 0) { // Get the sum of nodes in left subtree if (node.left == null) ls = 0; else if (isLeaf(node.left) != 0) ls = node.left.data; else ls = 2 * (node.left.data); // Get the sum of nodes in right subtree if (node.right == null) rs = 0; else if (isLeaf(node.right) != 0) rs = node.right.data; else rs = 2 * (node.right.data); /* If root's data is equal to sum of nodes in left and right subtrees then return 1 else return 0*/ if ((node.data == rs + ls)) return 1; else return 0; } return 0; } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(26); tree.root.left = new Node(10); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(6); tree.root.right.right = new Node(3); if (tree.isSumTree(tree.root) != 0) System.out.println(\"The given tree is a SumTree\"); else System.out.println(\"The given tree is not a SumTree\"); }} // This code has been contributed by Mayank Jaiswal",
"e": 45263,
"s": 42892,
"text": null
},
{
"code": "# Python3 program to check if# Binary tree is sum tree or not # A binary tree node has data,# left child and right childclass node: def __init__(self, x): self.data = x self.left = None self.right = None def isLeaf(node): if(node == None): return 0 if(node.left == None and node.right == None): return 1 return 0 # A utility function to get the sum# of values in tree with root as rootdef sum(root): if(root == None): return 0 return (sum(root.left) + root.data + sum(root.right)) # returns 1 if SumTree property holds# for the given treedef isSumTree(node): # If node is None or # it's a leaf node then return true if(node == None or isLeaf(node)): return 1 if(isSumTree(node.left) and isSumTree(node.right)): # Get the sum of nodes in left subtree if(node.left == None): ls = 0 elif(isLeaf(node.left)): ls = node.left.data else: ls = 2 * (node.left.data) # Get the sum of nodes in right subtree if(node.right == None): rs = 0 elif(isLeaf(node.right)): rs = node.right.data else: rs = 2 * (node.right.data) # If root's data is equal to sum of nodes # in left and right subtrees then return 1 # else return 0 return(node.data == ls + rs) return 0 # Driver codeif __name__ == '__main__': root = node(26) root.left = node(10) root.right = node(3) root.left.left = node(4) root.left.right = node(6) root.right.right = node(3) if(isSumTree(root)): print(\"The given tree is a SumTree \") else: print(\"The given tree is not a SumTree \") # This code is contributed by kirtishsurangalikar",
"e": 47057,
"s": 45263,
"text": null
},
{
"code": "// C# program to check if Binary tree// is sum tree or notusing System; // A binary tree node has data, left// child and right childpublic class Node{ public int data; public Node left, right, nextRight; public Node(int d) { data = d; left = right = nextRight = null; }} public class BinaryTree{ public static Node root; // Utility function to check if// the given node is leaf or notpublic int isLeaf(Node node){ if (node == null) return 0; if (node.left == null && node.right == null) return 1; return 0;} // Returns 1 if SumTree property holds// for the given treepublic int isSumTree(Node node){ // For sum of nodes in left subtree int ls; // For sum of nodes in right subtree int rs; // If node is NULL or it's a leaf // node then return true if (node == null || isLeaf(node) == 1) return 1; if (isSumTree(node.left) != 0 && isSumTree(node.right) != 0) { // Get the sum of nodes in left subtree if (node.left == null) ls = 0; else if (isLeaf(node.left) != 0) ls = node.left.data; else ls = 2 * (node.left.data); // Get the sum of nodes in right subtree if (node.right == null) rs = 0; else if (isLeaf(node.right) != 0) rs = node.right.data; else rs = 2 * (node.right.data); // If root's data is equal to sum of // nodes in left and right subtrees // then return 1 else return 0 if ((node.data == rs + ls)) return 1; else return 0; } return 0;} // Driver codestatic public void Main(){ BinaryTree tree = new BinaryTree(); BinaryTree.root = new Node(26); BinaryTree.root.left = new Node(10); BinaryTree.root.right = new Node(3); BinaryTree.root.left.left = new Node(4); BinaryTree.root.left.right = new Node(6); BinaryTree.root.right.right = new Node(3); if (tree.isSumTree(BinaryTree.root) != 0) { Console.WriteLine(\"The given tree is a SumTree\"); } else { Console.WriteLine(\"The given tree is \" + \"not a SumTree\"); }}} // This code is contributed by avanitrachhadiya2155",
"e": 49358,
"s": 47057,
"text": null
},
{
"code": "<script> // JavaScript program to check // if Binary tree is sum tree or not class Node { constructor(item) { this.data = item; this.left = null; this.right = null; this.nextRight = null; } } let root; /* Utility function to check if the given node is leaf or not */ function isLeaf(node) { if (node == null) return 0; if (node.left == null && node.right == null) return 1; return 0; } /* returns 1 if SumTree property holds for the given tree */ function isSumTree(node) { let ls; // for sum of nodes in left subtree let rs; // for sum of nodes in right subtree /* If node is NULL or it's a leaf node then return true */ if (node == null || isLeaf(node) == 1) return 1; if (isSumTree(node.left) != 0 && isSumTree(node.right) != 0) { // Get the sum of nodes in left subtree if (node.left == null) ls = 0; else if (isLeaf(node.left) != 0) ls = node.left.data; else ls = 2 * (node.left.data); // Get the sum of nodes in right subtree if (node.right == null) rs = 0; else if (isLeaf(node.right) != 0) rs = node.right.data; else rs = 2 * (node.right.data); /* If root's data is equal to sum of nodes in left and right subtrees then return 1 else return 0*/ if ((node.data == rs + ls)) return 1; else return 0; } return 0; } root = new Node(26); root.left = new Node(10); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(6); root.right.right = new Node(3); if (isSumTree(root) != 0) document.write(\"The given tree is a SumTree\"); else document.write(\"The given tree is not a SumTree\"); </script>",
"e": 51450,
"s": 49358,
"text": null
},
{
"code": null,
"e": 51459,
"s": 51450,
"text": "Output: "
},
{
"code": null,
"e": 51487,
"s": 51459,
"text": "The given tree is a SumTree"
},
{
"code": null,
"e": 51509,
"s": 51487,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 51518,
"s": 51509,
"text": "Method 3"
},
{
"code": null,
"e": 51681,
"s": 51518,
"text": "Similar to postorder traversal iteratively find the sum in each stepReturn left + right + current data if left + right is equal to current node dataElse return -1"
},
{
"code": null,
"e": 51750,
"s": 51681,
"text": "Similar to postorder traversal iteratively find the sum in each step"
},
{
"code": null,
"e": 51831,
"s": 51750,
"text": "Return left + right + current data if left + right is equal to current node data"
},
{
"code": null,
"e": 51846,
"s": 51831,
"text": "Else return -1"
},
{
"code": null,
"e": 51850,
"s": 51846,
"text": "C++"
},
{
"code": null,
"e": 51856,
"s": 51850,
"text": "C++14"
},
{
"code": null,
"e": 51861,
"s": 51856,
"text": "Java"
},
{
"code": null,
"e": 51869,
"s": 51861,
"text": "Python3"
},
{
"code": null,
"e": 51880,
"s": 51869,
"text": "Javascript"
},
{
"code": "// C++ program to check if Binary tree// is sum tree or not#include<bits/stdc++.h>using namespace std; /* A binary tree node has data,left child and right child */struct node{ int data; node* left; node* right;}; /* Utility function to check ifthe given node is leaf or not */int isLeaf(node *node){ if(node == NULL) return 0; if(node->left == NULL && node->right == NULL) return 1; return 0;} /* returns data if SumTree property holds for the given tree else return -1*/int isSumTree(node* node){ if(node == NULL) return 0; int ls; // for sum of nodes in left subtree int rs; // for sum of nodes in right subtree ls = isSumTree(node->left); if(ls == -1) // To stop for further traversal of tree if found not sumTree return -1; rs = isSumTree(node->right); if(rs == -1) // To stop for further traversal of tree if found not sumTree return -1; if(isLeaf(node) || ls + rs == node->data) return ls + rs + node->data; else return -1; } /* Helper function that allocates a new nodewith the given data and NULL left and rightpointers.*/node* newNode(int data){ node* node1 = new node(); node1->data = data; node1->left = NULL; node1->right = NULL; return(node1);} /* Driver code */int main(){ node *root = newNode(26); root->left = newNode(10); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(6); root->right->right = newNode(3); int total = isSumTree(root); if(total != -1 && total == 2*(root->data)) cout<<\"Tree is a Sum Tree\"; else cout<<\"Given Tree is not sum Tree\"; return 0;} // This code is contributed by Mugunthan",
"e": 53625,
"s": 51880,
"text": null
},
{
"code": "// C++ program to check if Binary tree// is sum tree or not#include<bits/stdc++.h>using namespace std; /* A binary tree node has data,left child and right child */struct node{ int data; node* left; node* right;}; /* Utility function to check ifthe given node is leaf or not */int isLeaf(node *node){ if(node == NULL) return 0; if(node->left == NULL && node->right == NULL) return 1; return 0;} /* returns data if SumTree property holds for the given tree else return -1*/int isSumTree(node* node){ if(node == NULL) return 0; int ls; // for sum of nodes in left subtree int rs; // for sum of nodes in right subtree ls = isSumTree(node->left); if(ls == -1) // To stop for further traversal of tree if found not sumTree return -1; rs = isSumTree(node->right); if(rs == -1) // To stop for further traversal of tree if found not sumTree return -1; if(isLeaf(node) || ls + rs == node->data) return ls + rs + node->data; else return -1; } /* Helper function that allocates a new nodewith the given data and NULL left and rightpointers.*/node* newNode(int data){ node* node1 = new node(); node1->data = data; node1->left = NULL; node1->right = NULL; return(node1);} /* Driver code */int main(){ node *root = newNode(26); root->left = newNode(10); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(6); root->right->right = newNode(3); int total = isSumTree(root); if(total != -1 && total == 2*(root->data)) cout<<\"Sum Tree\"; else cout<<\"No sum Tree\"; return 0;} // This code is contributed by Mugunthan",
"e": 55345,
"s": 53625,
"text": null
},
{
"code": "// Java program to check if Binary tree// is sum tree or not import java.util.*; class GFG{/* A binary tree node has data,left child and right child */ static class Node {int data;Node left, right; } /* Utility function to check ifthe given node is leaf or not */static int isLeaf(Node node){ if(node == null) return 0; if(node.left == null && node.right == null) return 1; return 0;} /* returns data if SumTree property holds for the given tree else return -1*/static int isSumTree(Node node){ if(node == null) return 0; int ls; // for sum of nodes in left subtree int rs; // for sum of nodes in right subtree ls = isSumTree(node.left); if(ls == -1) // To stop for further traversal of tree if found not sumTree return -1; rs = isSumTree(node.right); if(rs == -1) // To stop for further traversal of tree if found not sumTree return -1; if(isLeaf(node)==1 || ls + rs == node.data) return ls + rs + node.data; else return -1; } /* Helper function that allocates a new nodewith the given data and null left and rightpointers.*/static Node newNode(int data){ Node node1 = new Node(); node1.data = data; node1.left = null; node1.right = null; return(node1);} public static void main(String args[]){ Node root = newNode(26); root.left = newNode(10); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(6); root.right.right = newNode(3); int total = isSumTree(root); if(total != -1 && total == 2*(root.data)) System.out.print(\"Tree is a Sum Tree\"); else System.out.print(\"Given Tree is not sum Tree\");}} // This code is contributed by jana_sayantan.",
"e": 57093,
"s": 55345,
"text": null
},
{
"code": "# Python3 program to check if# Binary tree is sum tree or not # A binary tree node has data,# left child and right childclass node: def __init__(self, x): self.data = x self.left = None self.right = None def isLeaf(node): if(node == None): return 0 if(node.left == None and node.right == None): return 1 return 0 # returns data if SumTree property holds for the given# tree else return -1def isSumTree(node): if(node == None): return 0 ls = isSumTree(node.left) if(ls == -1): #To stop for further traversal of tree if found not sumTree return -1 rs = isSumTree(node.right) if(rs == -1): #To stop for further traversal of tree if found not sumTree return -1 if(isLeaf(node) or ls + rs == node.data): return ls + rs + node.data else: return -1 # Driver codeif __name__ == '__main__': root = node(26) root.left = node(10) root.right = node(3) root.left.left = node(4) root.left.right = node(6) root.right.right = node(3) if(isSumTree(root)): print(\"The given tree is a SumTree \") else: print(\"The given tree is not a SumTree \") # This code is contributed by Mugunthan",
"e": 58366,
"s": 57093,
"text": null
},
{
"code": "<script> // JavaScript program to check if// Binary tree is sum tree or not // A binary tree node has data,// left child and right childclass node{ constructor(x){ this.data = x this.left = null this.right = null } } function isLeaf(node){ if(node == null) return 0 if(node.left == null && node.right == null) return 1 return 0} // returns data if SumTree property holds for the given// tree else return -1function isSumTree(node){ if(node == null) return 0 let ls = isSumTree(node.left) if(ls == -1) // To stop for further traversal of tree if found not sumTree return -1 let rs = isSumTree(node.right) if(rs == -1) // To stop for further traversal of tree if found not sumTree return -1 if(isLeaf(node) || ls + rs == node.data) return ls + rs + node.data else return -1} // Driver codelet root = new node(26)root.left = new node(10)root.right = new node(3)root.left.left = new node(4)root.left.right = new node(6)root.right.right = new node(3) if(isSumTree(root)) document.write(\"The given tree is a SumTree \")else document.write(\"The given tree is not a SumTree \") // This code is contributed by shinjanpatra </script>",
"e": 59655,
"s": 58366,
"text": null
},
{
"code": null,
"e": 59722,
"s": 59655,
"text": "Time Complexity: O(n), since each element is traversed only once "
},
{
"code": null,
"e": 59737,
"s": 59722,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 59758,
"s": 59737,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 59775,
"s": 59758,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 59783,
"s": 59775,
"text": "rag2127"
},
{
"code": null,
"e": 59793,
"s": 59783,
"text": "pratham76"
},
{
"code": null,
"e": 59803,
"s": 59793,
"text": "rutvik_56"
},
{
"code": null,
"e": 59815,
"s": 59803,
"text": "unknown2108"
},
{
"code": null,
"e": 59835,
"s": 59815,
"text": "kirtishsurangalikar"
},
{
"code": null,
"e": 59846,
"s": 59835,
"text": "decode2207"
},
{
"code": null,
"e": 59863,
"s": 59846,
"text": "surinderdawra388"
},
{
"code": null,
"e": 59879,
"s": 59863,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 59895,
"s": 59879,
"text": "mugunthanramesh"
},
{
"code": null,
"e": 59908,
"s": 59895,
"text": "shinjanpatra"
},
{
"code": null,
"e": 59922,
"s": 59908,
"text": "jana_sayantan"
},
{
"code": null,
"e": 59928,
"s": 59922,
"text": "Adobe"
},
{
"code": null,
"e": 59935,
"s": 59928,
"text": "Amazon"
},
{
"code": null,
"e": 59949,
"s": 59935,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 59954,
"s": 59949,
"text": "Tree"
},
{
"code": null,
"e": 59961,
"s": 59954,
"text": "Amazon"
},
{
"code": null,
"e": 59975,
"s": 59961,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 59981,
"s": 59975,
"text": "Adobe"
},
{
"code": null,
"e": 59986,
"s": 59981,
"text": "Tree"
},
{
"code": null,
"e": 60084,
"s": 59986,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 60127,
"s": 60084,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 60168,
"s": 60127,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 60201,
"s": 60168,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 60215,
"s": 60201,
"text": "Decision Tree"
},
{
"code": null,
"e": 60265,
"s": 60215,
"text": "A program to check if a binary tree is BST or not"
},
{
"code": null,
"e": 60323,
"s": 60265,
"text": "Construct Tree from given Inorder and Preorder traversals"
},
{
"code": null,
"e": 60359,
"s": 60323,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 60407,
"s": 60359,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
}
] |
Converting array of Numbers to cumulative sum array in JavaScript
|
We have an array of numbers like this β
const arr = [1, 1, 5, 2, -4, 6, 10];
We are required to write a function that returns a new array, of the same size but with each
element being the sum of all elements until that point.
Therefore, the output should look like β
const output = [1, 2, 7, 9, 5, 11, 21];
Therefore, letβs write the function partialSum(),
The full code for this function will be β
const arr = [1, 1, 5, 2, -4, 6, 10];
const partialSum = (arr) => {
const output = [];
arr.forEach((num, index) => {
if(index === 0){
output[index] = num;
}else{
output[index] = num + output[index - 1];
}
});
return output;
};
console.log(partialSum(arr));
Here, we iterated over the array and kept assigning the elements of output array a new value
every time, the value being the sum of current number and its predecessor.
The output of the code in the console will be β
[
1, 2, 7, 9,
5, 11, 21
]
|
[
{
"code": null,
"e": 1102,
"s": 1062,
"text": "We have an array of numbers like this β"
},
{
"code": null,
"e": 1139,
"s": 1102,
"text": "const arr = [1, 1, 5, 2, -4, 6, 10];"
},
{
"code": null,
"e": 1288,
"s": 1139,
"text": "We are required to write a function that returns a new array, of the same size but with each\nelement being the sum of all elements until that point."
},
{
"code": null,
"e": 1329,
"s": 1288,
"text": "Therefore, the output should look like β"
},
{
"code": null,
"e": 1369,
"s": 1329,
"text": "const output = [1, 2, 7, 9, 5, 11, 21];"
},
{
"code": null,
"e": 1419,
"s": 1369,
"text": "Therefore, letβs write the function partialSum(),"
},
{
"code": null,
"e": 1461,
"s": 1419,
"text": "The full code for this function will be β"
},
{
"code": null,
"e": 1766,
"s": 1461,
"text": "const arr = [1, 1, 5, 2, -4, 6, 10];\nconst partialSum = (arr) => {\n const output = [];\n arr.forEach((num, index) => {\n\n if(index === 0){\n output[index] = num;\n }else{\n output[index] = num + output[index - 1];\n }\n });\n return output;\n};\nconsole.log(partialSum(arr));"
},
{
"code": null,
"e": 1934,
"s": 1766,
"text": "Here, we iterated over the array and kept assigning the elements of output array a new value\nevery time, the value being the sum of current number and its predecessor."
},
{
"code": null,
"e": 1982,
"s": 1934,
"text": "The output of the code in the console will be β"
},
{
"code": null,
"e": 2014,
"s": 1982,
"text": "[\n 1, 2, 7, 9,\n 5, 11, 21\n]"
}
] |
12 Best Practices For Android Development - GeeksforGeeks
|
15 Aug, 2021
As Android engineers, weβre all motivated by the desire to create memorable experiences for people all across the world. And, with more people relying on your apps than ever before, expectations are higher, and your job as a designer isnβt getting any easier. Now not only do you have to be updated but also stand unique from other developers to make your unique mark in the market. Listed down are few best practices that you can take on to have better outcomes in your development.
Not all apps are built with the same approach. You have to brainstorm, plan and pick an appropriate method before starting the development process. Before proceeding you will have to make a prior move that your further app will be a Native, Hybrid, or Web-based app. There are pros and cons of each of these development methods, having proper research will help you better.
We all know that Coding is an Art. And once an individual starts coding correctly he/she starts loving the flavor. Moreover how creatively you code, shows how better developer you are. Your Quality Of Code Always Matters. Because writing long code is never a smart step, it not only increases the chances of having more bugs and consumes a lot of time, and creates lots of complexity. Here are few points listed you can adopt for superior code quality.
To give the finest look to your code you can initially study the code of an expert, analyze their approach and try to modify that.
Provide the purposes of every function you use.
Use descriptive names.Always keep your code simple and sober, remove unnecessary lines and keep your work short and descriptive.
Use descriptive names.
Always keep your code simple and sober, remove unnecessary lines and keep your work short and descriptive.
Tip: Use Proguard, this will help to remove all unused codes and minimize the APK size.
Android itself is a very vast concept, and itβs very much impractical to imagine that you are a master in all the concepts and techniques. And when it comes to programming or building application nothing can help you out other than the stackβs documentation. Learning how to use/read and understand the Android Documentation is important this will help you to build lots of applications with a variety of features. So itβs highly recommended to go through developer training at android:- Getting Started | Android Developers
Your project work seems more friendly if itβs highly interacted with the users and it seems more helpful as well. While coding, every text field is planned for a different job. We take input in some text fields as numbers or as alphabets. It is counted as better practice if only the number pad is open if we ask the user for numeric value. The syntax will be:
XML
<EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editText" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:hint="User Name" android:layout_below="@+id/imageView" android:layout_alignLeft="@+id/imageView" android:layout_alignStart="@+id/imageView" android:numeric="integer" />
Other than that if your field is for the password, then it must show a password hint to, easily remember the password. It can be achieved as.
XML
<EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editText2" android:layout_alignLeft="@+id/editText" android:layout_alignStart="@+id/editText" android:hint="Pass Word" android:layout_below="@+id/editText" android:layout_alignRight="@+id/editText" android:layout_alignEnd="@+id/editText" android:password="true" />
Having deep hierarchical code views actually makes the UI slower to manage the layout. Deep hierarchies can mostly be avoided by using the correct view group. Itβs a recommendation to use a single-level hierarchy.
XML
<RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/magnifying_glass" /> <TextView android:id="@+id/top_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_toRightOf="@id/image" android:text="top text" /> <TextView android:id="@+id/bottom_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/top_text" android:layout_toRightOf="@id/image" android:text="bottom text" /></RelativeLayout>
The duties of Developers are different that from Designers. For the maximum part, builders tend to be great with technical concepts, whilst designers have recognition for being greater creative. But with that said, you canβt have your blinders on while youβre growing an app. You want to apprehend how the layout additives are going to create so that you can code the app accordingly. To get designers and developers operating collectively and effectively, your whole group desires to be on the identical page. You can use mood boards and lots of other tools to have a thought and maintain the tracking of the design elements organized. This will make your improvement manner plenty less difficult and decrease the possibilities of getting to make masses of modifications overdue in the sport on the way to accommodate the designers. For the ones of you that recognize a way to expand and layout, you should still sort out your design elements in these early stages.
Always keep your Gradle updated and use the latest Gradle plugin for android.
Enable Offline mode, Gradle Daemon, and Parallel build of your project. to use Gradle offline see the setting done below.
Check the Offline work checkbox. Click Apply or OK.
Use specific dependency versions instead of Dynamics versions.
Add below flags in gradle.properties
org.gradle.jvmargs=-Xmx2048m β Amount of memory allocation increases around 2GB to the Gradle Daemon VM.
org.gradle.daemon=true β improves the build and allows the data and code to store in memory for the next build.
org.gradle.configureondemand=true β only project-related tasks are configured, saves time from the Configuration phase of Gradle.
org.gradle.parallel=true β executes tasks from different projects in parallel. Especially useful for modularising the app.
android.enableBuildCache=true β speed up build items by sorting files and directories created in previous builds.
org.gradle.caching=true β Turns on Gradle-caching.
Be it a website or an app the way of picking a layout before developing your project. But before we choose any layout we need to understand that how the UI of the project is created. So when we talk about layouts as we know there are ConstraintLayout, LinearLayout, RelativeLayout, FrameLayout, CoordinatorLayout, and out of all these layouts, you just need to do performance analysis for some of them before getting started with it. If you have some part of your XML getting reused and you want to Avoid replication of code in different layouts. Just add <include/> by extracting them in a separate layout.
So, ADB is basically a tool that is not only used for reverse engineering but also by a lot of android-tech enthusiasts but very few numbers its total potentials or use it at the fullest and is mostly overlooked. ADB- a command-line tool or we can say a client-server program that lets you communicate with android operating systems. Though developers are not using the features of this tool daily or as quotidian, you can ease your lots of developing experiences. It has lots of features like it can add or remove files/data from your android devices and also address lots hidden of data with just a few clicks on your computer. Developers use these tools for testing and making changes in android OS devices. If a user forgets his mobile password, we can use ADB to delete the password file from the android directory, reboot it and the device is unlocked.
Handling the configuration of the android app is one of the hectic tasks for android developers. Basically what happens in configuration change is the android usually destroys your applicationβs existing Activities and Fragments and recreates them. Proper handling of the Orientationgives a rich-user experience and makes the app work smooth too. Now you want to listen for simple screen orientation changes programmatically and have your application react to them, you can use the OrientationEventListener class to do this within your Activity. Letβs see its implementation in Activity. Just instantiate an OrientationEventListener and provide its implementation. Following is the example of the Activity class called SimpleOrientationActivity logs orientation information to LogCat:
Java
public class SimpleOrientationActivity extends Activity { OrientationEventListener mOrientationListener; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mOrientationListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) { @Override public void onOrientationChanged(int orientation) { Log.v(DEBUG_TAG, "Orientation changed to " + orientation); } }; if (mOrientationListener.canDetectOrientation() == true) { Log.v(DEBUG_TAG, "Can detect orientation"); mOrientationListener.enable(); } else { Log.v(DEBUG_TAG, "Cannot detect orientation"); mOrientationListener.disable(); } } @Override protected void onDestroy() { super.onDestroy(); mOrientationListener.disable(); }
No matter what sort of application the developer intended to make but security should definitely be prioritized by the developer, from facts security clouds are one of the most neglected because itβs not only a large concept but many seem to be imperfect with it. Your apps will have tons of data and the sensitive information of your company as well as the users on your app. Depending on the app you develop may have payment information crucial information like home address, phone number, and many more things of a user-provided the. Users will hesitate to provide you with information if your app isnβt secure. If security gets breached, it could be so damaging to your brand that it will be tough to recover.
So as a developer itβs your duty to take measures and use encryptions and other tactics like (Two- Factor-Authentication 2FA), to protect sensitive info.
Tip: Make sure your application has the feature to wipe out all the data and set up automatic backup as well if urgent the user demands.
Switch to Android Studio β Itβs an official IDE of AndroidUse Android Debug Databaseβ Allow you to use the database and send preferences into the browser.Use legit external libraries and give them required permissions only. Firstly ignore third-party libraries.Avoid using floating-point β Floating points are around 2times slower than the integers on android devices.If there are lots of modifications to strings of characters, Use StringBuffer or StringBuilder classes.Install Modularization in-App.Use strings.xml β Adding text as String resources is always useful in the long run especially when support for new languages needs to be added.
Switch to Android Studio β Itβs an official IDE of Android
Use Android Debug Databaseβ Allow you to use the database and send preferences into the browser.
Use legit external libraries and give them required permissions only. Firstly ignore third-party libraries.
Avoid using floating-point β Floating points are around 2times slower than the integers on android devices.
If there are lots of modifications to strings of characters, Use StringBuffer or StringBuilder classes.
Install Modularization in-App.
Use strings.xml β Adding text as String resources is always useful in the long run especially when support for new languages needs to be added.
Developing a mobile app is not everyoneβs cup of tea. Itβs not only a vast development stack but also has lots of varieties in each of its parts. On your road of development, you will have to cross bumps and breakers to achieve milestones, So, I believe having few guidelines and best practices helps you develop the application much easier if you implement it in your routine.
Picked
Android
GBlog
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Android Listview in Java with Example
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Top 10 Front End Developer Skills That You Need in 2022
Socket Programming in C/C++
DSA Sheet by Love Babbar
Must Do Coding Questions for Product Based Companies
|
[
{
"code": null,
"e": 24751,
"s": 24723,
"text": "\n15 Aug, 2021"
},
{
"code": null,
"e": 25235,
"s": 24751,
"text": "As Android engineers, weβre all motivated by the desire to create memorable experiences for people all across the world. And, with more people relying on your apps than ever before, expectations are higher, and your job as a designer isnβt getting any easier. Now not only do you have to be updated but also stand unique from other developers to make your unique mark in the market. Listed down are few best practices that you can take on to have better outcomes in your development."
},
{
"code": null,
"e": 25610,
"s": 25235,
"text": "Not all apps are built with the same approach. You have to brainstorm, plan and pick an appropriate method before starting the development process. Before proceeding you will have to make a prior move that your further app will be a Native, Hybrid, or Web-based app. There are pros and cons of each of these development methods, having proper research will help you better. "
},
{
"code": null,
"e": 26064,
"s": 25610,
"text": "We all know that Coding is an Art. And once an individual starts coding correctly he/she starts loving the flavor. Moreover how creatively you code, shows how better developer you are. Your Quality Of Code Always Matters. Because writing long code is never a smart step, it not only increases the chances of having more bugs and consumes a lot of time, and creates lots of complexity. Here are few points listed you can adopt for superior code quality. "
},
{
"code": null,
"e": 26195,
"s": 26064,
"text": "To give the finest look to your code you can initially study the code of an expert, analyze their approach and try to modify that."
},
{
"code": null,
"e": 26243,
"s": 26195,
"text": "Provide the purposes of every function you use."
},
{
"code": null,
"e": 26372,
"s": 26243,
"text": "Use descriptive names.Always keep your code simple and sober, remove unnecessary lines and keep your work short and descriptive."
},
{
"code": null,
"e": 26395,
"s": 26372,
"text": "Use descriptive names."
},
{
"code": null,
"e": 26502,
"s": 26395,
"text": "Always keep your code simple and sober, remove unnecessary lines and keep your work short and descriptive."
},
{
"code": null,
"e": 26591,
"s": 26502,
"text": "Tip: Use Proguard, this will help to remove all unused codes and minimize the APK size. "
},
{
"code": null,
"e": 27118,
"s": 26591,
"text": "Android itself is a very vast concept, and itβs very much impractical to imagine that you are a master in all the concepts and techniques. And when it comes to programming or building application nothing can help you out other than the stackβs documentation. Learning how to use/read and understand the Android Documentation is important this will help you to build lots of applications with a variety of features. So itβs highly recommended to go through developer training at android:- Getting Started | Android Developers "
},
{
"code": null,
"e": 27479,
"s": 27118,
"text": "Your project work seems more friendly if itβs highly interacted with the users and it seems more helpful as well. While coding, every text field is planned for a different job. We take input in some text fields as numbers or as alphabets. It is counted as better practice if only the number pad is open if we ask the user for numeric value. The syntax will be:"
},
{
"code": null,
"e": 27483,
"s": 27479,
"text": "XML"
},
{
"code": "<EditText android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:id=\"@+id/editText\" android:layout_alignParentRight=\"true\" android:layout_alignParentEnd=\"true\" android:hint=\"User Name\" android:layout_below=\"@+id/imageView\" android:layout_alignLeft=\"@+id/imageView\" android:layout_alignStart=\"@+id/imageView\" android:numeric=\"integer\" />",
"e": 27866,
"s": 27483,
"text": null
},
{
"code": null,
"e": 28008,
"s": 27866,
"text": "Other than that if your field is for the password, then it must show a password hint to, easily remember the password. It can be achieved as."
},
{
"code": null,
"e": 28012,
"s": 28008,
"text": "XML"
},
{
"code": "<EditText android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:id=\"@+id/editText2\" android:layout_alignLeft=\"@+id/editText\" android:layout_alignStart=\"@+id/editText\" android:hint=\"Pass Word\" android:layout_below=\"@+id/editText\" android:layout_alignRight=\"@+id/editText\" android:layout_alignEnd=\"@+id/editText\" android:password=\"true\" />",
"e": 28397,
"s": 28012,
"text": null
},
{
"code": null,
"e": 28611,
"s": 28397,
"text": "Having deep hierarchical code views actually makes the UI slower to manage the layout. Deep hierarchies can mostly be avoided by using the correct view group. Itβs a recommendation to use a single-level hierarchy."
},
{
"code": null,
"e": 28615,
"s": 28611,
"text": "XML"
},
{
"code": "<RelativeLayout android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\"> <ImageView android:id=\"@+id/image\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:src=\"@drawable/magnifying_glass\" /> <TextView android:id=\"@+id/top_text\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_toRightOf=\"@id/image\" android:text=\"top text\" /> <TextView android:id=\"@+id/bottom_text\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/top_text\" android:layout_toRightOf=\"@id/image\" android:text=\"bottom text\" /></RelativeLayout>",
"e": 29390,
"s": 28615,
"text": null
},
{
"code": null,
"e": 30357,
"s": 29390,
"text": "The duties of Developers are different that from Designers. For the maximum part, builders tend to be great with technical concepts, whilst designers have recognition for being greater creative. But with that said, you canβt have your blinders on while youβre growing an app. You want to apprehend how the layout additives are going to create so that you can code the app accordingly. To get designers and developers operating collectively and effectively, your whole group desires to be on the identical page. You can use mood boards and lots of other tools to have a thought and maintain the tracking of the design elements organized. This will make your improvement manner plenty less difficult and decrease the possibilities of getting to make masses of modifications overdue in the sport on the way to accommodate the designers. For the ones of you that recognize a way to expand and layout, you should still sort out your design elements in these early stages."
},
{
"code": null,
"e": 30435,
"s": 30357,
"text": "Always keep your Gradle updated and use the latest Gradle plugin for android."
},
{
"code": null,
"e": 30558,
"s": 30435,
"text": "Enable Offline mode, Gradle Daemon, and Parallel build of your project. to use Gradle offline see the setting done below."
},
{
"code": null,
"e": 30610,
"s": 30558,
"text": "Check the Offline work checkbox. Click Apply or OK."
},
{
"code": null,
"e": 30673,
"s": 30610,
"text": "Use specific dependency versions instead of Dynamics versions."
},
{
"code": null,
"e": 30710,
"s": 30673,
"text": "Add below flags in gradle.properties"
},
{
"code": null,
"e": 30815,
"s": 30710,
"text": "org.gradle.jvmargs=-Xmx2048m β Amount of memory allocation increases around 2GB to the Gradle Daemon VM."
},
{
"code": null,
"e": 30927,
"s": 30815,
"text": "org.gradle.daemon=true β improves the build and allows the data and code to store in memory for the next build."
},
{
"code": null,
"e": 31057,
"s": 30927,
"text": "org.gradle.configureondemand=true β only project-related tasks are configured, saves time from the Configuration phase of Gradle."
},
{
"code": null,
"e": 31180,
"s": 31057,
"text": "org.gradle.parallel=true β executes tasks from different projects in parallel. Especially useful for modularising the app."
},
{
"code": null,
"e": 31294,
"s": 31180,
"text": "android.enableBuildCache=true β speed up build items by sorting files and directories created in previous builds."
},
{
"code": null,
"e": 31345,
"s": 31294,
"text": "org.gradle.caching=true β Turns on Gradle-caching."
},
{
"code": null,
"e": 31955,
"s": 31345,
"text": "Be it a website or an app the way of picking a layout before developing your project. But before we choose any layout we need to understand that how the UI of the project is created. So when we talk about layouts as we know there are ConstraintLayout, LinearLayout, RelativeLayout, FrameLayout, CoordinatorLayout, and out of all these layouts, you just need to do performance analysis for some of them before getting started with it. If you have some part of your XML getting reused and you want to Avoid replication of code in different layouts. Just add <include/> by extracting them in a separate layout. "
},
{
"code": null,
"e": 32815,
"s": 31955,
"text": "So, ADB is basically a tool that is not only used for reverse engineering but also by a lot of android-tech enthusiasts but very few numbers its total potentials or use it at the fullest and is mostly overlooked. ADB- a command-line tool or we can say a client-server program that lets you communicate with android operating systems. Though developers are not using the features of this tool daily or as quotidian, you can ease your lots of developing experiences. It has lots of features like it can add or remove files/data from your android devices and also address lots hidden of data with just a few clicks on your computer. Developers use these tools for testing and making changes in android OS devices. If a user forgets his mobile password, we can use ADB to delete the password file from the android directory, reboot it and the device is unlocked. "
},
{
"code": null,
"e": 33600,
"s": 32815,
"text": "Handling the configuration of the android app is one of the hectic tasks for android developers. Basically what happens in configuration change is the android usually destroys your applicationβs existing Activities and Fragments and recreates them. Proper handling of the Orientationgives a rich-user experience and makes the app work smooth too. Now you want to listen for simple screen orientation changes programmatically and have your application react to them, you can use the OrientationEventListener class to do this within your Activity. Letβs see its implementation in Activity. Just instantiate an OrientationEventListener and provide its implementation. Following is the example of the Activity class called SimpleOrientationActivity logs orientation information to LogCat:"
},
{
"code": null,
"e": 33605,
"s": 33600,
"text": "Java"
},
{
"code": "public class SimpleOrientationActivity extends Activity { OrientationEventListener mOrientationListener; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mOrientationListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) { @Override public void onOrientationChanged(int orientation) { Log.v(DEBUG_TAG, \"Orientation changed to \" + orientation); } }; if (mOrientationListener.canDetectOrientation() == true) { Log.v(DEBUG_TAG, \"Can detect orientation\"); mOrientationListener.enable(); } else { Log.v(DEBUG_TAG, \"Cannot detect orientation\"); mOrientationListener.disable(); } } @Override protected void onDestroy() { super.onDestroy(); mOrientationListener.disable(); }",
"e": 34589,
"s": 33605,
"text": null
},
{
"code": null,
"e": 35303,
"s": 34589,
"text": "No matter what sort of application the developer intended to make but security should definitely be prioritized by the developer, from facts security clouds are one of the most neglected because itβs not only a large concept but many seem to be imperfect with it. Your apps will have tons of data and the sensitive information of your company as well as the users on your app. Depending on the app you develop may have payment information crucial information like home address, phone number, and many more things of a user-provided the. Users will hesitate to provide you with information if your app isnβt secure. If security gets breached, it could be so damaging to your brand that it will be tough to recover."
},
{
"code": null,
"e": 35458,
"s": 35303,
"text": "So as a developer itβs your duty to take measures and use encryptions and other tactics like (Two- Factor-Authentication 2FA), to protect sensitive info. "
},
{
"code": null,
"e": 35595,
"s": 35458,
"text": "Tip: Make sure your application has the feature to wipe out all the data and set up automatic backup as well if urgent the user demands."
},
{
"code": null,
"e": 36240,
"s": 35595,
"text": "Switch to Android Studio β Itβs an official IDE of AndroidUse Android Debug Databaseβ Allow you to use the database and send preferences into the browser.Use legit external libraries and give them required permissions only. Firstly ignore third-party libraries.Avoid using floating-point β Floating points are around 2times slower than the integers on android devices.If there are lots of modifications to strings of characters, Use StringBuffer or StringBuilder classes.Install Modularization in-App.Use strings.xml β Adding text as String resources is always useful in the long run especially when support for new languages needs to be added."
},
{
"code": null,
"e": 36299,
"s": 36240,
"text": "Switch to Android Studio β Itβs an official IDE of Android"
},
{
"code": null,
"e": 36396,
"s": 36299,
"text": "Use Android Debug Databaseβ Allow you to use the database and send preferences into the browser."
},
{
"code": null,
"e": 36504,
"s": 36396,
"text": "Use legit external libraries and give them required permissions only. Firstly ignore third-party libraries."
},
{
"code": null,
"e": 36612,
"s": 36504,
"text": "Avoid using floating-point β Floating points are around 2times slower than the integers on android devices."
},
{
"code": null,
"e": 36716,
"s": 36612,
"text": "If there are lots of modifications to strings of characters, Use StringBuffer or StringBuilder classes."
},
{
"code": null,
"e": 36747,
"s": 36716,
"text": "Install Modularization in-App."
},
{
"code": null,
"e": 36891,
"s": 36747,
"text": "Use strings.xml β Adding text as String resources is always useful in the long run especially when support for new languages needs to be added."
},
{
"code": null,
"e": 37272,
"s": 36891,
"text": "Developing a mobile app is not everyoneβs cup of tea. Itβs not only a vast development stack but also has lots of varieties in each of its parts. On your road of development, you will have to cross bumps and breakers to achieve milestones, So, I believe having few guidelines and best practices helps you develop the application much easier if you implement it in your routine. "
},
{
"code": null,
"e": 37279,
"s": 37272,
"text": "Picked"
},
{
"code": null,
"e": 37287,
"s": 37279,
"text": "Android"
},
{
"code": null,
"e": 37293,
"s": 37287,
"text": "GBlog"
},
{
"code": null,
"e": 37301,
"s": 37293,
"text": "Android"
},
{
"code": null,
"e": 37399,
"s": 37301,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37408,
"s": 37399,
"text": "Comments"
},
{
"code": null,
"e": 37421,
"s": 37408,
"text": "Old Comments"
},
{
"code": null,
"e": 37460,
"s": 37421,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 37510,
"s": 37460,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 37548,
"s": 37510,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 37599,
"s": 37548,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 37641,
"s": 37599,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 37715,
"s": 37641,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 37771,
"s": 37715,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 37799,
"s": 37771,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 37824,
"s": 37799,
"text": "DSA Sheet by Love Babbar"
}
] |
Mito: Speed Up Dataset Manipulation with No Coding | by Angelica Lo Duca | Towards Data Science
|
Iβm always looking for new tools to improve my Data Scientist activity. This time I came across Mito, a spreadsheet provided as a Python library, which allows you to manipulate a dataset in a simple and fast way, and above all in an interactive way.
Mito provides a graphical interface within the Jupyter Lab environment, so you can manipulate any dataset.
In practice, Mito combines the classic functionalities of spreadsheets (such as their user friendly usability), with all potentialities of Python. In fact, all the operations carried out within the interface are automatically translated into a Python code that can also be used elsewhere.
Mito provides the following features:
import/export datasets
add/delete columns to a dataset
build pivot tables
merge two datasets
plot charts
filter/sort columns
columns statistics
In this article, I give an overview of Mito, as well as a practical example of usage.
Mito is an interactive spreadsheet, provided as a Python library, which runs within Jupiter Lab, which must be installed in advance.
Mito can be easily installed through the following commands:
python3 -m pip install mitoinstallerpython3 -m mitoinstaller install
The Mito Official Documentation comes with a detailed description of common installation problems, which can help you if the installation process fails. In my case, the installation was ok.
Once installed, you must restart Jupyter Lab, if it is running, in order to enable Mito. You can run Jupyter Lab from command line through the following command:
jupyter lab
In order to run the Mito interactive interface, you can create a new notebook and write the following code in a cell:
import mitosheetmitosheet.sheet()
Each time you modify a dataset through the Mito interface, Mito generates the equivalent Python code in the cell below.
Datasets are stored as Pandas dataframes, which can be also manipulated directly in a cell.
The first time you run Mito, a new popup opens, asking for some information, such as your email and other similar stuff:
After Signed up, the Mito interactive interface starts within the notebook environment. You can enable the full screen modality, by clicking the top right button.
The interface provides the following menu bar:
Starting from the left, the following menu items are available:
undo β erase the last change done on the dataset;
import β load a new dataset from the file system. A popup opens, which permits you to browse among the directories of the filesystem. Supported formats include Excel (XLSX) and CSV;
export β download a manipulated dataset as a CSV to your local filesystem;
add column β add a new column to the dataset. You can change the column name, as well as the column values. In this last case, you can either enter values manually or calculate values from the other columns. It is sufficient to double click on the first row of the column to insert a formula;
delete column β erase a column completely;
pivot β build a pivot table. The resulting table is opened into a new tab, thus it can be manipulated separately;
merge β merge two datasets. You can choose among the following merge types:
graph β plot a graph for Exploratory Data Analysis (EDA). You can choose the columns associated to X and Y axes and then choose one of the supported graphs (see figure on the left for the supported graph types). All the graphs are generated in Plotly, one of the most famous Python libraries for Data Visualization. Mito saves the HTML file generated by Plotly for each graph. You can even copy the code produced to generate the graph;
save β save the current mitosheet;
replay β re-run the saved operations on new data.
If you click on a column name, a new popup opens, like the following one:
You can select the column type and order values (ascending or descending). You can even add one or more filters or a group of filters, for example to select only values matching some specific criteria. You can also search for specific values in a column.
Finally, in the Summary Stats tab, the distribution of your column is shown, as well as more specific summary information, including count, unique, top and frequency.
As use-case, I exploit the diamond.csv dataset, available on Kaggle. Firstly, I create a new notebook and in the first cell I write the following code:
import mitosheetmitosheet.sheet()
I select the first column, named Unnamed: 0, then I click on the DEL COL button, as shown in the following figure:
As a result, the column is deleted, as well as the corresponding Python code is generated in the cell below:
# Imported /Users/angelica/mitosheet_test/source/diamonds.csvimport pandas as pddiamonds_csv = pd.read_csv(r'/Users/angelica/mitosheet_test/source/diamonds.csv')# Deleted column(s) Unnamed: 0 from diamonds_csvdiamonds_csv.drop(['Unnamed: 0'], axis=1, inplace=True)
Now, I build a pivot table, which shows the average price per colour and cut type. I click the Pivot button and I select the following options in the popup window:
I also rename column names, simply by double clicking on the column name. With a single operation, Mito produces the following table:
Mito generates the corresponding code automatically:
# Pivoted diamonds_csv into df2unused_columns = diamonds_csv.columns.difference(set(['color']).union(set(['cut'])).union(set({'price'})))tmp_df = diamonds_csv.drop(unused_columns, axis=1)pivot_table = tmp_df.pivot_table( index=['color'], columns=['cut'], values=['price'], aggfunc={'price': ['mean']})# Flatten the column headerspivot_table.columns = [flatten_column_header(col) for col in pivot_table.columns.values]# Reset the column name and the indexesdf2 = pivot_table.reset_index()# Renamed price mean Fair to Fair in df2df2.rename(columns={"price mean Fair": "Fair"}, inplace=True)# Renamed price mean Good to Good in df2df2.rename(columns={"price mean Good": "Good"}, inplace=True)# Renamed price mean Ideal to Ideal in df2df2.rename(columns={"price mean Ideal": "Ideal"}, inplace=True)# Renamed price mean Premium to Premium in df2df2.rename(columns={"price mean Premium": "Premium"}, inplace=True)# Renamed price mean Very Good to Very Good in df2df2.rename(columns={"price mean Very Good": "Very Good"}, inplace=True)
Given the previous defined pivot table, I build a bar chart, which shows for each colour and cut type, the average price. Mito permits to add maximum three series in each graph. Thus in my graph, I include Ideal, Premium and Very Good.
Mito permits either to download the generated graph as a png file or to copy the graph code:
# Import plotly and create a figureimport plotly.graph_objects as gofig = go.Figure()# Add the bar chart traces to the graphfor column_header in ['Ideal', 'Premium', 'Very Good']: fig.add_trace( go.Bar( x=df2['color'], y=df2[column_header], name=column_header ) )# Update the title and stacking mode of the graph# See Plotly documentation for customizations: https://plotly.com/python/reference/bar/fig.update_layout( xaxis_title='color', yaxis_title='', title='color, Ideal, Premium, Very Good bar chart', barmode='group',)fig.show(renderer="iframe")
Since the graph is generated in Plotly, I can modify it by following the Plotly guidelines.
Now I load a second dataset, which contains for each cut type, its owner:
The idea is to merge the original dataset with the second one, previous loaded. I click the Merge button and I configure how to merge the two datasets, as shown in the following figure:
As a result, a new dataset is created, which includes all the columns of both the starting datasets:
As in the previous cases, Mito generates the Python code for the merging operation:
# Imported /Users/angelica/CNR/Git/mitosheet_test/source/cut_owners.csvimport pandas as pdcut_owners_csv = pd.read_csv(r'/Users/angelica/CNR/Git/mitosheet_test/source/cut_owners.csv')# Imported /Users/angelica/CNR/Git/mitosheet_test/source/cut_owners.csvimport pandas as pdcut_owners_csv_1 = pd.read_csv(r'/Users/angelica/CNR/Git/mitosheet_test/source/cut_owners.csv')# Merged diamonds_csv and cut_owners_csvtemp_df = cut_owners_csv.drop_duplicates(subset='cut') # Remove duplicates so lookup merge only returns first matchdf5 = diamonds_csv.merge(temp_df, left_on=['cut'], right_on=['cut'], how='left', suffixes=['_diamonds_csv', '_cut_owners_csv'])
Finally, I perform some operations on a single column. I can open the associated popup window by clicking the funnel icon near the column name. I consider the carat column, which is numeric and I sort it in ascending order, simply by clicking the Ascending button in the Filter/Sort tab. Then I create a new filter, which selects only rows with a value greater than 0.3.
Again, Mito generates automatically the Python code:
# Sorted carat in df5 in ascending orderdf5 = df5.sort_values(by='carat', ascending=True, na_position='first')# Filtered carat in df5df5 = df5[df5['carat'] > 0.3]
Now, I select the Summary Stats tab and Mito shows the following statistics on the carat column:
In this article, I have described Mito, a spreadsheet which permits to manipulate datasets very quickly. Mito can be easily run in Jupyter Lab, thus you just have to try it :)
The full code used in this article can be downloaded from my Github Repository.
If you have read this far, for me it is already a lot for today. Thanks! You can read more about me in this article.
You could subscribe for few dollars per month and unlock unlimited articles β click here.
towardsdatascience.com
towardsdatascience.com
alod83.medium.com
Disclaimer: This is not a sponsored article. I donβt have any affiliation with Mito or its authors. The article shows an unbiased overview of the framework, aiming at making data science tools accessible to the broader people.
|
[
{
"code": null,
"e": 422,
"s": 172,
"text": "Iβm always looking for new tools to improve my Data Scientist activity. This time I came across Mito, a spreadsheet provided as a Python library, which allows you to manipulate a dataset in a simple and fast way, and above all in an interactive way."
},
{
"code": null,
"e": 529,
"s": 422,
"text": "Mito provides a graphical interface within the Jupyter Lab environment, so you can manipulate any dataset."
},
{
"code": null,
"e": 818,
"s": 529,
"text": "In practice, Mito combines the classic functionalities of spreadsheets (such as their user friendly usability), with all potentialities of Python. In fact, all the operations carried out within the interface are automatically translated into a Python code that can also be used elsewhere."
},
{
"code": null,
"e": 856,
"s": 818,
"text": "Mito provides the following features:"
},
{
"code": null,
"e": 879,
"s": 856,
"text": "import/export datasets"
},
{
"code": null,
"e": 911,
"s": 879,
"text": "add/delete columns to a dataset"
},
{
"code": null,
"e": 930,
"s": 911,
"text": "build pivot tables"
},
{
"code": null,
"e": 949,
"s": 930,
"text": "merge two datasets"
},
{
"code": null,
"e": 961,
"s": 949,
"text": "plot charts"
},
{
"code": null,
"e": 981,
"s": 961,
"text": "filter/sort columns"
},
{
"code": null,
"e": 1000,
"s": 981,
"text": "columns statistics"
},
{
"code": null,
"e": 1086,
"s": 1000,
"text": "In this article, I give an overview of Mito, as well as a practical example of usage."
},
{
"code": null,
"e": 1219,
"s": 1086,
"text": "Mito is an interactive spreadsheet, provided as a Python library, which runs within Jupiter Lab, which must be installed in advance."
},
{
"code": null,
"e": 1280,
"s": 1219,
"text": "Mito can be easily installed through the following commands:"
},
{
"code": null,
"e": 1349,
"s": 1280,
"text": "python3 -m pip install mitoinstallerpython3 -m mitoinstaller install"
},
{
"code": null,
"e": 1539,
"s": 1349,
"text": "The Mito Official Documentation comes with a detailed description of common installation problems, which can help you if the installation process fails. In my case, the installation was ok."
},
{
"code": null,
"e": 1701,
"s": 1539,
"text": "Once installed, you must restart Jupyter Lab, if it is running, in order to enable Mito. You can run Jupyter Lab from command line through the following command:"
},
{
"code": null,
"e": 1713,
"s": 1701,
"text": "jupyter lab"
},
{
"code": null,
"e": 1831,
"s": 1713,
"text": "In order to run the Mito interactive interface, you can create a new notebook and write the following code in a cell:"
},
{
"code": null,
"e": 1865,
"s": 1831,
"text": "import mitosheetmitosheet.sheet()"
},
{
"code": null,
"e": 1985,
"s": 1865,
"text": "Each time you modify a dataset through the Mito interface, Mito generates the equivalent Python code in the cell below."
},
{
"code": null,
"e": 2077,
"s": 1985,
"text": "Datasets are stored as Pandas dataframes, which can be also manipulated directly in a cell."
},
{
"code": null,
"e": 2198,
"s": 2077,
"text": "The first time you run Mito, a new popup opens, asking for some information, such as your email and other similar stuff:"
},
{
"code": null,
"e": 2361,
"s": 2198,
"text": "After Signed up, the Mito interactive interface starts within the notebook environment. You can enable the full screen modality, by clicking the top right button."
},
{
"code": null,
"e": 2408,
"s": 2361,
"text": "The interface provides the following menu bar:"
},
{
"code": null,
"e": 2472,
"s": 2408,
"text": "Starting from the left, the following menu items are available:"
},
{
"code": null,
"e": 2522,
"s": 2472,
"text": "undo β erase the last change done on the dataset;"
},
{
"code": null,
"e": 2704,
"s": 2522,
"text": "import β load a new dataset from the file system. A popup opens, which permits you to browse among the directories of the filesystem. Supported formats include Excel (XLSX) and CSV;"
},
{
"code": null,
"e": 2779,
"s": 2704,
"text": "export β download a manipulated dataset as a CSV to your local filesystem;"
},
{
"code": null,
"e": 3072,
"s": 2779,
"text": "add column β add a new column to the dataset. You can change the column name, as well as the column values. In this last case, you can either enter values manually or calculate values from the other columns. It is sufficient to double click on the first row of the column to insert a formula;"
},
{
"code": null,
"e": 3115,
"s": 3072,
"text": "delete column β erase a column completely;"
},
{
"code": null,
"e": 3229,
"s": 3115,
"text": "pivot β build a pivot table. The resulting table is opened into a new tab, thus it can be manipulated separately;"
},
{
"code": null,
"e": 3305,
"s": 3229,
"text": "merge β merge two datasets. You can choose among the following merge types:"
},
{
"code": null,
"e": 3741,
"s": 3305,
"text": "graph β plot a graph for Exploratory Data Analysis (EDA). You can choose the columns associated to X and Y axes and then choose one of the supported graphs (see figure on the left for the supported graph types). All the graphs are generated in Plotly, one of the most famous Python libraries for Data Visualization. Mito saves the HTML file generated by Plotly for each graph. You can even copy the code produced to generate the graph;"
},
{
"code": null,
"e": 3776,
"s": 3741,
"text": "save β save the current mitosheet;"
},
{
"code": null,
"e": 3826,
"s": 3776,
"text": "replay β re-run the saved operations on new data."
},
{
"code": null,
"e": 3900,
"s": 3826,
"text": "If you click on a column name, a new popup opens, like the following one:"
},
{
"code": null,
"e": 4155,
"s": 3900,
"text": "You can select the column type and order values (ascending or descending). You can even add one or more filters or a group of filters, for example to select only values matching some specific criteria. You can also search for specific values in a column."
},
{
"code": null,
"e": 4322,
"s": 4155,
"text": "Finally, in the Summary Stats tab, the distribution of your column is shown, as well as more specific summary information, including count, unique, top and frequency."
},
{
"code": null,
"e": 4474,
"s": 4322,
"text": "As use-case, I exploit the diamond.csv dataset, available on Kaggle. Firstly, I create a new notebook and in the first cell I write the following code:"
},
{
"code": null,
"e": 4508,
"s": 4474,
"text": "import mitosheetmitosheet.sheet()"
},
{
"code": null,
"e": 4623,
"s": 4508,
"text": "I select the first column, named Unnamed: 0, then I click on the DEL COL button, as shown in the following figure:"
},
{
"code": null,
"e": 4732,
"s": 4623,
"text": "As a result, the column is deleted, as well as the corresponding Python code is generated in the cell below:"
},
{
"code": null,
"e": 4997,
"s": 4732,
"text": "# Imported /Users/angelica/mitosheet_test/source/diamonds.csvimport pandas as pddiamonds_csv = pd.read_csv(r'/Users/angelica/mitosheet_test/source/diamonds.csv')# Deleted column(s) Unnamed: 0 from diamonds_csvdiamonds_csv.drop(['Unnamed: 0'], axis=1, inplace=True)"
},
{
"code": null,
"e": 5161,
"s": 4997,
"text": "Now, I build a pivot table, which shows the average price per colour and cut type. I click the Pivot button and I select the following options in the popup window:"
},
{
"code": null,
"e": 5295,
"s": 5161,
"text": "I also rename column names, simply by double clicking on the column name. With a single operation, Mito produces the following table:"
},
{
"code": null,
"e": 5348,
"s": 5295,
"text": "Mito generates the corresponding code automatically:"
},
{
"code": null,
"e": 6389,
"s": 5348,
"text": "# Pivoted diamonds_csv into df2unused_columns = diamonds_csv.columns.difference(set(['color']).union(set(['cut'])).union(set({'price'})))tmp_df = diamonds_csv.drop(unused_columns, axis=1)pivot_table = tmp_df.pivot_table( index=['color'], columns=['cut'], values=['price'], aggfunc={'price': ['mean']})# Flatten the column headerspivot_table.columns = [flatten_column_header(col) for col in pivot_table.columns.values]# Reset the column name and the indexesdf2 = pivot_table.reset_index()# Renamed price mean Fair to Fair in df2df2.rename(columns={\"price mean Fair\": \"Fair\"}, inplace=True)# Renamed price mean Good to Good in df2df2.rename(columns={\"price mean Good\": \"Good\"}, inplace=True)# Renamed price mean Ideal to Ideal in df2df2.rename(columns={\"price mean Ideal\": \"Ideal\"}, inplace=True)# Renamed price mean Premium to Premium in df2df2.rename(columns={\"price mean Premium\": \"Premium\"}, inplace=True)# Renamed price mean Very Good to Very Good in df2df2.rename(columns={\"price mean Very Good\": \"Very Good\"}, inplace=True)"
},
{
"code": null,
"e": 6625,
"s": 6389,
"text": "Given the previous defined pivot table, I build a bar chart, which shows for each colour and cut type, the average price. Mito permits to add maximum three series in each graph. Thus in my graph, I include Ideal, Premium and Very Good."
},
{
"code": null,
"e": 6718,
"s": 6625,
"text": "Mito permits either to download the generated graph as a png file or to copy the graph code:"
},
{
"code": null,
"e": 7336,
"s": 6718,
"text": "# Import plotly and create a figureimport plotly.graph_objects as gofig = go.Figure()# Add the bar chart traces to the graphfor column_header in ['Ideal', 'Premium', 'Very Good']: fig.add_trace( go.Bar( x=df2['color'], y=df2[column_header], name=column_header ) )# Update the title and stacking mode of the graph# See Plotly documentation for customizations: https://plotly.com/python/reference/bar/fig.update_layout( xaxis_title='color', yaxis_title='', title='color, Ideal, Premium, Very Good bar chart', barmode='group',)fig.show(renderer=\"iframe\")"
},
{
"code": null,
"e": 7428,
"s": 7336,
"text": "Since the graph is generated in Plotly, I can modify it by following the Plotly guidelines."
},
{
"code": null,
"e": 7502,
"s": 7428,
"text": "Now I load a second dataset, which contains for each cut type, its owner:"
},
{
"code": null,
"e": 7688,
"s": 7502,
"text": "The idea is to merge the original dataset with the second one, previous loaded. I click the Merge button and I configure how to merge the two datasets, as shown in the following figure:"
},
{
"code": null,
"e": 7789,
"s": 7688,
"text": "As a result, a new dataset is created, which includes all the columns of both the starting datasets:"
},
{
"code": null,
"e": 7873,
"s": 7789,
"text": "As in the previous cases, Mito generates the Python code for the merging operation:"
},
{
"code": null,
"e": 8524,
"s": 7873,
"text": "# Imported /Users/angelica/CNR/Git/mitosheet_test/source/cut_owners.csvimport pandas as pdcut_owners_csv = pd.read_csv(r'/Users/angelica/CNR/Git/mitosheet_test/source/cut_owners.csv')# Imported /Users/angelica/CNR/Git/mitosheet_test/source/cut_owners.csvimport pandas as pdcut_owners_csv_1 = pd.read_csv(r'/Users/angelica/CNR/Git/mitosheet_test/source/cut_owners.csv')# Merged diamonds_csv and cut_owners_csvtemp_df = cut_owners_csv.drop_duplicates(subset='cut') # Remove duplicates so lookup merge only returns first matchdf5 = diamonds_csv.merge(temp_df, left_on=['cut'], right_on=['cut'], how='left', suffixes=['_diamonds_csv', '_cut_owners_csv'])"
},
{
"code": null,
"e": 8895,
"s": 8524,
"text": "Finally, I perform some operations on a single column. I can open the associated popup window by clicking the funnel icon near the column name. I consider the carat column, which is numeric and I sort it in ascending order, simply by clicking the Ascending button in the Filter/Sort tab. Then I create a new filter, which selects only rows with a value greater than 0.3."
},
{
"code": null,
"e": 8948,
"s": 8895,
"text": "Again, Mito generates automatically the Python code:"
},
{
"code": null,
"e": 9111,
"s": 8948,
"text": "# Sorted carat in df5 in ascending orderdf5 = df5.sort_values(by='carat', ascending=True, na_position='first')# Filtered carat in df5df5 = df5[df5['carat'] > 0.3]"
},
{
"code": null,
"e": 9208,
"s": 9111,
"text": "Now, I select the Summary Stats tab and Mito shows the following statistics on the carat column:"
},
{
"code": null,
"e": 9384,
"s": 9208,
"text": "In this article, I have described Mito, a spreadsheet which permits to manipulate datasets very quickly. Mito can be easily run in Jupyter Lab, thus you just have to try it :)"
},
{
"code": null,
"e": 9464,
"s": 9384,
"text": "The full code used in this article can be downloaded from my Github Repository."
},
{
"code": null,
"e": 9581,
"s": 9464,
"text": "If you have read this far, for me it is already a lot for today. Thanks! You can read more about me in this article."
},
{
"code": null,
"e": 9671,
"s": 9581,
"text": "You could subscribe for few dollars per month and unlock unlimited articles β click here."
},
{
"code": null,
"e": 9694,
"s": 9671,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9717,
"s": 9694,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9735,
"s": 9717,
"text": "alod83.medium.com"
}
] |
PCA using Python (scikit-learn) | by Michael Galarnyk | Towards Data Science
|
My last tutorial went over Logistic Regression using Python. One of the things learned was that you can speed up the fitting of a machine learning algorithm by changing the optimization algorithm. A more common way of speeding up a machine learning algorithm is by using Principal Component Analysis (PCA). If your learning algorithm is too slow because the input dimension is too high, then using PCA to speed it up can be a reasonable choice. This is probably the most common application of PCA. Another common application of PCA is for data visualization.
To understand the value of using PCA for data visualization, the first part of this tutorial post goes over a basic visualization of the IRIS dataset after applying PCA. The second part uses PCA to speed up a machine learning algorithm (logistic regression) on the MNIST dataset.
With that, letβs get started! If you get lost, I recommend opening the video below in a separate tab.
The code used in this tutorial is available below
PCA for Data Visualization
PCA to Speed-up Machine Learning Algorithms
For a lot of machine learning applications it helps to be able to visualize your data. Visualizing 2 or 3 dimensional data is not that challenging. However, even the Iris dataset used in this part of the tutorial is 4 dimensional. You can use PCA to reduce that 4 dimensional data into 2 or 3 dimensions so that you can plot and hopefully understand the data better.
The Iris dataset is one of datasets scikit-learn comes with that do not require the downloading of any file from some external website. The code below will load the iris dataset.
import pandas as pdurl = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"# load dataset into Pandas DataFramedf = pd.read_csv(url, names=['sepal length','sepal width','petal length','petal width','target'])
PCA is effected by scale so you need to scale the features in your data before applying PCA. Use StandardScaler to help you standardize the datasetβs features onto unit scale (mean = 0 and variance = 1) which is a requirement for the optimal performance of many machine learning algorithms. If you want to see the negative effect not scaling your data can have, scikit-learn has a section on the effects of not standardizing your data.
from sklearn.preprocessing import StandardScalerfeatures = ['sepal length', 'sepal width', 'petal length', 'petal width']# Separating out the featuresx = df.loc[:, features].values# Separating out the targety = df.loc[:,['target']].values# Standardizing the featuresx = StandardScaler().fit_transform(x)
The original data has 4 columns (sepal length, sepal width, petal length, and petal width). In this section, the code projects the original data which is 4 dimensional into 2 dimensions. I should note that after dimensionality reduction, there usually isnβt a particular meaning assigned to each principal component. The new components are just the two main dimensions of variation.
from sklearn.decomposition import PCApca = PCA(n_components=2)principalComponents = pca.fit_transform(x)principalDf = pd.DataFrame(data = principalComponents , columns = ['principal component 1', 'principal component 2'])
finalDf = pd.concat([principalDf, df[['target']]], axis = 1)
Concatenating DataFrame along axis = 1. finalDf is the final DataFrame before plotting the data.
This section is just plotting 2 dimensional data. Notice on the graph below that the classes seem well separated from each other.
fig = plt.figure(figsize = (8,8))ax = fig.add_subplot(1,1,1) ax.set_xlabel('Principal Component 1', fontsize = 15)ax.set_ylabel('Principal Component 2', fontsize = 15)ax.set_title('2 component PCA', fontsize = 20)targets = ['Iris-setosa', 'Iris-versicolor', 'Iris-virginica']colors = ['r', 'g', 'b']for target, color in zip(targets,colors): indicesToKeep = finalDf['target'] == target ax.scatter(finalDf.loc[indicesToKeep, 'principal component 1'] , finalDf.loc[indicesToKeep, 'principal component 2'] , c = color , s = 50)ax.legend(targets)ax.grid()
The explained variance tells you how much information (variance) can be attributed to each of the principal components. This is important as while you can convert 4 dimensional space to 2 dimensional space, you lose some of the variance (information) when you do this. By using the attribute explained_variance_ratio_, you can see that the first principal component contains 72.77% of the variance and the second principal component contains 23.03% of the variance. Together, the two components contain 95.80% of the information.
pca.explained_variance_ratio_
While there are other ways to speed up machine learning algorithms, one less commonly known way is to use PCA. For this section, we arenβt using the IRIS dataset as the dataset only has 150 rows and only 4 feature columns. The MNIST database of handwritten digits is more suitable as it has 784 feature columns (784 dimensions), a training set of 60,000 examples, and a test set of 10,000 examples.
You can also add a data_home parameter to fetch_mldata to change where you download the data.
from sklearn.datasets import fetch_openmlmnist = fetch_openml('mnist_784')
The images that you downloaded are contained in mnist.data and has a shape of (70000, 784) meaning there are 70,000 images with 784 dimensions (784 features).
The labels (the integers 0β9) are contained in mnist.target. The features are 784 dimensional (28 x 28 images) and the labels are simply numbers from 0β9.
Typically the train test split is 80% training and 20% test. In this case, I chose 6/7th of the data to be training and 1/7th of the data to be in the test set.
from sklearn.model_selection import train_test_split# test_size: what proportion of original data is used for test settrain_img, test_img, train_lbl, test_lbl = train_test_split( mnist.data, mnist.target, test_size=1/7.0, random_state=0)
The text in this paragraph is almost an exact copy of what was written earlier. PCA is effected by scale so you need to scale the features in the data before applying PCA. You can transform the data onto unit scale (mean = 0 and variance = 1) which is a requirement for the optimal performance of many machine learning algorithms. StandardScaler helps standardize the datasetβs features. Note you fit on the training set and transform on the training and test set. If you want to see the negative effect not scaling your data can have, scikit-learn has a section on the effects of not standardizing your data.
from sklearn.preprocessing import StandardScalerscaler = StandardScaler()# Fit on training set only.scaler.fit(train_img)# Apply transform to both the training set and the test set.train_img = scaler.transform(train_img)test_img = scaler.transform(test_img)
Notice the code below has .95 for the number of components parameter. It means that scikit-learn choose the minimum number of principal components such that 95% of the variance is retained.
from sklearn.decomposition import PCA# Make an instance of the Modelpca = PCA(.95)
Fit PCA on training set. Note: you are fitting PCA on the training set only.
pca.fit(train_img)
Note: You can find out how many components PCA choose after fitting the model using pca.n_components_ . In this case, 95% of the variance amounts to 330 principal components.
train_img = pca.transform(train_img)test_img = pca.transform(test_img)
Step 1: Import the model you want to use
In sklearn, all machine learning models are implemented as Python classes
from sklearn.linear_model import LogisticRegression
Step 2: Make an instance of the Model.
# all parameters not specified are set to their defaults# default solver is incredibly slow which is why it was changed to 'lbfgs'logisticRegr = LogisticRegression(solver = 'lbfgs')
Step 3: Training the model on the data, storing the information learned from the data
Model is learning the relationship between digits and labels
logisticRegr.fit(train_img, train_lbl)
Step 4: Predict the labels of new data (new images)
Uses the information the model learned during the model training process
The code below predicts for one observation
# Predict for One Observation (image)logisticRegr.predict(test_img[0].reshape(1,-1))
The code below predicts for multiple observations at once
# Predict for One Observation (image)logisticRegr.predict(test_img[0:10])
Measuring Model Performance
While accuracy is not always the best metric for machine learning algorithms (precision, recall, F1 Score, ROC Curve, etc would be better), it is used here for simplicity.
logisticRegr.score(test_img, test_lbl)
The whole point of this section of the tutorial was to show that you can use PCA to speed up the fitting of machine learning algorithms. The table below shows how long it took to fit logistic regression on my MacBook after using PCA (retaining different amounts of variance each time).
The earlier parts of the tutorial have demonstrated using PCA to compress high dimensional data to lower dimensional data. I wanted to briefly mention that PCA can also take the compressed representation of the data (lower dimensional data) back to an approximation of the original high dimensional data. If you are interested in the code that produces the image below, check out my github.
This is a post that I could have written on for a lot longer as PCA has many different uses. I hope this post helps you with whatever you are working on. My next machine learning tutorial goes over How to Speed up Scikit-Learn Model Training. If you any questions or thoughts on the tutorial, feel free to reach out in the comments below or through Twitter. If you want to learn about other algorithms, please consider taking my Machine Learning with Scikit-Learn LinkedIn Learning course.
|
[
{
"code": null,
"e": 730,
"s": 171,
"text": "My last tutorial went over Logistic Regression using Python. One of the things learned was that you can speed up the fitting of a machine learning algorithm by changing the optimization algorithm. A more common way of speeding up a machine learning algorithm is by using Principal Component Analysis (PCA). If your learning algorithm is too slow because the input dimension is too high, then using PCA to speed it up can be a reasonable choice. This is probably the most common application of PCA. Another common application of PCA is for data visualization."
},
{
"code": null,
"e": 1010,
"s": 730,
"text": "To understand the value of using PCA for data visualization, the first part of this tutorial post goes over a basic visualization of the IRIS dataset after applying PCA. The second part uses PCA to speed up a machine learning algorithm (logistic regression) on the MNIST dataset."
},
{
"code": null,
"e": 1112,
"s": 1010,
"text": "With that, letβs get started! If you get lost, I recommend opening the video below in a separate tab."
},
{
"code": null,
"e": 1162,
"s": 1112,
"text": "The code used in this tutorial is available below"
},
{
"code": null,
"e": 1189,
"s": 1162,
"text": "PCA for Data Visualization"
},
{
"code": null,
"e": 1233,
"s": 1189,
"text": "PCA to Speed-up Machine Learning Algorithms"
},
{
"code": null,
"e": 1600,
"s": 1233,
"text": "For a lot of machine learning applications it helps to be able to visualize your data. Visualizing 2 or 3 dimensional data is not that challenging. However, even the Iris dataset used in this part of the tutorial is 4 dimensional. You can use PCA to reduce that 4 dimensional data into 2 or 3 dimensions so that you can plot and hopefully understand the data better."
},
{
"code": null,
"e": 1779,
"s": 1600,
"text": "The Iris dataset is one of datasets scikit-learn comes with that do not require the downloading of any file from some external website. The code below will load the iris dataset."
},
{
"code": null,
"e": 2012,
"s": 1779,
"text": "import pandas as pdurl = \"https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data\"# load dataset into Pandas DataFramedf = pd.read_csv(url, names=['sepal length','sepal width','petal length','petal width','target'])"
},
{
"code": null,
"e": 2448,
"s": 2012,
"text": "PCA is effected by scale so you need to scale the features in your data before applying PCA. Use StandardScaler to help you standardize the datasetβs features onto unit scale (mean = 0 and variance = 1) which is a requirement for the optimal performance of many machine learning algorithms. If you want to see the negative effect not scaling your data can have, scikit-learn has a section on the effects of not standardizing your data."
},
{
"code": null,
"e": 2752,
"s": 2448,
"text": "from sklearn.preprocessing import StandardScalerfeatures = ['sepal length', 'sepal width', 'petal length', 'petal width']# Separating out the featuresx = df.loc[:, features].values# Separating out the targety = df.loc[:,['target']].values# Standardizing the featuresx = StandardScaler().fit_transform(x)"
},
{
"code": null,
"e": 3135,
"s": 2752,
"text": "The original data has 4 columns (sepal length, sepal width, petal length, and petal width). In this section, the code projects the original data which is 4 dimensional into 2 dimensions. I should note that after dimensionality reduction, there usually isnβt a particular meaning assigned to each principal component. The new components are just the two main dimensions of variation."
},
{
"code": null,
"e": 3369,
"s": 3135,
"text": "from sklearn.decomposition import PCApca = PCA(n_components=2)principalComponents = pca.fit_transform(x)principalDf = pd.DataFrame(data = principalComponents , columns = ['principal component 1', 'principal component 2'])"
},
{
"code": null,
"e": 3430,
"s": 3369,
"text": "finalDf = pd.concat([principalDf, df[['target']]], axis = 1)"
},
{
"code": null,
"e": 3527,
"s": 3430,
"text": "Concatenating DataFrame along axis = 1. finalDf is the final DataFrame before plotting the data."
},
{
"code": null,
"e": 3657,
"s": 3527,
"text": "This section is just plotting 2 dimensional data. Notice on the graph below that the classes seem well separated from each other."
},
{
"code": null,
"e": 4256,
"s": 3657,
"text": "fig = plt.figure(figsize = (8,8))ax = fig.add_subplot(1,1,1) ax.set_xlabel('Principal Component 1', fontsize = 15)ax.set_ylabel('Principal Component 2', fontsize = 15)ax.set_title('2 component PCA', fontsize = 20)targets = ['Iris-setosa', 'Iris-versicolor', 'Iris-virginica']colors = ['r', 'g', 'b']for target, color in zip(targets,colors): indicesToKeep = finalDf['target'] == target ax.scatter(finalDf.loc[indicesToKeep, 'principal component 1'] , finalDf.loc[indicesToKeep, 'principal component 2'] , c = color , s = 50)ax.legend(targets)ax.grid()"
},
{
"code": null,
"e": 4786,
"s": 4256,
"text": "The explained variance tells you how much information (variance) can be attributed to each of the principal components. This is important as while you can convert 4 dimensional space to 2 dimensional space, you lose some of the variance (information) when you do this. By using the attribute explained_variance_ratio_, you can see that the first principal component contains 72.77% of the variance and the second principal component contains 23.03% of the variance. Together, the two components contain 95.80% of the information."
},
{
"code": null,
"e": 4816,
"s": 4786,
"text": "pca.explained_variance_ratio_"
},
{
"code": null,
"e": 5215,
"s": 4816,
"text": "While there are other ways to speed up machine learning algorithms, one less commonly known way is to use PCA. For this section, we arenβt using the IRIS dataset as the dataset only has 150 rows and only 4 feature columns. The MNIST database of handwritten digits is more suitable as it has 784 feature columns (784 dimensions), a training set of 60,000 examples, and a test set of 10,000 examples."
},
{
"code": null,
"e": 5309,
"s": 5215,
"text": "You can also add a data_home parameter to fetch_mldata to change where you download the data."
},
{
"code": null,
"e": 5384,
"s": 5309,
"text": "from sklearn.datasets import fetch_openmlmnist = fetch_openml('mnist_784')"
},
{
"code": null,
"e": 5543,
"s": 5384,
"text": "The images that you downloaded are contained in mnist.data and has a shape of (70000, 784) meaning there are 70,000 images with 784 dimensions (784 features)."
},
{
"code": null,
"e": 5698,
"s": 5543,
"text": "The labels (the integers 0β9) are contained in mnist.target. The features are 784 dimensional (28 x 28 images) and the labels are simply numbers from 0β9."
},
{
"code": null,
"e": 5859,
"s": 5698,
"text": "Typically the train test split is 80% training and 20% test. In this case, I chose 6/7th of the data to be training and 1/7th of the data to be in the test set."
},
{
"code": null,
"e": 6097,
"s": 5859,
"text": "from sklearn.model_selection import train_test_split# test_size: what proportion of original data is used for test settrain_img, test_img, train_lbl, test_lbl = train_test_split( mnist.data, mnist.target, test_size=1/7.0, random_state=0)"
},
{
"code": null,
"e": 6707,
"s": 6097,
"text": "The text in this paragraph is almost an exact copy of what was written earlier. PCA is effected by scale so you need to scale the features in the data before applying PCA. You can transform the data onto unit scale (mean = 0 and variance = 1) which is a requirement for the optimal performance of many machine learning algorithms. StandardScaler helps standardize the datasetβs features. Note you fit on the training set and transform on the training and test set. If you want to see the negative effect not scaling your data can have, scikit-learn has a section on the effects of not standardizing your data."
},
{
"code": null,
"e": 6965,
"s": 6707,
"text": "from sklearn.preprocessing import StandardScalerscaler = StandardScaler()# Fit on training set only.scaler.fit(train_img)# Apply transform to both the training set and the test set.train_img = scaler.transform(train_img)test_img = scaler.transform(test_img)"
},
{
"code": null,
"e": 7155,
"s": 6965,
"text": "Notice the code below has .95 for the number of components parameter. It means that scikit-learn choose the minimum number of principal components such that 95% of the variance is retained."
},
{
"code": null,
"e": 7238,
"s": 7155,
"text": "from sklearn.decomposition import PCA# Make an instance of the Modelpca = PCA(.95)"
},
{
"code": null,
"e": 7315,
"s": 7238,
"text": "Fit PCA on training set. Note: you are fitting PCA on the training set only."
},
{
"code": null,
"e": 7334,
"s": 7315,
"text": "pca.fit(train_img)"
},
{
"code": null,
"e": 7509,
"s": 7334,
"text": "Note: You can find out how many components PCA choose after fitting the model using pca.n_components_ . In this case, 95% of the variance amounts to 330 principal components."
},
{
"code": null,
"e": 7580,
"s": 7509,
"text": "train_img = pca.transform(train_img)test_img = pca.transform(test_img)"
},
{
"code": null,
"e": 7621,
"s": 7580,
"text": "Step 1: Import the model you want to use"
},
{
"code": null,
"e": 7695,
"s": 7621,
"text": "In sklearn, all machine learning models are implemented as Python classes"
},
{
"code": null,
"e": 7747,
"s": 7695,
"text": "from sklearn.linear_model import LogisticRegression"
},
{
"code": null,
"e": 7786,
"s": 7747,
"text": "Step 2: Make an instance of the Model."
},
{
"code": null,
"e": 7968,
"s": 7786,
"text": "# all parameters not specified are set to their defaults# default solver is incredibly slow which is why it was changed to 'lbfgs'logisticRegr = LogisticRegression(solver = 'lbfgs')"
},
{
"code": null,
"e": 8054,
"s": 7968,
"text": "Step 3: Training the model on the data, storing the information learned from the data"
},
{
"code": null,
"e": 8115,
"s": 8054,
"text": "Model is learning the relationship between digits and labels"
},
{
"code": null,
"e": 8154,
"s": 8115,
"text": "logisticRegr.fit(train_img, train_lbl)"
},
{
"code": null,
"e": 8206,
"s": 8154,
"text": "Step 4: Predict the labels of new data (new images)"
},
{
"code": null,
"e": 8279,
"s": 8206,
"text": "Uses the information the model learned during the model training process"
},
{
"code": null,
"e": 8323,
"s": 8279,
"text": "The code below predicts for one observation"
},
{
"code": null,
"e": 8408,
"s": 8323,
"text": "# Predict for One Observation (image)logisticRegr.predict(test_img[0].reshape(1,-1))"
},
{
"code": null,
"e": 8466,
"s": 8408,
"text": "The code below predicts for multiple observations at once"
},
{
"code": null,
"e": 8540,
"s": 8466,
"text": "# Predict for One Observation (image)logisticRegr.predict(test_img[0:10])"
},
{
"code": null,
"e": 8568,
"s": 8540,
"text": "Measuring Model Performance"
},
{
"code": null,
"e": 8740,
"s": 8568,
"text": "While accuracy is not always the best metric for machine learning algorithms (precision, recall, F1 Score, ROC Curve, etc would be better), it is used here for simplicity."
},
{
"code": null,
"e": 8779,
"s": 8740,
"text": "logisticRegr.score(test_img, test_lbl)"
},
{
"code": null,
"e": 9065,
"s": 8779,
"text": "The whole point of this section of the tutorial was to show that you can use PCA to speed up the fitting of machine learning algorithms. The table below shows how long it took to fit logistic regression on my MacBook after using PCA (retaining different amounts of variance each time)."
},
{
"code": null,
"e": 9456,
"s": 9065,
"text": "The earlier parts of the tutorial have demonstrated using PCA to compress high dimensional data to lower dimensional data. I wanted to briefly mention that PCA can also take the compressed representation of the data (lower dimensional data) back to an approximation of the original high dimensional data. If you are interested in the code that produces the image below, check out my github."
}
] |
Merry GAN-mas: Introduction to NVIDIA StyleGAN2 ADA | by Jeff Heaton | Towards Data Science
|
Generative Adversarial Neural Networks (GANs) are a type of neural network that can generate random βfakeβ images based on a training set of real images. GANs were introduced by Ian Goodfellow in his 2014 paper. GANs trained to produce human faces have received much media attention since the release of NVIDIA StyleGAN in 2018. Websites like Which Face is Real and This Person Does Not Exist demonstrate the amazing capabilities of NVIDIA StyleGAN. In this article I will explore the latest GAN technology, NVIDIA StyleGAN2 and demonstrate how to train it to produce holiday images.
The first step is to obtain a set of images to train the GAN. I created a Python utility called pyimgdata that you can use to download images from Flickr and perform other preprocessing. Flickr is a great place to obtain images and is used by many GAN paper authors, such as NVIDIA. Flickr is beneficial because it has an API to obtain images and contains license information for each upload. When building a dataset of images, it is generally advisable to use only images published by their authors with a permissive license.
My Flickr download utility makes use of a configuration file, such as the following:
This script downloads the results of the specified search into the specified path. The filenames will have the specified prefix. I specify all licenses because I do not intend to publish this image list. This actually brings up an open issue in copyright law. If a neural network learns from copyrighted and produces new work, is the AI bound to the original copyright? Similarly, is a human musician who listens to copyrighted music beholden to the copyright owner for inspiration that the music had on the musician's brain? For the purposes of copyright, I consider my GAN and its images to be a derivative work.
The license specifies which licenses you wish to download:
0 β All Rights Reserved
1 β Attribution-NonCommercial-ShareAlike License
2 β Attribution-NonCommercial License
3 β Attribution-NonCommercial-NoDerivs License
4 β Attribution License
5 β Attribution-ShareAlike License
6 β Attribution-NoDerivs License
7 β No known copyright restrictions
8 β United States Government Work
9 β Public Domain Dedication (CC0)
10 β Public Domain Mark
The process section of the configuration file allows the program to perform basic preprocessing on the images. For StyleGAN 2, the images must be square.
For this project, I collected around 3,000 images from Flickr, a sampling of which you can see here:
Training a GAN requires considerable computational power, particularly GPUs. Even with multiple high-end GPUs, training will take days. For this project, I had access to a Lenovo ThinkPad P53 and ThinkStation P920 that Lenovo had loaned me for my YouTube channel. Having access to dual high-end GPUs considerably speeds the training process.
StyleGAN2 ADA requires TensorFlow 1.14, which is somewhat older than the TensorFlow 2.x that I currently run on my machine. Additionally, TensorFlow 1.14 would require older CUDA drivers than I presently have installed. Because of these reasons, I created a Docker image to run StyleGAN2 ADA.
This Docker image can be run with the following command. This assumes you have NVIDIA Docker installed.
nvidia-docker run -it -u $(id -u):$(id -g) -v /home/username/:/mnt --device /dev/nvidia0:/dev/nvidia0 --device /dev/nvidiactl:/dev/nvidiactl --device /dev/nvidia-uvm:/dev/nvidia-uvm stylegan2:1.0 /bin/bash
The above command establishes the following:
-u $(id -u):$(id -g) β This causes the user to be logged in to Docker to be the same as the user running the Docker command. This ensures that all permissions and ownerships are correct on the mounted volumes.
/home/username/:/mnt β You should mount a volume to access your images and store results.
/bin/bash β We start the BASH shell to allow you to execute commands.
Your images must be converted to TFRecords. All of your images must be of the same size, square, and color depth. You cannot mix color and greyscale images. The following command converts a data set named βChristmasβ. The source JPEGs should be in the /mnt/data/christmas, and the resulting TFRecords will be written to /mnt/datasets/christmas.
python dataset_tool.py create_from_images /mnt/datasets/christmas /mnt/data/christmas
To actually train your GAN, you will enter a command similar to the following.
python train.py --gpus=1 --data=/mnt/datasets/christmas --mirror=1 --kimg 3000 --outdir=/mnt/results --aug=ada
You must provide an input directory that contains your image TFRecords. You must also provide an output results directory. The results directory will contain your generator's snapshots, sample images as training progresses, and a log.
While it takes considerable processing power to train a GAN, producing images with a GAN takes considerably less processing power. A GPU is still required to generate images; however, the GPU provided by Google CoLab is sufficient to perform this training. Images generated by the GAN will appear as follows:
The complete Jupyter notebook to generate your own Christmas images is stored here.
StyleGAN2 images are generated with a 512 number latent vector. The GAN was trained to generate images for random input vectors. Such a large vector is tedious to enter into source code, so seed values are generally used to generate this vector. While two very similar latent vectors will produce very similar looking images; two seeds with close numeric values will not necessarily produce similar images. Seeds are typically integer values, such as 1001, 1002, etc. The following function expands a seed to the full 512-number vector for a GAN generator specified by Gs.
def seed2vec(Gs, seed): rnd = np.random.RandomState(seed) return rnd.randn(1, *Gs.input_shape[1:])
The GAN contains several random values that can be changed for a given latent vector or seed. Changing these values will not substantially change a particular vectorβs output image. Generally, changing this value might change hair placement or some other minor, aesthetic appearance for a face-GAN. You need to provide a second seed is provided to initialize these random values.
def init_random_state(Gs, seed): rnd = np.random.RandomState(seed) noise_vars = [var for name, var in Gs.components.synthesis.vars.items() if name.startswith('noise')] tflib.set_vars({var: rnd.randn(*var.shape.as_list()) for var in noise_vars}) # [height, width]
Finally, we are ready to generate the image. The return value from this function is a numpy RGB array for the generated image.
def generate_image(Gs, z, truncation_psi): # Render images for dlatents initialized from random seeds. Gs_kwargs = { 'output_transform': dict(func=tflib.convert_images_to_uint8, nchw_to_nhwc=True), 'randomize_noise': False } if truncation_psi is not None: Gs_kwargs['truncation_psi'] = truncation_psi label = np.zeros([1] + Gs.input_shapes[1][1:]) images = Gs.run(z, label, **Gs_kwargs) # [minibatch, height, width, channel] return images[0]
The provided GitHub notebook also demonstrates how to fine-tune a GAN and generate a transformation video. Both of these features relate to the direct modification of the latent vector.
I produced a YouTube video covering much of the same topics as this article to see the transformation videos and fine-tuning.
|
[
{
"code": null,
"e": 755,
"s": 171,
"text": "Generative Adversarial Neural Networks (GANs) are a type of neural network that can generate random βfakeβ images based on a training set of real images. GANs were introduced by Ian Goodfellow in his 2014 paper. GANs trained to produce human faces have received much media attention since the release of NVIDIA StyleGAN in 2018. Websites like Which Face is Real and This Person Does Not Exist demonstrate the amazing capabilities of NVIDIA StyleGAN. In this article I will explore the latest GAN technology, NVIDIA StyleGAN2 and demonstrate how to train it to produce holiday images."
},
{
"code": null,
"e": 1282,
"s": 755,
"text": "The first step is to obtain a set of images to train the GAN. I created a Python utility called pyimgdata that you can use to download images from Flickr and perform other preprocessing. Flickr is a great place to obtain images and is used by many GAN paper authors, such as NVIDIA. Flickr is beneficial because it has an API to obtain images and contains license information for each upload. When building a dataset of images, it is generally advisable to use only images published by their authors with a permissive license."
},
{
"code": null,
"e": 1367,
"s": 1282,
"text": "My Flickr download utility makes use of a configuration file, such as the following:"
},
{
"code": null,
"e": 1982,
"s": 1367,
"text": "This script downloads the results of the specified search into the specified path. The filenames will have the specified prefix. I specify all licenses because I do not intend to publish this image list. This actually brings up an open issue in copyright law. If a neural network learns from copyrighted and produces new work, is the AI bound to the original copyright? Similarly, is a human musician who listens to copyrighted music beholden to the copyright owner for inspiration that the music had on the musician's brain? For the purposes of copyright, I consider my GAN and its images to be a derivative work."
},
{
"code": null,
"e": 2041,
"s": 1982,
"text": "The license specifies which licenses you wish to download:"
},
{
"code": null,
"e": 2065,
"s": 2041,
"text": "0 β All Rights Reserved"
},
{
"code": null,
"e": 2114,
"s": 2065,
"text": "1 β Attribution-NonCommercial-ShareAlike License"
},
{
"code": null,
"e": 2152,
"s": 2114,
"text": "2 β Attribution-NonCommercial License"
},
{
"code": null,
"e": 2199,
"s": 2152,
"text": "3 β Attribution-NonCommercial-NoDerivs License"
},
{
"code": null,
"e": 2223,
"s": 2199,
"text": "4 β Attribution License"
},
{
"code": null,
"e": 2258,
"s": 2223,
"text": "5 β Attribution-ShareAlike License"
},
{
"code": null,
"e": 2291,
"s": 2258,
"text": "6 β Attribution-NoDerivs License"
},
{
"code": null,
"e": 2327,
"s": 2291,
"text": "7 β No known copyright restrictions"
},
{
"code": null,
"e": 2361,
"s": 2327,
"text": "8 β United States Government Work"
},
{
"code": null,
"e": 2396,
"s": 2361,
"text": "9 β Public Domain Dedication (CC0)"
},
{
"code": null,
"e": 2420,
"s": 2396,
"text": "10 β Public Domain Mark"
},
{
"code": null,
"e": 2574,
"s": 2420,
"text": "The process section of the configuration file allows the program to perform basic preprocessing on the images. For StyleGAN 2, the images must be square."
},
{
"code": null,
"e": 2675,
"s": 2574,
"text": "For this project, I collected around 3,000 images from Flickr, a sampling of which you can see here:"
},
{
"code": null,
"e": 3017,
"s": 2675,
"text": "Training a GAN requires considerable computational power, particularly GPUs. Even with multiple high-end GPUs, training will take days. For this project, I had access to a Lenovo ThinkPad P53 and ThinkStation P920 that Lenovo had loaned me for my YouTube channel. Having access to dual high-end GPUs considerably speeds the training process."
},
{
"code": null,
"e": 3310,
"s": 3017,
"text": "StyleGAN2 ADA requires TensorFlow 1.14, which is somewhat older than the TensorFlow 2.x that I currently run on my machine. Additionally, TensorFlow 1.14 would require older CUDA drivers than I presently have installed. Because of these reasons, I created a Docker image to run StyleGAN2 ADA."
},
{
"code": null,
"e": 3414,
"s": 3310,
"text": "This Docker image can be run with the following command. This assumes you have NVIDIA Docker installed."
},
{
"code": null,
"e": 3621,
"s": 3414,
"text": "nvidia-docker run -it -u $(id -u):$(id -g) -v /home/username/:/mnt --device /dev/nvidia0:/dev/nvidia0 --device /dev/nvidiactl:/dev/nvidiactl --device /dev/nvidia-uvm:/dev/nvidia-uvm stylegan2:1.0 /bin/bash "
},
{
"code": null,
"e": 3666,
"s": 3621,
"text": "The above command establishes the following:"
},
{
"code": null,
"e": 3876,
"s": 3666,
"text": "-u $(id -u):$(id -g) β This causes the user to be logged in to Docker to be the same as the user running the Docker command. This ensures that all permissions and ownerships are correct on the mounted volumes."
},
{
"code": null,
"e": 3966,
"s": 3876,
"text": "/home/username/:/mnt β You should mount a volume to access your images and store results."
},
{
"code": null,
"e": 4036,
"s": 3966,
"text": "/bin/bash β We start the BASH shell to allow you to execute commands."
},
{
"code": null,
"e": 4381,
"s": 4036,
"text": "Your images must be converted to TFRecords. All of your images must be of the same size, square, and color depth. You cannot mix color and greyscale images. The following command converts a data set named βChristmasβ. The source JPEGs should be in the /mnt/data/christmas, and the resulting TFRecords will be written to /mnt/datasets/christmas."
},
{
"code": null,
"e": 4467,
"s": 4381,
"text": "python dataset_tool.py create_from_images /mnt/datasets/christmas /mnt/data/christmas"
},
{
"code": null,
"e": 4546,
"s": 4467,
"text": "To actually train your GAN, you will enter a command similar to the following."
},
{
"code": null,
"e": 4657,
"s": 4546,
"text": "python train.py --gpus=1 --data=/mnt/datasets/christmas --mirror=1 --kimg 3000 --outdir=/mnt/results --aug=ada"
},
{
"code": null,
"e": 4892,
"s": 4657,
"text": "You must provide an input directory that contains your image TFRecords. You must also provide an output results directory. The results directory will contain your generator's snapshots, sample images as training progresses, and a log."
},
{
"code": null,
"e": 5201,
"s": 4892,
"text": "While it takes considerable processing power to train a GAN, producing images with a GAN takes considerably less processing power. A GPU is still required to generate images; however, the GPU provided by Google CoLab is sufficient to perform this training. Images generated by the GAN will appear as follows:"
},
{
"code": null,
"e": 5285,
"s": 5201,
"text": "The complete Jupyter notebook to generate your own Christmas images is stored here."
},
{
"code": null,
"e": 5858,
"s": 5285,
"text": "StyleGAN2 images are generated with a 512 number latent vector. The GAN was trained to generate images for random input vectors. Such a large vector is tedious to enter into source code, so seed values are generally used to generate this vector. While two very similar latent vectors will produce very similar looking images; two seeds with close numeric values will not necessarily produce similar images. Seeds are typically integer values, such as 1001, 1002, etc. The following function expands a seed to the full 512-number vector for a GAN generator specified by Gs."
},
{
"code": null,
"e": 5959,
"s": 5858,
"text": "def seed2vec(Gs, seed): rnd = np.random.RandomState(seed) return rnd.randn(1, *Gs.input_shape[1:])"
},
{
"code": null,
"e": 6339,
"s": 5959,
"text": "The GAN contains several random values that can be changed for a given latent vector or seed. Changing these values will not substantially change a particular vectorβs output image. Generally, changing this value might change hair placement or some other minor, aesthetic appearance for a face-GAN. You need to provide a second seed is provided to initialize these random values."
},
{
"code": null,
"e": 6606,
"s": 6339,
"text": "def init_random_state(Gs, seed): rnd = np.random.RandomState(seed) noise_vars = [var for name, var in Gs.components.synthesis.vars.items() if name.startswith('noise')] tflib.set_vars({var: rnd.randn(*var.shape.as_list()) for var in noise_vars}) # [height, width]"
},
{
"code": null,
"e": 6733,
"s": 6606,
"text": "Finally, we are ready to generate the image. The return value from this function is a numpy RGB array for the generated image."
},
{
"code": null,
"e": 7217,
"s": 6733,
"text": "def generate_image(Gs, z, truncation_psi): # Render images for dlatents initialized from random seeds. Gs_kwargs = { 'output_transform': dict(func=tflib.convert_images_to_uint8, nchw_to_nhwc=True), 'randomize_noise': False } if truncation_psi is not None: Gs_kwargs['truncation_psi'] = truncation_psi label = np.zeros([1] + Gs.input_shapes[1][1:]) images = Gs.run(z, label, **Gs_kwargs) # [minibatch, height, width, channel] return images[0]"
},
{
"code": null,
"e": 7403,
"s": 7217,
"text": "The provided GitHub notebook also demonstrates how to fine-tune a GAN and generate a transformation video. Both of these features relate to the direct modification of the latent vector."
}
] |
Python Basics: Iteration, Iterables, Iterators, and Looping | by Ventsislav Yordanov | Towards Data Science
|
After reading this blog post, youβll know:
How the iteration in Python works under the hood
What are iterables and iterators and how to create them
What is the iterator protocol
What is a lazy evaluation
What are the generator functions and generator expressions
Python doesnβt have traditional for loops. Letβs see a pseudocode of how a traditional for loop looks in many other programming languages.
The initializer section is executed only once, before entering the loop.
The condition section must be a boolean expression. If this expression evaluates to True, the next loop iteration is executed.
The iterator section defines what happens after each iteration.
Now, letβs see how a traditional for loop can be written in JavaScript.
Output:
1012151820
Many of the other programming languages have this kind of for loop, but Python doesnβt have it. However, Python has something called for loop, but it works like a foreach loop.
Output:
1012151820
From the example above, we can see that in Pythonβs for loops we donβt have any of the sections weβve seen previously. There is no initializing, condition or iterator section.
An iterable is an object capable of returning its members one by one. Said in other words, an iterable is anything that you can loop over with a for loop in Python.
Sequences are a very common type of iterable. Some examples for built-in sequence types are lists, strings, and tuples.
They support efficient element access using integer indices via the __getitem()__ special method (indexing) and define a __length()__ method that returns the length of the sequence.
Output:
10blueberryβ€
Also, we can use the slicing technique on them. If you donβt know what is slicing, you can check one of my previous articles when I explain it. The explanation for the slicing technique is in the βSubsetting Listsβ section.
Output:
[10, 12]('pineapple', 'blueberry')love Python β€οΈ
Many things in Python are iterables, but not all of them are sequences. Dictionaries, file objects, sets, and generators are all iterables, but none of them is a sequence.
Letβs think about how we can loop over an iterable without using a for loop in Python. Some of us may think that we can use a while loop and generate indices to achieve this.
Output:
12345
It seems that this approach works very well for lists and other sequence objects. What about the non-sequence objects? They donβt support indexing, so this approach will not work for them.
Output:
--------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-22-af1fab82d68f> in <module>() 2 numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} 3 while index < len(numbers):----> 4 print(numbers[index]) 5 index += 1TypeError: 'set' object does not support indexing
Hmmm, but how the Pythonβs for loop works on these iterables then? We can see that it works with sets.
Output:
12345
An iterator is an object representing a stream of data. You can create an iterator object by applying the iter() built-in function to an iterable.
Output:
<list_iterator object at 0x000001DBCEC33B70><tuple_iterator object at 0x000001DBCEC33B00><str_iterator object at 0x000001DBCEC33C18>
You can use an iterator to manually loop over the iterable it came from. A repeated passing of iterator to the built-in function next()returns successive items in the stream. Once, when you consumed an item from an iterator, itβs gone. When no more data are available a StopIteration exception is raised.
Output:
102030--------------------------------------------------------------------StopIteration Traceback (most recent call last)<ipython-input-14-fd36f9d8809f> in <module>() 4 print(next(iterator)) 5 print(next(iterator))----> 6 print(next(iterator))StopIteration:
Under the hood, Pythonβs for loop is using iterators.
Now, we know what the iterables and iterators are and how to use them. We can try to define a function that loops through an iterable without using a for loop.
To achieve this, we need to:
Create an iterator from the given iterable
Repedeatly get the next item from the iterator
Execute the wanted action
Stop the looping, if we got a StopIteration exception when weβre trying to get the next item
Letβs try to use this function with a set of numbers and the print built-in function.
Output:
12345
We can see that the function weβve defined works very well with sets, which are not sequences. This time we can pass any iterable and it will work. Under the hood, all forms of looping over iterables in Python is working this way.
The iterator objects are required to support the following two methods, which together form the iterator protocol:
iterator.__iter__()Return the iterator object itself. This is required to allow both containers (also called collections) and iterators to be used with the for and in statements.
iterator.__next__()Return the next item from the container. If there are no more items, raise the StopIteration exception.
From the methods descriptions above, we see that we can loop over an iterator. So, the iterators are also iterables.
Remember that when we apply the iter() function to an iterable we get an iterator. If we call the iter() function on an iterator it will always give us itself back.
Output:
True100200300
This may sound a little bit confusing. However, donβt worry if you donβt understand all things of the first time. Letβs recap!
An iterable is something you can loop over.
An iterator is an object representing a stream of data. It does the iterating over an iterable.
Additionally, in Python, the iterators are also iterables which act as their own iterators.
However, the difference is that iterators donβt have some of the features that some iterables have. They donβt have length and canβt be indexed.
Examples
Output:
--------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-15-778b5f9befc3> in <module>() 1 numbers = [100, 200, 300] 2 iterator = iter(numbers)----> 3 print(len(iterator))TypeError: object of type 'list_iterator' has no len()
Output:
--------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-16-64c378cb8a99> in <module>() 1 numbers = [100, 200, 300] 2 iterator = iter(numbers)----> 3 print(iterator[0])TypeError: 'list_iterator' object is not subscriptable
Iterators allow us to both work with and create lazy iterables that donβt do any work until we ask them for their next item.
Source: https://opensource.com/article/18/3/loop-better-deeper-look-iteration-python
Because of their laziness, the iterators can help us to deal with infinitely long iterables. In some cases, we canβt even store all the information in the memory, so we can use an iterator which can give us the next item every time we ask it. Iterators can save us a lot of memory and CPU time.
This approach is called lazy evaluation.
We have seen some examples with iterators. Moreover, Python has many built-in classes that are iterators. For example, an enumerate and reversed objects are iterators.
Output:
<class 'enumerate'>(0, 'apple')
Output:
<class 'reversed'>blueberry
The Pythonβs zip, map and filer objects are also iterators.
Output:
<class 'zip'>(1, 1)(2, 4)
Output:
<class 'map'>14
Output:
<class 'filter'>3
Moreover, the file objects in Python are also iterators.
Output:
<class '_io.TextIOWrapper'>This is the first line.This is the second line.This is the third line.
We can also iterate over key-value pairs of a Python dictionary using the items() method.
Output:
<class 'dict_items'>name Ventsislavage 24
Many people use Python to solve Data Science problems. In some cases, the data you work with can be very large. In this cases, we canβt load all the data in the memory.
The solution is to load the data in chunks, then perform the desired operation/s on each chunk, discard the chunk and load the next chunk of data. Said in other words we need to create an iterator. We can achieve this by using the read_csv function in pandas. We just need to specify the chunksize.
In this example, weβll see the idea with a small dataset called βiris speciesβ, but the same concept will work with very large datasets, too. Iβve changed the column names, you can find my version here.
Output:
{'Iris-setosa': 50, 'Iris-versicolor': 50, 'Iris-virginica': 50}
There are a lot of iterator objects in the Python standard library and in third-party libraries.
In some cases, we may want to create a custom iterator. We can do that by defining a class that has __init__, __next__, and __iter__ methods.
Letβs try to create a custom iterator class that generate numbers between min value and max value.
Output:
<class '__main__.generate_numbers'>404142
We can see that this works. However, it is much easier to use a generator function or generator expression to create a custom iterator.
Usually, we use a generator function or generator expression when we want to create a custom iterator. They are simpler to use and need less code to achieve the same result.
Letβs see what is a generator function from the Python docs.
A function which returns a generator iterator. It looks like a normal function except that it contains yield expressions for producing a series of values usable in a for-loop or that can be retrieved one at a time with the next() function.
Source: https://docs.python.org/3.7/glossary.html#term-generator
Now, we can try to re-create our custom iterator using a generator function.
Output:
<class 'generator'>101112
The yield expression is the thing that separates a generation function from a normal function. This expression is helping us to use the iteratorβs laziness.
Each yield temporarily suspends processing, remembering the location execution state (including local variables and pending try-statements). When the generator iterator resumes, it picks up where it left off (in contrast to functions which start fresh on every invocation).
Source: https://docs.python.org/3.7/glossary.html#term-generator-iterator
The generator expressions are very similar to the list comprehensions. Just like a list comprehension, the general expressions are concise. In most cases, they are written in one line of code.
An expression that returns an iterator. It looks like a normal expression followed by a for expression defining a loop variable, range, and an optional if expression.
Source: https://docs.python.org/3.7/glossary.html#term-generator-expression
The general formula is:(output expression for iterator variable in iterable)
Letβs see how we can define a simple generator expression.
Output:
<class 'generator'>149
We can also add a conditional expression on the iterable. We can do it like this:
Output:
<class 'generator'>[4, 16]
They can be multiple conditional expressions on the iterable for more complex filtering.
Output:
<class 'generator'>[16]
Also, we can add an if-else clause on the output expression like this:
Output:
<class 'generator'>['odd', 'even', 'odd', 'even', 'odd']
An iterable is something you can loop over.
Sequences are a very common type of iterable.
Many things in Python are iterables, but not all of them are sequences.
An iterator is an object representing a stream of data. It does the iterating over an iterable. You can use an iterator to get the next value or to loop over it. Once, you loop over an iterator, there are no more stream values.
Iterators use the lazy evaluation approach.
Many built-in classes in Python are iterators.
A generator function is a function which returns an iterator.
A generator expression is an expression that returns an iterator.
You can look at the itertools library. This library includes functions creating iterators for efficient looping.
You can also read the docs or read/watch some of the resources below.
My next article about list comprehensions in Python.
https://opensource.com/article/18/3/loop-better-deeper-look-iteration-python
https://www.youtube.com/watch?v=V2PkkMS2Ack
https://www.datacamp.com/community/tutorials/python-iterator-tutorial
https://www.datacamp.com/courses/python-data-science-toolbox-part-2
https://en.wikipedia.org/wiki/Foreach_loop
https://docs.python.org/3.7/glossary.html#term-sequence
https://docs.python.org/3.7/glossary.html#term-generator
https://docs.python.org/3.7/library/stdtypes.html#iterator-types
https://docs.python.org/3/howto/functional.html?#iterators
You can also check my previous blog posts.
Jupyter Notebook Shortcuts
Python Basics for Data Science
Python Basics: List Comprehensions
Data Science with Python: Intro to Data Visualization with Matplotlib
Data Science with Python: Intro to Loading, Subsetting, and Filtering Data with pandas
Introduction to Natural Language Processing for Text
If you want to be notified when I post a new blog post you can subscribe to my newsletter.
Here is my LinkedIn profile in case you want to connect with me. Iβll be happy to be connected with you.
Thank you for the read. I hope that you have enjoyed the article. If you like it, please hold the clap button and share it with your friends. Iβll be happy to hear your feedback. If you have some questions, feel free to ask them. π
|
[
{
"code": null,
"e": 215,
"s": 172,
"text": "After reading this blog post, youβll know:"
},
{
"code": null,
"e": 264,
"s": 215,
"text": "How the iteration in Python works under the hood"
},
{
"code": null,
"e": 320,
"s": 264,
"text": "What are iterables and iterators and how to create them"
},
{
"code": null,
"e": 350,
"s": 320,
"text": "What is the iterator protocol"
},
{
"code": null,
"e": 376,
"s": 350,
"text": "What is a lazy evaluation"
},
{
"code": null,
"e": 435,
"s": 376,
"text": "What are the generator functions and generator expressions"
},
{
"code": null,
"e": 574,
"s": 435,
"text": "Python doesnβt have traditional for loops. Letβs see a pseudocode of how a traditional for loop looks in many other programming languages."
},
{
"code": null,
"e": 647,
"s": 574,
"text": "The initializer section is executed only once, before entering the loop."
},
{
"code": null,
"e": 774,
"s": 647,
"text": "The condition section must be a boolean expression. If this expression evaluates to True, the next loop iteration is executed."
},
{
"code": null,
"e": 838,
"s": 774,
"text": "The iterator section defines what happens after each iteration."
},
{
"code": null,
"e": 910,
"s": 838,
"text": "Now, letβs see how a traditional for loop can be written in JavaScript."
},
{
"code": null,
"e": 918,
"s": 910,
"text": "Output:"
},
{
"code": null,
"e": 929,
"s": 918,
"text": "1012151820"
},
{
"code": null,
"e": 1106,
"s": 929,
"text": "Many of the other programming languages have this kind of for loop, but Python doesnβt have it. However, Python has something called for loop, but it works like a foreach loop."
},
{
"code": null,
"e": 1114,
"s": 1106,
"text": "Output:"
},
{
"code": null,
"e": 1125,
"s": 1114,
"text": "1012151820"
},
{
"code": null,
"e": 1301,
"s": 1125,
"text": "From the example above, we can see that in Pythonβs for loops we donβt have any of the sections weβve seen previously. There is no initializing, condition or iterator section."
},
{
"code": null,
"e": 1466,
"s": 1301,
"text": "An iterable is an object capable of returning its members one by one. Said in other words, an iterable is anything that you can loop over with a for loop in Python."
},
{
"code": null,
"e": 1586,
"s": 1466,
"text": "Sequences are a very common type of iterable. Some examples for built-in sequence types are lists, strings, and tuples."
},
{
"code": null,
"e": 1768,
"s": 1586,
"text": "They support efficient element access using integer indices via the __getitem()__ special method (indexing) and define a __length()__ method that returns the length of the sequence."
},
{
"code": null,
"e": 1776,
"s": 1768,
"text": "Output:"
},
{
"code": null,
"e": 1789,
"s": 1776,
"text": "10blueberryβ€"
},
{
"code": null,
"e": 2013,
"s": 1789,
"text": "Also, we can use the slicing technique on them. If you donβt know what is slicing, you can check one of my previous articles when I explain it. The explanation for the slicing technique is in the βSubsetting Listsβ section."
},
{
"code": null,
"e": 2021,
"s": 2013,
"text": "Output:"
},
{
"code": null,
"e": 2070,
"s": 2021,
"text": "[10, 12]('pineapple', 'blueberry')love Python β€οΈ"
},
{
"code": null,
"e": 2242,
"s": 2070,
"text": "Many things in Python are iterables, but not all of them are sequences. Dictionaries, file objects, sets, and generators are all iterables, but none of them is a sequence."
},
{
"code": null,
"e": 2417,
"s": 2242,
"text": "Letβs think about how we can loop over an iterable without using a for loop in Python. Some of us may think that we can use a while loop and generate indices to achieve this."
},
{
"code": null,
"e": 2425,
"s": 2417,
"text": "Output:"
},
{
"code": null,
"e": 2431,
"s": 2425,
"text": "12345"
},
{
"code": null,
"e": 2620,
"s": 2431,
"text": "It seems that this approach works very well for lists and other sequence objects. What about the non-sequence objects? They donβt support indexing, so this approach will not work for them."
},
{
"code": null,
"e": 2628,
"s": 2620,
"text": "Output:"
},
{
"code": null,
"e": 2998,
"s": 2628,
"text": "--------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-22-af1fab82d68f> in <module>() 2 numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} 3 while index < len(numbers):----> 4 print(numbers[index]) 5 index += 1TypeError: 'set' object does not support indexing"
},
{
"code": null,
"e": 3101,
"s": 2998,
"text": "Hmmm, but how the Pythonβs for loop works on these iterables then? We can see that it works with sets."
},
{
"code": null,
"e": 3109,
"s": 3101,
"text": "Output:"
},
{
"code": null,
"e": 3115,
"s": 3109,
"text": "12345"
},
{
"code": null,
"e": 3262,
"s": 3115,
"text": "An iterator is an object representing a stream of data. You can create an iterator object by applying the iter() built-in function to an iterable."
},
{
"code": null,
"e": 3270,
"s": 3262,
"text": "Output:"
},
{
"code": null,
"e": 3403,
"s": 3270,
"text": "<list_iterator object at 0x000001DBCEC33B70><tuple_iterator object at 0x000001DBCEC33B00><str_iterator object at 0x000001DBCEC33C18>"
},
{
"code": null,
"e": 3708,
"s": 3403,
"text": "You can use an iterator to manually loop over the iterable it came from. A repeated passing of iterator to the built-in function next()returns successive items in the stream. Once, when you consumed an item from an iterator, itβs gone. When no more data are available a StopIteration exception is raised."
},
{
"code": null,
"e": 3716,
"s": 3708,
"text": "Output:"
},
{
"code": null,
"e": 4005,
"s": 3716,
"text": "102030--------------------------------------------------------------------StopIteration Traceback (most recent call last)<ipython-input-14-fd36f9d8809f> in <module>() 4 print(next(iterator)) 5 print(next(iterator))----> 6 print(next(iterator))StopIteration:"
},
{
"code": null,
"e": 4059,
"s": 4005,
"text": "Under the hood, Pythonβs for loop is using iterators."
},
{
"code": null,
"e": 4219,
"s": 4059,
"text": "Now, we know what the iterables and iterators are and how to use them. We can try to define a function that loops through an iterable without using a for loop."
},
{
"code": null,
"e": 4248,
"s": 4219,
"text": "To achieve this, we need to:"
},
{
"code": null,
"e": 4291,
"s": 4248,
"text": "Create an iterator from the given iterable"
},
{
"code": null,
"e": 4338,
"s": 4291,
"text": "Repedeatly get the next item from the iterator"
},
{
"code": null,
"e": 4364,
"s": 4338,
"text": "Execute the wanted action"
},
{
"code": null,
"e": 4457,
"s": 4364,
"text": "Stop the looping, if we got a StopIteration exception when weβre trying to get the next item"
},
{
"code": null,
"e": 4543,
"s": 4457,
"text": "Letβs try to use this function with a set of numbers and the print built-in function."
},
{
"code": null,
"e": 4551,
"s": 4543,
"text": "Output:"
},
{
"code": null,
"e": 4557,
"s": 4551,
"text": "12345"
},
{
"code": null,
"e": 4788,
"s": 4557,
"text": "We can see that the function weβve defined works very well with sets, which are not sequences. This time we can pass any iterable and it will work. Under the hood, all forms of looping over iterables in Python is working this way."
},
{
"code": null,
"e": 4903,
"s": 4788,
"text": "The iterator objects are required to support the following two methods, which together form the iterator protocol:"
},
{
"code": null,
"e": 5082,
"s": 4903,
"text": "iterator.__iter__()Return the iterator object itself. This is required to allow both containers (also called collections) and iterators to be used with the for and in statements."
},
{
"code": null,
"e": 5205,
"s": 5082,
"text": "iterator.__next__()Return the next item from the container. If there are no more items, raise the StopIteration exception."
},
{
"code": null,
"e": 5322,
"s": 5205,
"text": "From the methods descriptions above, we see that we can loop over an iterator. So, the iterators are also iterables."
},
{
"code": null,
"e": 5487,
"s": 5322,
"text": "Remember that when we apply the iter() function to an iterable we get an iterator. If we call the iter() function on an iterator it will always give us itself back."
},
{
"code": null,
"e": 5495,
"s": 5487,
"text": "Output:"
},
{
"code": null,
"e": 5509,
"s": 5495,
"text": "True100200300"
},
{
"code": null,
"e": 5636,
"s": 5509,
"text": "This may sound a little bit confusing. However, donβt worry if you donβt understand all things of the first time. Letβs recap!"
},
{
"code": null,
"e": 5680,
"s": 5636,
"text": "An iterable is something you can loop over."
},
{
"code": null,
"e": 5776,
"s": 5680,
"text": "An iterator is an object representing a stream of data. It does the iterating over an iterable."
},
{
"code": null,
"e": 5868,
"s": 5776,
"text": "Additionally, in Python, the iterators are also iterables which act as their own iterators."
},
{
"code": null,
"e": 6013,
"s": 5868,
"text": "However, the difference is that iterators donβt have some of the features that some iterables have. They donβt have length and canβt be indexed."
},
{
"code": null,
"e": 6022,
"s": 6013,
"text": "Examples"
},
{
"code": null,
"e": 6030,
"s": 6022,
"text": "Output:"
},
{
"code": null,
"e": 6359,
"s": 6030,
"text": "--------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-15-778b5f9befc3> in <module>() 1 numbers = [100, 200, 300] 2 iterator = iter(numbers)----> 3 print(len(iterator))TypeError: object of type 'list_iterator' has no len()"
},
{
"code": null,
"e": 6367,
"s": 6359,
"text": "Output:"
},
{
"code": null,
"e": 6694,
"s": 6367,
"text": "--------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-16-64c378cb8a99> in <module>() 1 numbers = [100, 200, 300] 2 iterator = iter(numbers)----> 3 print(iterator[0])TypeError: 'list_iterator' object is not subscriptable"
},
{
"code": null,
"e": 6819,
"s": 6694,
"text": "Iterators allow us to both work with and create lazy iterables that donβt do any work until we ask them for their next item."
},
{
"code": null,
"e": 6904,
"s": 6819,
"text": "Source: https://opensource.com/article/18/3/loop-better-deeper-look-iteration-python"
},
{
"code": null,
"e": 7199,
"s": 6904,
"text": "Because of their laziness, the iterators can help us to deal with infinitely long iterables. In some cases, we canβt even store all the information in the memory, so we can use an iterator which can give us the next item every time we ask it. Iterators can save us a lot of memory and CPU time."
},
{
"code": null,
"e": 7240,
"s": 7199,
"text": "This approach is called lazy evaluation."
},
{
"code": null,
"e": 7408,
"s": 7240,
"text": "We have seen some examples with iterators. Moreover, Python has many built-in classes that are iterators. For example, an enumerate and reversed objects are iterators."
},
{
"code": null,
"e": 7416,
"s": 7408,
"text": "Output:"
},
{
"code": null,
"e": 7448,
"s": 7416,
"text": "<class 'enumerate'>(0, 'apple')"
},
{
"code": null,
"e": 7456,
"s": 7448,
"text": "Output:"
},
{
"code": null,
"e": 7484,
"s": 7456,
"text": "<class 'reversed'>blueberry"
},
{
"code": null,
"e": 7544,
"s": 7484,
"text": "The Pythonβs zip, map and filer objects are also iterators."
},
{
"code": null,
"e": 7552,
"s": 7544,
"text": "Output:"
},
{
"code": null,
"e": 7578,
"s": 7552,
"text": "<class 'zip'>(1, 1)(2, 4)"
},
{
"code": null,
"e": 7586,
"s": 7578,
"text": "Output:"
},
{
"code": null,
"e": 7602,
"s": 7586,
"text": "<class 'map'>14"
},
{
"code": null,
"e": 7610,
"s": 7602,
"text": "Output:"
},
{
"code": null,
"e": 7628,
"s": 7610,
"text": "<class 'filter'>3"
},
{
"code": null,
"e": 7685,
"s": 7628,
"text": "Moreover, the file objects in Python are also iterators."
},
{
"code": null,
"e": 7693,
"s": 7685,
"text": "Output:"
},
{
"code": null,
"e": 7791,
"s": 7693,
"text": "<class '_io.TextIOWrapper'>This is the first line.This is the second line.This is the third line."
},
{
"code": null,
"e": 7881,
"s": 7791,
"text": "We can also iterate over key-value pairs of a Python dictionary using the items() method."
},
{
"code": null,
"e": 7889,
"s": 7881,
"text": "Output:"
},
{
"code": null,
"e": 7931,
"s": 7889,
"text": "<class 'dict_items'>name Ventsislavage 24"
},
{
"code": null,
"e": 8100,
"s": 7931,
"text": "Many people use Python to solve Data Science problems. In some cases, the data you work with can be very large. In this cases, we canβt load all the data in the memory."
},
{
"code": null,
"e": 8399,
"s": 8100,
"text": "The solution is to load the data in chunks, then perform the desired operation/s on each chunk, discard the chunk and load the next chunk of data. Said in other words we need to create an iterator. We can achieve this by using the read_csv function in pandas. We just need to specify the chunksize."
},
{
"code": null,
"e": 8602,
"s": 8399,
"text": "In this example, weβll see the idea with a small dataset called βiris speciesβ, but the same concept will work with very large datasets, too. Iβve changed the column names, you can find my version here."
},
{
"code": null,
"e": 8610,
"s": 8602,
"text": "Output:"
},
{
"code": null,
"e": 8675,
"s": 8610,
"text": "{'Iris-setosa': 50, 'Iris-versicolor': 50, 'Iris-virginica': 50}"
},
{
"code": null,
"e": 8772,
"s": 8675,
"text": "There are a lot of iterator objects in the Python standard library and in third-party libraries."
},
{
"code": null,
"e": 8914,
"s": 8772,
"text": "In some cases, we may want to create a custom iterator. We can do that by defining a class that has __init__, __next__, and __iter__ methods."
},
{
"code": null,
"e": 9013,
"s": 8914,
"text": "Letβs try to create a custom iterator class that generate numbers between min value and max value."
},
{
"code": null,
"e": 9021,
"s": 9013,
"text": "Output:"
},
{
"code": null,
"e": 9063,
"s": 9021,
"text": "<class '__main__.generate_numbers'>404142"
},
{
"code": null,
"e": 9199,
"s": 9063,
"text": "We can see that this works. However, it is much easier to use a generator function or generator expression to create a custom iterator."
},
{
"code": null,
"e": 9373,
"s": 9199,
"text": "Usually, we use a generator function or generator expression when we want to create a custom iterator. They are simpler to use and need less code to achieve the same result."
},
{
"code": null,
"e": 9434,
"s": 9373,
"text": "Letβs see what is a generator function from the Python docs."
},
{
"code": null,
"e": 9674,
"s": 9434,
"text": "A function which returns a generator iterator. It looks like a normal function except that it contains yield expressions for producing a series of values usable in a for-loop or that can be retrieved one at a time with the next() function."
},
{
"code": null,
"e": 9739,
"s": 9674,
"text": "Source: https://docs.python.org/3.7/glossary.html#term-generator"
},
{
"code": null,
"e": 9816,
"s": 9739,
"text": "Now, we can try to re-create our custom iterator using a generator function."
},
{
"code": null,
"e": 9824,
"s": 9816,
"text": "Output:"
},
{
"code": null,
"e": 9850,
"s": 9824,
"text": "<class 'generator'>101112"
},
{
"code": null,
"e": 10007,
"s": 9850,
"text": "The yield expression is the thing that separates a generation function from a normal function. This expression is helping us to use the iteratorβs laziness."
},
{
"code": null,
"e": 10281,
"s": 10007,
"text": "Each yield temporarily suspends processing, remembering the location execution state (including local variables and pending try-statements). When the generator iterator resumes, it picks up where it left off (in contrast to functions which start fresh on every invocation)."
},
{
"code": null,
"e": 10355,
"s": 10281,
"text": "Source: https://docs.python.org/3.7/glossary.html#term-generator-iterator"
},
{
"code": null,
"e": 10548,
"s": 10355,
"text": "The generator expressions are very similar to the list comprehensions. Just like a list comprehension, the general expressions are concise. In most cases, they are written in one line of code."
},
{
"code": null,
"e": 10715,
"s": 10548,
"text": "An expression that returns an iterator. It looks like a normal expression followed by a for expression defining a loop variable, range, and an optional if expression."
},
{
"code": null,
"e": 10791,
"s": 10715,
"text": "Source: https://docs.python.org/3.7/glossary.html#term-generator-expression"
},
{
"code": null,
"e": 10868,
"s": 10791,
"text": "The general formula is:(output expression for iterator variable in iterable)"
},
{
"code": null,
"e": 10927,
"s": 10868,
"text": "Letβs see how we can define a simple generator expression."
},
{
"code": null,
"e": 10935,
"s": 10927,
"text": "Output:"
},
{
"code": null,
"e": 10958,
"s": 10935,
"text": "<class 'generator'>149"
},
{
"code": null,
"e": 11040,
"s": 10958,
"text": "We can also add a conditional expression on the iterable. We can do it like this:"
},
{
"code": null,
"e": 11048,
"s": 11040,
"text": "Output:"
},
{
"code": null,
"e": 11075,
"s": 11048,
"text": "<class 'generator'>[4, 16]"
},
{
"code": null,
"e": 11164,
"s": 11075,
"text": "They can be multiple conditional expressions on the iterable for more complex filtering."
},
{
"code": null,
"e": 11172,
"s": 11164,
"text": "Output:"
},
{
"code": null,
"e": 11196,
"s": 11172,
"text": "<class 'generator'>[16]"
},
{
"code": null,
"e": 11267,
"s": 11196,
"text": "Also, we can add an if-else clause on the output expression like this:"
},
{
"code": null,
"e": 11275,
"s": 11267,
"text": "Output:"
},
{
"code": null,
"e": 11332,
"s": 11275,
"text": "<class 'generator'>['odd', 'even', 'odd', 'even', 'odd']"
},
{
"code": null,
"e": 11376,
"s": 11332,
"text": "An iterable is something you can loop over."
},
{
"code": null,
"e": 11422,
"s": 11376,
"text": "Sequences are a very common type of iterable."
},
{
"code": null,
"e": 11494,
"s": 11422,
"text": "Many things in Python are iterables, but not all of them are sequences."
},
{
"code": null,
"e": 11722,
"s": 11494,
"text": "An iterator is an object representing a stream of data. It does the iterating over an iterable. You can use an iterator to get the next value or to loop over it. Once, you loop over an iterator, there are no more stream values."
},
{
"code": null,
"e": 11766,
"s": 11722,
"text": "Iterators use the lazy evaluation approach."
},
{
"code": null,
"e": 11813,
"s": 11766,
"text": "Many built-in classes in Python are iterators."
},
{
"code": null,
"e": 11875,
"s": 11813,
"text": "A generator function is a function which returns an iterator."
},
{
"code": null,
"e": 11941,
"s": 11875,
"text": "A generator expression is an expression that returns an iterator."
},
{
"code": null,
"e": 12054,
"s": 11941,
"text": "You can look at the itertools library. This library includes functions creating iterators for efficient looping."
},
{
"code": null,
"e": 12124,
"s": 12054,
"text": "You can also read the docs or read/watch some of the resources below."
},
{
"code": null,
"e": 12177,
"s": 12124,
"text": "My next article about list comprehensions in Python."
},
{
"code": null,
"e": 12254,
"s": 12177,
"text": "https://opensource.com/article/18/3/loop-better-deeper-look-iteration-python"
},
{
"code": null,
"e": 12298,
"s": 12254,
"text": "https://www.youtube.com/watch?v=V2PkkMS2Ack"
},
{
"code": null,
"e": 12368,
"s": 12298,
"text": "https://www.datacamp.com/community/tutorials/python-iterator-tutorial"
},
{
"code": null,
"e": 12436,
"s": 12368,
"text": "https://www.datacamp.com/courses/python-data-science-toolbox-part-2"
},
{
"code": null,
"e": 12479,
"s": 12436,
"text": "https://en.wikipedia.org/wiki/Foreach_loop"
},
{
"code": null,
"e": 12535,
"s": 12479,
"text": "https://docs.python.org/3.7/glossary.html#term-sequence"
},
{
"code": null,
"e": 12592,
"s": 12535,
"text": "https://docs.python.org/3.7/glossary.html#term-generator"
},
{
"code": null,
"e": 12657,
"s": 12592,
"text": "https://docs.python.org/3.7/library/stdtypes.html#iterator-types"
},
{
"code": null,
"e": 12716,
"s": 12657,
"text": "https://docs.python.org/3/howto/functional.html?#iterators"
},
{
"code": null,
"e": 12759,
"s": 12716,
"text": "You can also check my previous blog posts."
},
{
"code": null,
"e": 12786,
"s": 12759,
"text": "Jupyter Notebook Shortcuts"
},
{
"code": null,
"e": 12817,
"s": 12786,
"text": "Python Basics for Data Science"
},
{
"code": null,
"e": 12852,
"s": 12817,
"text": "Python Basics: List Comprehensions"
},
{
"code": null,
"e": 12922,
"s": 12852,
"text": "Data Science with Python: Intro to Data Visualization with Matplotlib"
},
{
"code": null,
"e": 13009,
"s": 12922,
"text": "Data Science with Python: Intro to Loading, Subsetting, and Filtering Data with pandas"
},
{
"code": null,
"e": 13062,
"s": 13009,
"text": "Introduction to Natural Language Processing for Text"
},
{
"code": null,
"e": 13153,
"s": 13062,
"text": "If you want to be notified when I post a new blog post you can subscribe to my newsletter."
},
{
"code": null,
"e": 13258,
"s": 13153,
"text": "Here is my LinkedIn profile in case you want to connect with me. Iβll be happy to be connected with you."
}
] |
Print all permutations of a given string
|
Printing all permutations of a given string is an example of backtracking problem. We will reduce the size of the substring to solve the sub-problems, then again backtrack to get another permutation from that section.
For an example, if the string is ABC, the all permutations will be ABC, ACB, BAC, BCA, CAB, CBA.
The complexity of this algorithm is O(n!). It is a huge complexity. When the string size increases, it takes a longer time to finish the task.
Input:
A string βABCβ
Output:
All permutations of ABC is:
ABC
ACB
BAC
BCA
CBA
CAB
stringPermutation(str, left, right)
Input: The string and left and right index of characters.
Output: Print all permutations of the string.
Begin
if left = right, then
display str
else
for i := left to right, do
swap str[left] and str[i]
stringPermutation(str, left+1, right)
swap str[left] and str[i] //for backtrack
done
End
#include<iostream>
using namespace std;
void stringPermutation(string str, int left, int right) {
if(left == right)
cout << str << endl;
else {
for(int i = left; i<= right; i++) {
swap(str[left], str[i]);
stringPermutation(str, left + 1, right);
swap(str[left], str[i]); //swap back for backtracking
}
}
}
int main() {
string str = "ABC";
cout << "All permutations of " << str << " is: " <<endl<<endl;
stringPermutation(str, 0, str.size()-1);
}
All permutations of ABC is:
ABC
ACB
BAC
BCA
CBA
CAB
|
[
{
"code": null,
"e": 1280,
"s": 1062,
"text": "Printing all permutations of a given string is an example of backtracking problem. We will reduce the size of the substring to solve the sub-problems, then again backtrack to get another permutation from that section."
},
{
"code": null,
"e": 1377,
"s": 1280,
"text": "For an example, if the string is ABC, the all permutations will be ABC, ACB, BAC, BCA, CAB, CBA."
},
{
"code": null,
"e": 1520,
"s": 1377,
"text": "The complexity of this algorithm is O(n!). It is a huge complexity. When the string size increases, it takes a longer time to finish the task."
},
{
"code": null,
"e": 1602,
"s": 1520,
"text": "Input:\nA string βABCβ\nOutput:\nAll permutations of ABC is:\nABC\nACB\nBAC\nBCA\nCBA\nCAB"
},
{
"code": null,
"e": 1638,
"s": 1602,
"text": "stringPermutation(str, left, right)"
},
{
"code": null,
"e": 1696,
"s": 1638,
"text": "Input: The string and left and right index of characters."
},
{
"code": null,
"e": 1742,
"s": 1696,
"text": "Output: Print all permutations of the string."
},
{
"code": null,
"e": 1992,
"s": 1742,
"text": "Begin\n if left = right, then\n display str\n else\n for i := left to right, do\n swap str[left] and str[i]\n stringPermutation(str, left+1, right)\n swap str[left] and str[i] //for backtrack\n done\nEnd"
},
{
"code": null,
"e": 2503,
"s": 1992,
"text": "#include<iostream>\nusing namespace std;\n\nvoid stringPermutation(string str, int left, int right) {\n if(left == right)\n cout << str << endl;\n else {\n for(int i = left; i<= right; i++) {\n swap(str[left], str[i]);\n stringPermutation(str, left + 1, right);\n swap(str[left], str[i]); //swap back for backtracking\n }\n }\n}\n\nint main() {\n string str = \"ABC\";\n cout << \"All permutations of \" << str << \" is: \" <<endl<<endl;\n stringPermutation(str, 0, str.size()-1);\n}\n"
},
{
"code": null,
"e": 2555,
"s": 2503,
"text": "All permutations of ABC is:\nABC\nACB\nBAC\nBCA\nCBA\nCAB"
}
] |
Get filename from path without extension using Python - GeeksforGeeks
|
26 Mar, 2021
Getting a filename from Python using a path is a complex process not because of the regex we need to use to separate the filename from the path but because of the different types of separators used in file paths in different operating systems. For example, UNIX-based systems like Linux or Mac Os uses β/β (Forward Slash) as separators of the directory while Windows uses β\β (Back Slash) for separating the directories inside the path. So to avoid all these problems we would use a built-in package in python ntpath and use that to first extract the basename (the name that contains the filename with the extension). Then we could use simple python slicing to find the filename without the extension.
Firstly we would use the ntpath module. Secondly, we would extract the base name of the file from the path and append it to a separate array. The code for the same goes like this.
Python3
# import moduleimport ntpath # used path style of both the UNIX# and Windows os to show it works on both.paths = [ "E:\Programming Source Codes\Python\sample.py", "D:\home\Riot Games\VALORANT\live\VALORANT.exe"] # empty array to store file basenamesfilenames = [] for path in paths: # used basename method to get the filename filenames.append(ntpath.basename(path))
Then we would take the array generated and find the last occurrence of the β.β character in the string. Remember finding only the instance of β.β instead of the last occurrence may create problems if the name of the file itself contains β.β. We would find that index using rfind and then finally slice the part of the string before the index to get the filename. The code looks something like this. Again you can store those filenames in a list and use them elsewhere but here we decided to print them to the screen simply.
Python3
# get names from the listfor name in filenames: # finding the index where # the last "." occurs k = name.rfind(".") # printing the filename print(name[:k])
Below is the complete program:
Python3
# import moduleimport ntpath # used path style of both the UNIX# and Windows os to show it works on both.paths = [ "E:\Programming Source Codes\Python\sample.py", "D:\home\Riot Games\VALORANT\live\VALORANT.exe"] # empty array to store file basenamesfilenames = [] for path in paths: # used basename method to get the filename filenames.append(ntpath.basename(path)) # get names from the listfor name in filenames: # finding the index where # the last "." occurs k = name.rfind(".") # printing the filename print(name[:k])
Output:
Picked
python-file-handling
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
Defaultdict in Python
|
[
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 26261,
"s": 25555,
"text": "Getting a filename from Python using a path is a complex process not because of the regex we need to use to separate the filename from the path but because of the different types of separators used in file paths in different operating systems. For example, UNIX-based systems like Linux or Mac Os uses β/β (Forward Slash) as separators of the directory while Windows uses β\\β (Back Slash) for separating the directories inside the path. So to avoid all these problems we would use a built-in package in python ntpath and use that to first extract the basename (the name that contains the filename with the extension). Then we could use simple python slicing to find the filename without the extension. "
},
{
"code": null,
"e": 26441,
"s": 26261,
"text": "Firstly we would use the ntpath module. Secondly, we would extract the base name of the file from the path and append it to a separate array. The code for the same goes like this."
},
{
"code": null,
"e": 26449,
"s": 26441,
"text": "Python3"
},
{
"code": "# import moduleimport ntpath # used path style of both the UNIX# and Windows os to show it works on both.paths = [ \"E:\\Programming Source Codes\\Python\\sample.py\", \"D:\\home\\Riot Games\\VALORANT\\live\\VALORANT.exe\"] # empty array to store file basenamesfilenames = [] for path in paths: # used basename method to get the filename filenames.append(ntpath.basename(path))",
"e": 26830,
"s": 26449,
"text": null
},
{
"code": null,
"e": 27355,
"s": 26830,
"text": "Then we would take the array generated and find the last occurrence of the β.β character in the string. Remember finding only the instance of β.β instead of the last occurrence may create problems if the name of the file itself contains β.β. We would find that index using rfind and then finally slice the part of the string before the index to get the filename. The code looks something like this. Again you can store those filenames in a list and use them elsewhere but here we decided to print them to the screen simply."
},
{
"code": null,
"e": 27363,
"s": 27355,
"text": "Python3"
},
{
"code": "# get names from the listfor name in filenames: # finding the index where # the last \".\" occurs k = name.rfind(\".\") # printing the filename print(name[:k])",
"e": 27545,
"s": 27363,
"text": null
},
{
"code": null,
"e": 27576,
"s": 27545,
"text": "Below is the complete program:"
},
{
"code": null,
"e": 27584,
"s": 27576,
"text": "Python3"
},
{
"code": "# import moduleimport ntpath # used path style of both the UNIX# and Windows os to show it works on both.paths = [ \"E:\\Programming Source Codes\\Python\\sample.py\", \"D:\\home\\Riot Games\\VALORANT\\live\\VALORANT.exe\"] # empty array to store file basenamesfilenames = [] for path in paths: # used basename method to get the filename filenames.append(ntpath.basename(path)) # get names from the listfor name in filenames: # finding the index where # the last \".\" occurs k = name.rfind(\".\") # printing the filename print(name[:k])",
"e": 28152,
"s": 27584,
"text": null
},
{
"code": null,
"e": 28160,
"s": 28152,
"text": "Output:"
},
{
"code": null,
"e": 28167,
"s": 28160,
"text": "Picked"
},
{
"code": null,
"e": 28188,
"s": 28167,
"text": "python-file-handling"
},
{
"code": null,
"e": 28203,
"s": 28188,
"text": "python-modules"
},
{
"code": null,
"e": 28210,
"s": 28203,
"text": "Python"
},
{
"code": null,
"e": 28308,
"s": 28210,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28340,
"s": 28308,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28382,
"s": 28340,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28424,
"s": 28382,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28480,
"s": 28424,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28507,
"s": 28480,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28538,
"s": 28507,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28567,
"s": 28538,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28606,
"s": 28567,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28642,
"s": 28606,
"text": "Python | Pandas dataframe.groupby()"
}
] |
Building REST API using R Programming - GeeksforGeeks
|
12 Oct, 2020
REST(Representational state transfer) API is an architectural style that includes specific constraints for building APIs to ensure that they are consistent, efficient, and scalable. REST API is a collection of syntax and constraints which are used in the development and operation of web services that include sending & receiving information through there endpoint i.e a URL providing an interface to the external environment.
REST was first presented by Roy Fielding in 2000. The abstraction of information in REST is termed as a resource. REST uses a resource identifier to identify the particular resource in an interaction between components. It allows an application to access resources or functionality available on another server which is remote to that applicationβs architectural and security domain.
REST uses resource methods to perform the desired transition. An API can only be considered RESTful when it meets the following conditions:
Uniform Interface: A well-defined interface between the server and the client.
Stateless: A state is managed via the requests themselves and not through the support of an external service.
Cacheable: Responses should be cacheable in order to improve scalability.
Client-Server: Well defined separation of client and server.
Layered System: Client should be unaware of intermediaries between the client and the server.
Code on Demand: Response can include logic executable by the client
The 4 most important HTTP protocol methods;
GET: Retrieves data from a remote server and can be a single resource or a list of resources.POST: Creates a new resource on a remote server. *PUT: Updates the data on a remote server.DELETE: Deletes data from a remote server.
GET: Retrieves data from a remote server and can be a single resource or a list of resources.
POST: Creates a new resource on a remote server. *
PUT: Updates the data on a remote server.
DELETE: Deletes data from a remote server.
REST API can be used with any language as the requests are based on the universal HTTP protocol. In R Language, we use the httr package and jsonlite package to make a GET request, parse the results, and finally page through all the data. This requires converting the raw data from the GET request to JSON format and then into a parsed data frame.
The Package
Plumber package is used to create REST API such as providing data for an analytics dashboard etc. It allows to easily convert R code into an endpoint.
R
# Installing the packageinstall.packages("plumber") # Loading packagelibrary(plumber)
Using the plumber package building an API. Making two files, one is my_api.r containing all endpoints and the second is server.r to load all endpoints of API by starting the server.
my_api.R
R
# Loading packagelibrary(plumber) #* Revert back the input#* @param msg Input a message to revert#* @get /revertrevert <- function(msg = ""){ list(msg = paste0("The input message is: ", msg, "'"))} #* Plotting a bar graph#* @png#* @get /plotfunction(){ normal_func <- rnorm(60) barplot(normal_func)}
server.R
R
# Loading packagelibrary(plumber) # Routing APIr <- plumb("api.R") # Running APIr$run(port = 8000, swagger = TRUE)
Outputs:
Normal_func:
The normal function is output with rnorm().
Running API:
The api.R file is run with port 8000 and swagger is TRUE.
Revert() on Swagger:
The input message is asked to execute the function.
The input message is outputted in JSON format and response headers.
Plot() on Swagger:
The plot() is executed with Swagger UI and can also be executed using a Curl statement.
The Bar graph is outputted after running the plot().
The response headers are generated without a default response.
So REST API is used in the Software industry and IT industry with the full scope on a daily basis.
R Data-science
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Remove rows with NA in one column of R DataFrame
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
Logistic Regression in R Programming
|
[
{
"code": null,
"e": 24704,
"s": 24676,
"text": "\n12 Oct, 2020"
},
{
"code": null,
"e": 25131,
"s": 24704,
"text": "REST(Representational state transfer) API is an architectural style that includes specific constraints for building APIs to ensure that they are consistent, efficient, and scalable. REST API is a collection of syntax and constraints which are used in the development and operation of web services that include sending & receiving information through there endpoint i.e a URL providing an interface to the external environment."
},
{
"code": null,
"e": 25514,
"s": 25131,
"text": "REST was first presented by Roy Fielding in 2000. The abstraction of information in REST is termed as a resource. REST uses a resource identifier to identify the particular resource in an interaction between components. It allows an application to access resources or functionality available on another server which is remote to that applicationβs architectural and security domain."
},
{
"code": null,
"e": 25654,
"s": 25514,
"text": "REST uses resource methods to perform the desired transition. An API can only be considered RESTful when it meets the following conditions:"
},
{
"code": null,
"e": 25733,
"s": 25654,
"text": "Uniform Interface: A well-defined interface between the server and the client."
},
{
"code": null,
"e": 25843,
"s": 25733,
"text": "Stateless: A state is managed via the requests themselves and not through the support of an external service."
},
{
"code": null,
"e": 25917,
"s": 25843,
"text": "Cacheable: Responses should be cacheable in order to improve scalability."
},
{
"code": null,
"e": 25978,
"s": 25917,
"text": "Client-Server: Well defined separation of client and server."
},
{
"code": null,
"e": 26072,
"s": 25978,
"text": "Layered System: Client should be unaware of intermediaries between the client and the server."
},
{
"code": null,
"e": 26140,
"s": 26072,
"text": "Code on Demand: Response can include logic executable by the client"
},
{
"code": null,
"e": 26184,
"s": 26140,
"text": "The 4 most important HTTP protocol methods;"
},
{
"code": null,
"e": 26411,
"s": 26184,
"text": "GET: Retrieves data from a remote server and can be a single resource or a list of resources.POST: Creates a new resource on a remote server. *PUT: Updates the data on a remote server.DELETE: Deletes data from a remote server."
},
{
"code": null,
"e": 26505,
"s": 26411,
"text": "GET: Retrieves data from a remote server and can be a single resource or a list of resources."
},
{
"code": null,
"e": 26556,
"s": 26505,
"text": "POST: Creates a new resource on a remote server. *"
},
{
"code": null,
"e": 26598,
"s": 26556,
"text": "PUT: Updates the data on a remote server."
},
{
"code": null,
"e": 26641,
"s": 26598,
"text": "DELETE: Deletes data from a remote server."
},
{
"code": null,
"e": 26988,
"s": 26641,
"text": "REST API can be used with any language as the requests are based on the universal HTTP protocol. In R Language, we use the httr package and jsonlite package to make a GET request, parse the results, and finally page through all the data. This requires converting the raw data from the GET request to JSON format and then into a parsed data frame."
},
{
"code": null,
"e": 27000,
"s": 26988,
"text": "The Package"
},
{
"code": null,
"e": 27151,
"s": 27000,
"text": "Plumber package is used to create REST API such as providing data for an analytics dashboard etc. It allows to easily convert R code into an endpoint."
},
{
"code": null,
"e": 27153,
"s": 27151,
"text": "R"
},
{
"code": "# Installing the packageinstall.packages(\"plumber\") # Loading packagelibrary(plumber)",
"e": 27240,
"s": 27153,
"text": null
},
{
"code": null,
"e": 27422,
"s": 27240,
"text": "Using the plumber package building an API. Making two files, one is my_api.r containing all endpoints and the second is server.r to load all endpoints of API by starting the server."
},
{
"code": null,
"e": 27431,
"s": 27422,
"text": "my_api.R"
},
{
"code": null,
"e": 27433,
"s": 27431,
"text": "R"
},
{
"code": "# Loading packagelibrary(plumber) #* Revert back the input#* @param msg Input a message to revert#* @get /revertrevert <- function(msg = \"\"){ list(msg = paste0(\"The input message is: \", msg, \"'\"))} #* Plotting a bar graph#* @png#* @get /plotfunction(){ normal_func <- rnorm(60) barplot(normal_func)}",
"e": 27774,
"s": 27433,
"text": null
},
{
"code": null,
"e": 27783,
"s": 27774,
"text": "server.R"
},
{
"code": null,
"e": 27785,
"s": 27783,
"text": "R"
},
{
"code": "# Loading packagelibrary(plumber) # Routing APIr <- plumb(\"api.R\") # Running APIr$run(port = 8000, swagger = TRUE)",
"e": 27902,
"s": 27785,
"text": null
},
{
"code": null,
"e": 27911,
"s": 27902,
"text": "Outputs:"
},
{
"code": null,
"e": 27924,
"s": 27911,
"text": "Normal_func:"
},
{
"code": null,
"e": 27968,
"s": 27924,
"text": "The normal function is output with rnorm()."
},
{
"code": null,
"e": 27981,
"s": 27968,
"text": "Running API:"
},
{
"code": null,
"e": 28039,
"s": 27981,
"text": "The api.R file is run with port 8000 and swagger is TRUE."
},
{
"code": null,
"e": 28060,
"s": 28039,
"text": "Revert() on Swagger:"
},
{
"code": null,
"e": 28112,
"s": 28060,
"text": "The input message is asked to execute the function."
},
{
"code": null,
"e": 28180,
"s": 28112,
"text": "The input message is outputted in JSON format and response headers."
},
{
"code": null,
"e": 28199,
"s": 28180,
"text": "Plot() on Swagger:"
},
{
"code": null,
"e": 28287,
"s": 28199,
"text": "The plot() is executed with Swagger UI and can also be executed using a Curl statement."
},
{
"code": null,
"e": 28340,
"s": 28287,
"text": "The Bar graph is outputted after running the plot()."
},
{
"code": null,
"e": 28403,
"s": 28340,
"text": "The response headers are generated without a default response."
},
{
"code": null,
"e": 28502,
"s": 28403,
"text": "So REST API is used in the Software industry and IT industry with the full scope on a daily basis."
},
{
"code": null,
"e": 28517,
"s": 28502,
"text": "R Data-science"
},
{
"code": null,
"e": 28528,
"s": 28517,
"text": "R Language"
},
{
"code": null,
"e": 28626,
"s": 28528,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28635,
"s": 28626,
"text": "Comments"
},
{
"code": null,
"e": 28648,
"s": 28635,
"text": "Old Comments"
},
{
"code": null,
"e": 28700,
"s": 28648,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 28732,
"s": 28700,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 28784,
"s": 28732,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28828,
"s": 28784,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 28877,
"s": 28828,
"text": "Remove rows with NA in one column of R DataFrame"
},
{
"code": null,
"e": 28915,
"s": 28877,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28950,
"s": 28915,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29008,
"s": 28950,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29044,
"s": 29008,
"text": "K-Means Clustering in R Programming"
}
] |
Throwable getMessage() method in Java with Examples - GeeksforGeeks
|
06 Feb, 2019
The getMessage() method of Throwable class is used to return a detailed message of the Throwable object which can also be null. One can use this method to get the detail message of exception as a string value.
Syntax:
public String getMessage()
Return Value: This method returns the detailed message of this Throwable instance.
Below programs demonstrate the getMessage() method of java.lang.Throwable Class
Example 1:
// Java program to demonstrate// the getMessage() Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { // divide the numbers divide(2, 0); } catch (ArithmeticException e) { System.out.println("Message String = " + e.getMessage()); } } // method which divide two numbers public static void divide(int a, int b) throws ArithmeticException { int c = a / b; System.out.println("Result:" + c); }}
Message String = / by zero
Example 2:
// Java program to demonstrate// the getMessage() Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { test(); } catch (Throwable e) { System.out.println("Message of Exception : " + e.getMessage()); } } // method which throws UnsupportedOperationException public static void test() throws UnsupportedOperationException { throw new UnsupportedOperationException(); }}
Message of Exception : null
References:https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#getMessage()
Java-Exception Handling
Java-Exceptions
Java-Functions
Java-lang package
java-Throwable
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multithreading in Java
|
[
{
"code": null,
"e": 26007,
"s": 25979,
"text": "\n06 Feb, 2019"
},
{
"code": null,
"e": 26217,
"s": 26007,
"text": "The getMessage() method of Throwable class is used to return a detailed message of the Throwable object which can also be null. One can use this method to get the detail message of exception as a string value."
},
{
"code": null,
"e": 26225,
"s": 26217,
"text": "Syntax:"
},
{
"code": null,
"e": 26252,
"s": 26225,
"text": "public String getMessage()"
},
{
"code": null,
"e": 26335,
"s": 26252,
"text": "Return Value: This method returns the detailed message of this Throwable instance."
},
{
"code": null,
"e": 26415,
"s": 26335,
"text": "Below programs demonstrate the getMessage() method of java.lang.Throwable Class"
},
{
"code": null,
"e": 26426,
"s": 26415,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// the getMessage() Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { // divide the numbers divide(2, 0); } catch (ArithmeticException e) { System.out.println(\"Message String = \" + e.getMessage()); } } // method which divide two numbers public static void divide(int a, int b) throws ArithmeticException { int c = a / b; System.out.println(\"Result:\" + c); }}",
"e": 27043,
"s": 26426,
"text": null
},
{
"code": null,
"e": 27071,
"s": 27043,
"text": "Message String = / by zero\n"
},
{
"code": null,
"e": 27082,
"s": 27071,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate// the getMessage() Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { test(); } catch (Throwable e) { System.out.println(\"Message of Exception : \" + e.getMessage()); } } // method which throws UnsupportedOperationException public static void test() throws UnsupportedOperationException { throw new UnsupportedOperationException(); }}",
"e": 27654,
"s": 27082,
"text": null
},
{
"code": null,
"e": 27683,
"s": 27654,
"text": "Message of Exception : null\n"
},
{
"code": null,
"e": 27775,
"s": 27683,
"text": "References:https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#getMessage()"
},
{
"code": null,
"e": 27799,
"s": 27775,
"text": "Java-Exception Handling"
},
{
"code": null,
"e": 27815,
"s": 27799,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 27830,
"s": 27815,
"text": "Java-Functions"
},
{
"code": null,
"e": 27848,
"s": 27830,
"text": "Java-lang package"
},
{
"code": null,
"e": 27863,
"s": 27848,
"text": "java-Throwable"
},
{
"code": null,
"e": 27868,
"s": 27863,
"text": "Java"
},
{
"code": null,
"e": 27873,
"s": 27868,
"text": "Java"
},
{
"code": null,
"e": 27971,
"s": 27873,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27986,
"s": 27971,
"text": "Stream In Java"
},
{
"code": null,
"e": 28037,
"s": 27986,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28067,
"s": 28037,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28086,
"s": 28067,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28117,
"s": 28086,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28135,
"s": 28117,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28167,
"s": 28135,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28187,
"s": 28167,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28211,
"s": 28187,
"text": "Singleton Class in Java"
}
] |
Java 11 - Var in Lambda
|
Java 11 allows to use var in a lambda expression and it can be used to apply modifiers to local variables.
(@NonNull var value1, @Nullable var value2) -> value1 + value2
Consider the following example β
ApiTester.java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@interface NonNull {}
public class APITester {
public static void main(String[] args) {
List<String> tutorialsList = Arrays.asList("Java", "HTML");
String tutorials = tutorialsList.stream()
.map((@NonNull var tutorial) -> tutorial.toUpperCase())
.collect(Collectors.joining(", "));
System.out.println(tutorials);
}
}
Java
HTML
There are certain limitations on using var in lambda expressions.
var parameters cannot be mixed with other parameters. Following will throw compilation error.
var parameters cannot be mixed with other parameters. Following will throw compilation error.
(var v1, v2) -> v1 + v2
var parameters cannot be mixed with other typed parameters. Following will throw compilation error.
var parameters cannot be mixed with other typed parameters. Following will throw compilation error.
(var v1, String v2) -> v1 + v2
var parameters can only be used with parenthesis. Following will throw compilation error.
var parameters can only be used with parenthesis. Following will throw compilation error.
var v1 -> v1.toLowerCase()
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2180,
"s": 2073,
"text": "Java 11 allows to use var in a lambda expression and it can be used to apply modifiers to local variables."
},
{
"code": null,
"e": 2244,
"s": 2180,
"text": "(@NonNull var value1, @Nullable var value2) -> value1 + value2\n"
},
{
"code": null,
"e": 2277,
"s": 2244,
"text": "Consider the following example β"
},
{
"code": null,
"e": 2292,
"s": 2277,
"text": "ApiTester.java"
},
{
"code": null,
"e": 2741,
"s": 2292,
"text": "import java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\n@interface NonNull {}\n\npublic class APITester {\n public static void main(String[] args) {\t\t\n List<String> tutorialsList = Arrays.asList(\"Java\", \"HTML\");\n\n String tutorials = tutorialsList.stream()\n .map((@NonNull var tutorial) -> tutorial.toUpperCase())\n .collect(Collectors.joining(\", \"));\n\n System.out.println(tutorials);\n }\n}"
},
{
"code": null,
"e": 2752,
"s": 2741,
"text": "Java\nHTML\n"
},
{
"code": null,
"e": 2818,
"s": 2752,
"text": "There are certain limitations on using var in lambda expressions."
},
{
"code": null,
"e": 2912,
"s": 2818,
"text": "var parameters cannot be mixed with other parameters. Following will throw compilation error."
},
{
"code": null,
"e": 3006,
"s": 2912,
"text": "var parameters cannot be mixed with other parameters. Following will throw compilation error."
},
{
"code": null,
"e": 3031,
"s": 3006,
"text": "(var v1, v2) -> v1 + v2\n"
},
{
"code": null,
"e": 3131,
"s": 3031,
"text": "var parameters cannot be mixed with other typed parameters. Following will throw compilation error."
},
{
"code": null,
"e": 3231,
"s": 3131,
"text": "var parameters cannot be mixed with other typed parameters. Following will throw compilation error."
},
{
"code": null,
"e": 3263,
"s": 3231,
"text": "(var v1, String v2) -> v1 + v2\n"
},
{
"code": null,
"e": 3353,
"s": 3263,
"text": "var parameters can only be used with parenthesis. Following will throw compilation error."
},
{
"code": null,
"e": 3443,
"s": 3353,
"text": "var parameters can only be used with parenthesis. Following will throw compilation error."
},
{
"code": null,
"e": 3471,
"s": 3443,
"text": "var v1 -> v1.toLowerCase()\n"
},
{
"code": null,
"e": 3504,
"s": 3471,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3520,
"s": 3504,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3553,
"s": 3520,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3569,
"s": 3553,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3604,
"s": 3569,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3618,
"s": 3604,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3652,
"s": 3618,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3666,
"s": 3652,
"text": " Tushar Kale"
},
{
"code": null,
"e": 3703,
"s": 3666,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3718,
"s": 3703,
"text": " Monica Mittal"
},
{
"code": null,
"e": 3751,
"s": 3718,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3770,
"s": 3751,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3777,
"s": 3770,
"text": " Print"
},
{
"code": null,
"e": 3788,
"s": 3777,
"text": " Add Notes"
}
] |
How to Change the username or userID in Kali Linux? - GeeksforGeeks
|
30 Jun, 2020
Kali Linux allows us to enter the username while installing it and it assigns the username a unique user id to identify the user and it assigns the id itself. Now there come situations when we have to change the username or user id. This can be done easily with the help of usermod command.
But before change the username or user id we shall be aware of what is the user id or username. The details of a user such as userID, username, the complete name of the user, default shell, etc. are stored in a file which is /etc/passwd and all the password related details like the hash of the password is stored in /etc/shadow file. To get the userid or other details of a user we read passwd file and even in that file we read the line which has the details of the user in it. In order to do that we use the following command.
1. To get the user id of a user
cat /etc/passwd | grep oldusername
Replace the oldusername with the name of the user you want to use.
This will display us a few details of the user along with the userid.
2. To change the Username. We use usermod command along with -l parameter in order to change the username of a particular user.
usermod -l newusername oldusername
Replace the oldusername with the name of the user you want to change and the newusername with the new name of the user.
This command will change the username of the oldusername to the newusername but will not change the files and userID of the user.
3. To change the UserID we use usermod command along with -u parameter in order to change the userid of a particular user.
usermod -u 1234 newusername
Replace the newusername with the username you want to change the id of. And Replace 1234 with the id you want to set for the user.
This command will change the userid of the user from the default one to 1234.
Kali-Linux
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
Conditional Statements | Shell Script
Tail command in Linux with examples
'crontab' in Linux with Examples
UDP Server-Client implementation in C
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
scp command in Linux with Examples
Compiling with g++
|
[
{
"code": null,
"e": 25911,
"s": 25883,
"text": "\n30 Jun, 2020"
},
{
"code": null,
"e": 26202,
"s": 25911,
"text": "Kali Linux allows us to enter the username while installing it and it assigns the username a unique user id to identify the user and it assigns the id itself. Now there come situations when we have to change the username or user id. This can be done easily with the help of usermod command."
},
{
"code": null,
"e": 26732,
"s": 26202,
"text": "But before change the username or user id we shall be aware of what is the user id or username. The details of a user such as userID, username, the complete name of the user, default shell, etc. are stored in a file which is /etc/passwd and all the password related details like the hash of the password is stored in /etc/shadow file. To get the userid or other details of a user we read passwd file and even in that file we read the line which has the details of the user in it. In order to do that we use the following command."
},
{
"code": null,
"e": 26764,
"s": 26732,
"text": "1. To get the user id of a user"
},
{
"code": null,
"e": 26799,
"s": 26764,
"text": "cat /etc/passwd | grep oldusername"
},
{
"code": null,
"e": 26866,
"s": 26799,
"text": "Replace the oldusername with the name of the user you want to use."
},
{
"code": null,
"e": 26936,
"s": 26866,
"text": "This will display us a few details of the user along with the userid."
},
{
"code": null,
"e": 27064,
"s": 26936,
"text": "2. To change the Username. We use usermod command along with -l parameter in order to change the username of a particular user."
},
{
"code": null,
"e": 27099,
"s": 27064,
"text": "usermod -l newusername oldusername"
},
{
"code": null,
"e": 27219,
"s": 27099,
"text": "Replace the oldusername with the name of the user you want to change and the newusername with the new name of the user."
},
{
"code": null,
"e": 27349,
"s": 27219,
"text": "This command will change the username of the oldusername to the newusername but will not change the files and userID of the user."
},
{
"code": null,
"e": 27472,
"s": 27349,
"text": "3. To change the UserID we use usermod command along with -u parameter in order to change the userid of a particular user."
},
{
"code": null,
"e": 27500,
"s": 27472,
"text": "usermod -u 1234 newusername"
},
{
"code": null,
"e": 27631,
"s": 27500,
"text": "Replace the newusername with the username you want to change the id of. And Replace 1234 with the id you want to set for the user."
},
{
"code": null,
"e": 27709,
"s": 27631,
"text": "This command will change the userid of the user from the default one to 1234."
},
{
"code": null,
"e": 27720,
"s": 27709,
"text": "Kali-Linux"
},
{
"code": null,
"e": 27731,
"s": 27720,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27829,
"s": 27731,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27864,
"s": 27829,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 27902,
"s": 27864,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 27938,
"s": 27902,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 27971,
"s": 27938,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 28009,
"s": 27971,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 28044,
"s": 28009,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 28081,
"s": 28044,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 28117,
"s": 28081,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 28152,
"s": 28117,
"text": "scp command in Linux with Examples"
}
] |
Number of connected components in a 2-D matrix of strings - GeeksforGeeks
|
02 Aug, 2021
Given a 2-D matrix mat[][] the task is to count the number of connected components in the matrix. A connected component is formed by all equal elements that share some common side with at least one other element of the same component.Examples:
Input: mat[][] = {"bbba",
"baaa"}
Output: 2
The two connected components are:
bbb
b
AND
a
aaa
Input: mat[][] = {"aabba",
"aabba",
"aaaca"}
Output: 4
Approach: For every cell that hasnβt been visited before performing DFS. DFS will cover all the connected cells (up, left, right, and down) with same value. So the answer would be the total times DFS is run.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;#define maxRow 500#define maxCol 500 bool visited[maxRow][maxCol] = { 0 }; // Function that return true if mat[row][col]// is valid and hasn't been visitedbool isSafe(string M[], int row, int col, char c, int n, int l){ // If row and column are valid and element // is matched and hasn't been visited then // the cell is safe return (row >= 0 && row < n) && (col >= 0 && col < l) && (M[row][col] == c && !visited[row][col]);} // Function for depth first searchvoid DFS(string M[], int row, int col, char c, int n, int l){ // These arrays are used to get row and column // numbers of 4 neighbours of a given cell int rowNbr[] = { -1, 1, 0, 0 }; int colNbr[] = { 0, 0, 1, -1 }; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 4; ++k) if (isSafe(M, row + rowNbr[k], col + colNbr[k], c, n, l)) DFS(M, row + rowNbr[k], col + colNbr[k], c, n, l);} // Function to return the number of// connectewd components in the matrixint connectedComponents(string M[], int n){ int connectedComp = 0; int l = M[0].length(); for (int i = 0; i < n; i++) { for (int j = 0; j < l; j++) { if (!visited[i][j]) { char c = M[i][j]; DFS(M, i, j, c, n, l); connectedComp++; } } } return connectedComp;} // Driver codeint main(){ string M[] = {"aabba", "aabba", "aaaca"}; int n = sizeof(M)/sizeof(M[0]); cout << connectedComponents(M, n); return 0;}
// Java implementation of the approachclass GFG{static final int maxRow = 500;static final int maxCol = 500; static boolean visited[][] = new boolean[maxRow][maxCol]; // Function that return true if mat[row][col]// is valid and hasn't been visitedstatic boolean isSafe(String M[], int row, int col, char c, int n, int l){ // If row and column are valid and element // is matched and hasn't been visited then // the cell is safe return (row >= 0 && row < n) && (col >= 0 && col < l) && (M[row].charAt(col) == c && !visited[row][col]);} // Function for depth first searchstatic void DFS(String M[], int row, int col, char c, int n, int l){ // These arrays are used to get row and column // numbers of 4 neighbours of a given cell int rowNbr[] = {-1, 1, 0, 0}; int colNbr[] = {0, 0, 1, -1}; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 4; ++k) { if (isSafe(M, row + rowNbr[k], col + colNbr[k], c, n, l)) { DFS(M, row + rowNbr[k], col + colNbr[k], c, n, l); } }} // Function to return the number of// connectewd components in the matrixstatic int connectedComponents(String M[], int n){ int connectedComp = 0; int l = M[0].length(); for (int i = 0; i < n; i++) { for (int j = 0; j < l; j++) { if (!visited[i][j]) { char c = M[i].charAt(j); DFS(M, i, j, c, n, l); connectedComp++; } } } return connectedComp;} // Driver codepublic static void main(String[] args){ String M[] = {"aabba", "aabba", "aaaca"}; int n = M.length; System.out.println(connectedComponents(M, n));}} // This code contributed by PrinciRaj1992
# Python3 implementation of the approachimport numpy as np maxRow = 500maxCol = 500 visited = np.zeros((maxCol, maxRow)) # Function that return true if mat[row][col]# is valid and hasn't been visiteddef isSafe(M, row, col, c, n, l) : # If row and column are valid and element # is matched and hasn't been visited then # the cell is safe return ((row >= 0 and row < n) and (col >= 0 and col < l) and (M[row][col] == c and not visited[row][col])); # Function for depth first searchdef DFS(M, row, col, c, n, l) : # These arrays are used to get row # and column numbers of 4 neighbours # of a given cell rowNbr = [ -1, 1, 0, 0 ]; colNbr = [ 0, 0, 1, -1 ]; # Mark this cell as visited visited[row][col] = True; # Recur for all connected neighbours for k in range(4) : if (isSafe(M, row + rowNbr[k], col + colNbr[k], c, n, l)) : DFS(M, row + rowNbr[k], col + colNbr[k], c, n, l); # Function to return the number of# connectewd components in the matrixdef connectedComponents(M, n) : connectedComp = 0; l = len(M[0]); for i in range(n) : for j in range(l) : if (not visited[i][j]) : c = M[i][j]; DFS(M, i, j, c, n, l); connectedComp += 1; return connectedComp; # Driver codeif __name__ == "__main__" : M = ["aabba", "aabba", "aaaca"]; n = len(M) print(connectedComponents(M, n)); # This code is contributed by Ryuga
// C# implementation of the approachusing System; class GFG{ static readonly int maxRow = 500;static readonly int maxCol = 500; static bool [,]visited = new bool[maxRow,maxCol]; // Function that return true if mat[row,col]// is valid and hasn't been visitedstatic bool isSafe(String []M, int row, int col, char c, int n, int l){ // If row and column are valid and element // is matched and hasn't been visited then // the cell is safe return (row >= 0 && row < n) && (col >= 0 && col < l) && (M[row][col] == c && !visited[row,col]);} // Function for depth first searchstatic void DFS(String []M, int row, int col, char c, int n, int l){ // These arrays are used to get row and column // numbers of 4 neighbours of a given cell int []rowNbr = {-1, 1, 0, 0}; int []colNbr = {0, 0, 1, -1}; // Mark this cell as visited visited[row,col] = true; // Recur for all connected neighbours for (int k = 0; k < 4; ++k) { if (isSafe(M, row + rowNbr[k], col + colNbr[k], c, n, l)) { DFS(M, row + rowNbr[k], col + colNbr[k], c, n, l); } }} // Function to return the number of// connectewd components in the matrixstatic int connectedComponents(String []M, int n){ int connectedComp = 0; int l = M[0].Length; for (int i = 0; i < n; i++) { for (int j = 0; j < l; j++) { if (!visited[i,j]) { char c = M[i][j]; DFS(M, i, j, c, n, l); connectedComp++; } } } return connectedComp;} // Driver codepublic static void Main(String[] args){ String []M = {"aabba", "aabba", "aaaca"}; int n = M.Length; Console.WriteLine(connectedComponents(M, n));}} // This code contributed by Rajput-Ji
<script> // JavaScript implementation of the approach var maxRow = 500; var maxCol = 500; var visited = Array(maxRow).fill().map(()=>Array(maxCol).fill(false)); // Function that return true if mat[row][col] // is valid and hasn't been visited function isSafe( M , row , col, c , n , l) { // If row and column are valid and element // is matched and hasn't been visited then // the cell is safe return (row >= 0 && row < n) && (col >= 0 && col < l) && (M[row].charAt(col) == c && !visited[row][col]); } // Function for depth first search function DFS( M , row , col, c , n , l) { // These arrays are used to get row and column // numbers of 4 neighbours of a given cell var rowNbr = [ -1, 1, 0, 0 ]; var colNbr = [ 0, 0, 1, -1 ]; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (var k = 0; k < 4; ++k) { if (isSafe(M, row + rowNbr[k], col + colNbr[k], c, n, l)) { DFS(M, row + rowNbr[k], col + colNbr[k], c, n, l); } } } // Function to return the number of // connectewd components in the matrix function connectedComponents( M , n) { var connectedComp = 0; var l = M[0].length; for (var i = 0; i < n; i++) { for (j = 0; j < l; j++) { if (!visited[i][j]) { var c = M[i].charAt(j); DFS(M, i, j, c, n, l); connectedComp++; } } } return connectedComp; } // Driver code var M = [ "aabba", "aabba", "aaaca" ]; var n = M.length; document.write(connectedComponents(M, n)); // This code contributed by gauravrajput1 </script>
4
Time Complexity: O(row * cols)Auxiliary Space: O(row * cols)
ankthon
princiraj1992
Rajput-Ji
GauravRajput1
pankajsharmagfg
DFS
Algorithms
Competitive Programming
Matrix
DFS
Matrix
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Quadratic Probing in Hashing
SCAN (Elevator) Disk Scheduling Algorithms
K means Clustering - Introduction
Difference between Informed and Uninformed Search in AI
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Competitive Programming - A Complete Guide
Modulo 10^9+7 (1000000007)
Top 10 Algorithms and Data Structures for Competitive Programming
|
[
{
"code": null,
"e": 24692,
"s": 24664,
"text": "\n02 Aug, 2021"
},
{
"code": null,
"e": 24938,
"s": 24692,
"text": "Given a 2-D matrix mat[][] the task is to count the number of connected components in the matrix. A connected component is formed by all equal elements that share some common side with at least one other element of the same component.Examples: "
},
{
"code": null,
"e": 25207,
"s": 24938,
"text": "Input: mat[][] = {\"bbba\", \n \"baaa\"}\nOutput: 2\nThe two connected components are:\nbbb \nb\n\nAND\n\n a\naaa\n\nInput: mat[][] = {\"aabba\", \n \"aabba\", \n \"aaaca\"}\nOutput: 4"
},
{
"code": null,
"e": 25469,
"s": 25209,
"text": "Approach: For every cell that hasnβt been visited before performing DFS. DFS will cover all the connected cells (up, left, right, and down) with same value. So the answer would be the total times DFS is run.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25473,
"s": 25469,
"text": "C++"
},
{
"code": null,
"e": 25478,
"s": 25473,
"text": "Java"
},
{
"code": null,
"e": 25486,
"s": 25478,
"text": "Python3"
},
{
"code": null,
"e": 25489,
"s": 25486,
"text": "C#"
},
{
"code": null,
"e": 25500,
"s": 25489,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define maxRow 500#define maxCol 500 bool visited[maxRow][maxCol] = { 0 }; // Function that return true if mat[row][col]// is valid and hasn't been visitedbool isSafe(string M[], int row, int col, char c, int n, int l){ // If row and column are valid and element // is matched and hasn't been visited then // the cell is safe return (row >= 0 && row < n) && (col >= 0 && col < l) && (M[row][col] == c && !visited[row][col]);} // Function for depth first searchvoid DFS(string M[], int row, int col, char c, int n, int l){ // These arrays are used to get row and column // numbers of 4 neighbours of a given cell int rowNbr[] = { -1, 1, 0, 0 }; int colNbr[] = { 0, 0, 1, -1 }; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 4; ++k) if (isSafe(M, row + rowNbr[k], col + colNbr[k], c, n, l)) DFS(M, row + rowNbr[k], col + colNbr[k], c, n, l);} // Function to return the number of// connectewd components in the matrixint connectedComponents(string M[], int n){ int connectedComp = 0; int l = M[0].length(); for (int i = 0; i < n; i++) { for (int j = 0; j < l; j++) { if (!visited[i][j]) { char c = M[i][j]; DFS(M, i, j, c, n, l); connectedComp++; } } } return connectedComp;} // Driver codeint main(){ string M[] = {\"aabba\", \"aabba\", \"aaaca\"}; int n = sizeof(M)/sizeof(M[0]); cout << connectedComponents(M, n); return 0;}",
"e": 27254,
"s": 25500,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{static final int maxRow = 500;static final int maxCol = 500; static boolean visited[][] = new boolean[maxRow][maxCol]; // Function that return true if mat[row][col]// is valid and hasn't been visitedstatic boolean isSafe(String M[], int row, int col, char c, int n, int l){ // If row and column are valid and element // is matched and hasn't been visited then // the cell is safe return (row >= 0 && row < n) && (col >= 0 && col < l) && (M[row].charAt(col) == c && !visited[row][col]);} // Function for depth first searchstatic void DFS(String M[], int row, int col, char c, int n, int l){ // These arrays are used to get row and column // numbers of 4 neighbours of a given cell int rowNbr[] = {-1, 1, 0, 0}; int colNbr[] = {0, 0, 1, -1}; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 4; ++k) { if (isSafe(M, row + rowNbr[k], col + colNbr[k], c, n, l)) { DFS(M, row + rowNbr[k], col + colNbr[k], c, n, l); } }} // Function to return the number of// connectewd components in the matrixstatic int connectedComponents(String M[], int n){ int connectedComp = 0; int l = M[0].length(); for (int i = 0; i < n; i++) { for (int j = 0; j < l; j++) { if (!visited[i][j]) { char c = M[i].charAt(j); DFS(M, i, j, c, n, l); connectedComp++; } } } return connectedComp;} // Driver codepublic static void main(String[] args){ String M[] = {\"aabba\", \"aabba\", \"aaaca\"}; int n = M.length; System.out.println(connectedComponents(M, n));}} // This code contributed by PrinciRaj1992",
"e": 29161,
"s": 27254,
"text": null
},
{
"code": "# Python3 implementation of the approachimport numpy as np maxRow = 500maxCol = 500 visited = np.zeros((maxCol, maxRow)) # Function that return true if mat[row][col]# is valid and hasn't been visiteddef isSafe(M, row, col, c, n, l) : # If row and column are valid and element # is matched and hasn't been visited then # the cell is safe return ((row >= 0 and row < n) and (col >= 0 and col < l) and (M[row][col] == c and not visited[row][col])); # Function for depth first searchdef DFS(M, row, col, c, n, l) : # These arrays are used to get row # and column numbers of 4 neighbours # of a given cell rowNbr = [ -1, 1, 0, 0 ]; colNbr = [ 0, 0, 1, -1 ]; # Mark this cell as visited visited[row][col] = True; # Recur for all connected neighbours for k in range(4) : if (isSafe(M, row + rowNbr[k], col + colNbr[k], c, n, l)) : DFS(M, row + rowNbr[k], col + colNbr[k], c, n, l); # Function to return the number of# connectewd components in the matrixdef connectedComponents(M, n) : connectedComp = 0; l = len(M[0]); for i in range(n) : for j in range(l) : if (not visited[i][j]) : c = M[i][j]; DFS(M, i, j, c, n, l); connectedComp += 1; return connectedComp; # Driver codeif __name__ == \"__main__\" : M = [\"aabba\", \"aabba\", \"aaaca\"]; n = len(M) print(connectedComponents(M, n)); # This code is contributed by Ryuga",
"e": 30737,
"s": 29161,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ static readonly int maxRow = 500;static readonly int maxCol = 500; static bool [,]visited = new bool[maxRow,maxCol]; // Function that return true if mat[row,col]// is valid and hasn't been visitedstatic bool isSafe(String []M, int row, int col, char c, int n, int l){ // If row and column are valid and element // is matched and hasn't been visited then // the cell is safe return (row >= 0 && row < n) && (col >= 0 && col < l) && (M[row][col] == c && !visited[row,col]);} // Function for depth first searchstatic void DFS(String []M, int row, int col, char c, int n, int l){ // These arrays are used to get row and column // numbers of 4 neighbours of a given cell int []rowNbr = {-1, 1, 0, 0}; int []colNbr = {0, 0, 1, -1}; // Mark this cell as visited visited[row,col] = true; // Recur for all connected neighbours for (int k = 0; k < 4; ++k) { if (isSafe(M, row + rowNbr[k], col + colNbr[k], c, n, l)) { DFS(M, row + rowNbr[k], col + colNbr[k], c, n, l); } }} // Function to return the number of// connectewd components in the matrixstatic int connectedComponents(String []M, int n){ int connectedComp = 0; int l = M[0].Length; for (int i = 0; i < n; i++) { for (int j = 0; j < l; j++) { if (!visited[i,j]) { char c = M[i][j]; DFS(M, i, j, c, n, l); connectedComp++; } } } return connectedComp;} // Driver codepublic static void Main(String[] args){ String []M = {\"aabba\", \"aabba\", \"aaaca\"}; int n = M.Length; Console.WriteLine(connectedComponents(M, n));}} // This code contributed by Rajput-Ji",
"e": 32615,
"s": 30737,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach var maxRow = 500; var maxCol = 500; var visited = Array(maxRow).fill().map(()=>Array(maxCol).fill(false)); // Function that return true if mat[row][col] // is valid and hasn't been visited function isSafe( M , row , col, c , n , l) { // If row and column are valid and element // is matched and hasn't been visited then // the cell is safe return (row >= 0 && row < n) && (col >= 0 && col < l) && (M[row].charAt(col) == c && !visited[row][col]); } // Function for depth first search function DFS( M , row , col, c , n , l) { // These arrays are used to get row and column // numbers of 4 neighbours of a given cell var rowNbr = [ -1, 1, 0, 0 ]; var colNbr = [ 0, 0, 1, -1 ]; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (var k = 0; k < 4; ++k) { if (isSafe(M, row + rowNbr[k], col + colNbr[k], c, n, l)) { DFS(M, row + rowNbr[k], col + colNbr[k], c, n, l); } } } // Function to return the number of // connectewd components in the matrix function connectedComponents( M , n) { var connectedComp = 0; var l = M[0].length; for (var i = 0; i < n; i++) { for (j = 0; j < l; j++) { if (!visited[i][j]) { var c = M[i].charAt(j); DFS(M, i, j, c, n, l); connectedComp++; } } } return connectedComp; } // Driver code var M = [ \"aabba\", \"aabba\", \"aaaca\" ]; var n = M.length; document.write(connectedComponents(M, n)); // This code contributed by gauravrajput1 </script>",
"e": 34494,
"s": 32615,
"text": null
},
{
"code": null,
"e": 34496,
"s": 34494,
"text": "4"
},
{
"code": null,
"e": 34559,
"s": 34498,
"text": "Time Complexity: O(row * cols)Auxiliary Space: O(row * cols)"
},
{
"code": null,
"e": 34567,
"s": 34559,
"text": "ankthon"
},
{
"code": null,
"e": 34581,
"s": 34567,
"text": "princiraj1992"
},
{
"code": null,
"e": 34591,
"s": 34581,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34605,
"s": 34591,
"text": "GauravRajput1"
},
{
"code": null,
"e": 34621,
"s": 34605,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 34625,
"s": 34621,
"text": "DFS"
},
{
"code": null,
"e": 34636,
"s": 34625,
"text": "Algorithms"
},
{
"code": null,
"e": 34660,
"s": 34636,
"text": "Competitive Programming"
},
{
"code": null,
"e": 34667,
"s": 34660,
"text": "Matrix"
},
{
"code": null,
"e": 34671,
"s": 34667,
"text": "DFS"
},
{
"code": null,
"e": 34678,
"s": 34671,
"text": "Matrix"
},
{
"code": null,
"e": 34689,
"s": 34678,
"text": "Algorithms"
},
{
"code": null,
"e": 34787,
"s": 34689,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34796,
"s": 34787,
"text": "Comments"
},
{
"code": null,
"e": 34809,
"s": 34796,
"text": "Old Comments"
},
{
"code": null,
"e": 34834,
"s": 34809,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 34863,
"s": 34834,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 34906,
"s": 34863,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 34940,
"s": 34906,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 34996,
"s": 34940,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 35039,
"s": 34996,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 35080,
"s": 35039,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 35123,
"s": 35080,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 35150,
"s": 35123,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
Python | Count true booleans in a list - GeeksforGeeks
|
25 Jun, 2019
Given a list of booleans, write a Python program to find the count of true booleans in the given list.
Examples:
Input : [True, False, True, True, False]
Output : 3
Input : [False, True, False, True]
Output : 2
Method #1 : Using List comprehension
One simple method to count True booleans in a list is using list comprehension.
# Python3 program to count True booleans in a list def count(lst): return sum(bool(x) for x in lst) # Driver codelst = [True, False, True, True, False]print(count(lst))
3
Method #2 : Using sum()
# Python3 program to count True booleans in a list def count(lst): return sum(lst) # Driver codelst = [True, False, True, True, False]print(count(lst))
3
A more robust and transparent method to use sum is given below.
def count(lst): return sum(1 for x in lst if x)
Method #3 : count() method
# Python3 program to count True booleans in a list def count(lst): return lst.count(True) # Driver codelst = [True, False, True, True, False]print(count(lst))
3
Method #4 : filter()
# Python3 program to count True booleans in a list def count(lst): return len(list(filter(None, lst))) # Driver codelst = [True, False, True, True, False]print(count(lst))
3
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 ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 24360,
"s": 24332,
"text": "\n25 Jun, 2019"
},
{
"code": null,
"e": 24463,
"s": 24360,
"text": "Given a list of booleans, write a Python program to find the count of true booleans in the given list."
},
{
"code": null,
"e": 24473,
"s": 24463,
"text": "Examples:"
},
{
"code": null,
"e": 24573,
"s": 24473,
"text": "Input : [True, False, True, True, False]\nOutput : 3\n\nInput : [False, True, False, True]\nOutput : 2\n"
},
{
"code": null,
"e": 24611,
"s": 24573,
"text": " Method #1 : Using List comprehension"
},
{
"code": null,
"e": 24691,
"s": 24611,
"text": "One simple method to count True booleans in a list is using list comprehension."
},
{
"code": "# Python3 program to count True booleans in a list def count(lst): return sum(bool(x) for x in lst) # Driver codelst = [True, False, True, True, False]print(count(lst))",
"e": 24871,
"s": 24691,
"text": null
},
{
"code": null,
"e": 24874,
"s": 24871,
"text": "3\n"
},
{
"code": null,
"e": 24899,
"s": 24874,
"text": " Method #2 : Using sum()"
},
{
"code": "# Python3 program to count True booleans in a list def count(lst): return sum(lst) # Driver codelst = [True, False, True, True, False]print(count(lst))",
"e": 25066,
"s": 24899,
"text": null
},
{
"code": null,
"e": 25069,
"s": 25066,
"text": "3\n"
},
{
"code": null,
"e": 25133,
"s": 25069,
"text": "A more robust and transparent method to use sum is given below."
},
{
"code": "def count(lst): return sum(1 for x in lst if x)",
"e": 25190,
"s": 25133,
"text": null
},
{
"code": null,
"e": 25218,
"s": 25190,
"text": " Method #3 : count() method"
},
{
"code": "# Python3 program to count True booleans in a list def count(lst): return lst.count(True) # Driver codelst = [True, False, True, True, False]print(count(lst))",
"e": 25392,
"s": 25218,
"text": null
},
{
"code": null,
"e": 25395,
"s": 25392,
"text": "3\n"
},
{
"code": null,
"e": 25417,
"s": 25395,
"text": " Method #4 : filter()"
},
{
"code": "# Python3 program to count True booleans in a list def count(lst): return len(list(filter(None, lst))) # Driver codelst = [True, False, True, True, False]print(count(lst))",
"e": 25604,
"s": 25417,
"text": null
},
{
"code": null,
"e": 25607,
"s": 25604,
"text": "3\n"
},
{
"code": null,
"e": 25614,
"s": 25607,
"text": "Python"
},
{
"code": null,
"e": 25630,
"s": 25614,
"text": "Python Programs"
},
{
"code": null,
"e": 25728,
"s": 25630,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25760,
"s": 25728,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25782,
"s": 25760,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25824,
"s": 25782,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25850,
"s": 25824,
"text": "Python String | replace()"
},
{
"code": null,
"e": 25887,
"s": 25850,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 25909,
"s": 25887,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25948,
"s": 25909,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 25994,
"s": 25948,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26032,
"s": 25994,
"text": "Python | Convert a list to dictionary"
}
] |
JavaScript Importing and Exporting Modules
|
To import and export modules using JavaScript, the code is as follows β
Note β To run this example you will need to run a localhost server.
INDEX.html
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>JavaScript Importing and Exporting Modules</h1>
<button class="Btn">IMPORT</button>
<div class="result"></div>
<h3>
Click on the above button to import module
</h3>
<script src="script.js" type="module"></script>
<script src="sample.js" type="module"></script>
</body>
</html>
script.js
import test from './sample.js';
document.querySelector('.Btn').addEventListener('click',()=>{
test();
})
sample.js
let resultEle = document.querySelector(".result");
export default function testImport(){
resultEle.innerHTML = 'Module testImport has been imported';
}
On clicking the βIMPORTβ button β
|
[
{
"code": null,
"e": 1134,
"s": 1062,
"text": "To import and export modules using JavaScript, the code is as follows β"
},
{
"code": null,
"e": 1202,
"s": 1134,
"text": "Note β To run this example you will need to run a localhost server."
},
{
"code": null,
"e": 1213,
"s": 1202,
"text": "INDEX.html"
},
{
"code": null,
"e": 1224,
"s": 1213,
"text": " Live Demo"
},
{
"code": null,
"e": 1847,
"s": 1224,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 18px;\n font-weight: 500;\n }\n</style>\n</head>\n<body>\n<h1>JavaScript Importing and Exporting Modules</h1>\n<button class=\"Btn\">IMPORT</button>\n<div class=\"result\"></div>\n<h3>\nClick on the above button to import module\n</h3>\n<script src=\"script.js\" type=\"module\"></script>\n<script src=\"sample.js\" type=\"module\"></script>\n</body>\n</html>"
},
{
"code": null,
"e": 1857,
"s": 1847,
"text": "script.js"
},
{
"code": null,
"e": 1965,
"s": 1857,
"text": "import test from './sample.js';\ndocument.querySelector('.Btn').addEventListener('click',()=>{\n test();\n})"
},
{
"code": null,
"e": 1975,
"s": 1965,
"text": "sample.js"
},
{
"code": null,
"e": 2130,
"s": 1975,
"text": "let resultEle = document.querySelector(\".result\");\nexport default function testImport(){\n resultEle.innerHTML = 'Module testImport has been imported';\n}"
},
{
"code": null,
"e": 2164,
"s": 2130,
"text": "On clicking the βIMPORTβ button β"
}
] |
Shannon-Fano Algorithm for Data Compression - GeeksforGeeks
|
07 Dec, 2021
DATA COMPRESSION AND ITS TYPES Data Compression, also known as source coding, is the process of encoding or converting data in such a way that it consumes less memory space. Data compression reduces the number of resources required to store and transmit data. It can be done in two ways- lossless compression and lossy compression. Lossy compression reduces the size of data by removing unnecessary information, while there is no data loss in lossless compression.
WHAT IS SHANNON FANO CODING? Shannon Fano Algorithm is an entropy encoding technique for lossless data compression of multimedia. Named after Claude Shannon and Robert Fano, it assigns a code to each symbol based on their probabilities of occurrence. It is a variable-length encoding scheme, that is, the codes assigned to the symbols will be of varying length.
HOW DOES IT WORK? The steps of the algorithm are as follows:
Create a list of probabilities or frequency counts for the given set of symbols so that the relative frequency of occurrence of each symbol is known.Sort the list of symbols in decreasing order of probability, the most probable ones to the left and least probable to the right.Split the list into two parts, with the total probability of both the parts being as close to each other as possible.Assign the value 0 to the left part and 1 to the right part.Repeat steps 3 and 4 for each part, until all the symbols are split into individual subgroups.
Create a list of probabilities or frequency counts for the given set of symbols so that the relative frequency of occurrence of each symbol is known.
Sort the list of symbols in decreasing order of probability, the most probable ones to the left and least probable to the right.
Split the list into two parts, with the total probability of both the parts being as close to each other as possible.
Assign the value 0 to the left part and 1 to the right part.
Repeat steps 3 and 4 for each part, until all the symbols are split into individual subgroups.
The Shannon codes are considered accurate if the code of each symbol is unique.
EXAMPLE: The given task is to construct Shannon codes for the given set of symbols using the Shannon-Fano lossless compression technique.
Step:
Tree:
Solution:
1. Upon arranging the symbols in decreasing order of probability:
P(D) + P(B) = 0.30 + 0.2 = 0.58
and,
P(A) + P(C) + P(E) = 0.22 + 0.15 + 0.05 = 0.42
And since the almost equally split the table, the most is divided it the blockquote table isblockquotento
{D, B} and {A, C, E}
and assign them the values 0 and 1 respectively.
Step:
Tree:
2. Now, in {D, B} group,
P(D) = 0.30 and P(B) = 0.28
which means that P(D)~P(B), so divide {D, B} into {D} and {B} and assign 0 to D and 1 to B.
Step:
Tree:
3. In {A, C, E} group,
P(A) = 0.22 and P(C) + P(E) = 0.20
So the group is divided into
{A} and {C, E}
and they are assigned values 0 and 1 respectively.
4. In {C, E} group,
P(C) = 0.15 and P(E) = 0.05
So divide them into {C} and {E} and assign 0 to {C} and 1 to {E}
Step:
Tree:
Note: The splitting is now stopped as each symbol is separated now.
The Shannon codes for the set of symbols are:
As it can be seen, these are all unique and of varying lengths.
Below is the implementation of the above approach:
C++
Python3
// C++ program for Shannon Fano Algorithm // include header files#include <bits/stdc++.h>using namespace std; // declare structure nodestruct node { // for storing symbol string sym; // for storing probability or frequency float pro; int arr[20]; int top;} p[20]; typedef struct node node; // function to find shannon codevoid shannon(int l, int h, node p[]){ float pack1 = 0, pack2 = 0, diff1 = 0, diff2 = 0; int i, d, k, j; if ((l + 1) == h || l == h || l > h) { if (l == h || l > h) return; p[h].arr[++(p[h].top)] = 0; p[l].arr[++(p[l].top)] = 1; return; } else { for (i = l; i <= h - 1; i++) pack1 = pack1 + p[i].pro; pack2 = pack2 + p[h].pro; diff1 = pack1 - pack2; if (diff1 < 0) diff1 = diff1 * -1; j = 2; while (j != h - l + 1) { k = h - j; pack1 = pack2 = 0; for (i = l; i <= k; i++) pack1 = pack1 + p[i].pro; for (i = h; i > k; i--) pack2 = pack2 + p[i].pro; diff2 = pack1 - pack2; if (diff2 < 0) diff2 = diff2 * -1; if (diff2 >= diff1) break; diff1 = diff2; j++; } k++; for (i = l; i <= k; i++) p[i].arr[++(p[i].top)] = 1; for (i = k + 1; i <= h; i++) p[i].arr[++(p[i].top)] = 0; // Invoke shannon function shannon(l, k, p); shannon(k + 1, h, p); }} // Function to sort the symbols// based on their probability or frequencyvoid sortByProbability(int n, node p[]){ int i, j; node temp; for (j = 1; j <= n - 1; j++) { for (i = 0; i < n - 1; i++) { if ((p[i].pro) > (p[i + 1].pro)) { temp.pro = p[i].pro; temp.sym = p[i].sym; p[i].pro = p[i + 1].pro; p[i].sym = p[i + 1].sym; p[i + 1].pro = temp.pro; p[i + 1].sym = temp.sym; } } }} // function to display shannon codesvoid display(int n, node p[]){ int i, j; cout << "\n\n\n\tSymbol\tProbability\tCode"; for (i = n - 1; i >= 0; i--) { cout << "\n\t" << p[i].sym << "\t\t" << p[i].pro << "\t"; for (j = 0; j <= p[i].top; j++) cout << p[i].arr[j]; }} // Driver codeint main(){ int n, i, j; float total = 0; string ch; node temp; // Input number of symbols cout << "Enter number of symbols\t: "; n = 5; cout << n << endl; // Input symbols for (i = 0; i < n; i++) { cout << "Enter symbol " << i + 1 << " : "; ch = (char)(65 + i); cout << ch << endl; // Insert the symbol to node p[i].sym += ch; } // Input probability of symbols float x[] = { 0.22, 0.28, 0.15, 0.30, 0.05 }; for (i = 0; i < n; i++) { cout << "\nEnter probability of " << p[i].sym << " : "; cout << x[i] << endl; // Insert the value to node p[i].pro = x[i]; total = total + p[i].pro; // checking max probability if (total > 1) { cout << "Invalid. Enter new values"; total = total - p[i].pro; i--; } } p[i].pro = 1 - total; // Sorting the symbols based on // their probability or frequency sortByProbability(n, p); for (i = 0; i < n; i++) p[i].top = -1; // Find the shannon code shannon(0, n - 1, p); // Display the codes display(n, p); return 0;}
# Python3 program for Shannon Fano Algorithm # declare structure nodeclass node : def __init__(self) -> None: # for storing symbol self.sym='' # for storing probability or frequency self.pro=0.0 self.arr=[0]*20 self.top=0p=[node() for _ in range(20)] # function to find shannon codedef shannon(l, h, p): pack1 = 0; pack2 = 0; diff1 = 0; diff2 = 0 if ((l + 1) == h or l == h or l > h) : if (l == h or l > h): return p[h].top+=1 p[h].arr[(p[h].top)] = 0 p[l].top+=1 p[l].arr[(p[l].top)] = 1 return else : for i in range(l,h): pack1 = pack1 + p[i].pro pack2 = pack2 + p[h].pro diff1 = pack1 - pack2 if (diff1 < 0): diff1 = diff1 * -1 j = 2 while (j != h - l + 1) : k = h - j pack1 = pack2 = 0 for i in range(l, k+1): pack1 = pack1 + p[i].pro for i in range(h,k,-1): pack2 = pack2 + p[i].pro diff2 = pack1 - pack2 if (diff2 < 0): diff2 = diff2 * -1 if (diff2 >= diff1): break diff1 = diff2 j+=1 k+=1 for i in range(l,k+1): p[i].top+=1 p[i].arr[(p[i].top)] = 1 for i in range(k + 1,h+1): p[i].top+=1 p[i].arr[(p[i].top)] = 0 # Invoke shannon function shannon(l, k, p) shannon(k + 1, h, p) # Function to sort the symbols# based on their probability or frequencydef sortByProbability(n, p): temp=node() for j in range(1,n) : for i in range(n - 1) : if ((p[i].pro) > (p[i + 1].pro)) : temp.pro = p[i].pro temp.sym = p[i].sym p[i].pro = p[i + 1].pro p[i].sym = p[i + 1].sym p[i + 1].pro = temp.pro p[i + 1].sym = temp.sym # function to display shannon codesdef display(n, p): print("\n\n\n\tSymbol\tProbability\tCode",end='') for i in range(n - 1,-1,-1): print("\n\t", p[i].sym, "\t\t", p[i].pro,"\t",end='') for j in range(p[i].top+1): print(p[i].arr[j],end='') # Driver codeif __name__ == '__main__': total = 0 # Input number of symbols print("Enter number of symbols\t: ",end='') n = 5 print(n) i=0 # Input symbols for i in range(n): print("Enter symbol", i + 1," : ",end="") ch = chr(65 + i) print(ch) # Insert the symbol to node p[i].sym += ch # Input probability of symbols x = [0.22, 0.28, 0.15, 0.30, 0.05] for i in range(n): print("\nEnter probability of", p[i].sym, ": ",end="") print(x[i]) # Insert the value to node p[i].pro = x[i] total = total + p[i].pro # checking max probability if (total > 1) : print("Invalid. Enter new values") total = total - p[i].pro i-=1 i+=1 p[i].pro = 1 - total # Sorting the symbols based on # their probability or frequency sortByProbability(n, p) for i in range(n): p[i].top = -1 # Find the shannon code shannon(0, n - 1, p) # Display the codes display(n, p)
Enter number of symbols : 5
Enter symbol 1 : A
Enter symbol 2 : B
Enter symbol 3 : C
Enter symbol 4 : D
Enter symbol 5 : E
Enter probability of A : 0.22
Enter probability of B : 0.28
Enter probability of C : 0.15
Enter probability of D : 0.3
Enter probability of E : 0.05
Symbol Probability Code
D 0.3 00
B 0.28 01
A 0.22 10
C 0.15 110
E 0.05 111
arorakashish0911
vaibhavsinghtanwar3
amartyaghoshgfg
Probability
Technical Scripter 2018
Algorithms
Computer Networks
Technical Scripter
Tree
Tree
Algorithms
Probability
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
How to write a Pseudo Code?
Recursive Practice Problems with Solutions
Layers of OSI Model
TCP/IP Model
TCP Server-Client implementation in C
Basics of Computer Networking
Differences between TCP and UDP
|
[
{
"code": null,
"e": 24474,
"s": 24446,
"text": "\n07 Dec, 2021"
},
{
"code": null,
"e": 24939,
"s": 24474,
"text": "DATA COMPRESSION AND ITS TYPES Data Compression, also known as source coding, is the process of encoding or converting data in such a way that it consumes less memory space. Data compression reduces the number of resources required to store and transmit data. It can be done in two ways- lossless compression and lossy compression. Lossy compression reduces the size of data by removing unnecessary information, while there is no data loss in lossless compression."
},
{
"code": null,
"e": 25302,
"s": 24939,
"text": "WHAT IS SHANNON FANO CODING? Shannon Fano Algorithm is an entropy encoding technique for lossless data compression of multimedia. Named after Claude Shannon and Robert Fano, it assigns a code to each symbol based on their probabilities of occurrence. It is a variable-length encoding scheme, that is, the codes assigned to the symbols will be of varying length. "
},
{
"code": null,
"e": 25365,
"s": 25302,
"text": "HOW DOES IT WORK? The steps of the algorithm are as follows: "
},
{
"code": null,
"e": 25914,
"s": 25365,
"text": "Create a list of probabilities or frequency counts for the given set of symbols so that the relative frequency of occurrence of each symbol is known.Sort the list of symbols in decreasing order of probability, the most probable ones to the left and least probable to the right.Split the list into two parts, with the total probability of both the parts being as close to each other as possible.Assign the value 0 to the left part and 1 to the right part.Repeat steps 3 and 4 for each part, until all the symbols are split into individual subgroups."
},
{
"code": null,
"e": 26064,
"s": 25914,
"text": "Create a list of probabilities or frequency counts for the given set of symbols so that the relative frequency of occurrence of each symbol is known."
},
{
"code": null,
"e": 26193,
"s": 26064,
"text": "Sort the list of symbols in decreasing order of probability, the most probable ones to the left and least probable to the right."
},
{
"code": null,
"e": 26311,
"s": 26193,
"text": "Split the list into two parts, with the total probability of both the parts being as close to each other as possible."
},
{
"code": null,
"e": 26372,
"s": 26311,
"text": "Assign the value 0 to the left part and 1 to the right part."
},
{
"code": null,
"e": 26467,
"s": 26372,
"text": "Repeat steps 3 and 4 for each part, until all the symbols are split into individual subgroups."
},
{
"code": null,
"e": 26547,
"s": 26467,
"text": "The Shannon codes are considered accurate if the code of each symbol is unique."
},
{
"code": null,
"e": 26685,
"s": 26547,
"text": "EXAMPLE: The given task is to construct Shannon codes for the given set of symbols using the Shannon-Fano lossless compression technique."
},
{
"code": null,
"e": 26693,
"s": 26685,
"text": "Step: "
},
{
"code": null,
"e": 26700,
"s": 26693,
"text": "Tree: "
},
{
"code": null,
"e": 26711,
"s": 26700,
"text": "Solution: "
},
{
"code": null,
"e": 26777,
"s": 26711,
"text": "1. Upon arranging the symbols in decreasing order of probability:"
},
{
"code": null,
"e": 26809,
"s": 26777,
"text": "P(D) + P(B) = 0.30 + 0.2 = 0.58"
},
{
"code": null,
"e": 26815,
"s": 26809,
"text": "and, "
},
{
"code": null,
"e": 26862,
"s": 26815,
"text": "P(A) + P(C) + P(E) = 0.22 + 0.15 + 0.05 = 0.42"
},
{
"code": null,
"e": 26969,
"s": 26862,
"text": "And since the almost equally split the table, the most is divided it the blockquote table isblockquotento "
},
{
"code": null,
"e": 26990,
"s": 26969,
"text": "{D, B} and {A, C, E}"
},
{
"code": null,
"e": 27039,
"s": 26990,
"text": "and assign them the values 0 and 1 respectively."
},
{
"code": null,
"e": 27046,
"s": 27039,
"text": "Step: "
},
{
"code": null,
"e": 27053,
"s": 27046,
"text": "Tree: "
},
{
"code": null,
"e": 27079,
"s": 27053,
"text": "2. Now, in {D, B} group, "
},
{
"code": null,
"e": 27107,
"s": 27079,
"text": "P(D) = 0.30 and P(B) = 0.28"
},
{
"code": null,
"e": 27199,
"s": 27107,
"text": "which means that P(D)~P(B), so divide {D, B} into {D} and {B} and assign 0 to D and 1 to B."
},
{
"code": null,
"e": 27206,
"s": 27199,
"text": "Step: "
},
{
"code": null,
"e": 27213,
"s": 27206,
"text": "Tree: "
},
{
"code": null,
"e": 27237,
"s": 27213,
"text": "3. In {A, C, E} group, "
},
{
"code": null,
"e": 27272,
"s": 27237,
"text": "P(A) = 0.22 and P(C) + P(E) = 0.20"
},
{
"code": null,
"e": 27302,
"s": 27272,
"text": "So the group is divided into "
},
{
"code": null,
"e": 27317,
"s": 27302,
"text": "{A} and {C, E}"
},
{
"code": null,
"e": 27368,
"s": 27317,
"text": "and they are assigned values 0 and 1 respectively."
},
{
"code": null,
"e": 27389,
"s": 27368,
"text": "4. In {C, E} group, "
},
{
"code": null,
"e": 27417,
"s": 27389,
"text": "P(C) = 0.15 and P(E) = 0.05"
},
{
"code": null,
"e": 27482,
"s": 27417,
"text": "So divide them into {C} and {E} and assign 0 to {C} and 1 to {E}"
},
{
"code": null,
"e": 27488,
"s": 27482,
"text": "Step:"
},
{
"code": null,
"e": 27494,
"s": 27488,
"text": "Tree:"
},
{
"code": null,
"e": 27562,
"s": 27494,
"text": "Note: The splitting is now stopped as each symbol is separated now."
},
{
"code": null,
"e": 27610,
"s": 27562,
"text": "The Shannon codes for the set of symbols are: "
},
{
"code": null,
"e": 27674,
"s": 27610,
"text": "As it can be seen, these are all unique and of varying lengths."
},
{
"code": null,
"e": 27727,
"s": 27674,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27731,
"s": 27727,
"text": "C++"
},
{
"code": null,
"e": 27739,
"s": 27731,
"text": "Python3"
},
{
"code": "// C++ program for Shannon Fano Algorithm // include header files#include <bits/stdc++.h>using namespace std; // declare structure nodestruct node { // for storing symbol string sym; // for storing probability or frequency float pro; int arr[20]; int top;} p[20]; typedef struct node node; // function to find shannon codevoid shannon(int l, int h, node p[]){ float pack1 = 0, pack2 = 0, diff1 = 0, diff2 = 0; int i, d, k, j; if ((l + 1) == h || l == h || l > h) { if (l == h || l > h) return; p[h].arr[++(p[h].top)] = 0; p[l].arr[++(p[l].top)] = 1; return; } else { for (i = l; i <= h - 1; i++) pack1 = pack1 + p[i].pro; pack2 = pack2 + p[h].pro; diff1 = pack1 - pack2; if (diff1 < 0) diff1 = diff1 * -1; j = 2; while (j != h - l + 1) { k = h - j; pack1 = pack2 = 0; for (i = l; i <= k; i++) pack1 = pack1 + p[i].pro; for (i = h; i > k; i--) pack2 = pack2 + p[i].pro; diff2 = pack1 - pack2; if (diff2 < 0) diff2 = diff2 * -1; if (diff2 >= diff1) break; diff1 = diff2; j++; } k++; for (i = l; i <= k; i++) p[i].arr[++(p[i].top)] = 1; for (i = k + 1; i <= h; i++) p[i].arr[++(p[i].top)] = 0; // Invoke shannon function shannon(l, k, p); shannon(k + 1, h, p); }} // Function to sort the symbols// based on their probability or frequencyvoid sortByProbability(int n, node p[]){ int i, j; node temp; for (j = 1; j <= n - 1; j++) { for (i = 0; i < n - 1; i++) { if ((p[i].pro) > (p[i + 1].pro)) { temp.pro = p[i].pro; temp.sym = p[i].sym; p[i].pro = p[i + 1].pro; p[i].sym = p[i + 1].sym; p[i + 1].pro = temp.pro; p[i + 1].sym = temp.sym; } } }} // function to display shannon codesvoid display(int n, node p[]){ int i, j; cout << \"\\n\\n\\n\\tSymbol\\tProbability\\tCode\"; for (i = n - 1; i >= 0; i--) { cout << \"\\n\\t\" << p[i].sym << \"\\t\\t\" << p[i].pro << \"\\t\"; for (j = 0; j <= p[i].top; j++) cout << p[i].arr[j]; }} // Driver codeint main(){ int n, i, j; float total = 0; string ch; node temp; // Input number of symbols cout << \"Enter number of symbols\\t: \"; n = 5; cout << n << endl; // Input symbols for (i = 0; i < n; i++) { cout << \"Enter symbol \" << i + 1 << \" : \"; ch = (char)(65 + i); cout << ch << endl; // Insert the symbol to node p[i].sym += ch; } // Input probability of symbols float x[] = { 0.22, 0.28, 0.15, 0.30, 0.05 }; for (i = 0; i < n; i++) { cout << \"\\nEnter probability of \" << p[i].sym << \" : \"; cout << x[i] << endl; // Insert the value to node p[i].pro = x[i]; total = total + p[i].pro; // checking max probability if (total > 1) { cout << \"Invalid. Enter new values\"; total = total - p[i].pro; i--; } } p[i].pro = 1 - total; // Sorting the symbols based on // their probability or frequency sortByProbability(n, p); for (i = 0; i < n; i++) p[i].top = -1; // Find the shannon code shannon(0, n - 1, p); // Display the codes display(n, p); return 0;}",
"e": 31273,
"s": 27739,
"text": null
},
{
"code": "# Python3 program for Shannon Fano Algorithm # declare structure nodeclass node : def __init__(self) -> None: # for storing symbol self.sym='' # for storing probability or frequency self.pro=0.0 self.arr=[0]*20 self.top=0p=[node() for _ in range(20)] # function to find shannon codedef shannon(l, h, p): pack1 = 0; pack2 = 0; diff1 = 0; diff2 = 0 if ((l + 1) == h or l == h or l > h) : if (l == h or l > h): return p[h].top+=1 p[h].arr[(p[h].top)] = 0 p[l].top+=1 p[l].arr[(p[l].top)] = 1 return else : for i in range(l,h): pack1 = pack1 + p[i].pro pack2 = pack2 + p[h].pro diff1 = pack1 - pack2 if (diff1 < 0): diff1 = diff1 * -1 j = 2 while (j != h - l + 1) : k = h - j pack1 = pack2 = 0 for i in range(l, k+1): pack1 = pack1 + p[i].pro for i in range(h,k,-1): pack2 = pack2 + p[i].pro diff2 = pack1 - pack2 if (diff2 < 0): diff2 = diff2 * -1 if (diff2 >= diff1): break diff1 = diff2 j+=1 k+=1 for i in range(l,k+1): p[i].top+=1 p[i].arr[(p[i].top)] = 1 for i in range(k + 1,h+1): p[i].top+=1 p[i].arr[(p[i].top)] = 0 # Invoke shannon function shannon(l, k, p) shannon(k + 1, h, p) # Function to sort the symbols# based on their probability or frequencydef sortByProbability(n, p): temp=node() for j in range(1,n) : for i in range(n - 1) : if ((p[i].pro) > (p[i + 1].pro)) : temp.pro = p[i].pro temp.sym = p[i].sym p[i].pro = p[i + 1].pro p[i].sym = p[i + 1].sym p[i + 1].pro = temp.pro p[i + 1].sym = temp.sym # function to display shannon codesdef display(n, p): print(\"\\n\\n\\n\\tSymbol\\tProbability\\tCode\",end='') for i in range(n - 1,-1,-1): print(\"\\n\\t\", p[i].sym, \"\\t\\t\", p[i].pro,\"\\t\",end='') for j in range(p[i].top+1): print(p[i].arr[j],end='') # Driver codeif __name__ == '__main__': total = 0 # Input number of symbols print(\"Enter number of symbols\\t: \",end='') n = 5 print(n) i=0 # Input symbols for i in range(n): print(\"Enter symbol\", i + 1,\" : \",end=\"\") ch = chr(65 + i) print(ch) # Insert the symbol to node p[i].sym += ch # Input probability of symbols x = [0.22, 0.28, 0.15, 0.30, 0.05] for i in range(n): print(\"\\nEnter probability of\", p[i].sym, \": \",end=\"\") print(x[i]) # Insert the value to node p[i].pro = x[i] total = total + p[i].pro # checking max probability if (total > 1) : print(\"Invalid. Enter new values\") total = total - p[i].pro i-=1 i+=1 p[i].pro = 1 - total # Sorting the symbols based on # their probability or frequency sortByProbability(n, p) for i in range(n): p[i].top = -1 # Find the shannon code shannon(0, n - 1, p) # Display the codes display(n, p)",
"e": 34637,
"s": 31273,
"text": null
},
{
"code": null,
"e": 35075,
"s": 34637,
"text": "Enter number of symbols : 5\nEnter symbol 1 : A\nEnter symbol 2 : B\nEnter symbol 3 : C\nEnter symbol 4 : D\nEnter symbol 5 : E\n\nEnter probability of A : 0.22\n\nEnter probability of B : 0.28\n\nEnter probability of C : 0.15\n\nEnter probability of D : 0.3\n\nEnter probability of E : 0.05\n\n\n\n Symbol Probability Code\n D 0.3 00\n B 0.28 01\n A 0.22 10\n C 0.15 110\n E 0.05 111"
},
{
"code": null,
"e": 35094,
"s": 35077,
"text": "arorakashish0911"
},
{
"code": null,
"e": 35114,
"s": 35094,
"text": "vaibhavsinghtanwar3"
},
{
"code": null,
"e": 35130,
"s": 35114,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 35142,
"s": 35130,
"text": "Probability"
},
{
"code": null,
"e": 35166,
"s": 35142,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 35177,
"s": 35166,
"text": "Algorithms"
},
{
"code": null,
"e": 35195,
"s": 35177,
"text": "Computer Networks"
},
{
"code": null,
"e": 35214,
"s": 35195,
"text": "Technical Scripter"
},
{
"code": null,
"e": 35219,
"s": 35214,
"text": "Tree"
},
{
"code": null,
"e": 35224,
"s": 35219,
"text": "Tree"
},
{
"code": null,
"e": 35235,
"s": 35224,
"text": "Algorithms"
},
{
"code": null,
"e": 35247,
"s": 35235,
"text": "Probability"
},
{
"code": null,
"e": 35265,
"s": 35247,
"text": "Computer Networks"
},
{
"code": null,
"e": 35363,
"s": 35265,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35372,
"s": 35363,
"text": "Comments"
},
{
"code": null,
"e": 35385,
"s": 35372,
"text": "Old Comments"
},
{
"code": null,
"e": 35434,
"s": 35385,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 35459,
"s": 35434,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 35486,
"s": 35459,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 35514,
"s": 35486,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 35557,
"s": 35514,
"text": "Recursive Practice Problems with Solutions"
},
{
"code": null,
"e": 35577,
"s": 35557,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 35590,
"s": 35577,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 35628,
"s": 35590,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 35658,
"s": 35628,
"text": "Basics of Computer Networking"
}
] |
Bootstrap - Plugins Overview
|
The components discussed in the previous chapters under Layout Components are just the beginning. Bootstrap comes bundled with 12 jQuery plugins that extend the features and can add more interaction to your site. To get started with the Bootstrapβs JavaScript plugins, you donβt need to be an advanced JavaScript developer. By utilizing Bootstrap Data API, most of the plugins can be triggered without writing a single line of code.
Bootstrap Plugins can be included on your site in two forms β
Individually β Using Bootstrap's individual *.js files. Some plugins and CSS components depend on other plugins. If you include plugins individually, make sure to check for these dependencies in the docs.
Individually β Using Bootstrap's individual *.js files. Some plugins and CSS components depend on other plugins. If you include plugins individually, make sure to check for these dependencies in the docs.
Or compiled (all at once) β Using bootstrap.js or the minified bootstrap.min.js. Do not attempt to include both, as both bootstrap.js and bootstrap.min.js contain all plugins in a single file.
Or compiled (all at once) β Using bootstrap.js or the minified bootstrap.min.js. Do not attempt to include both, as both bootstrap.js and bootstrap.min.js contain all plugins in a single file.
All of the Bootstrap plugins are accessible using the included Data API. Hence, you donβt need to include a single line of JavaScript to invoke any of the plugin features.
All of the Bootstrap plugins are accessible using the included Data API. Hence, you donβt need to include a single line of JavaScript to invoke any of the plugin features.
In some situations it may be desirable to turn this functionality of Data API off. If you need to turn off the Data API, you can unbind the attributes by adding the following line of JavaScript β
In some situations it may be desirable to turn this functionality of Data API off. If you need to turn off the Data API, you can unbind the attributes by adding the following line of JavaScript β
$(document).off('.data-api')
To turn off a specific/single plugin, just include the plugin's name as a namespace along with the data-api namespace like this β
To turn off a specific/single plugin, just include the plugin's name as a namespace along with the data-api namespace like this β
$(document).off('.alert.data-api')
The developers of Bootstrap believe that you should be able to use all of the plugins purely through the JavaScript API. All public APIs are single, chainable methods, and return the collection acted upon say for example β
$(".btn.danger").button("toggle").addClass("fat")
All methods accept an optional options object, a string which targets a particular method, or nothing (which initiates a plugin with default behavior) as shown below β
// initialized with defaults
$("#myModal").modal()
// initialized with no keyboard
$("#myModal").modal({ keyboard: false })
// initializes and invokes show immediately
$("#myModal").modal('show')
Each plugin also exposes its raw constructor on a Constructor property: $.fn.popover.Constructor. If you'd like to get a particular plugin instance, retrieve it directly from an element β
$('[rel = popover]').data('popover').
Bootstrap plugins can sometimes be used with other UI frameworks. In these circumstances, namespace collisions can occasionally occur. To overcome this call .noConflict on the plugin you wish to revert the value of.
// return $.fn.button to previously assigned value
var bootstrapButton = $.fn.button.noConflict()
// give $().bootstrapBtn the Bootstrap functionality
$.fn.bootstrapBtn = bootstrapButton
Bootstrap provides custom events for most plugin's unique actions. Generally, these events come in two forms β
Infinitive form β This is triggered at the start of an event. E.g. show. Infinitive events provide preventDefault functionality. This provides the ability to stop the execution of an action before it starts.
Infinitive form β This is triggered at the start of an event. E.g. show. Infinitive events provide preventDefault functionality. This provides the ability to stop the execution of an action before it starts.
$('#myModal').on('show.bs.modal', function (e) {
// stops modal from being shown
if (!data) return e.preventDefault()
})
Past participle form β This is triggered on the completion of an action. E.g. shown.
Past participle form β This is triggered on the completion of an action. E.g. shown.
26 Lectures
2 hours
Anadi Sharma
54 Lectures
4.5 hours
Frahaan Hussain
161 Lectures
14.5 hours
Eduonix Learning Solutions
20 Lectures
4 hours
Azaz Patel
15 Lectures
1.5 hours
Muhammad Ismail
62 Lectures
8 hours
Yossef Ayman Zedan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3764,
"s": 3331,
"text": "The components discussed in the previous chapters under Layout Components are just the beginning. Bootstrap comes bundled with 12 jQuery plugins that extend the features and can add more interaction to your site. To get started with the Bootstrapβs JavaScript plugins, you donβt need to be an advanced JavaScript developer. By utilizing Bootstrap Data API, most of the plugins can be triggered without writing a single line of code."
},
{
"code": null,
"e": 3826,
"s": 3764,
"text": "Bootstrap Plugins can be included on your site in two forms β"
},
{
"code": null,
"e": 4031,
"s": 3826,
"text": "Individually β Using Bootstrap's individual *.js files. Some plugins and CSS components depend on other plugins. If you include plugins individually, make sure to check for these dependencies in the docs."
},
{
"code": null,
"e": 4236,
"s": 4031,
"text": "Individually β Using Bootstrap's individual *.js files. Some plugins and CSS components depend on other plugins. If you include plugins individually, make sure to check for these dependencies in the docs."
},
{
"code": null,
"e": 4429,
"s": 4236,
"text": "Or compiled (all at once) β Using bootstrap.js or the minified bootstrap.min.js. Do not attempt to include both, as both bootstrap.js and bootstrap.min.js contain all plugins in a single file."
},
{
"code": null,
"e": 4622,
"s": 4429,
"text": "Or compiled (all at once) β Using bootstrap.js or the minified bootstrap.min.js. Do not attempt to include both, as both bootstrap.js and bootstrap.min.js contain all plugins in a single file."
},
{
"code": null,
"e": 4794,
"s": 4622,
"text": "All of the Bootstrap plugins are accessible using the included Data API. Hence, you donβt need to include a single line of JavaScript to invoke any of the plugin features."
},
{
"code": null,
"e": 4966,
"s": 4794,
"text": "All of the Bootstrap plugins are accessible using the included Data API. Hence, you donβt need to include a single line of JavaScript to invoke any of the plugin features."
},
{
"code": null,
"e": 5162,
"s": 4966,
"text": "In some situations it may be desirable to turn this functionality of Data API off. If you need to turn off the Data API, you can unbind the attributes by adding the following line of JavaScript β"
},
{
"code": null,
"e": 5358,
"s": 5162,
"text": "In some situations it may be desirable to turn this functionality of Data API off. If you need to turn off the Data API, you can unbind the attributes by adding the following line of JavaScript β"
},
{
"code": null,
"e": 5388,
"s": 5358,
"text": "$(document).off('.data-api')\n"
},
{
"code": null,
"e": 5518,
"s": 5388,
"text": "To turn off a specific/single plugin, just include the plugin's name as a namespace along with the data-api namespace like this β"
},
{
"code": null,
"e": 5648,
"s": 5518,
"text": "To turn off a specific/single plugin, just include the plugin's name as a namespace along with the data-api namespace like this β"
},
{
"code": null,
"e": 5684,
"s": 5648,
"text": "$(document).off('.alert.data-api')\n"
},
{
"code": null,
"e": 5907,
"s": 5684,
"text": "The developers of Bootstrap believe that you should be able to use all of the plugins purely through the JavaScript API. All public APIs are single, chainable methods, and return the collection acted upon say for example β"
},
{
"code": null,
"e": 5958,
"s": 5907,
"text": "$(\".btn.danger\").button(\"toggle\").addClass(\"fat\")\n"
},
{
"code": null,
"e": 6126,
"s": 5958,
"text": "All methods accept an optional options object, a string which targets a particular method, or nothing (which initiates a plugin with default behavior) as shown below β"
},
{
"code": null,
"e": 6365,
"s": 6126,
"text": "// initialized with defaults\n$(\"#myModal\").modal() \n\n // initialized with no keyboard \n$(\"#myModal\").modal({ keyboard: false }) \n\n// initializes and invokes show immediately\n$(\"#myModal\").modal('show') "
},
{
"code": null,
"e": 6553,
"s": 6365,
"text": "Each plugin also exposes its raw constructor on a Constructor property: $.fn.popover.Constructor. If you'd like to get a particular plugin instance, retrieve it directly from an element β"
},
{
"code": null,
"e": 6592,
"s": 6553,
"text": "$('[rel = popover]').data('popover').\n"
},
{
"code": null,
"e": 6808,
"s": 6592,
"text": "Bootstrap plugins can sometimes be used with other UI frameworks. In these circumstances, namespace collisions can occasionally occur. To overcome this call .noConflict on the plugin you wish to revert the value of."
},
{
"code": null,
"e": 7008,
"s": 6808,
"text": "// return $.fn.button to previously assigned value\nvar bootstrapButton = $.fn.button.noConflict()\n\n// give $().bootstrapBtn the Bootstrap functionality\n$.fn.bootstrapBtn = bootstrapButton "
},
{
"code": null,
"e": 7119,
"s": 7008,
"text": "Bootstrap provides custom events for most plugin's unique actions. Generally, these events come in two forms β"
},
{
"code": null,
"e": 7327,
"s": 7119,
"text": "Infinitive form β This is triggered at the start of an event. E.g. show. Infinitive events provide preventDefault functionality. This provides the ability to stop the execution of an action before it starts."
},
{
"code": null,
"e": 7535,
"s": 7327,
"text": "Infinitive form β This is triggered at the start of an event. E.g. show. Infinitive events provide preventDefault functionality. This provides the ability to stop the execution of an action before it starts."
},
{
"code": null,
"e": 7663,
"s": 7535,
"text": "$('#myModal').on('show.bs.modal', function (e) {\n // stops modal from being shown\n if (!data) return e.preventDefault() \n})"
},
{
"code": null,
"e": 7748,
"s": 7663,
"text": "Past participle form β This is triggered on the completion of an action. E.g. shown."
},
{
"code": null,
"e": 7833,
"s": 7748,
"text": "Past participle form β This is triggered on the completion of an action. E.g. shown."
},
{
"code": null,
"e": 7866,
"s": 7833,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7880,
"s": 7866,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7915,
"s": 7880,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 7932,
"s": 7915,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7969,
"s": 7932,
"text": "\n 161 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 7997,
"s": 7969,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 8030,
"s": 7997,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 8042,
"s": 8030,
"text": " Azaz Patel"
},
{
"code": null,
"e": 8077,
"s": 8042,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8094,
"s": 8077,
"text": " Muhammad Ismail"
},
{
"code": null,
"e": 8127,
"s": 8094,
"text": "\n 62 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 8147,
"s": 8127,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 8154,
"s": 8147,
"text": " Print"
},
{
"code": null,
"e": 8165,
"s": 8154,
"text": " Add Notes"
}
] |
How to delete a character from a string using python?
|
If you want to delete a character at a certain index from the string, you can use string slicing to create a string without that character. For example,
>>> s = "Hello World"
>>> s[:4] + s[5:]
"Hell World"
But if you want to remove all occurances of a character or a list of characters, you can use the following methods:
The string class has a method replace that can be used to replace substrings in a string. We can use this method to replace characters we want to remove with an empty string. For example:
>>> "Hello people".replace("e", "")
"Hllo popl"
If you want to remove multiple characters from a string in a single line, it's better to use regular expressions. You can separate multiple characters by "|" and use the re.sub(chars_to_replace, string_to_replace_with, str). For example:
>>> import re
>>> re.sub("e|l", "", "Hello people")
"Ho pop"
Note: You can also use the [] to create group of characters to replace in regex.
|
[
{
"code": null,
"e": 1215,
"s": 1062,
"text": "If you want to delete a character at a certain index from the string, you can use string slicing to create a string without that character. For example,"
},
{
"code": null,
"e": 1268,
"s": 1215,
"text": ">>> s = \"Hello World\"\n>>> s[:4] + s[5:]\n\"Hell World\""
},
{
"code": null,
"e": 1384,
"s": 1268,
"text": "But if you want to remove all occurances of a character or a list of characters, you can use the following methods:"
},
{
"code": null,
"e": 1572,
"s": 1384,
"text": "The string class has a method replace that can be used to replace substrings in a string. We can use this method to replace characters we want to remove with an empty string. For example:"
},
{
"code": null,
"e": 1620,
"s": 1572,
"text": ">>> \"Hello people\".replace(\"e\", \"\")\n\"Hllo popl\""
},
{
"code": null,
"e": 1858,
"s": 1620,
"text": "If you want to remove multiple characters from a string in a single line, it's better to use regular expressions. You can separate multiple characters by \"|\" and use the re.sub(chars_to_replace, string_to_replace_with, str). For example:"
},
{
"code": null,
"e": 1919,
"s": 1858,
"text": ">>> import re\n>>> re.sub(\"e|l\", \"\", \"Hello people\")\n\"Ho pop\""
},
{
"code": null,
"e": 2000,
"s": 1919,
"text": "Note: You can also use the [] to create group of characters to replace in regex."
}
] |
Minimum operations required to make all Array elements divisible by K - GeeksforGeeks
|
13 May, 2021
Given an array a[], integer K and an integer X (which is initially initialized to 0). Our task is to find the minimum number of moves required to update the array such that each of its elements is divisible by K by performing the following operations:
Choose one index i from 1 to N and increase ai by X and then increase X by 1. This operation cannot be applied more than once to each element of the array
Only increase the value of X by 1.
Examples:
Input: K = 3, a = [1, 2, 2, 18] Output: 5 Explanation: Initially X = 0 hence update X to 1. For X = 1 add X to the second element of array to make the array [1, 3, 2, 18] and increase X by 1. For X = 2 add X to the first element of array [3, 3, 2, 18] and increase X by 1. For X = 3 just increase X by 1. For X = 4 add X to the third element of array to make the array [3, 3, 6, 18] and increase X by 1. At last, the array becomes [3, 3, 6, 18] where all the elements are divisible by K = 3.Input: K = 5, a[] = [15, 25, 5, 10, 20, 1005, 70, 80, 90, 100] Output: 0 Explanation: Here all elements are already divisible by 5.
Approach: The main idea is to find the maximum value of X that is needed to update the elements of the array to make it divisible by K.
To do this we need to find the maximum value of (K β (ai mod K)) to add to the array elements to make it divisible by K.
However, there can be equal elements so keep track of the number of such elements, using map data structures.
When found another such element in the array then update the answer with (K β (ai mod K)) + (K * number of Equal Elements) because with every move we increase X by 1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find the// Minimum number of moves required to// update the array such that each of// its element is divisible by K #include <bits/stdc++.h>using namespace std; // Function to find the// Minimum number of moves required to// update the array such that each of// its element is divisible by Kvoid compute(int a[], int N, int K){ // Initialize Map data structure map<long, long> eqVal; long maxX = 0; // Iterate for all the elements // of the array for (int i = 0; i < N; i++) { // Calculate the // value to be added long val = a[i] % K; val = (val == 0 ? 0 : K - val); // Check if the value equals // to 0 then simply continue if (val == 0) continue; // Check if the value to be // added is present in the map if (eqVal.find(val) != eqVal.end()) { long numVal = eqVal[val]; // Update the answer maxX = max(maxX, val + (K * numVal)); eqVal[val]++; } else { eqVal[val]++; maxX = max(maxX, val); } } // Print the required result // We need to add 1 to maxX // because we cant ignore the // first move where initially X=0 // and we need to increase it by 1 // to make some changes in array cout << (maxX == 0 ? 0 : maxX + 1) << endl;} // Driver codeint main(){ int K = 3; int a[] = { 1, 2, 2, 18 }; int N = sizeof(a) / sizeof(a[0]); compute(a, N, K); return 0;}
// Java implementation to find the// minimum number of moves required to// update the array such that each of// its element is divisible by Kimport java.util.*; class GFG{ // Function to find the minimum// number of moves required to// update the array such that each of// its element is divisible by Kstatic void compute(int a[], int N, int K){ // Initialize Map data structure Map<Long, Long> eqVal = new HashMap<Long, Long>(); long maxX = 0; // Iterate for all the elements // of the array for(int i = 0; i < N; i++) { // Calculate the // value to be added long val = a[i] % K; val = (val == 0 ? 0 : K - val); // Check if the value equals // to 0 then simply continue if (val == 0) continue; // Check if the value to be // added is present in the map if (eqVal.containsKey(val)) { long numVal = eqVal.get(val); // Update the answer maxX = Math.max(maxX, val + (K * numVal)); eqVal.put(val, eqVal.getOrDefault(val, 0l) + 1l); } else { eqVal.put(val, 1l); maxX = Math.max(maxX, val); } } // Print the required result // We need to add 1 to maxX // because we cant ignore the // first move where initially X=0 // and we need to increase it by 1 // to make some changes in array System.out.println(maxX == 0 ? 0 : maxX + 1);} // Driver codepublic static void main(String[] args){ int K = 3; int a[] = { 1, 2, 2, 18 }; int N = a.length; compute(a, N, K);}} // This code is contributed by offbeat
# Python3 implementation to find the# Minimum number of moves required to# update the array such that each of# its element is divisible by Kfrom collections import defaultdict # Function to find the Minimum number# of moves required to update the# array such that each of its# element is divisible by Kdef compute(a, N, K): # Initialize Map data structure eqVal = defaultdict(int) maxX = 0 # Iterate for all the elements # of the array for i in range(N): # Calculate the # value to be added val = a[i] % K if (val != 0): val = K - val # Check if the value equals # to 0 then simply continue if (val == 0): continue # Check if the value to be # added is present in the map if (val in eqVal): numVal = eqVal[val] # Update the answer maxX = max(maxX, val + (K * numVal)) eqVal[val] += 1 else: eqVal[val] += 1 maxX = max(maxX, val) # Print the required result # We need to add 1 to maxX # because we cant ignore the # first move where initially X=0 # and we need to increase it by 1 # to make some changes in array if maxX == 0: print(0) else: print(maxX + 1) # Driver codeif __name__ == "__main__": K = 3 a = [ 1, 2, 2, 18 ] N = len(a) compute(a, N, K) # This code is contributed by chitranayal
// C# implementation to find the// minimum number of moves required to// update the array such that each of// its element is divisible by Kusing System;using System.Collections.Generic; class GFG{ // Function to find the minimum// number of moves required to// update the array such that each of// its element is divisible by Kstatic void compute(int []a, int N, int K){ // Initialize Map data structure Dictionary<long, long> eqVal = new Dictionary<long, long>(); long maxX = 0; // Iterate for all the elements // of the array for(int i = 0; i < N; i++) { // Calculate the // value to be added long val = a[i] % K; val = (val == 0 ? 0 : K - val); // Check if the value equals // to 0 then simply continue if (val == 0) continue; // Check if the value to be // added is present in the map if (eqVal.ContainsKey(val)) { long numVal = eqVal[val]; // Update the answer maxX = Math.Max(maxX, val + (K * numVal)); eqVal[val] = 1 + eqVal.GetValueOrDefault(val, 0); } else { eqVal.Add(val, 1); maxX = Math.Max(maxX, val); } } // Print the required result // We need to add 1 to maxX // because we cant ignore the // first move where initially X=0 // and we need to increase it by 1 // to make some changes in array Console.Write(maxX == 0 ? 0 : maxX + 1);} // Driver codepublic static void Main(string[] args){ int K = 3; int []a = { 1, 2, 2, 18 }; int N = a.Length; compute(a, N, K);}} // This code is contributed by rutvik_56
<script> // Javascript implementation to find the// minimum number of moves required to// update the array such that each of// its element is divisible by K // Function to find the minimum// number of moves required to// update the array such that each of// its element is divisible by K function compute(a,N,K) { // Initialize Map data structure let eqVal = new Map(); let maxX = 0; // Iterate for all the elements // of the array for(let i = 0; i < N; i++) { // Calculate the // value to be added let val = a[i] % K; val = (val == 0 ? 0 : K - val); // Check if the value equals // to 0 then simply continue if (val == 0) continue; // Check if the value to be // added is present in the map if (eqVal.has(val)) { let numVal = eqVal.get(val); // Update the answer maxX = Math.max(maxX, val + (K * numVal)); eqVal.set(val,eqVal.get(val) + 1); } else { eqVal.set(val, 1); maxX = Math.max(maxX, val); } } // Print the required result // We need to add 1 to maxX // because we cant ignore the // first move where initially X=0 // and we need to increase it by 1 // to make some changes in array document.write(maxX == 0 ? 0 : maxX + 1); } // Driver code let K = 3; let a=[1, 2, 2, 18]; let N = a.length; compute(a, N, K); // This code is contributed by avanitrachhadiya2155 </script>
5
Time Complexity: O(N)
offbeat
ukasp
rutvik_56
avanitrachhadiya2155
divisibility
optimization-technique
Algorithms
Arrays
Competitive Programming
Mathematical
Arrays
Mathematical
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Recursive Practice Problems with Solutions
Playfair Cipher with Examples
Arrays in Java
Stack Data Structure (Introduction and Program)
Arrays in C/C++
Multidimensional Arrays in Java
Program for array rotation
|
[
{
"code": null,
"e": 24405,
"s": 24377,
"text": "\n13 May, 2021"
},
{
"code": null,
"e": 24657,
"s": 24405,
"text": "Given an array a[], integer K and an integer X (which is initially initialized to 0). Our task is to find the minimum number of moves required to update the array such that each of its elements is divisible by K by performing the following operations:"
},
{
"code": null,
"e": 24812,
"s": 24657,
"text": "Choose one index i from 1 to N and increase ai by X and then increase X by 1. This operation cannot be applied more than once to each element of the array"
},
{
"code": null,
"e": 24847,
"s": 24812,
"text": "Only increase the value of X by 1."
},
{
"code": null,
"e": 24857,
"s": 24847,
"text": "Examples:"
},
{
"code": null,
"e": 25480,
"s": 24857,
"text": "Input: K = 3, a = [1, 2, 2, 18] Output: 5 Explanation: Initially X = 0 hence update X to 1. For X = 1 add X to the second element of array to make the array [1, 3, 2, 18] and increase X by 1. For X = 2 add X to the first element of array [3, 3, 2, 18] and increase X by 1. For X = 3 just increase X by 1. For X = 4 add X to the third element of array to make the array [3, 3, 6, 18] and increase X by 1. At last, the array becomes [3, 3, 6, 18] where all the elements are divisible by K = 3.Input: K = 5, a[] = [15, 25, 5, 10, 20, 1005, 70, 80, 90, 100] Output: 0 Explanation: Here all elements are already divisible by 5."
},
{
"code": null,
"e": 25616,
"s": 25480,
"text": "Approach: The main idea is to find the maximum value of X that is needed to update the elements of the array to make it divisible by K."
},
{
"code": null,
"e": 25737,
"s": 25616,
"text": "To do this we need to find the maximum value of (K β (ai mod K)) to add to the array elements to make it divisible by K."
},
{
"code": null,
"e": 25847,
"s": 25737,
"text": "However, there can be equal elements so keep track of the number of such elements, using map data structures."
},
{
"code": null,
"e": 26014,
"s": 25847,
"text": "When found another such element in the array then update the answer with (K β (ai mod K)) + (K * number of Equal Elements) because with every move we increase X by 1."
},
{
"code": null,
"e": 26065,
"s": 26014,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26069,
"s": 26065,
"text": "C++"
},
{
"code": null,
"e": 26074,
"s": 26069,
"text": "Java"
},
{
"code": null,
"e": 26082,
"s": 26074,
"text": "Python3"
},
{
"code": null,
"e": 26085,
"s": 26082,
"text": "C#"
},
{
"code": null,
"e": 26096,
"s": 26085,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the// Minimum number of moves required to// update the array such that each of// its element is divisible by K #include <bits/stdc++.h>using namespace std; // Function to find the// Minimum number of moves required to// update the array such that each of// its element is divisible by Kvoid compute(int a[], int N, int K){ // Initialize Map data structure map<long, long> eqVal; long maxX = 0; // Iterate for all the elements // of the array for (int i = 0; i < N; i++) { // Calculate the // value to be added long val = a[i] % K; val = (val == 0 ? 0 : K - val); // Check if the value equals // to 0 then simply continue if (val == 0) continue; // Check if the value to be // added is present in the map if (eqVal.find(val) != eqVal.end()) { long numVal = eqVal[val]; // Update the answer maxX = max(maxX, val + (K * numVal)); eqVal[val]++; } else { eqVal[val]++; maxX = max(maxX, val); } } // Print the required result // We need to add 1 to maxX // because we cant ignore the // first move where initially X=0 // and we need to increase it by 1 // to make some changes in array cout << (maxX == 0 ? 0 : maxX + 1) << endl;} // Driver codeint main(){ int K = 3; int a[] = { 1, 2, 2, 18 }; int N = sizeof(a) / sizeof(a[0]); compute(a, N, K); return 0;}",
"e": 27639,
"s": 26096,
"text": null
},
{
"code": "// Java implementation to find the// minimum number of moves required to// update the array such that each of// its element is divisible by Kimport java.util.*; class GFG{ // Function to find the minimum// number of moves required to// update the array such that each of// its element is divisible by Kstatic void compute(int a[], int N, int K){ // Initialize Map data structure Map<Long, Long> eqVal = new HashMap<Long, Long>(); long maxX = 0; // Iterate for all the elements // of the array for(int i = 0; i < N; i++) { // Calculate the // value to be added long val = a[i] % K; val = (val == 0 ? 0 : K - val); // Check if the value equals // to 0 then simply continue if (val == 0) continue; // Check if the value to be // added is present in the map if (eqVal.containsKey(val)) { long numVal = eqVal.get(val); // Update the answer maxX = Math.max(maxX, val + (K * numVal)); eqVal.put(val, eqVal.getOrDefault(val, 0l) + 1l); } else { eqVal.put(val, 1l); maxX = Math.max(maxX, val); } } // Print the required result // We need to add 1 to maxX // because we cant ignore the // first move where initially X=0 // and we need to increase it by 1 // to make some changes in array System.out.println(maxX == 0 ? 0 : maxX + 1);} // Driver codepublic static void main(String[] args){ int K = 3; int a[] = { 1, 2, 2, 18 }; int N = a.length; compute(a, N, K);}} // This code is contributed by offbeat",
"e": 29391,
"s": 27639,
"text": null
},
{
"code": "# Python3 implementation to find the# Minimum number of moves required to# update the array such that each of# its element is divisible by Kfrom collections import defaultdict # Function to find the Minimum number# of moves required to update the# array such that each of its# element is divisible by Kdef compute(a, N, K): # Initialize Map data structure eqVal = defaultdict(int) maxX = 0 # Iterate for all the elements # of the array for i in range(N): # Calculate the # value to be added val = a[i] % K if (val != 0): val = K - val # Check if the value equals # to 0 then simply continue if (val == 0): continue # Check if the value to be # added is present in the map if (val in eqVal): numVal = eqVal[val] # Update the answer maxX = max(maxX, val + (K * numVal)) eqVal[val] += 1 else: eqVal[val] += 1 maxX = max(maxX, val) # Print the required result # We need to add 1 to maxX # because we cant ignore the # first move where initially X=0 # and we need to increase it by 1 # to make some changes in array if maxX == 0: print(0) else: print(maxX + 1) # Driver codeif __name__ == \"__main__\": K = 3 a = [ 1, 2, 2, 18 ] N = len(a) compute(a, N, K) # This code is contributed by chitranayal",
"e": 30867,
"s": 29391,
"text": null
},
{
"code": "// C# implementation to find the// minimum number of moves required to// update the array such that each of// its element is divisible by Kusing System;using System.Collections.Generic; class GFG{ // Function to find the minimum// number of moves required to// update the array such that each of// its element is divisible by Kstatic void compute(int []a, int N, int K){ // Initialize Map data structure Dictionary<long, long> eqVal = new Dictionary<long, long>(); long maxX = 0; // Iterate for all the elements // of the array for(int i = 0; i < N; i++) { // Calculate the // value to be added long val = a[i] % K; val = (val == 0 ? 0 : K - val); // Check if the value equals // to 0 then simply continue if (val == 0) continue; // Check if the value to be // added is present in the map if (eqVal.ContainsKey(val)) { long numVal = eqVal[val]; // Update the answer maxX = Math.Max(maxX, val + (K * numVal)); eqVal[val] = 1 + eqVal.GetValueOrDefault(val, 0); } else { eqVal.Add(val, 1); maxX = Math.Max(maxX, val); } } // Print the required result // We need to add 1 to maxX // because we cant ignore the // first move where initially X=0 // and we need to increase it by 1 // to make some changes in array Console.Write(maxX == 0 ? 0 : maxX + 1);} // Driver codepublic static void Main(string[] args){ int K = 3; int []a = { 1, 2, 2, 18 }; int N = a.Length; compute(a, N, K);}} // This code is contributed by rutvik_56",
"e": 32685,
"s": 30867,
"text": null
},
{
"code": "<script> // Javascript implementation to find the// minimum number of moves required to// update the array such that each of// its element is divisible by K // Function to find the minimum// number of moves required to// update the array such that each of// its element is divisible by K function compute(a,N,K) { // Initialize Map data structure let eqVal = new Map(); let maxX = 0; // Iterate for all the elements // of the array for(let i = 0; i < N; i++) { // Calculate the // value to be added let val = a[i] % K; val = (val == 0 ? 0 : K - val); // Check if the value equals // to 0 then simply continue if (val == 0) continue; // Check if the value to be // added is present in the map if (eqVal.has(val)) { let numVal = eqVal.get(val); // Update the answer maxX = Math.max(maxX, val + (K * numVal)); eqVal.set(val,eqVal.get(val) + 1); } else { eqVal.set(val, 1); maxX = Math.max(maxX, val); } } // Print the required result // We need to add 1 to maxX // because we cant ignore the // first move where initially X=0 // and we need to increase it by 1 // to make some changes in array document.write(maxX == 0 ? 0 : maxX + 1); } // Driver code let K = 3; let a=[1, 2, 2, 18]; let N = a.length; compute(a, N, K); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 34318,
"s": 32685,
"text": null
},
{
"code": null,
"e": 34320,
"s": 34318,
"text": "5"
},
{
"code": null,
"e": 34343,
"s": 34320,
"text": "Time Complexity: O(N) "
},
{
"code": null,
"e": 34351,
"s": 34343,
"text": "offbeat"
},
{
"code": null,
"e": 34357,
"s": 34351,
"text": "ukasp"
},
{
"code": null,
"e": 34367,
"s": 34357,
"text": "rutvik_56"
},
{
"code": null,
"e": 34388,
"s": 34367,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 34401,
"s": 34388,
"text": "divisibility"
},
{
"code": null,
"e": 34424,
"s": 34401,
"text": "optimization-technique"
},
{
"code": null,
"e": 34435,
"s": 34424,
"text": "Algorithms"
},
{
"code": null,
"e": 34442,
"s": 34435,
"text": "Arrays"
},
{
"code": null,
"e": 34466,
"s": 34442,
"text": "Competitive Programming"
},
{
"code": null,
"e": 34479,
"s": 34466,
"text": "Mathematical"
},
{
"code": null,
"e": 34486,
"s": 34479,
"text": "Arrays"
},
{
"code": null,
"e": 34499,
"s": 34486,
"text": "Mathematical"
},
{
"code": null,
"e": 34510,
"s": 34499,
"text": "Algorithms"
},
{
"code": null,
"e": 34608,
"s": 34510,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34617,
"s": 34608,
"text": "Comments"
},
{
"code": null,
"e": 34630,
"s": 34617,
"text": "Old Comments"
},
{
"code": null,
"e": 34679,
"s": 34630,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 34704,
"s": 34679,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 34731,
"s": 34704,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 34774,
"s": 34731,
"text": "Recursive Practice Problems with Solutions"
},
{
"code": null,
"e": 34804,
"s": 34774,
"text": "Playfair Cipher with Examples"
},
{
"code": null,
"e": 34819,
"s": 34804,
"text": "Arrays in Java"
},
{
"code": null,
"e": 34867,
"s": 34819,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 34883,
"s": 34867,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 34915,
"s": 34883,
"text": "Multidimensional Arrays in Java"
}
] |
C Program for factorial of a number - GeeksforGeeks
|
07 Aug, 2019
Factorial of a non-negative integer is multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720.
Recursive:
// C program to find factorial of given number #include <stdio.h> // Function to find factorial of given numberunsigned int factorial(unsigned int n){ if (n == 0) return 1; return n * factorial(n - 1);} // Driver codeint main(){ int num = 5; printf("Factorial of %d is %d", num, factorial(num)); return 0;}
Factorial of 5 is 120
Iterative :
#include <stdio.h> // Function to find factorial of given numberunsigned int factorial(unsigned int n){ int res = 1, i; for (i = 2; i <= n; i++) res *= i; return res;} // Driver codeint main(){ int num = 5; printf("Factorial of %d is %d", num, factorial(num)); return 0;}
Factorial of 5 is 120
One line Solution (Using Ternary operator):
// C++ program to find factorial of given number #include <iostream> int factorial(int n){ // single line to find factorial return (n == 1 || n == 0) ? 1 : n * factorial(n - 1);} // Driver codeint main(){ int num = 5; printf("Factorial of %d is %d", num, factorial(num)); return 0;}// This code is contributed by Rithika palaniswamy.
Factorial of 5 is 120
Using tgamma() method:
Example:
Input: n = 4
Output: 24
Syntax:
tgamma(n+1)=n!
It works upto 20! because c can't store large value
Implementation: use math.h header file for this
#include <math.h>#include <stdio.h> int main(){ // use long long int // for larger values of n int n = 4; // tgamma(n+1)=n! n = tgamma(n + 1); printf("%d", n); return 0; // This code is contributed by Soumyadip Basak}
24
The above solutions cause overflow for large numbers. Please refer factorial of large number for a solution that works for large numbers.
Please refer complete article on Program for factorial of a number for more details!
basaksoumyadip7
factorial
C Programs
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C program to sort an array in ascending order
Program to find Prime Numbers Between given Interval
How to Append a Character to a String in C
Producer Consumer Problem in C
Program to calculate First and Follow sets of given grammar
time() function in C
|
[
{
"code": null,
"e": 24458,
"s": 24430,
"text": "\n07 Aug, 2019"
},
{
"code": null,
"e": 24612,
"s": 24458,
"text": "Factorial of a non-negative integer is multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720."
},
{
"code": null,
"e": 24623,
"s": 24612,
"text": "Recursive:"
},
{
"code": "// C program to find factorial of given number #include <stdio.h> // Function to find factorial of given numberunsigned int factorial(unsigned int n){ if (n == 0) return 1; return n * factorial(n - 1);} // Driver codeint main(){ int num = 5; printf(\"Factorial of %d is %d\", num, factorial(num)); return 0;}",
"e": 24965,
"s": 24623,
"text": null
},
{
"code": null,
"e": 24988,
"s": 24965,
"text": "Factorial of 5 is 120\n"
},
{
"code": null,
"e": 25000,
"s": 24988,
"text": "Iterative :"
},
{
"code": "#include <stdio.h> // Function to find factorial of given numberunsigned int factorial(unsigned int n){ int res = 1, i; for (i = 2; i <= n; i++) res *= i; return res;} // Driver codeint main(){ int num = 5; printf(\"Factorial of %d is %d\", num, factorial(num)); return 0;}",
"e": 25309,
"s": 25000,
"text": null
},
{
"code": null,
"e": 25332,
"s": 25309,
"text": "Factorial of 5 is 120\n"
},
{
"code": null,
"e": 25376,
"s": 25332,
"text": "One line Solution (Using Ternary operator):"
},
{
"code": "// C++ program to find factorial of given number #include <iostream> int factorial(int n){ // single line to find factorial return (n == 1 || n == 0) ? 1 : n * factorial(n - 1);} // Driver codeint main(){ int num = 5; printf(\"Factorial of %d is %d\", num, factorial(num)); return 0;}// This code is contributed by Rithika palaniswamy.",
"e": 25767,
"s": 25376,
"text": null
},
{
"code": null,
"e": 25790,
"s": 25767,
"text": "Factorial of 5 is 120\n"
},
{
"code": null,
"e": 25813,
"s": 25790,
"text": "Using tgamma() method:"
},
{
"code": null,
"e": 25822,
"s": 25813,
"text": "Example:"
},
{
"code": null,
"e": 25847,
"s": 25822,
"text": "Input: n = 4\nOutput: 24\n"
},
{
"code": null,
"e": 25855,
"s": 25847,
"text": "Syntax:"
},
{
"code": null,
"e": 25923,
"s": 25855,
"text": "tgamma(n+1)=n!\nIt works upto 20! because c can't store large value\n"
},
{
"code": null,
"e": 25971,
"s": 25923,
"text": "Implementation: use math.h header file for this"
},
{
"code": "#include <math.h>#include <stdio.h> int main(){ // use long long int // for larger values of n int n = 4; // tgamma(n+1)=n! n = tgamma(n + 1); printf(\"%d\", n); return 0; // This code is contributed by Soumyadip Basak}",
"e": 26220,
"s": 25971,
"text": null
},
{
"code": null,
"e": 26224,
"s": 26220,
"text": "24\n"
},
{
"code": null,
"e": 26362,
"s": 26224,
"text": "The above solutions cause overflow for large numbers. Please refer factorial of large number for a solution that works for large numbers."
},
{
"code": null,
"e": 26447,
"s": 26362,
"text": "Please refer complete article on Program for factorial of a number for more details!"
},
{
"code": null,
"e": 26463,
"s": 26447,
"text": "basaksoumyadip7"
},
{
"code": null,
"e": 26473,
"s": 26463,
"text": "factorial"
},
{
"code": null,
"e": 26484,
"s": 26473,
"text": "C Programs"
},
{
"code": null,
"e": 26494,
"s": 26484,
"text": "factorial"
},
{
"code": null,
"e": 26592,
"s": 26494,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26601,
"s": 26592,
"text": "Comments"
},
{
"code": null,
"e": 26614,
"s": 26601,
"text": "Old Comments"
},
{
"code": null,
"e": 26655,
"s": 26614,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 26690,
"s": 26655,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 26734,
"s": 26690,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 26793,
"s": 26734,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 26839,
"s": 26793,
"text": "C program to sort an array in ascending order"
},
{
"code": null,
"e": 26892,
"s": 26839,
"text": "Program to find Prime Numbers Between given Interval"
},
{
"code": null,
"e": 26935,
"s": 26892,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 26966,
"s": 26935,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 27026,
"s": 26966,
"text": "Program to calculate First and Follow sets of given grammar"
}
] |
C++ String Library - replace
|
It replaces the portion of the string that begins at character pos and spans len characters.
Following is the declaration for std::string::replace.
string& replace (size_t pos, size_t len, const string& str,
size_t subpos, size_t sublen);
string& replace (size_t pos,size_t len,const string& str,
size_t subpos, size_t sublen);
string& replace (size_t pos,size_t len,const string& str,
size_t subpos, size_t sublen = npos);
pos β It is an insertion point.
pos β It is an insertion point.
str β It is a string object.
str β It is a string object.
len β It contains information about number of characters to erase.
len β It contains information about number of characters to erase.
It returns *this.
if an exception is thrown, there are no changes in the string.
In below example for std::string::replace.
#include <iostream>
#include <string>
int main () {
std::string base="this is a test string.";
std::string str2="n example";
std::string str3="sample phrase";
std::string str4="useful.";
std::string str=base;
str.replace(9,5,str2);
str.replace(19,6,str3,7,6);
str.replace(8,10,"just a");
str.replace(8,6,"a shorty",7);
str.replace(22,1,3,'!');
str.replace(str.begin(),str.end()-3,str3);
str.replace(str.begin(),str.begin()+6,"replace");
str.replace(str.begin()+8,str.begin()+14,"is coolness",7);
str.replace(str.begin()+12,str.end()-4,4,'o');
str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());
std::cout << str << '\n';
return 0;
}
The sample output should be like this β
replace is useful.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2696,
"s": 2603,
"text": "It replaces the portion of the string that begins at character pos and spans len characters."
},
{
"code": null,
"e": 2751,
"s": 2696,
"text": "Following is the declaration for std::string::replace."
},
{
"code": null,
"e": 2861,
"s": 2751,
"text": "string& replace (size_t pos, size_t len, const string& str,\n size_t subpos, size_t sublen);"
},
{
"code": null,
"e": 2967,
"s": 2861,
"text": "string& replace (size_t pos,size_t len,const string& str,\n size_t subpos, size_t sublen);"
},
{
"code": null,
"e": 3080,
"s": 2967,
"text": "string& replace (size_t pos,size_t len,const string& str,\n size_t subpos, size_t sublen = npos);"
},
{
"code": null,
"e": 3112,
"s": 3080,
"text": "pos β It is an insertion point."
},
{
"code": null,
"e": 3144,
"s": 3112,
"text": "pos β It is an insertion point."
},
{
"code": null,
"e": 3173,
"s": 3144,
"text": "str β It is a string object."
},
{
"code": null,
"e": 3202,
"s": 3173,
"text": "str β It is a string object."
},
{
"code": null,
"e": 3269,
"s": 3202,
"text": "len β It contains information about number of characters to erase."
},
{
"code": null,
"e": 3336,
"s": 3269,
"text": "len β It contains information about number of characters to erase."
},
{
"code": null,
"e": 3354,
"s": 3336,
"text": "It returns *this."
},
{
"code": null,
"e": 3417,
"s": 3354,
"text": "if an exception is thrown, there are no changes in the string."
},
{
"code": null,
"e": 3460,
"s": 3417,
"text": "In below example for std::string::replace."
},
{
"code": null,
"e": 4158,
"s": 3460,
"text": "#include <iostream>\n#include <string>\n\nint main () {\n std::string base=\"this is a test string.\";\n std::string str2=\"n example\";\n std::string str3=\"sample phrase\";\n std::string str4=\"useful.\";\n\n std::string str=base;\n str.replace(9,5,str2);\n str.replace(19,6,str3,7,6);\n str.replace(8,10,\"just a\");\n str.replace(8,6,\"a shorty\",7);\n str.replace(22,1,3,'!');\n\n str.replace(str.begin(),str.end()-3,str3);\n str.replace(str.begin(),str.begin()+6,\"replace\");\n str.replace(str.begin()+8,str.begin()+14,\"is coolness\",7);\n str.replace(str.begin()+12,str.end()-4,4,'o');\n str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());\n std::cout << str << '\\n';\n return 0;\n}"
},
{
"code": null,
"e": 4198,
"s": 4158,
"text": "The sample output should be like this β"
},
{
"code": null,
"e": 4218,
"s": 4198,
"text": "replace is useful.\n"
},
{
"code": null,
"e": 4225,
"s": 4218,
"text": " Print"
},
{
"code": null,
"e": 4236,
"s": 4225,
"text": " Add Notes"
}
] |
8085 program to multiply two 8 bit numbers using logical instructions - GeeksforGeeks
|
22 May, 2018
Prerequisite β Logical instructions in 8085 microprocessorProblem β Write a assembly language program multiply two 8 bit numbers and store the result at memory address 3050 in 8085 microprocessor.
Example β
The value of accumulator(A) after using RLC instruction is:
A = 2n*A
Where n = number of times RLC instruction is used.
Assumptions βAssume that the first number is stored at register B, and second number is stored at register C. And the result must not have any carry.
Algorithm β
Assign the value 05 to register BAssign the value 04 to register CMove the content of B in ARotate accumulator left without carryRotate accumulator left without carryStore the content of accumulator at memory address 3050Halt of the program
Assign the value 05 to register B
Assign the value 04 to register C
Move the content of B in A
Rotate accumulator left without carry
Rotate accumulator left without carry
Store the content of accumulator at memory address 3050
Halt of the program
Program β
Explanation β
MVI B 05: assign the value 05 to B register.MVI C 04: assign the value 04 to C register.MOV A, B: move the content of register B to register A.RLC: rotate the content of accumulator left without carry.RLC: rotate the content of accumulator left without carry.STA 3050: store the content of register A at memory location 3050HLT: stops the execution of the program.
MVI B 05: assign the value 05 to B register.
MVI C 04: assign the value 04 to C register.
MOV A, B: move the content of register B to register A.
RLC: rotate the content of accumulator left without carry.
RLC: rotate the content of accumulator left without carry.
STA 3050: store the content of register A at memory location 3050
HLT: stops the execution of the program.
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Logical and Physical Address in Operating System
Memory Hierarchy Design and its Characteristics
Architecture of 8085 microprocessor
Pin diagram of 8086 microprocessor
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Architecture of 8086
Computer Organization | RISC and CISC
Memory mapped I/O and Isolated I/O
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Programmable peripheral interface 8255
|
[
{
"code": null,
"e": 25050,
"s": 25022,
"text": "\n22 May, 2018"
},
{
"code": null,
"e": 25247,
"s": 25050,
"text": "Prerequisite β Logical instructions in 8085 microprocessorProblem β Write a assembly language program multiply two 8 bit numbers and store the result at memory address 3050 in 8085 microprocessor."
},
{
"code": null,
"e": 25257,
"s": 25247,
"text": "Example β"
},
{
"code": null,
"e": 25317,
"s": 25257,
"text": "The value of accumulator(A) after using RLC instruction is:"
},
{
"code": null,
"e": 25326,
"s": 25317,
"text": "A = 2n*A"
},
{
"code": null,
"e": 25377,
"s": 25326,
"text": "Where n = number of times RLC instruction is used."
},
{
"code": null,
"e": 25527,
"s": 25377,
"text": "Assumptions βAssume that the first number is stored at register B, and second number is stored at register C. And the result must not have any carry."
},
{
"code": null,
"e": 25539,
"s": 25527,
"text": "Algorithm β"
},
{
"code": null,
"e": 25780,
"s": 25539,
"text": "Assign the value 05 to register BAssign the value 04 to register CMove the content of B in ARotate accumulator left without carryRotate accumulator left without carryStore the content of accumulator at memory address 3050Halt of the program"
},
{
"code": null,
"e": 25814,
"s": 25780,
"text": "Assign the value 05 to register B"
},
{
"code": null,
"e": 25848,
"s": 25814,
"text": "Assign the value 04 to register C"
},
{
"code": null,
"e": 25875,
"s": 25848,
"text": "Move the content of B in A"
},
{
"code": null,
"e": 25913,
"s": 25875,
"text": "Rotate accumulator left without carry"
},
{
"code": null,
"e": 25951,
"s": 25913,
"text": "Rotate accumulator left without carry"
},
{
"code": null,
"e": 26007,
"s": 25951,
"text": "Store the content of accumulator at memory address 3050"
},
{
"code": null,
"e": 26027,
"s": 26007,
"text": "Halt of the program"
},
{
"code": null,
"e": 26037,
"s": 26027,
"text": "Program β"
},
{
"code": null,
"e": 26051,
"s": 26037,
"text": "Explanation β"
},
{
"code": null,
"e": 26416,
"s": 26051,
"text": "MVI B 05: assign the value 05 to B register.MVI C 04: assign the value 04 to C register.MOV A, B: move the content of register B to register A.RLC: rotate the content of accumulator left without carry.RLC: rotate the content of accumulator left without carry.STA 3050: store the content of register A at memory location 3050HLT: stops the execution of the program."
},
{
"code": null,
"e": 26461,
"s": 26416,
"text": "MVI B 05: assign the value 05 to B register."
},
{
"code": null,
"e": 26506,
"s": 26461,
"text": "MVI C 04: assign the value 04 to C register."
},
{
"code": null,
"e": 26562,
"s": 26506,
"text": "MOV A, B: move the content of register B to register A."
},
{
"code": null,
"e": 26621,
"s": 26562,
"text": "RLC: rotate the content of accumulator left without carry."
},
{
"code": null,
"e": 26680,
"s": 26621,
"text": "RLC: rotate the content of accumulator left without carry."
},
{
"code": null,
"e": 26746,
"s": 26680,
"text": "STA 3050: store the content of register A at memory location 3050"
},
{
"code": null,
"e": 26787,
"s": 26746,
"text": "HLT: stops the execution of the program."
},
{
"code": null,
"e": 26802,
"s": 26787,
"text": "microprocessor"
},
{
"code": null,
"e": 26821,
"s": 26802,
"text": "system-programming"
},
{
"code": null,
"e": 26858,
"s": 26821,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 26873,
"s": 26858,
"text": "microprocessor"
},
{
"code": null,
"e": 26971,
"s": 26873,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26980,
"s": 26971,
"text": "Comments"
},
{
"code": null,
"e": 26993,
"s": 26980,
"text": "Old Comments"
},
{
"code": null,
"e": 27042,
"s": 26993,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 27090,
"s": 27042,
"text": "Memory Hierarchy Design and its Characteristics"
},
{
"code": null,
"e": 27126,
"s": 27090,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 27161,
"s": 27126,
"text": "Pin diagram of 8086 microprocessor"
},
{
"code": null,
"e": 27256,
"s": 27161,
"text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)"
},
{
"code": null,
"e": 27277,
"s": 27256,
"text": "Architecture of 8086"
},
{
"code": null,
"e": 27315,
"s": 27277,
"text": "Computer Organization | RISC and CISC"
},
{
"code": null,
"e": 27350,
"s": 27315,
"text": "Memory mapped I/O and Isolated I/O"
},
{
"code": null,
"e": 27441,
"s": 27350,
"text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)"
}
] |
[NLP] Basics: Understanding Regular Expressions | by CeΜline Van den Rul | Towards Data Science
|
When I started learning natural language processing, regular expressions truly felt like a foreign language. I struggled to understand the syntax and it would take me hours to write a regular expression that would return the input I was looking for. Naturally, I tried to stay away from them as long as I could.
But the truth is, as a data scientist, youβll have to engage with regular expressions one day or the other. They form part of the basic techniques in natural language processing and learning them will go a long way to making you a more efficient programmer.
So itβs time to sit down and get to it. Think of learning regular expressions like a grammar class: theyβre painful, it will seem incomprehensible at first but once you understand it and learn it, youβll feel so relieved itβs behind you. And I promise you, itβs not that hard in the end.
Note that the programming sotfware I will use in this article is R.
Simply put, a regular expression is βinstructionβ given to a function on what and how to match or replace a set of strings.
Letβs start with some basics in regular expressions, that is some basic syntax you should know.
Brackets [] are used to specify a disjunction of characters. For instance, using the brackets to put w or W allows me to return a capital W or small w.
/[wW]oodchuck/ --> Woodchuck or woodchuck /[abc]/ --> βaβ, βbβ, or βcβ/[1234567890]/ --> any digit
If you add a dash, you specify a range. For instance, putting A-Z in brackets allows R to return all matches of an upper case letter.
/[A-Z]/ β machtes an upper case letter/[a-z]/ β matches a lower case letter/[0β9]/ β matches a single digit
The caret ^ can be used for negation or just to mean ^.
/[ΛA-Z]/ --> not an upper case letter/[ΛSs]/ --> neither βSβ nor βsβ/[Λ\.]/ --> not a period/[eΛ]/ --> either βeβ or βΛβ/aΛb/ --> the pattern βaΛbβ
The question mark ? marks optionality of the previous expression. For instance, putting a ? at the end of the woodchucks returns results for woodchuck (without an s) and woodchucks (with an s).
/woodchucks?/ --> woodchuck or woodchucks/colou?r/ --> color or colour
You can use the period . to specify any character between two expressions. For instance, putting beg.n will return you words such as begin or begun.
/beg.n/ --> Match any character between beg and n (e.g. begin, begun)
The us of * or +allows you to add 1 or more of a previous character.
oo*h! β 0 or more of a previous character (e.g. ooh!, ooooh!)o+h! β 1 or more of a previous character (e.g. ooh!, ooooooh!)baa+ β baa, baaaa, baaaaaa, baaaaaaa
Anchors are used to assert something about the string or the matching process. As such, they are not used in a specific word or character but help with more general queries as you can see in the examples below.
. β any character except a new line\\w β any word character\\W β anything but a word character\\d β any digit character\\D β anything but a digit character\\b β a word boundary\\B β anything but a word boundary\\s β any space character\\S β anything but a space character
POSIX character classes are helpful if you want to match a specific character class, e.g. digits. In other words, it makes one small sequence of characters match a larger set of characters.
[[:alpha:]] β alphabetic characters[[:digit:]] β digits[[:punct:]] β punctuation[[:space:]] β space, tab, newline etc.[[:lower:]] β lowercase alphatic characters[[:upper:]] β upper case alphabetic characters
Now this is where the action starts. When dealing with character strings, it is very likely that youβll have to use the commands strsplit(), grep() and gsub() to activate the input you want R to return to you.
The example below shows a way of using strsplit to split the words within a sentence, in this case all the words within the dashes β ...β.
richard3 <- βnow is the winter of our discontentβstrsplit(richard3, β β) # the second argument specifies the space
grep allows you to βgrabβ the word or set of words you want, depending on the matching pattern you set. For instance, in the code below I ask R to return me the character string that contains the word βbothβ.
grep.ex <- c(βsome like Pythonβ, βsome prefer Rβ, βsome like bothβ)grep(βbothβ, grep.ex) # in numerical formgrep(βbothβ, grep.ex, value=TRUE) #prints the character string itself
gsub allows you to, for instance, replace a word by another one. In this case, I chose to replace Romeo by Superman in the character string below.
r_and_j <- βO Romeo, Romeo, wherefore art thou Romeo?βgsub(βRomeoβ, βSupermanβ, r_and_j, ignore.case = FALSE)
Letβs start applying these commands to regular expressions. Iβll show you a couple of examples below.
dollar <- c(βI paid $15 for this book.β, βthey received $50,000 in grant moneyβ, βtwo dollarsβ)
Note that it the example above you have three different sentences, two of them use the $ sign and one of them uses the word βdollarsβ. Using only $ to match your pattern will yield to all three sentences being returned. However, if you add the \\ before the $ you can specify you only want the sentences using the $ sign.
grep(β$β, dollar) grep(β\\$β, dollar)
Here are a few other examples below of how to use grep matching your regular expressions on the words βashesβ, βsharkβ, βbashβ:
# matches all three vector elementsgrep(βshβ, c(βashesβ, βsharkβ, βbashβ), value=TRUE) # matches only βsharkβgrep(β^shβ, c(βashesβ, βsharkβ, βbashβ), value=TRUE) # matches only βbashβgrep(βsh$β, c(βashesβ, βsharkβ, βbashβ), value=TRUE)
On the words βgaffeβ, βchafeβ and βchalkβ:
quant.ex <- c(βgaffeβ, βchafeβ, βchalkβ, βencyclopaediaβ, βencyclopediaβ)# Searching for one or more occurences of f and we want to see the value not only the index (thatβs why we put value = TRUE)grep(βf+β, quant.ex, value=TRUE) # one or two βfβgrep(βf{1,2}β, quant.ex, value=TRUE) # at least one βfβgrep(βf{1,}β, quant.ex, value=TRUE)
In the examples below, you can play around with gsub to replace words in your sentence with anything you want.
ex.sentence <- βAct 3, scene 1. To be, or not to be, that is the Question:β
If you remember the regular expressions you learned in the first part of this article, you should be able to guess what kind of input R will return. Otherwise, Iβve added it to the code below for you to better understand all the different ways to use regular expressions to return what you want.
gsub(β.β, β*β, ex.sentence, ignore.case=TRUE, perl=TRUE)[1] "**********************************************************"gsub(β\\wβ, β*β, ex.sentence, ignore.case=TRUE, perl=TRUE)[1] "*** *, ***** *. ** **, ** *** ** **, **** ** *** ********:"gsub(β\\Wβ, β*β, ex.sentence, ignore.case=TRUE, perl=TRUE)[1] "Act*3**scene*1**To*be**or*not*to*be**that*is*the*Question*"gsub(β\\dβ, β*β, ex.sentence, ignore.case=TRUE, perl=TRUE)[1] "Act *, scene *. To be, or not to be, that is the Question:"gsub(β\\Dβ, β*β, ex.sentence, ignore.case=TRUE, perl=TRUE)[1] "****3********1********************************************"gsub(β\\bβ, β*β, ex.sentence, ignore.case=TRUE, perl=TRUE)[1] "*Act* *3*, *scene* *1*. *To* *be*, *or* *not* *to* *be*, *that* *is* *the* *Question*:"gsub(β\\Bβ, β*β, ex.sentence, ignore.case=TRUE, perl=TRUE)[1] "A*c*t 3,* s*c*e*n*e 1.* T*o b*e,* o*r n*o*t t*o b*e,* t*h*a*t i*s t*h*e Q*u*e*s*t*i*o*n:*"gsub(β\\sβ, β*β, ex.sentence, ignore.case=TRUE, perl=TRUE)[1] "Act*3,*scene*1.*To*be,*or*not*to*be,*that*is*the*Question:"gsub(β\\Sβ, β*β, ex.sentence, ignore.case=TRUE, perl=TRUE)[1] "*** ** ***** ** ** *** ** *** ** *** **** ** *** *********"
Otherwise, try to guess the answer to the last one:
letters.digits <- βa1 b2 c3 d4 e5 f6 g7 h8 i9βgsub(β(\\w)(\\d)β, β\\2\\1β, letters.digits)
Thatβs it! I hope youβve enjoyed this article and that Iβve managed to make regular expression a bit more easier for you to understand.
I regularly write articles about Data Science and Natural Language Processing. Follow me on Twitter or Medium to check out more articles like these or simply to keep updated about the next ones. Thanks for reading!
PS: the answer to the last one is β1a 2b 3c 4d 5e 6f 7g 8h 9iβ. In other words, youβve re-written all the letters and digits using regular expressions. Pretty cool no?
|
[
{
"code": null,
"e": 484,
"s": 172,
"text": "When I started learning natural language processing, regular expressions truly felt like a foreign language. I struggled to understand the syntax and it would take me hours to write a regular expression that would return the input I was looking for. Naturally, I tried to stay away from them as long as I could."
},
{
"code": null,
"e": 742,
"s": 484,
"text": "But the truth is, as a data scientist, youβll have to engage with regular expressions one day or the other. They form part of the basic techniques in natural language processing and learning them will go a long way to making you a more efficient programmer."
},
{
"code": null,
"e": 1030,
"s": 742,
"text": "So itβs time to sit down and get to it. Think of learning regular expressions like a grammar class: theyβre painful, it will seem incomprehensible at first but once you understand it and learn it, youβll feel so relieved itβs behind you. And I promise you, itβs not that hard in the end."
},
{
"code": null,
"e": 1098,
"s": 1030,
"text": "Note that the programming sotfware I will use in this article is R."
},
{
"code": null,
"e": 1222,
"s": 1098,
"text": "Simply put, a regular expression is βinstructionβ given to a function on what and how to match or replace a set of strings."
},
{
"code": null,
"e": 1318,
"s": 1222,
"text": "Letβs start with some basics in regular expressions, that is some basic syntax you should know."
},
{
"code": null,
"e": 1470,
"s": 1318,
"text": "Brackets [] are used to specify a disjunction of characters. For instance, using the brackets to put w or W allows me to return a capital W or small w."
},
{
"code": null,
"e": 1569,
"s": 1470,
"text": "/[wW]oodchuck/ --> Woodchuck or woodchuck /[abc]/ --> βaβ, βbβ, or βcβ/[1234567890]/ --> any digit"
},
{
"code": null,
"e": 1703,
"s": 1569,
"text": "If you add a dash, you specify a range. For instance, putting A-Z in brackets allows R to return all matches of an upper case letter."
},
{
"code": null,
"e": 1811,
"s": 1703,
"text": "/[A-Z]/ β machtes an upper case letter/[a-z]/ β matches a lower case letter/[0β9]/ β matches a single digit"
},
{
"code": null,
"e": 1867,
"s": 1811,
"text": "The caret ^ can be used for negation or just to mean ^."
},
{
"code": null,
"e": 2015,
"s": 1867,
"text": "/[ΛA-Z]/ --> not an upper case letter/[ΛSs]/ --> neither βSβ nor βsβ/[Λ\\.]/ --> not a period/[eΛ]/ --> either βeβ or βΛβ/aΛb/ --> the pattern βaΛbβ"
},
{
"code": null,
"e": 2209,
"s": 2015,
"text": "The question mark ? marks optionality of the previous expression. For instance, putting a ? at the end of the woodchucks returns results for woodchuck (without an s) and woodchucks (with an s)."
},
{
"code": null,
"e": 2280,
"s": 2209,
"text": "/woodchucks?/ --> woodchuck or woodchucks/colou?r/ --> color or colour"
},
{
"code": null,
"e": 2429,
"s": 2280,
"text": "You can use the period . to specify any character between two expressions. For instance, putting beg.n will return you words such as begin or begun."
},
{
"code": null,
"e": 2499,
"s": 2429,
"text": "/beg.n/ --> Match any character between beg and n (e.g. begin, begun)"
},
{
"code": null,
"e": 2568,
"s": 2499,
"text": "The us of * or +allows you to add 1 or more of a previous character."
},
{
"code": null,
"e": 2728,
"s": 2568,
"text": "oo*h! β 0 or more of a previous character (e.g. ooh!, ooooh!)o+h! β 1 or more of a previous character (e.g. ooh!, ooooooh!)baa+ β baa, baaaa, baaaaaa, baaaaaaa"
},
{
"code": null,
"e": 2939,
"s": 2728,
"text": "Anchors are used to assert something about the string or the matching process. As such, they are not used in a specific word or character but help with more general queries as you can see in the examples below."
},
{
"code": null,
"e": 3211,
"s": 2939,
"text": ". β any character except a new line\\\\w β any word character\\\\W β anything but a word character\\\\d β any digit character\\\\D β anything but a digit character\\\\b β a word boundary\\\\B β anything but a word boundary\\\\s β any space character\\\\S β anything but a space character"
},
{
"code": null,
"e": 3401,
"s": 3211,
"text": "POSIX character classes are helpful if you want to match a specific character class, e.g. digits. In other words, it makes one small sequence of characters match a larger set of characters."
},
{
"code": null,
"e": 3609,
"s": 3401,
"text": "[[:alpha:]] β alphabetic characters[[:digit:]] β digits[[:punct:]] β punctuation[[:space:]] β space, tab, newline etc.[[:lower:]] β lowercase alphatic characters[[:upper:]] β upper case alphabetic characters"
},
{
"code": null,
"e": 3819,
"s": 3609,
"text": "Now this is where the action starts. When dealing with character strings, it is very likely that youβll have to use the commands strsplit(), grep() and gsub() to activate the input you want R to return to you."
},
{
"code": null,
"e": 3958,
"s": 3819,
"text": "The example below shows a way of using strsplit to split the words within a sentence, in this case all the words within the dashes β ...β."
},
{
"code": null,
"e": 4073,
"s": 3958,
"text": "richard3 <- βnow is the winter of our discontentβstrsplit(richard3, β β) # the second argument specifies the space"
},
{
"code": null,
"e": 4282,
"s": 4073,
"text": "grep allows you to βgrabβ the word or set of words you want, depending on the matching pattern you set. For instance, in the code below I ask R to return me the character string that contains the word βbothβ."
},
{
"code": null,
"e": 4460,
"s": 4282,
"text": "grep.ex <- c(βsome like Pythonβ, βsome prefer Rβ, βsome like bothβ)grep(βbothβ, grep.ex) # in numerical formgrep(βbothβ, grep.ex, value=TRUE) #prints the character string itself"
},
{
"code": null,
"e": 4607,
"s": 4460,
"text": "gsub allows you to, for instance, replace a word by another one. In this case, I chose to replace Romeo by Superman in the character string below."
},
{
"code": null,
"e": 4717,
"s": 4607,
"text": "r_and_j <- βO Romeo, Romeo, wherefore art thou Romeo?βgsub(βRomeoβ, βSupermanβ, r_and_j, ignore.case = FALSE)"
},
{
"code": null,
"e": 4819,
"s": 4717,
"text": "Letβs start applying these commands to regular expressions. Iβll show you a couple of examples below."
},
{
"code": null,
"e": 4915,
"s": 4819,
"text": "dollar <- c(βI paid $15 for this book.β, βthey received $50,000 in grant moneyβ, βtwo dollarsβ)"
},
{
"code": null,
"e": 5237,
"s": 4915,
"text": "Note that it the example above you have three different sentences, two of them use the $ sign and one of them uses the word βdollarsβ. Using only $ to match your pattern will yield to all three sentences being returned. However, if you add the \\\\ before the $ you can specify you only want the sentences using the $ sign."
},
{
"code": null,
"e": 5275,
"s": 5237,
"text": "grep(β$β, dollar) grep(β\\\\$β, dollar)"
},
{
"code": null,
"e": 5403,
"s": 5275,
"text": "Here are a few other examples below of how to use grep matching your regular expressions on the words βashesβ, βsharkβ, βbashβ:"
},
{
"code": null,
"e": 5640,
"s": 5403,
"text": "# matches all three vector elementsgrep(βshβ, c(βashesβ, βsharkβ, βbashβ), value=TRUE) # matches only βsharkβgrep(β^shβ, c(βashesβ, βsharkβ, βbashβ), value=TRUE) # matches only βbashβgrep(βsh$β, c(βashesβ, βsharkβ, βbashβ), value=TRUE) "
},
{
"code": null,
"e": 5683,
"s": 5640,
"text": "On the words βgaffeβ, βchafeβ and βchalkβ:"
},
{
"code": null,
"e": 6020,
"s": 5683,
"text": "quant.ex <- c(βgaffeβ, βchafeβ, βchalkβ, βencyclopaediaβ, βencyclopediaβ)# Searching for one or more occurences of f and we want to see the value not only the index (thatβs why we put value = TRUE)grep(βf+β, quant.ex, value=TRUE) # one or two βfβgrep(βf{1,2}β, quant.ex, value=TRUE) # at least one βfβgrep(βf{1,}β, quant.ex, value=TRUE)"
},
{
"code": null,
"e": 6131,
"s": 6020,
"text": "In the examples below, you can play around with gsub to replace words in your sentence with anything you want."
},
{
"code": null,
"e": 6207,
"s": 6131,
"text": "ex.sentence <- βAct 3, scene 1. To be, or not to be, that is the Question:β"
},
{
"code": null,
"e": 6503,
"s": 6207,
"text": "If you remember the regular expressions you learned in the first part of this article, you should be able to guess what kind of input R will return. Otherwise, Iβve added it to the code below for you to better understand all the different ways to use regular expressions to return what you want."
},
{
"code": null,
"e": 7659,
"s": 6503,
"text": "gsub(β.β, β*β, ex.sentence, ignore.case=TRUE, perl=TRUE)[1] \"**********************************************************\"gsub(β\\\\wβ, β*β, ex.sentence, ignore.case=TRUE, perl=TRUE)[1] \"*** *, ***** *. ** **, ** *** ** **, **** ** *** ********:\"gsub(β\\\\Wβ, β*β, ex.sentence, ignore.case=TRUE, perl=TRUE)[1] \"Act*3**scene*1**To*be**or*not*to*be**that*is*the*Question*\"gsub(β\\\\dβ, β*β, ex.sentence, ignore.case=TRUE, perl=TRUE)[1] \"Act *, scene *. To be, or not to be, that is the Question:\"gsub(β\\\\Dβ, β*β, ex.sentence, ignore.case=TRUE, perl=TRUE)[1] \"****3********1********************************************\"gsub(β\\\\bβ, β*β, ex.sentence, ignore.case=TRUE, perl=TRUE)[1] \"*Act* *3*, *scene* *1*. *To* *be*, *or* *not* *to* *be*, *that* *is* *the* *Question*:\"gsub(β\\\\Bβ, β*β, ex.sentence, ignore.case=TRUE, perl=TRUE)[1] \"A*c*t 3,* s*c*e*n*e 1.* T*o b*e,* o*r n*o*t t*o b*e,* t*h*a*t i*s t*h*e Q*u*e*s*t*i*o*n:*\"gsub(β\\\\sβ, β*β, ex.sentence, ignore.case=TRUE, perl=TRUE)[1] \"Act*3,*scene*1.*To*be,*or*not*to*be,*that*is*the*Question:\"gsub(β\\\\Sβ, β*β, ex.sentence, ignore.case=TRUE, perl=TRUE)[1] \"*** ** ***** ** ** *** ** *** ** *** **** ** *** *********\""
},
{
"code": null,
"e": 7711,
"s": 7659,
"text": "Otherwise, try to guess the answer to the last one:"
},
{
"code": null,
"e": 7802,
"s": 7711,
"text": "letters.digits <- βa1 b2 c3 d4 e5 f6 g7 h8 i9βgsub(β(\\\\w)(\\\\d)β, β\\\\2\\\\1β, letters.digits)"
},
{
"code": null,
"e": 7938,
"s": 7802,
"text": "Thatβs it! I hope youβve enjoyed this article and that Iβve managed to make regular expression a bit more easier for you to understand."
},
{
"code": null,
"e": 8153,
"s": 7938,
"text": "I regularly write articles about Data Science and Natural Language Processing. Follow me on Twitter or Medium to check out more articles like these or simply to keep updated about the next ones. Thanks for reading!"
}
] |
Creating Dynamic Dashboards with Streamlit | by M Khorasani | Towards Data Science
|
For those of us who have heralded all the bells and whistles brought into existence by Streamlit, from its ease of use to its ability to create powerful visualizations, weβve largely overlooked one really handy feature. Its ability to render dynamic dashboards that can be updated in real time. I gather that most users are using Streamlit to create static dashboards or at most are utilizing the multitude of widgets available to redact dataframes that are then fed back into their visualizations. But I havenβt really seen anyone using one of the greatest inherent capabilities of Streamlit - to create instantaneously and constantly changing visuals. Bring in the mighty βplaceholder.β
Placeholders in Streamlit figuratively allow you to reserve a spot at the table should you choose to use it later at a time of your choice or not at all. As per Streamlitβs own API, the placeholder:
Inserts a container into your app that can be used to hold a single element. This allows you to, for example, remove elements at any point, or replace several elements at once (using a child multi-element container).
Perhaps it was solely designed to enable you to retroactively insert an element or widget just once into your code post an event. Regardless, it gives us this unique vantage to be able to constantly feed a stream of anything into the placeholder, effectively rendering a dashboard that is updating in real time. Without further ado, let me show you how to create a radar chart that is updated continuously.
First thingβs first, lets go ahead and insert the stack of packages weβll be using.
And incase you need to install any of the above packages, please proceed by using βpip installβ in Anaconda prompt.
pip install streamlit
Then we will create two placeholders, one for the radar chart itself and one for a start button that will trigger our script. You can name each placeholder as you wish by equating your instance name to βst.empty()β.
Subsequently, we will create the function for the radar chart using Plotly. Mind you, the input here to the radar chart is a list of randomly changing numbers, however it could literally be anything else. You could interface the list with a stream of data coming in through a serial COM port or via a remote web server.
Notice how in the gist above we are writing the completed figure to the βplaceholderβ we created earlier.
Finally, we wrap it all up by creating two buttons to start and stop the dynamic radar chart (the start button using a placeholder as well). In addition we use a while loop to continuously re-run our radar chart function with a sleep function to delay each iteration by half a second.
And now you have it, our radar chart in a dynamically updated dashboard!
If you want to learn more about data visualization, Python, and deploying a Streamlit web application to the cloud then check out the following (affiliate linked) courses:
|
[
{
"code": null,
"e": 860,
"s": 171,
"text": "For those of us who have heralded all the bells and whistles brought into existence by Streamlit, from its ease of use to its ability to create powerful visualizations, weβve largely overlooked one really handy feature. Its ability to render dynamic dashboards that can be updated in real time. I gather that most users are using Streamlit to create static dashboards or at most are utilizing the multitude of widgets available to redact dataframes that are then fed back into their visualizations. But I havenβt really seen anyone using one of the greatest inherent capabilities of Streamlit - to create instantaneously and constantly changing visuals. Bring in the mighty βplaceholder.β"
},
{
"code": null,
"e": 1059,
"s": 860,
"text": "Placeholders in Streamlit figuratively allow you to reserve a spot at the table should you choose to use it later at a time of your choice or not at all. As per Streamlitβs own API, the placeholder:"
},
{
"code": null,
"e": 1276,
"s": 1059,
"text": "Inserts a container into your app that can be used to hold a single element. This allows you to, for example, remove elements at any point, or replace several elements at once (using a child multi-element container)."
},
{
"code": null,
"e": 1683,
"s": 1276,
"text": "Perhaps it was solely designed to enable you to retroactively insert an element or widget just once into your code post an event. Regardless, it gives us this unique vantage to be able to constantly feed a stream of anything into the placeholder, effectively rendering a dashboard that is updating in real time. Without further ado, let me show you how to create a radar chart that is updated continuously."
},
{
"code": null,
"e": 1767,
"s": 1683,
"text": "First thingβs first, lets go ahead and insert the stack of packages weβll be using."
},
{
"code": null,
"e": 1883,
"s": 1767,
"text": "And incase you need to install any of the above packages, please proceed by using βpip installβ in Anaconda prompt."
},
{
"code": null,
"e": 1905,
"s": 1883,
"text": "pip install streamlit"
},
{
"code": null,
"e": 2121,
"s": 1905,
"text": "Then we will create two placeholders, one for the radar chart itself and one for a start button that will trigger our script. You can name each placeholder as you wish by equating your instance name to βst.empty()β."
},
{
"code": null,
"e": 2441,
"s": 2121,
"text": "Subsequently, we will create the function for the radar chart using Plotly. Mind you, the input here to the radar chart is a list of randomly changing numbers, however it could literally be anything else. You could interface the list with a stream of data coming in through a serial COM port or via a remote web server."
},
{
"code": null,
"e": 2547,
"s": 2441,
"text": "Notice how in the gist above we are writing the completed figure to the βplaceholderβ we created earlier."
},
{
"code": null,
"e": 2832,
"s": 2547,
"text": "Finally, we wrap it all up by creating two buttons to start and stop the dynamic radar chart (the start button using a placeholder as well). In addition we use a while loop to continuously re-run our radar chart function with a sleep function to delay each iteration by half a second."
},
{
"code": null,
"e": 2905,
"s": 2832,
"text": "And now you have it, our radar chart in a dynamically updated dashboard!"
}
] |
Top 25 Selenium Functions That Will Make You Pro | Towards Data Science
|
Web Scraping is a term for getting the data from webpages and making it so that you do not have to move a finger!
Get the data and then process it any way you want.
That is why today I want to show you some of the top functions that Selenium, which is a library for Web Scraping, has to offer.
I have written articles about Selenium and Web Scraping before, so before you begin with these, I would recommend you read this article βEverything About Web Scrapingβ, because of the setup process. And if you are already more advanced with Web Scraping, try my advanced scripts like βHow to Save Money with Pythonβ and βHow to Make an Analysis Tool with Pythonβ.
Letβs just jump right into it!
I have written about this one before, but get function is crucial and you can not do anything without it.
The get command launches a new browser and opens the given URL in your Webdriver. It simply takes the string as your specified URL and opens it for testing purposes.
If you are using Selenium IDE, it is similar to open command.
Example:
driver.get(βhttps://google.com");
The βdriverβ is your Webdriver on which you are going to perform all actions and it looks like this after executing the command above:
This function is crucial when you want to access elements on the page. Letβs say we want to access the βGoogle searchβ button in order to perform a search.
There are many ways to access elements, but my preferred one is to find XPath of the element. XPath is the elementβs ultimate location on the web page.
By clicking F12 you will inspect the page and get the background information about the page you are at.
By clicking the selection tool, you will be able to select elements.
After finding the button, click on the right at the blue marked section and Copy elementβs βFull Xpathβ.
self.driver.find_element_by_xpath('/html/body/div/div[4]/form/div[2]/div[1]/div[3]/center/input[1]')
That is the full command in order to find the specific element. I prefer full XPath over the regular XPath because regular one can be changed if the element in a new session changes and then next time you perform your script it does not work.
Overview of other find_element functions. (There is also find_elements ones)
Send_keys function is used for typing the text into a field that you selected by using the find_element function.
Letβs say we want to type βplateβ into google, that is why we use send_keys function.
google_tray = self.driver.find_element_by_xpath('/html/body/div/div[4]/form/div[2]/div[1]/div[1]/div/div[2]/input')google_tray.send_keys("plate")google_search = self.driver.find_element_by_xpath('/html/body/div/div[4]/form/div[2]/div[1]/div[3]/center/input[1]')google_search.click()
I saved the elements in their respective variables and then performed functions on them for more clarity.
At the end you end up with this:
This function uses the found element and performs a βclickβ on it. Simple stuff.
This is a code example for clicking the βGoogle Searchβ button.
google_search = self.driver.find_element_by_xpath('/html/body/div/div[4]/form/div[2]/div[1]/div[3]/center/input[1]')google_search.click()
This command is used for retrieving the Class object that represents the runtime class of this object. That means you perform this function to get the class of a certain element.
driver.getClass()
When you are already on a certain page with this command you can retrieve the URL you are at.
There are no parameters required for this command and it returns the string.
driver.current_url()
With this command, you will be able to retrieve the Source of the page.
There are no parameters required for this command and it returns the string.
driver.getPageSource()
This command can be combined with other commands like contains() to check if that string exists under that filter.
driver.getPageSource().contains("Example");
In this case, this will be a boolean value so either True or False.
Retrieve the Title of the website you are currently at.
There are no parameters required for this command and it returns the string. If the title is not found, null will be returned.
driver.getTitle()
With this command, you will get the text part of the Web Element.
There are no parameters required for this command and it returns the string.
driver.findElement(By.id("Price")).getText()
With this command, you will get the attribute of the Web Element.
We pass a single string parameter the is supposed to be an attribute that we want to know and returns a string value.
driver.findElement(By.id("Price")).getAttribute("val");
This command is used when we have multiple windows to handle.
The command helps us switch to the newly opened window and performs actions on the new window.
You can also switch back to the previous window if he/she desires.
String winHandleBefore = driver.getWindowHandle()driver.switchTo().window(winHandleBefore)
This command is similar to getWindowHandles(), but the basic difference is that we are dealing with multiple windows here. So more than two.
driver.getWindowHandles()
This command is used for finding elements on the page, based on the hyperlinks on the page and of the text that it consists of.
Letβs say we want to find the first link out of the Google search.
driver.findElement(By.linkText(βCar - Wikipediaβ))
There is also another option for this link searching:
Instead of typing the whole string you are looking for, you can also search for the partial or substrings on the page.
driver.findElement(By.partialLinkText(βBMWβ))
This command will find the first link out of Top Stories on Google.
After you input the text into the fields for a form, you can use the submit function to click that button and finish the form.
driver.findElement(By.<em>id</em>("submit")).submit();
This method closes the current window the user is working on.
The command does not require any parameter and it does not return any value.
driver.close()
It might seem very similar to close command, but the main difference is that it closes all windows that the user is keeping open at the moment.
The command does not require any parameter and it does not return any value.
driver.quit()
When you want to check whether the element is enabled in Web Driver.
First, you have to find the element and then check it.
It has a return value of boolean so either True or False.
driver.findElement(By.id("Price")).isEnabled()
With this function, you can get the size of a selected Web Element.
driver.findElements(By.id("Price")).size()
It returns the size of the element and output looks like this:
{'width': 77, 'height': 22}
This function is used to pausing the thread of execution for a certain amount of seconds.
For example, you type in the login credentials and before the next page loads, there is a time delay. That is why we use sleep to overcome those loading times.
This function is something useful in general and it is not from Selenium, but there are functions built-in for Selenium.
sleep(1)
This will pause the execution for 1 second.
With sleep function, you have to basically guess the loading time that you want to overcome but with pageLoadTimeout() you can set it to be specific.
driver.manage().timeouts().pageLoadTimeout(3, SECONDS);
This command will wait for 3 seconds for the page to load.
This is one more iteration of those sleeping/waiting functions that will help you achieve that perfect multithreading.
In order to avoid errors and Exceptions being thrown, we add a command to for a specific amount of time before locating the element on the page.
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
Wait 3 seconds before executing the next command.
These are being combined in order to switch between URLs and go back and forward as you please.
So you want to open another page, but instead of using get(), you want to use navigate here and easily manipulate between those pages.
driver.navigate().to("https://www.facebook.com");driver.navigate().back();driver.navigate().forward();
As mentioned before, this is not my first time writing about Selenium and Web Scraping in general. There are many more functions I would love to cover and many more to come. I hope you liked this tutorial and in order to keep up, follow me for more!
Thanks for reading!
|
[
{
"code": null,
"e": 285,
"s": 171,
"text": "Web Scraping is a term for getting the data from webpages and making it so that you do not have to move a finger!"
},
{
"code": null,
"e": 336,
"s": 285,
"text": "Get the data and then process it any way you want."
},
{
"code": null,
"e": 465,
"s": 336,
"text": "That is why today I want to show you some of the top functions that Selenium, which is a library for Web Scraping, has to offer."
},
{
"code": null,
"e": 829,
"s": 465,
"text": "I have written articles about Selenium and Web Scraping before, so before you begin with these, I would recommend you read this article βEverything About Web Scrapingβ, because of the setup process. And if you are already more advanced with Web Scraping, try my advanced scripts like βHow to Save Money with Pythonβ and βHow to Make an Analysis Tool with Pythonβ."
},
{
"code": null,
"e": 860,
"s": 829,
"text": "Letβs just jump right into it!"
},
{
"code": null,
"e": 966,
"s": 860,
"text": "I have written about this one before, but get function is crucial and you can not do anything without it."
},
{
"code": null,
"e": 1132,
"s": 966,
"text": "The get command launches a new browser and opens the given URL in your Webdriver. It simply takes the string as your specified URL and opens it for testing purposes."
},
{
"code": null,
"e": 1194,
"s": 1132,
"text": "If you are using Selenium IDE, it is similar to open command."
},
{
"code": null,
"e": 1203,
"s": 1194,
"text": "Example:"
},
{
"code": null,
"e": 1237,
"s": 1203,
"text": "driver.get(βhttps://google.com\");"
},
{
"code": null,
"e": 1372,
"s": 1237,
"text": "The βdriverβ is your Webdriver on which you are going to perform all actions and it looks like this after executing the command above:"
},
{
"code": null,
"e": 1528,
"s": 1372,
"text": "This function is crucial when you want to access elements on the page. Letβs say we want to access the βGoogle searchβ button in order to perform a search."
},
{
"code": null,
"e": 1680,
"s": 1528,
"text": "There are many ways to access elements, but my preferred one is to find XPath of the element. XPath is the elementβs ultimate location on the web page."
},
{
"code": null,
"e": 1784,
"s": 1680,
"text": "By clicking F12 you will inspect the page and get the background information about the page you are at."
},
{
"code": null,
"e": 1853,
"s": 1784,
"text": "By clicking the selection tool, you will be able to select elements."
},
{
"code": null,
"e": 1958,
"s": 1853,
"text": "After finding the button, click on the right at the blue marked section and Copy elementβs βFull Xpathβ."
},
{
"code": null,
"e": 2059,
"s": 1958,
"text": "self.driver.find_element_by_xpath('/html/body/div/div[4]/form/div[2]/div[1]/div[3]/center/input[1]')"
},
{
"code": null,
"e": 2302,
"s": 2059,
"text": "That is the full command in order to find the specific element. I prefer full XPath over the regular XPath because regular one can be changed if the element in a new session changes and then next time you perform your script it does not work."
},
{
"code": null,
"e": 2379,
"s": 2302,
"text": "Overview of other find_element functions. (There is also find_elements ones)"
},
{
"code": null,
"e": 2493,
"s": 2379,
"text": "Send_keys function is used for typing the text into a field that you selected by using the find_element function."
},
{
"code": null,
"e": 2579,
"s": 2493,
"text": "Letβs say we want to type βplateβ into google, that is why we use send_keys function."
},
{
"code": null,
"e": 2862,
"s": 2579,
"text": "google_tray = self.driver.find_element_by_xpath('/html/body/div/div[4]/form/div[2]/div[1]/div[1]/div/div[2]/input')google_tray.send_keys(\"plate\")google_search = self.driver.find_element_by_xpath('/html/body/div/div[4]/form/div[2]/div[1]/div[3]/center/input[1]')google_search.click()"
},
{
"code": null,
"e": 2968,
"s": 2862,
"text": "I saved the elements in their respective variables and then performed functions on them for more clarity."
},
{
"code": null,
"e": 3001,
"s": 2968,
"text": "At the end you end up with this:"
},
{
"code": null,
"e": 3082,
"s": 3001,
"text": "This function uses the found element and performs a βclickβ on it. Simple stuff."
},
{
"code": null,
"e": 3146,
"s": 3082,
"text": "This is a code example for clicking the βGoogle Searchβ button."
},
{
"code": null,
"e": 3284,
"s": 3146,
"text": "google_search = self.driver.find_element_by_xpath('/html/body/div/div[4]/form/div[2]/div[1]/div[3]/center/input[1]')google_search.click()"
},
{
"code": null,
"e": 3463,
"s": 3284,
"text": "This command is used for retrieving the Class object that represents the runtime class of this object. That means you perform this function to get the class of a certain element."
},
{
"code": null,
"e": 3481,
"s": 3463,
"text": "driver.getClass()"
},
{
"code": null,
"e": 3575,
"s": 3481,
"text": "When you are already on a certain page with this command you can retrieve the URL you are at."
},
{
"code": null,
"e": 3652,
"s": 3575,
"text": "There are no parameters required for this command and it returns the string."
},
{
"code": null,
"e": 3673,
"s": 3652,
"text": "driver.current_url()"
},
{
"code": null,
"e": 3745,
"s": 3673,
"text": "With this command, you will be able to retrieve the Source of the page."
},
{
"code": null,
"e": 3822,
"s": 3745,
"text": "There are no parameters required for this command and it returns the string."
},
{
"code": null,
"e": 3845,
"s": 3822,
"text": "driver.getPageSource()"
},
{
"code": null,
"e": 3960,
"s": 3845,
"text": "This command can be combined with other commands like contains() to check if that string exists under that filter."
},
{
"code": null,
"e": 4004,
"s": 3960,
"text": "driver.getPageSource().contains(\"Example\");"
},
{
"code": null,
"e": 4072,
"s": 4004,
"text": "In this case, this will be a boolean value so either True or False."
},
{
"code": null,
"e": 4128,
"s": 4072,
"text": "Retrieve the Title of the website you are currently at."
},
{
"code": null,
"e": 4255,
"s": 4128,
"text": "There are no parameters required for this command and it returns the string. If the title is not found, null will be returned."
},
{
"code": null,
"e": 4273,
"s": 4255,
"text": "driver.getTitle()"
},
{
"code": null,
"e": 4339,
"s": 4273,
"text": "With this command, you will get the text part of the Web Element."
},
{
"code": null,
"e": 4416,
"s": 4339,
"text": "There are no parameters required for this command and it returns the string."
},
{
"code": null,
"e": 4461,
"s": 4416,
"text": "driver.findElement(By.id(\"Price\")).getText()"
},
{
"code": null,
"e": 4527,
"s": 4461,
"text": "With this command, you will get the attribute of the Web Element."
},
{
"code": null,
"e": 4645,
"s": 4527,
"text": "We pass a single string parameter the is supposed to be an attribute that we want to know and returns a string value."
},
{
"code": null,
"e": 4701,
"s": 4645,
"text": "driver.findElement(By.id(\"Price\")).getAttribute(\"val\");"
},
{
"code": null,
"e": 4763,
"s": 4701,
"text": "This command is used when we have multiple windows to handle."
},
{
"code": null,
"e": 4858,
"s": 4763,
"text": "The command helps us switch to the newly opened window and performs actions on the new window."
},
{
"code": null,
"e": 4925,
"s": 4858,
"text": "You can also switch back to the previous window if he/she desires."
},
{
"code": null,
"e": 5016,
"s": 4925,
"text": "String winHandleBefore = driver.getWindowHandle()driver.switchTo().window(winHandleBefore)"
},
{
"code": null,
"e": 5157,
"s": 5016,
"text": "This command is similar to getWindowHandles(), but the basic difference is that we are dealing with multiple windows here. So more than two."
},
{
"code": null,
"e": 5183,
"s": 5157,
"text": "driver.getWindowHandles()"
},
{
"code": null,
"e": 5311,
"s": 5183,
"text": "This command is used for finding elements on the page, based on the hyperlinks on the page and of the text that it consists of."
},
{
"code": null,
"e": 5378,
"s": 5311,
"text": "Letβs say we want to find the first link out of the Google search."
},
{
"code": null,
"e": 5429,
"s": 5378,
"text": "driver.findElement(By.linkText(βCar - Wikipediaβ))"
},
{
"code": null,
"e": 5483,
"s": 5429,
"text": "There is also another option for this link searching:"
},
{
"code": null,
"e": 5602,
"s": 5483,
"text": "Instead of typing the whole string you are looking for, you can also search for the partial or substrings on the page."
},
{
"code": null,
"e": 5648,
"s": 5602,
"text": "driver.findElement(By.partialLinkText(βBMWβ))"
},
{
"code": null,
"e": 5716,
"s": 5648,
"text": "This command will find the first link out of Top Stories on Google."
},
{
"code": null,
"e": 5843,
"s": 5716,
"text": "After you input the text into the fields for a form, you can use the submit function to click that button and finish the form."
},
{
"code": null,
"e": 5898,
"s": 5843,
"text": "driver.findElement(By.<em>id</em>(\"submit\")).submit();"
},
{
"code": null,
"e": 5960,
"s": 5898,
"text": "This method closes the current window the user is working on."
},
{
"code": null,
"e": 6037,
"s": 5960,
"text": "The command does not require any parameter and it does not return any value."
},
{
"code": null,
"e": 6052,
"s": 6037,
"text": "driver.close()"
},
{
"code": null,
"e": 6196,
"s": 6052,
"text": "It might seem very similar to close command, but the main difference is that it closes all windows that the user is keeping open at the moment."
},
{
"code": null,
"e": 6273,
"s": 6196,
"text": "The command does not require any parameter and it does not return any value."
},
{
"code": null,
"e": 6287,
"s": 6273,
"text": "driver.quit()"
},
{
"code": null,
"e": 6356,
"s": 6287,
"text": "When you want to check whether the element is enabled in Web Driver."
},
{
"code": null,
"e": 6411,
"s": 6356,
"text": "First, you have to find the element and then check it."
},
{
"code": null,
"e": 6469,
"s": 6411,
"text": "It has a return value of boolean so either True or False."
},
{
"code": null,
"e": 6516,
"s": 6469,
"text": "driver.findElement(By.id(\"Price\")).isEnabled()"
},
{
"code": null,
"e": 6584,
"s": 6516,
"text": "With this function, you can get the size of a selected Web Element."
},
{
"code": null,
"e": 6627,
"s": 6584,
"text": "driver.findElements(By.id(\"Price\")).size()"
},
{
"code": null,
"e": 6690,
"s": 6627,
"text": "It returns the size of the element and output looks like this:"
},
{
"code": null,
"e": 6718,
"s": 6690,
"text": "{'width': 77, 'height': 22}"
},
{
"code": null,
"e": 6808,
"s": 6718,
"text": "This function is used to pausing the thread of execution for a certain amount of seconds."
},
{
"code": null,
"e": 6968,
"s": 6808,
"text": "For example, you type in the login credentials and before the next page loads, there is a time delay. That is why we use sleep to overcome those loading times."
},
{
"code": null,
"e": 7089,
"s": 6968,
"text": "This function is something useful in general and it is not from Selenium, but there are functions built-in for Selenium."
},
{
"code": null,
"e": 7098,
"s": 7089,
"text": "sleep(1)"
},
{
"code": null,
"e": 7142,
"s": 7098,
"text": "This will pause the execution for 1 second."
},
{
"code": null,
"e": 7292,
"s": 7142,
"text": "With sleep function, you have to basically guess the loading time that you want to overcome but with pageLoadTimeout() you can set it to be specific."
},
{
"code": null,
"e": 7348,
"s": 7292,
"text": "driver.manage().timeouts().pageLoadTimeout(3, SECONDS);"
},
{
"code": null,
"e": 7407,
"s": 7348,
"text": "This command will wait for 3 seconds for the page to load."
},
{
"code": null,
"e": 7526,
"s": 7407,
"text": "This is one more iteration of those sleeping/waiting functions that will help you achieve that perfect multithreading."
},
{
"code": null,
"e": 7671,
"s": 7526,
"text": "In order to avoid errors and Exceptions being thrown, we add a command to for a specific amount of time before locating the element on the page."
},
{
"code": null,
"e": 7735,
"s": 7671,
"text": "driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);"
},
{
"code": null,
"e": 7785,
"s": 7735,
"text": "Wait 3 seconds before executing the next command."
},
{
"code": null,
"e": 7881,
"s": 7785,
"text": "These are being combined in order to switch between URLs and go back and forward as you please."
},
{
"code": null,
"e": 8016,
"s": 7881,
"text": "So you want to open another page, but instead of using get(), you want to use navigate here and easily manipulate between those pages."
},
{
"code": null,
"e": 8119,
"s": 8016,
"text": "driver.navigate().to(\"https://www.facebook.com\");driver.navigate().back();driver.navigate().forward();"
},
{
"code": null,
"e": 8369,
"s": 8119,
"text": "As mentioned before, this is not my first time writing about Selenium and Web Scraping in general. There are many more functions I would love to cover and many more to come. I hope you liked this tutorial and in order to keep up, follow me for more!"
}
] |
MoviePy β Rotating Video File
|
01 Aug, 2020
In this article we will see how we can rotate a video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIFβs. Rotation is the act or process of moving or turning around of a video to its central point. Rotation of 360 degree will be a complete turn around a central point. We can rotate the video with any angle.
In order to do this we will use rotate method with the VideoFileClip object
Syntax : clip.rotate(degree)
Argument : It takes integer as argument
Return : It returns VideoFileClip object
Below is the implementation
# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro videoclip = VideoFileClip("dsa_geek.webm") # getting subclip as video is largeclip = clip.subclip(55, 65) # rotating clip by 45 degreeclip = clip.rotate(45) # showing clipclip.ipython_display(width = 480)
Output :
Moviepy - Building video __temp__.mp4.
Moviepy - Writing video __temp__.mp4
Moviepy - Done !
Moviepy - video ready __temp__.mp4
Another example
# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip("geeks.mp4") # getting subclip clip = clip.subclip(0, 7) # rotating clip by 180 degreeclip = clip.rotate(180) # showing clipclip.ipython_display()
Output :
Moviepy - Building video __temp__.mp4.
MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3
MoviePy - Done.
Moviepy - Writing video __temp__.mp4
Moviepy - Done !
Moviepy - video ready __temp__.mp4
Python-MoviePy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 413,
"s": 28,
"text": "In this article we will see how we can rotate a video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIFβs. Rotation is the act or process of moving or turning around of a video to its central point. Rotation of 360 degree will be a complete turn around a central point. We can rotate the video with any angle."
},
{
"code": null,
"e": 489,
"s": 413,
"text": "In order to do this we will use rotate method with the VideoFileClip object"
},
{
"code": null,
"e": 518,
"s": 489,
"text": "Syntax : clip.rotate(degree)"
},
{
"code": null,
"e": 558,
"s": 518,
"text": "Argument : It takes integer as argument"
},
{
"code": null,
"e": 599,
"s": 558,
"text": "Return : It returns VideoFileClip object"
},
{
"code": null,
"e": 627,
"s": 599,
"text": "Below is the implementation"
},
{
"code": "# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro videoclip = VideoFileClip(\"dsa_geek.webm\") # getting subclip as video is largeclip = clip.subclip(55, 65) # rotating clip by 45 degreeclip = clip.rotate(45) # showing clipclip.ipython_display(width = 480)",
"e": 941,
"s": 627,
"text": null
},
{
"code": null,
"e": 950,
"s": 941,
"text": "Output :"
},
{
"code": null,
"e": 1199,
"s": 950,
"text": "Moviepy - Building video __temp__.mp4.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4"
},
{
"code": null,
"e": 1215,
"s": 1199,
"text": "Another example"
},
{
"code": "# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip(\"geeks.mp4\") # getting subclip clip = clip.subclip(0, 7) # rotating clip by 180 degreeclip = clip.rotate(180) # showing clipclip.ipython_display()",
"e": 1481,
"s": 1215,
"text": null
},
{
"code": null,
"e": 1490,
"s": 1481,
"text": "Output :"
},
{
"code": null,
"e": 1932,
"s": 1490,
"text": "Moviepy - Building video __temp__.mp4.\nMoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3\n \nMoviePy - Done.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4\n"
},
{
"code": null,
"e": 1947,
"s": 1932,
"text": "Python-MoviePy"
},
{
"code": null,
"e": 1954,
"s": 1947,
"text": "Python"
}
] |
MVVM (Model View ViewModel) Architecture Pattern in Android
|
09 Jun, 2022
Developers always prefer a clean and structured code for the projects. By organizing the codes according to a design pattern helps in the maintenance of the software. By having knowledge of all crucial logic parts of the android application, it is easier to add and remove app features. Further, design patterns also assure that all the codes get covered in Unit Testing without the interference of other classes. Model β View β ViewModel (MVVM) is the industry-recognized software architecture pattern that overcomes all drawbacks of MVP and MVC design patterns. MVVM suggests separating the data presentation logic(Views or UI) from the core business logic part of the application.
Model: This layer is responsible for the abstraction of the data sources. Model and ViewModel work together to get and save the data.
View: The purpose of this layer is to inform the ViewModel about the userβs action. This layer observes the ViewModel and does not contain any kind of application logic.
ViewModel: It exposes those data streams which are relevant to the View. Moreover, it serve as a link between the Model and the View.
MVVM pattern has some similarities with the MVP(Model β View β Presenter) design pattern as the Presenter role is played by ViewModel. However, the drawbacks of the MVP pattern has been solved by MVVM in the following ways:
ViewModel does not hold any kind of reference to the View.Many to 1 relationship exist between View and ViewModel.No triggering methods to update the View.
ViewModel does not hold any kind of reference to the View.
Many to 1 relationship exist between View and ViewModel.
No triggering methods to update the View.
There are 2 ways to implement MVVM design pattern in Android projects:
Using the DataBinding library released by GoogleUsing any tool like RxJava for DataBinding.
Using the DataBinding library released by Google
Using any tool like RxJava for DataBinding.
Data Binding:
Google releases the Data Binding Library for Android that allows the developers to bind UI components in the XML layouts with the applicationβs data repositories. This helps in minimizing the code of core application logic that binds with View. Further, Two β way Data Binding is done for binding the objects to the XML layouts so that object and the layout both can send data to each other. This point can be visualized by the example of this tutorial.
Syntax for the two way data binding is @={variable}
Here is an example of a single activity User-Login android application to show the implementation of the MVVM architecture pattern on projects. The application will ask the user to input the Email ID and password. Based on the inputs received the ViewModel notifies the View what to show as a toast message. The ViewModel will not have a reference to the View.
To enable DataBinding in the android application, following codes needs to be added in the appβs build.gradle(build.gradle (:app)) file:
Enable DataBinding:
android {
dataBinding {
enabled = true
}
}
Add lifecycle dependency:
implementation βandroid.arch.lifecycle:extensions:1.1.1β
Below is the complete step-by-step implementation of the User-Login android application with MVVM pattern.
Note: Following steps are performed on Android Studio version 4.0
Step 1: Create a new project
Click on File, then New => New Project.
Choose Empty activity
Select language as Java/Kotlin
Select the minimum SDK as per your need.
Step 2: Modify String.xml file
All the strings which are used in the activity are listed in this file.
XML
<resources> <string name="app_name">GfG | MVVM Architecture</string> <string name="heading">MVVM Architecture Pattern</string> <string name="email_hint">Enter your Email ID</string> <string name="password_hint">Enter your password</string> <string name="button_text">Login</string></resources>
Step 3: Creating the Model class
Create a new class named Model to which will hold the Email ID and password entered by the user. Below is the code to implement the proper Model class.
Java
import androidx.annotation.Nullable; public class Model { @Nullable String email,password; // constructor to initialize // the variables public Model(String email, String password){ this.email = email; this.password = password; } // getter and setter methods // for email variable @Nullable public String getEmail() { return email; } public void setEmail(@Nullable String email) { this.email = email; } // getter and setter methods // for password variable @Nullable public String getPassword() { return password; } public void setPassword(@Nullable String password) { this.password = password; } }
Step 4: Working with the activity_main.xml file
Open the activity_main.xml file and add 2 EditText to get inputs for Email and Password. One Login Button is also required to validate the userβs input and display appropriate Toast message. Below is the code for designing a proper activity layout.
Note: For the proper functioning of Data Binding Library, it is required to set the layout tag at the top. The constraint layout tag of XML will not work in this case.
XML
<?xml version="1.0" encoding="utf-8"?><layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:bind="http://schemas.android.com/tools"> <!-- binding object of ViewModel to the XML layout --> <data> <variable name="viewModel" type="com.example.mvvmarchitecture.AppViewModel" /> </data> <!-- Provided Linear layout for the activity components --> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:layout_margin="8dp" android:background="#168BC34A" android:orientation="vertical"> <!-- TextView for the heading of the activity --> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/heading" android:textAlignment="center" android:textColor="@android:color/holo_green_dark" android:textSize="36sp" android:textStyle="bold" /> <!-- EditText field for the Email --> <EditText android:id="@+id/inEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="60dp" android:layout_marginEnd="10dp" android:layout_marginBottom="20dp" android:hint="@string/email_hint" android:inputType="textEmailAddress" android:padding="8dp" android:text="@={viewModel.userEmail}" /> <!-- EditText field for the password --> <EditText android:id="@+id/inPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginEnd="10dp" android:hint="@string/password_hint" android:inputType="textPassword" android:padding="8dp" android:text="@={viewModel.userPassword}" /> <!-- Login Button of the activity --> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginTop="60dp" android:layout_marginEnd="20dp" android:background="#4CAF50" android:fontFamily="@font/roboto" android:onClick="@{()-> viewModel.onButtonClicked()}" android:text="@string/button_text" android:textColor="@android:color/background_light" android:textSize="30sp" android:textStyle="bold" bind:toastMessage="@{viewModel.toastMessage}" /> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="135dp" app:srcCompat="@drawable/banner" /> </LinearLayout></layout>
Step 5: Creating the ViewModel class
This class will contain all the methods which are needed to be called in the application layout. The ViewModel class will extend BaseObservable because it converts the data into streams and notifies the View when the toast message property will change.
Java
import android.text.TextUtils;import android.util.Patterns;import androidx.databinding.BaseObservable;import androidx.databinding.Bindable; public class AppViewModel extends BaseObservable { // creating object of Model class private Model model; // string variables for // toast messages private String successMessage = "Login successful"; private String errorMessage = "Email or Password is not valid"; @Bindable // string variable for // toast message private String toastMessage = null; // getter and setter methods // for toast message public String getToastMessage() { return toastMessage; } private void setToastMessage(String toastMessage) { this.toastMessage = toastMessage; notifyPropertyChanged(BR.toastMessage); } // getter and setter methods // for email variable @Bindable public String getUserEmail() { return model.getEmail(); } public void setUserEmail(String email) { model.setEmail(email); notifyPropertyChanged(BR.userEmail); } // getter and setter methods // for password variable @Bindable public String getUserPassword() { return model.getPassword(); } public void setUserPassword(String password) { model.setPassword(password); notifyPropertyChanged(BR.userPassword); } // constructor of ViewModel class public AppViewModel() { // instantiating object of // model class model = new Model("",""); } // actions to be performed // when user clicks // the LOGIN button public void onButtonClicked() { if (isValid()) setToastMessage(successMessage); else setToastMessage(errorMessage); } // method to keep a check // that variable fields must // not be kept empty by user public boolean isValid() { return !TextUtils.isEmpty(getUserEmail()) && Patterns.EMAIL_ADDRESS.matcher(getUserEmail()).matches() && getUserPassword().length() > 5; }}
Step 6: Define functionalities of View in the MainActivity file
The View class is responsible for updating the UI of the application. According to the changes in the toast message provided by ViewModel, the Binding Adapter would trigger the View layer. The setter of Toast message will notify the observer(View) about the changes in data. After that, View will take appropriate actions.
Java
import android.os.Bundle;import android.view.View;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.databinding.BindingAdapter;import androidx.databinding.DataBindingUtil; import com.example.mvvmarchitecture.databinding.ActivityMainBinding; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // ViewModel updates the Model // after observing changes in the View // model will also update the view // via the ViewModel ActivityMainBinding activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main); activityMainBinding.setViewModel(new AppViewModel()); activityMainBinding.executePendingBindings(); } // any change in toastMessage attribute // defined on the Button with bind prefix // invokes this method @BindingAdapter({"toastMessage"}) public static void runMe( View view, String message) { if (message != null) Toast.makeText(view.getContext(), message, Toast.LENGTH_SHORT).show(); }}
Enhance the reusability of code.
All modules are independent which improves the testability of each layer.
Makes project files maintainable and easy to make changes.
This design pattern is not ideal for small projects.
If the data binding logic is too complex, the application debug will be a little harder.
adnanirshad158
tiwsonu58
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Navigation Drawer in Android
How to Create and Add Data to SQLite Database in Android?
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 739,
"s": 54,
"text": "Developers always prefer a clean and structured code for the projects. By organizing the codes according to a design pattern helps in the maintenance of the software. By having knowledge of all crucial logic parts of the android application, it is easier to add and remove app features. Further, design patterns also assure that all the codes get covered in Unit Testing without the interference of other classes. Model β View β ViewModel (MVVM) is the industry-recognized software architecture pattern that overcomes all drawbacks of MVP and MVC design patterns. MVVM suggests separating the data presentation logic(Views or UI) from the core business logic part of the application. "
},
{
"code": null,
"e": 873,
"s": 739,
"text": "Model: This layer is responsible for the abstraction of the data sources. Model and ViewModel work together to get and save the data."
},
{
"code": null,
"e": 1043,
"s": 873,
"text": "View: The purpose of this layer is to inform the ViewModel about the userβs action. This layer observes the ViewModel and does not contain any kind of application logic."
},
{
"code": null,
"e": 1177,
"s": 1043,
"text": "ViewModel: It exposes those data streams which are relevant to the View. Moreover, it serve as a link between the Model and the View."
},
{
"code": null,
"e": 1401,
"s": 1177,
"text": "MVVM pattern has some similarities with the MVP(Model β View β Presenter) design pattern as the Presenter role is played by ViewModel. However, the drawbacks of the MVP pattern has been solved by MVVM in the following ways:"
},
{
"code": null,
"e": 1557,
"s": 1401,
"text": "ViewModel does not hold any kind of reference to the View.Many to 1 relationship exist between View and ViewModel.No triggering methods to update the View."
},
{
"code": null,
"e": 1616,
"s": 1557,
"text": "ViewModel does not hold any kind of reference to the View."
},
{
"code": null,
"e": 1673,
"s": 1616,
"text": "Many to 1 relationship exist between View and ViewModel."
},
{
"code": null,
"e": 1715,
"s": 1673,
"text": "No triggering methods to update the View."
},
{
"code": null,
"e": 1786,
"s": 1715,
"text": "There are 2 ways to implement MVVM design pattern in Android projects:"
},
{
"code": null,
"e": 1878,
"s": 1786,
"text": "Using the DataBinding library released by GoogleUsing any tool like RxJava for DataBinding."
},
{
"code": null,
"e": 1927,
"s": 1878,
"text": "Using the DataBinding library released by Google"
},
{
"code": null,
"e": 1971,
"s": 1927,
"text": "Using any tool like RxJava for DataBinding."
},
{
"code": null,
"e": 1985,
"s": 1971,
"text": "Data Binding:"
},
{
"code": null,
"e": 2439,
"s": 1985,
"text": "Google releases the Data Binding Library for Android that allows the developers to bind UI components in the XML layouts with the applicationβs data repositories. This helps in minimizing the code of core application logic that binds with View. Further, Two β way Data Binding is done for binding the objects to the XML layouts so that object and the layout both can send data to each other. This point can be visualized by the example of this tutorial."
},
{
"code": null,
"e": 2491,
"s": 2439,
"text": "Syntax for the two way data binding is @={variable}"
},
{
"code": null,
"e": 2853,
"s": 2491,
"text": "Here is an example of a single activity User-Login android application to show the implementation of the MVVM architecture pattern on projects. The application will ask the user to input the Email ID and password. Based on the inputs received the ViewModel notifies the View what to show as a toast message. The ViewModel will not have a reference to the View. "
},
{
"code": null,
"e": 2990,
"s": 2853,
"text": "To enable DataBinding in the android application, following codes needs to be added in the appβs build.gradle(build.gradle (:app)) file:"
},
{
"code": null,
"e": 3010,
"s": 2990,
"text": "Enable DataBinding:"
},
{
"code": null,
"e": 3020,
"s": 3010,
"text": "android {"
},
{
"code": null,
"e": 3037,
"s": 3020,
"text": " dataBinding {"
},
{
"code": null,
"e": 3059,
"s": 3037,
"text": " enabled = true"
},
{
"code": null,
"e": 3067,
"s": 3059,
"text": " }"
},
{
"code": null,
"e": 3069,
"s": 3067,
"text": "}"
},
{
"code": null,
"e": 3095,
"s": 3069,
"text": "Add lifecycle dependency:"
},
{
"code": null,
"e": 3152,
"s": 3095,
"text": "implementation βandroid.arch.lifecycle:extensions:1.1.1β"
},
{
"code": null,
"e": 3261,
"s": 3154,
"text": "Below is the complete step-by-step implementation of the User-Login android application with MVVM pattern."
},
{
"code": null,
"e": 3327,
"s": 3261,
"text": "Note: Following steps are performed on Android Studio version 4.0"
},
{
"code": null,
"e": 3356,
"s": 3327,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 3396,
"s": 3356,
"text": "Click on File, then New => New Project."
},
{
"code": null,
"e": 3418,
"s": 3396,
"text": "Choose Empty activity"
},
{
"code": null,
"e": 3449,
"s": 3418,
"text": "Select language as Java/Kotlin"
},
{
"code": null,
"e": 3490,
"s": 3449,
"text": "Select the minimum SDK as per your need."
},
{
"code": null,
"e": 3521,
"s": 3490,
"text": "Step 2: Modify String.xml file"
},
{
"code": null,
"e": 3593,
"s": 3521,
"text": "All the strings which are used in the activity are listed in this file."
},
{
"code": null,
"e": 3597,
"s": 3593,
"text": "XML"
},
{
"code": "<resources> <string name=\"app_name\">GfG | MVVM Architecture</string> <string name=\"heading\">MVVM Architecture Pattern</string> <string name=\"email_hint\">Enter your Email ID</string> <string name=\"password_hint\">Enter your password</string> <string name=\"button_text\">Login</string></resources>",
"e": 3906,
"s": 3597,
"text": null
},
{
"code": null,
"e": 3942,
"s": 3909,
"text": "Step 3: Creating the Model class"
},
{
"code": null,
"e": 4096,
"s": 3944,
"text": "Create a new class named Model to which will hold the Email ID and password entered by the user. Below is the code to implement the proper Model class."
},
{
"code": null,
"e": 4103,
"s": 4098,
"text": "Java"
},
{
"code": "import androidx.annotation.Nullable; public class Model { @Nullable String email,password; // constructor to initialize // the variables public Model(String email, String password){ this.email = email; this.password = password; } // getter and setter methods // for email variable @Nullable public String getEmail() { return email; } public void setEmail(@Nullable String email) { this.email = email; } // getter and setter methods // for password variable @Nullable public String getPassword() { return password; } public void setPassword(@Nullable String password) { this.password = password; } }",
"e": 4810,
"s": 4103,
"text": null
},
{
"code": null,
"e": 4861,
"s": 4813,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 5112,
"s": 4863,
"text": "Open the activity_main.xml file and add 2 EditText to get inputs for Email and Password. One Login Button is also required to validate the userβs input and display appropriate Toast message. Below is the code for designing a proper activity layout."
},
{
"code": null,
"e": 5282,
"s": 5114,
"text": "Note: For the proper functioning of Data Binding Library, it is required to set the layout tag at the top. The constraint layout tag of XML will not work in this case."
},
{
"code": null,
"e": 5288,
"s": 5284,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><layout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:bind=\"http://schemas.android.com/tools\"> <!-- binding object of ViewModel to the XML layout --> <data> <variable name=\"viewModel\" type=\"com.example.mvvmarchitecture.AppViewModel\" /> </data> <!-- Provided Linear layout for the activity components --> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_gravity=\"center\" android:layout_margin=\"8dp\" android:background=\"#168BC34A\" android:orientation=\"vertical\"> <!-- TextView for the heading of the activity --> <TextView android:id=\"@+id/textView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"@string/heading\" android:textAlignment=\"center\" android:textColor=\"@android:color/holo_green_dark\" android:textSize=\"36sp\" android:textStyle=\"bold\" /> <!-- EditText field for the Email --> <EditText android:id=\"@+id/inEmail\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"60dp\" android:layout_marginEnd=\"10dp\" android:layout_marginBottom=\"20dp\" android:hint=\"@string/email_hint\" android:inputType=\"textEmailAddress\" android:padding=\"8dp\" android:text=\"@={viewModel.userEmail}\" /> <!-- EditText field for the password --> <EditText android:id=\"@+id/inPassword\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"10dp\" android:layout_marginEnd=\"10dp\" android:hint=\"@string/password_hint\" android:inputType=\"textPassword\" android:padding=\"8dp\" android:text=\"@={viewModel.userPassword}\" /> <!-- Login Button of the activity --> <Button android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"60dp\" android:layout_marginEnd=\"20dp\" android:background=\"#4CAF50\" android:fontFamily=\"@font/roboto\" android:onClick=\"@{()-> viewModel.onButtonClicked()}\" android:text=\"@string/button_text\" android:textColor=\"@android:color/background_light\" android:textSize=\"30sp\" android:textStyle=\"bold\" bind:toastMessage=\"@{viewModel.toastMessage}\" /> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"135dp\" app:srcCompat=\"@drawable/banner\" /> </LinearLayout></layout>",
"e": 8404,
"s": 5288,
"text": null
},
{
"code": null,
"e": 8444,
"s": 8407,
"text": "Step 5: Creating the ViewModel class"
},
{
"code": null,
"e": 8699,
"s": 8446,
"text": "This class will contain all the methods which are needed to be called in the application layout. The ViewModel class will extend BaseObservable because it converts the data into streams and notifies the View when the toast message property will change."
},
{
"code": null,
"e": 8706,
"s": 8701,
"text": "Java"
},
{
"code": "import android.text.TextUtils;import android.util.Patterns;import androidx.databinding.BaseObservable;import androidx.databinding.Bindable; public class AppViewModel extends BaseObservable { // creating object of Model class private Model model; // string variables for // toast messages private String successMessage = \"Login successful\"; private String errorMessage = \"Email or Password is not valid\"; @Bindable // string variable for // toast message private String toastMessage = null; // getter and setter methods // for toast message public String getToastMessage() { return toastMessage; } private void setToastMessage(String toastMessage) { this.toastMessage = toastMessage; notifyPropertyChanged(BR.toastMessage); } // getter and setter methods // for email variable @Bindable public String getUserEmail() { return model.getEmail(); } public void setUserEmail(String email) { model.setEmail(email); notifyPropertyChanged(BR.userEmail); } // getter and setter methods // for password variable @Bindable public String getUserPassword() { return model.getPassword(); } public void setUserPassword(String password) { model.setPassword(password); notifyPropertyChanged(BR.userPassword); } // constructor of ViewModel class public AppViewModel() { // instantiating object of // model class model = new Model(\"\",\"\"); } // actions to be performed // when user clicks // the LOGIN button public void onButtonClicked() { if (isValid()) setToastMessage(successMessage); else setToastMessage(errorMessage); } // method to keep a check // that variable fields must // not be kept empty by user public boolean isValid() { return !TextUtils.isEmpty(getUserEmail()) && Patterns.EMAIL_ADDRESS.matcher(getUserEmail()).matches() && getUserPassword().length() > 5; }}",
"e": 10747,
"s": 8706,
"text": null
},
{
"code": null,
"e": 10814,
"s": 10750,
"text": "Step 6: Define functionalities of View in the MainActivity file"
},
{
"code": null,
"e": 11139,
"s": 10816,
"text": "The View class is responsible for updating the UI of the application. According to the changes in the toast message provided by ViewModel, the Binding Adapter would trigger the View layer. The setter of Toast message will notify the observer(View) about the changes in data. After that, View will take appropriate actions."
},
{
"code": null,
"e": 11146,
"s": 11141,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.View;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.databinding.BindingAdapter;import androidx.databinding.DataBindingUtil; import com.example.mvvmarchitecture.databinding.ActivityMainBinding; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // ViewModel updates the Model // after observing changes in the View // model will also update the view // via the ViewModel ActivityMainBinding activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main); activityMainBinding.setViewModel(new AppViewModel()); activityMainBinding.executePendingBindings(); } // any change in toastMessage attribute // defined on the Button with bind prefix // invokes this method @BindingAdapter({\"toastMessage\"}) public static void runMe( View view, String message) { if (message != null) Toast.makeText(view.getContext(), message, Toast.LENGTH_SHORT).show(); }}",
"e": 12310,
"s": 11146,
"text": null
},
{
"code": null,
"e": 12346,
"s": 12313,
"text": "Enhance the reusability of code."
},
{
"code": null,
"e": 12420,
"s": 12346,
"text": "All modules are independent which improves the testability of each layer."
},
{
"code": null,
"e": 12479,
"s": 12420,
"text": "Makes project files maintainable and easy to make changes."
},
{
"code": null,
"e": 12532,
"s": 12479,
"text": "This design pattern is not ideal for small projects."
},
{
"code": null,
"e": 12621,
"s": 12532,
"text": "If the data binding logic is too complex, the application debug will be a little harder."
},
{
"code": null,
"e": 12638,
"s": 12623,
"text": "adnanirshad158"
},
{
"code": null,
"e": 12648,
"s": 12638,
"text": "tiwsonu58"
},
{
"code": null,
"e": 12656,
"s": 12648,
"text": "android"
},
{
"code": null,
"e": 12680,
"s": 12656,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 12688,
"s": 12680,
"text": "Android"
},
{
"code": null,
"e": 12693,
"s": 12688,
"text": "Java"
},
{
"code": null,
"e": 12712,
"s": 12693,
"text": "Technical Scripter"
},
{
"code": null,
"e": 12717,
"s": 12712,
"text": "Java"
},
{
"code": null,
"e": 12725,
"s": 12717,
"text": "Android"
},
{
"code": null,
"e": 12823,
"s": 12725,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12855,
"s": 12823,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 12886,
"s": 12855,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 12929,
"s": 12886,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 12958,
"s": 12929,
"text": "Navigation Drawer in Android"
},
{
"code": null,
"e": 13016,
"s": 12958,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 13031,
"s": 13016,
"text": "Arrays in Java"
},
{
"code": null,
"e": 13075,
"s": 13031,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 13111,
"s": 13075,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 13162,
"s": 13111,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
find_elements_by_css_selector() driver method β Selenium Python
|
14 Apr, 2020
Seleniumβs Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out β Navigating links using get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task.
This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_elements_by_css_selector() is discussed in this article. This method returns a list with type of elements specified.To grab a single first element, checkout β find_element_by_css_selector() driver method β Selenium Python
driver.find_elements_by_css_selector("css selector")
Example βFor instance, consider this page source:
<html> <body> <form id="loginForm"> <input name="1" type="text" /> <input name="1" type="password" /> <input name="1" type="submit" value="Login" /> </form> </body><html>
Now after you have created a driver, you can grab an element using β
login_form = driver.find_elements_by_css_selector('#loginForm')
Letβs try to practically implement this method and get a element instance for βhttps://www.geeksforgeeks.org/β. Letβs try to grab search form input using its class name βgsc-inputβ.Create a file called run.py to demonstrate find_elements_by_css_selector method β
# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = "geeksforgeeks" # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get elementselements = driver.find_elements_by_css_selector(".gsc-input") # print complete elements listprint(element)
Now run using β
Python run.py
First, it will open firefox window with geeksforgeeks, and then select the element and print it on terminal as show below.Browser Output βTerminal Output β
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Apr, 2020"
},
{
"code": null,
"e": 525,
"s": 28,
"text": "Seleniumβs Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out β Navigating links using get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task."
},
{
"code": null,
"e": 894,
"s": 525,
"text": "This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_elements_by_css_selector() is discussed in this article. This method returns a list with type of elements specified.To grab a single first element, checkout β find_element_by_css_selector() driver method β Selenium Python"
},
{
"code": null,
"e": 948,
"s": 894,
"text": "driver.find_elements_by_css_selector(\"css selector\")\n"
},
{
"code": null,
"e": 998,
"s": 948,
"text": "Example βFor instance, consider this page source:"
},
{
"code": "<html> <body> <form id=\"loginForm\"> <input name=\"1\" type=\"text\" /> <input name=\"1\" type=\"password\" /> <input name=\"1\" type=\"submit\" value=\"Login\" /> </form> </body><html>",
"e": 1177,
"s": 998,
"text": null
},
{
"code": null,
"e": 1246,
"s": 1177,
"text": "Now after you have created a driver, you can grab an element using β"
},
{
"code": null,
"e": 1311,
"s": 1246,
"text": "login_form = driver.find_elements_by_css_selector('#loginForm')\n"
},
{
"code": null,
"e": 1574,
"s": 1311,
"text": "Letβs try to practically implement this method and get a element instance for βhttps://www.geeksforgeeks.org/β. Letβs try to grab search form input using its class name βgsc-inputβ.Create a file called run.py to demonstrate find_elements_by_css_selector method β"
},
{
"code": "# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = \"geeksforgeeks\" # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get elementselements = driver.find_elements_by_css_selector(\".gsc-input\") # print complete elements listprint(element)",
"e": 1965,
"s": 1574,
"text": null
},
{
"code": null,
"e": 1981,
"s": 1965,
"text": "Now run using β"
},
{
"code": null,
"e": 1995,
"s": 1981,
"text": "Python run.py"
},
{
"code": null,
"e": 2151,
"s": 1995,
"text": "First, it will open firefox window with geeksforgeeks, and then select the element and print it on terminal as show below.Browser Output βTerminal Output β"
},
{
"code": null,
"e": 2167,
"s": 2151,
"text": "Python-selenium"
},
{
"code": null,
"e": 2176,
"s": 2167,
"text": "selenium"
},
{
"code": null,
"e": 2183,
"s": 2176,
"text": "Python"
},
{
"code": null,
"e": 2281,
"s": 2183,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2299,
"s": 2281,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2341,
"s": 2299,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2363,
"s": 2341,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2398,
"s": 2363,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2424,
"s": 2398,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2456,
"s": 2424,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2485,
"s": 2456,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2512,
"s": 2485,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2533,
"s": 2512,
"text": "Python OOPs Concepts"
}
] |
VB.Net - Excel Sheet
|
VB.Net provides support for interoperability between the COM object model of Microsoft Excel 2010 and your application.
To avail this interoperability in your application, you need to import the namespace Microsoft.Office.Interop.Excel in your Windows Form Application.
Let's start with creating a Window Forms Application by following the following steps in Microsoft Visual Studio: File β New Project β Windows Forms Applications
Finally, select OK, Microsoft Visual Studio creates your project and displays following Form1.
Insert a Button control Button1 in the form.
Add a reference to Microsoft Excel Object Library to your project. To do this β
Select Add Reference from the Project Menu.
Select Add Reference from the Project Menu.
On the COM tab, locate Microsoft Excel Object Library and then click Select.
On the COM tab, locate Microsoft Excel Object Library and then click Select.
Click OK.
Click OK.
Double click the code window and populate the Click event of Button1, as shown below.
' Add the following code snippet on top of Form1.vb
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim appXL As Excel.Application
Dim wbXl As Excel.Workbook
Dim shXL As Excel.Worksheet
Dim raXL As Excel.Range
' Start Excel and get Application object.
appXL = CreateObject("Excel.Application")
appXL.Visible = True
' Add a new workbook.
wbXl = appXL.Workbooks.Add
shXL = wbXl.ActiveSheet
' Add table headers going cell by cell.
shXL.Cells(1, 1).Value = "First Name"
shXL.Cells(1, 2).Value = "Last Name"
shXL.Cells(1, 3).Value = "Full Name"
shXL.Cells(1, 4).Value = "Specialization"
' Format A1:D1 as bold, vertical alignment = center.
With shXL.Range("A1", "D1")
.Font.Bold = True
.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
End With
' Create an array to set multiple values at once.
Dim students(5, 2) As String
students(0, 0) = "Zara"
students(0, 1) = "Ali"
students(1, 0) = "Nuha"
students(1, 1) = "Ali"
students(2, 0) = "Arilia"
students(2, 1) = "RamKumar"
students(3, 0) = "Rita"
students(3, 1) = "Jones"
students(4, 0) = "Umme"
students(4, 1) = "Ayman"
' Fill A2:B6 with an array of values (First and Last Names).
shXL.Range("A2", "B6").Value = students
' Fill C2:C6 with a relative formula (=A2 & " " & B2).
raXL = shXL.Range("C2", "C6")
raXL.Formula = "=A2 & "" "" & B2"
' Fill D2:D6 values.
With shXL
.Cells(2, 4).Value = "Biology"
.Cells(3, 4).Value = "Mathmematics"
.Cells(4, 4).Value = "Physics"
.Cells(5, 4).Value = "Mathmematics"
.Cells(6, 4).Value = "Arabic"
End With
' AutoFit columns A:D.
raXL = shXL.Range("A1", "D1")
raXL.EntireColumn.AutoFit()
' Make sure Excel is visible and give the user control
' of Excel's lifetime.
appXL.Visible = True
appXL.UserControl = True
' Release object references.
raXL = Nothing
shXL = Nothing
wbXl = Nothing
appXL.Quit()
appXL = Nothing
Exit Sub
Err_Handler:
MsgBox(Err.Description, vbCritical, "Error: " & Err.Number)
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window β
Clicking on the Button would display the following excel sheet. You will be asked to save the workbook.
|
[
{
"code": null,
"e": 2554,
"s": 2434,
"text": "VB.Net provides support for interoperability between the COM object model of Microsoft Excel 2010 and your application."
},
{
"code": null,
"e": 2704,
"s": 2554,
"text": "To avail this interoperability in your application, you need to import the namespace Microsoft.Office.Interop.Excel in your Windows Form Application."
},
{
"code": null,
"e": 2867,
"s": 2704,
"text": "Let's start with creating a Window Forms Application by following the following steps in Microsoft Visual Studio: File β New Project β Windows Forms Applications"
},
{
"code": null,
"e": 2963,
"s": 2867,
"text": "Finally, select OK, Microsoft Visual Studio creates your project and displays following Form1."
},
{
"code": null,
"e": 3008,
"s": 2963,
"text": "Insert a Button control Button1 in the form."
},
{
"code": null,
"e": 3088,
"s": 3008,
"text": "Add a reference to Microsoft Excel Object Library to your project. To do this β"
},
{
"code": null,
"e": 3132,
"s": 3088,
"text": "Select Add Reference from the Project Menu."
},
{
"code": null,
"e": 3176,
"s": 3132,
"text": "Select Add Reference from the Project Menu."
},
{
"code": null,
"e": 3253,
"s": 3176,
"text": "On the COM tab, locate Microsoft Excel Object Library and then click Select."
},
{
"code": null,
"e": 3330,
"s": 3253,
"text": "On the COM tab, locate Microsoft Excel Object Library and then click Select."
},
{
"code": null,
"e": 3340,
"s": 3330,
"text": "Click OK."
},
{
"code": null,
"e": 3350,
"s": 3340,
"text": "Click OK."
},
{
"code": null,
"e": 3436,
"s": 3350,
"text": "Double click the code window and populate the Click event of Button1, as shown below."
},
{
"code": null,
"e": 5900,
"s": 3436,
"text": "' Add the following code snippet on top of Form1.vb\nImports Excel = Microsoft.Office.Interop.Excel\nPublic Class Form1\n Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click\n Dim appXL As Excel.Application\n Dim wbXl As Excel.Workbook\n Dim shXL As Excel.Worksheet\n Dim raXL As Excel.Range\n \n ' Start Excel and get Application object.\n appXL = CreateObject(\"Excel.Application\")\n appXL.Visible = True\n \n ' Add a new workbook.\n wbXl = appXL.Workbooks.Add\n shXL = wbXl.ActiveSheet\n \n ' Add table headers going cell by cell.\n shXL.Cells(1, 1).Value = \"First Name\"\n shXL.Cells(1, 2).Value = \"Last Name\"\n shXL.Cells(1, 3).Value = \"Full Name\"\n shXL.Cells(1, 4).Value = \"Specialization\"\n \n ' Format A1:D1 as bold, vertical alignment = center.\n With shXL.Range(\"A1\", \"D1\")\n .Font.Bold = True\n .VerticalAlignment = Excel.XlVAlign.xlVAlignCenter\n End With\n \n ' Create an array to set multiple values at once.\n Dim students(5, 2) As String\n students(0, 0) = \"Zara\"\n students(0, 1) = \"Ali\"\n students(1, 0) = \"Nuha\"\n students(1, 1) = \"Ali\"\n students(2, 0) = \"Arilia\"\n students(2, 1) = \"RamKumar\"\n students(3, 0) = \"Rita\"\n students(3, 1) = \"Jones\"\n students(4, 0) = \"Umme\"\n students(4, 1) = \"Ayman\"\n \n ' Fill A2:B6 with an array of values (First and Last Names).\n shXL.Range(\"A2\", \"B6\").Value = students\n \n ' Fill C2:C6 with a relative formula (=A2 & \" \" & B2).\n raXL = shXL.Range(\"C2\", \"C6\")\n raXL.Formula = \"=A2 & \"\" \"\" & B2\"\n \n ' Fill D2:D6 values.\n With shXL\n .Cells(2, 4).Value = \"Biology\"\n .Cells(3, 4).Value = \"Mathmematics\"\n .Cells(4, 4).Value = \"Physics\"\n .Cells(5, 4).Value = \"Mathmematics\"\n .Cells(6, 4).Value = \"Arabic\"\n End With\n \n ' AutoFit columns A:D.\n raXL = shXL.Range(\"A1\", \"D1\")\n raXL.EntireColumn.AutoFit()\n \n ' Make sure Excel is visible and give the user control\n ' of Excel's lifetime.\n appXL.Visible = True\n appXL.UserControl = True\n \n ' Release object references.\n raXL = Nothing\n shXL = Nothing\n wbXl = Nothing\n appXL.Quit()\n appXL = Nothing\n Exit Sub\nErr_Handler:\n MsgBox(Err.Description, vbCritical, \"Error: \" & Err.Number)\n End Sub\nEnd Class"
},
{
"code": null,
"e": 6046,
"s": 5900,
"text": "When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window β"
}
] |
Viewing all defined variables in Python
|
11 Dec, 2020
In this article, we are going to discuss how to view all defined variables in Python. Viewing all defined variables plays a major role while debugging the code.
Method 1: Using dir() function
dir() is a built-in function to store all the variables inside a program along with the built-in variable functions and methods. It creates a list of all declared and built-in variables. There are two different ways to view all defined variables using dir( ). They are discussed below.
When no user-defined variable starts with β__β :
Define some variables of various types that are not starting with β__β
Call dir and store it in a variable. It stores all the variable names defined before in the form of a list and stores the variable names as a string.
Iterate over the whole list where dir( ) is stored.
Print the item if it doesnβt start with β__β
Example:
Python3
# Define some variables of various types# that are not starting with '__'var2 = "Welcome to geeksforgeeks"var3 = {"1": "a", "2": "b"}var4 = 25var5 = [1, 2, 3, 4, 5]var6 = (58, 59) # call dir and store it in a variable.# It stores all the variable names defined# before in the form of a list# and stores the variable names as a string.all_variables = dir() # Iterate over the whole list where dir( )# is stored.for name in all_variables: # Print the item if it doesn't start with '__' if not name.startswith('__'): myvalue = eval(name) print(name, "is", type(myvalue), "and is equal to ", myvalue)
Output:
var2 is <class βstrβ> and is equal to Welcome to geeksforgeeks
var3 is <class βdictβ> and is equal to {β1β: βaβ, β2β: βbβ}
var4 is <class βintβ> and is equal to 25
var5 is <class βlistβ> and is equal to [1, 2, 3, 4, 5]
var6 is <class βtupleβ> and is equal to (58, 59)
Storing the built-in variables and ignoring them
Create a new variable and store all built-in functions within it using dir( ).
Define some variables of various types.
Again call dir and store it in a list subtracting the built-in variables stored previously.
Iterate over the whole list.
Print the desired items
Example:
Python3
# Create a new variable and store all# built-in functions within it using dir( ).not_my_data = set(dir()) # Define some variables of various types.var2 = "Welcome to geeksforgeeks"var3 = {"1": "a", "2": "b"}var4 = 25var5 = [1, 2, 3, 4, 5]var6 = (58, 59) # Again call dir and store it in a list # subtracting the built-in variables stored# previously.my_data = set(dir()) - not_my_data # Iterate over the whole list is stored.for name in my_data: # Exclude the un-necessary variable named not_my_data if name != "not_my_data": val = eval(name) print(name, "is", type(val), "and is equal to ", val)
Output:
var2 is <class βstrβ> and is equal to Welcome to geeksforgeeks
var3 is <class βdictβ> and is equal to {β1β: βaβ, β2β: βbβ}
var6 is <class βtupleβ> and is equal to (58, 59)
var4 is <class βintβ> and is equal to 25
var5 is <class βlistβ> and is equal to [1, 2, 3, 4, 5]
Method 2: To print local and global variables
Locals() is a built-in function that returns a list of all local variables in that particular scope. And globals() does the same with the global variables.
Approach
Create a list of all global variables using globals( ) function, to store the built-in global variables.
Declare some global variables
Declare a function.
Declare some local variables inside it.
Store all the local variables in a list, using locals keyword.
Iterate over the list and print the local variables.
Store the global variables in a list using globals keyword and subtract the previously created list of built-in global variables from it.
Print them.
Call the function.
Example:
Python3
# Create a list of all global variables using# globals( ) function, To store the built-in# global variables.not_my_data = set(globals()) # Declare some global variablesfoo5 = "hii"foo6 = 7 # Declare a function.def func(): # Declare some local variables inside it. var2 = "Welcome to geeksforgeeks" var3 = {"1": "a", "2": "b"} var4 = 25 var5 = [1, 2, 3, 4, 5] var6 = (58, 59) # Store all the local variables in a list, # using locals keyword. locals_stored = set(locals()) # Iterate over the list and print the local # variables. print("Printing Local Variables") for name in locals_stored: val = eval(name) print(name, "is", type(val), "and is equal to ", val) # Store the global variables in a list using # globals keyword and subtract the previously # created list of built-in global variables from it. globals_stored = set(globals())-not_my_data # Print the global variables print("\nPrinting Global Variables") for name in globals_stored: # Excluding func and not_my_data as they are # also considered as a global variable if name != "not_my_data" and name != "func": val = eval(name) print(name, "is", type(val), "and is equal to ", val) # Call the function.func()
Output:
Printing Local Variables
var2 is <class βstrβ> and is equal to Welcome to geeksforgeeks
var6 is <class βtupleβ> and is equal to (58, 59)
var4 is <class βintβ> and is equal to 25
var5 is <class βlistβ> and is equal to [1, 2, 3, 4, 5]
var3 is <class βdictβ> and is equal to {β1β: βaβ, β2β: βbβ}
Printing Global Variables
foo6 is <class βintβ> and is equal to 7
foo5 is <class βstrβ> and is equal to hii
python-basics
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": "\n11 Dec, 2020"
},
{
"code": null,
"e": 189,
"s": 28,
"text": "In this article, we are going to discuss how to view all defined variables in Python. Viewing all defined variables plays a major role while debugging the code."
},
{
"code": null,
"e": 220,
"s": 189,
"text": "Method 1: Using dir() function"
},
{
"code": null,
"e": 506,
"s": 220,
"text": "dir() is a built-in function to store all the variables inside a program along with the built-in variable functions and methods. It creates a list of all declared and built-in variables. There are two different ways to view all defined variables using dir( ). They are discussed below."
},
{
"code": null,
"e": 555,
"s": 506,
"text": "When no user-defined variable starts with β__β :"
},
{
"code": null,
"e": 626,
"s": 555,
"text": "Define some variables of various types that are not starting with β__β"
},
{
"code": null,
"e": 776,
"s": 626,
"text": "Call dir and store it in a variable. It stores all the variable names defined before in the form of a list and stores the variable names as a string."
},
{
"code": null,
"e": 828,
"s": 776,
"text": "Iterate over the whole list where dir( ) is stored."
},
{
"code": null,
"e": 873,
"s": 828,
"text": "Print the item if it doesnβt start with β__β"
},
{
"code": null,
"e": 882,
"s": 873,
"text": "Example:"
},
{
"code": null,
"e": 890,
"s": 882,
"text": "Python3"
},
{
"code": "# Define some variables of various types# that are not starting with '__'var2 = \"Welcome to geeksforgeeks\"var3 = {\"1\": \"a\", \"2\": \"b\"}var4 = 25var5 = [1, 2, 3, 4, 5]var6 = (58, 59) # call dir and store it in a variable.# It stores all the variable names defined# before in the form of a list# and stores the variable names as a string.all_variables = dir() # Iterate over the whole list where dir( )# is stored.for name in all_variables: # Print the item if it doesn't start with '__' if not name.startswith('__'): myvalue = eval(name) print(name, \"is\", type(myvalue), \"and is equal to \", myvalue)",
"e": 1513,
"s": 890,
"text": null
},
{
"code": null,
"e": 1521,
"s": 1513,
"text": "Output:"
},
{
"code": null,
"e": 1585,
"s": 1521,
"text": "var2 is <class βstrβ> and is equal to Welcome to geeksforgeeks"
},
{
"code": null,
"e": 1646,
"s": 1585,
"text": "var3 is <class βdictβ> and is equal to {β1β: βaβ, β2β: βbβ}"
},
{
"code": null,
"e": 1688,
"s": 1646,
"text": "var4 is <class βintβ> and is equal to 25"
},
{
"code": null,
"e": 1744,
"s": 1688,
"text": "var5 is <class βlistβ> and is equal to [1, 2, 3, 4, 5]"
},
{
"code": null,
"e": 1794,
"s": 1744,
"text": "var6 is <class βtupleβ> and is equal to (58, 59)"
},
{
"code": null,
"e": 1843,
"s": 1794,
"text": "Storing the built-in variables and ignoring them"
},
{
"code": null,
"e": 1922,
"s": 1843,
"text": "Create a new variable and store all built-in functions within it using dir( )."
},
{
"code": null,
"e": 1962,
"s": 1922,
"text": "Define some variables of various types."
},
{
"code": null,
"e": 2054,
"s": 1962,
"text": "Again call dir and store it in a list subtracting the built-in variables stored previously."
},
{
"code": null,
"e": 2083,
"s": 2054,
"text": "Iterate over the whole list."
},
{
"code": null,
"e": 2107,
"s": 2083,
"text": "Print the desired items"
},
{
"code": null,
"e": 2116,
"s": 2107,
"text": "Example:"
},
{
"code": null,
"e": 2124,
"s": 2116,
"text": "Python3"
},
{
"code": "# Create a new variable and store all# built-in functions within it using dir( ).not_my_data = set(dir()) # Define some variables of various types.var2 = \"Welcome to geeksforgeeks\"var3 = {\"1\": \"a\", \"2\": \"b\"}var4 = 25var5 = [1, 2, 3, 4, 5]var6 = (58, 59) # Again call dir and store it in a list # subtracting the built-in variables stored# previously.my_data = set(dir()) - not_my_data # Iterate over the whole list is stored.for name in my_data: # Exclude the un-necessary variable named not_my_data if name != \"not_my_data\": val = eval(name) print(name, \"is\", type(val), \"and is equal to \", val)",
"e": 2748,
"s": 2124,
"text": null
},
{
"code": null,
"e": 2756,
"s": 2748,
"text": "Output:"
},
{
"code": null,
"e": 2820,
"s": 2756,
"text": "var2 is <class βstrβ> and is equal to Welcome to geeksforgeeks"
},
{
"code": null,
"e": 2881,
"s": 2820,
"text": "var3 is <class βdictβ> and is equal to {β1β: βaβ, β2β: βbβ}"
},
{
"code": null,
"e": 2931,
"s": 2881,
"text": "var6 is <class βtupleβ> and is equal to (58, 59)"
},
{
"code": null,
"e": 2973,
"s": 2931,
"text": "var4 is <class βintβ> and is equal to 25"
},
{
"code": null,
"e": 3029,
"s": 2973,
"text": "var5 is <class βlistβ> and is equal to [1, 2, 3, 4, 5]"
},
{
"code": null,
"e": 3076,
"s": 3029,
"text": "Method 2: To print local and global variables "
},
{
"code": null,
"e": 3232,
"s": 3076,
"text": "Locals() is a built-in function that returns a list of all local variables in that particular scope. And globals() does the same with the global variables."
},
{
"code": null,
"e": 3242,
"s": 3232,
"text": "Approach "
},
{
"code": null,
"e": 3347,
"s": 3242,
"text": "Create a list of all global variables using globals( ) function, to store the built-in global variables."
},
{
"code": null,
"e": 3377,
"s": 3347,
"text": "Declare some global variables"
},
{
"code": null,
"e": 3397,
"s": 3377,
"text": "Declare a function."
},
{
"code": null,
"e": 3437,
"s": 3397,
"text": "Declare some local variables inside it."
},
{
"code": null,
"e": 3500,
"s": 3437,
"text": "Store all the local variables in a list, using locals keyword."
},
{
"code": null,
"e": 3553,
"s": 3500,
"text": "Iterate over the list and print the local variables."
},
{
"code": null,
"e": 3691,
"s": 3553,
"text": "Store the global variables in a list using globals keyword and subtract the previously created list of built-in global variables from it."
},
{
"code": null,
"e": 3703,
"s": 3691,
"text": "Print them."
},
{
"code": null,
"e": 3722,
"s": 3703,
"text": "Call the function."
},
{
"code": null,
"e": 3731,
"s": 3722,
"text": "Example:"
},
{
"code": null,
"e": 3739,
"s": 3731,
"text": "Python3"
},
{
"code": "# Create a list of all global variables using# globals( ) function, To store the built-in# global variables.not_my_data = set(globals()) # Declare some global variablesfoo5 = \"hii\"foo6 = 7 # Declare a function.def func(): # Declare some local variables inside it. var2 = \"Welcome to geeksforgeeks\" var3 = {\"1\": \"a\", \"2\": \"b\"} var4 = 25 var5 = [1, 2, 3, 4, 5] var6 = (58, 59) # Store all the local variables in a list, # using locals keyword. locals_stored = set(locals()) # Iterate over the list and print the local # variables. print(\"Printing Local Variables\") for name in locals_stored: val = eval(name) print(name, \"is\", type(val), \"and is equal to \", val) # Store the global variables in a list using # globals keyword and subtract the previously # created list of built-in global variables from it. globals_stored = set(globals())-not_my_data # Print the global variables print(\"\\nPrinting Global Variables\") for name in globals_stored: # Excluding func and not_my_data as they are # also considered as a global variable if name != \"not_my_data\" and name != \"func\": val = eval(name) print(name, \"is\", type(val), \"and is equal to \", val) # Call the function.func()",
"e": 5061,
"s": 3739,
"text": null
},
{
"code": null,
"e": 5069,
"s": 5061,
"text": "Output:"
},
{
"code": null,
"e": 5094,
"s": 5069,
"text": "Printing Local Variables"
},
{
"code": null,
"e": 5158,
"s": 5094,
"text": "var2 is <class βstrβ> and is equal to Welcome to geeksforgeeks"
},
{
"code": null,
"e": 5208,
"s": 5158,
"text": "var6 is <class βtupleβ> and is equal to (58, 59)"
},
{
"code": null,
"e": 5250,
"s": 5208,
"text": "var4 is <class βintβ> and is equal to 25"
},
{
"code": null,
"e": 5306,
"s": 5250,
"text": "var5 is <class βlistβ> and is equal to [1, 2, 3, 4, 5]"
},
{
"code": null,
"e": 5367,
"s": 5306,
"text": "var3 is <class βdictβ> and is equal to {β1β: βaβ, β2β: βbβ}"
},
{
"code": null,
"e": 5393,
"s": 5367,
"text": "Printing Global Variables"
},
{
"code": null,
"e": 5434,
"s": 5393,
"text": "foo6 is <class βintβ> and is equal to 7"
},
{
"code": null,
"e": 5477,
"s": 5434,
"text": "foo5 is <class βstrβ> and is equal to hii"
},
{
"code": null,
"e": 5491,
"s": 5477,
"text": "python-basics"
},
{
"code": null,
"e": 5498,
"s": 5491,
"text": "Python"
},
{
"code": null,
"e": 5596,
"s": 5498,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5628,
"s": 5596,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5655,
"s": 5628,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5676,
"s": 5655,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 5699,
"s": 5676,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 5730,
"s": 5699,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 5786,
"s": 5730,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 5828,
"s": 5786,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 5870,
"s": 5828,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 5909,
"s": 5870,
"text": "Python | Get unique values from a list"
}
] |
How to Select DataFrame Columns by Index in R?
|
28 Nov, 2021
In this article, we will discuss how to select columns by index from a dataframe in R programming language.
Note: The indexing of the columns in the R programming language always starts from 1.
Here, we are going to select columns by using index with the base R in the dataframe.
Syntax:
dataframe[,c(column_indexes)]
Example:
R
# create a dataframe with 3 rows and 4 columnsdata=data.frame(name=c("akash","kyathi","preethi"), subjects=c("java","R","dbms"), marks=c(90,98,78)) # select second and third columnprint(data[,c(2,3)])
Output:
subjects marks
1 java 90
2 R 98
3 dbms 78
We can select by using the index range operator, as shown below.
Syntax:
dataframe[,column_index_start:column_index_end]
where.
column_index_start is the first index number, and column_index_end is the second index number.
Example:
R
# create a dataframe with 3 rows and 4 columnsdata=data.frame(name=c("akash","kyathi","preethi"), subjects=c("java","R","dbms"), marks=c(90,98,78)) # select first to third columnprint(data[,1:3])
Output:
name subjects marks
1 akash java 90
2 kyathi R 98
3 preethi dbms 78
We can exclude the index columns by specifying in the c() vector with a β sign.
Syntax:
dataframe[,-c(column_indexes)]
Example:
R
# create a dataframe with 3 rows and 4 columnsdata=data.frame(name=c("akash","kyathi","preethi"), subjects=c("java","R","dbms"), marks=c(90,98,78)) # exclude second and third columnprint(data[,-c(2,3)])
Output:
[1] "akash" "kyathi" "preethi"
The select() function from the dplyr package is used for selecting column by index.
Syntax:
dataframe %>%
select(column_numbers)
where
%>% operator is to load into dataframe
Syntax to import and install the dpylr package:
install.packages("dplyr")
library("dplyr")
Example:
R
# loads the packagelibrary("dplyr") # create a dataframe with 3 rows and 4 columnsdata = data.frame(name=c("akash", "kyathi", "preethi"), subjects=c("java", "R", "dbms"), marks=c(90, 98, 78)) # select 1 and 3 columnsdata % >%select(1, 3)
Output:
name marks
1 akash 90
2 kyathi 98
3 preethi 78
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 136,
"s": 28,
"text": "In this article, we will discuss how to select columns by index from a dataframe in R programming language."
},
{
"code": null,
"e": 222,
"s": 136,
"text": "Note: The indexing of the columns in the R programming language always starts from 1."
},
{
"code": null,
"e": 308,
"s": 222,
"text": "Here, we are going to select columns by using index with the base R in the dataframe."
},
{
"code": null,
"e": 316,
"s": 308,
"text": "Syntax:"
},
{
"code": null,
"e": 346,
"s": 316,
"text": "dataframe[,c(column_indexes)]"
},
{
"code": null,
"e": 355,
"s": 346,
"text": "Example:"
},
{
"code": null,
"e": 357,
"s": 355,
"text": "R"
},
{
"code": "# create a dataframe with 3 rows and 4 columnsdata=data.frame(name=c(\"akash\",\"kyathi\",\"preethi\"), subjects=c(\"java\",\"R\",\"dbms\"), marks=c(90,98,78)) # select second and third columnprint(data[,c(2,3)])",
"e": 590,
"s": 357,
"text": null
},
{
"code": null,
"e": 598,
"s": 590,
"text": "Output:"
},
{
"code": null,
"e": 666,
"s": 598,
"text": " subjects marks\n1 java 90\n2 R 98\n3 dbms 78"
},
{
"code": null,
"e": 731,
"s": 666,
"text": "We can select by using the index range operator, as shown below."
},
{
"code": null,
"e": 739,
"s": 731,
"text": "Syntax:"
},
{
"code": null,
"e": 787,
"s": 739,
"text": "dataframe[,column_index_start:column_index_end]"
},
{
"code": null,
"e": 794,
"s": 787,
"text": "where."
},
{
"code": null,
"e": 889,
"s": 794,
"text": "column_index_start is the first index number, and column_index_end is the second index number."
},
{
"code": null,
"e": 898,
"s": 889,
"text": "Example:"
},
{
"code": null,
"e": 900,
"s": 898,
"text": "R"
},
{
"code": "# create a dataframe with 3 rows and 4 columnsdata=data.frame(name=c(\"akash\",\"kyathi\",\"preethi\"), subjects=c(\"java\",\"R\",\"dbms\"), marks=c(90,98,78)) # select first to third columnprint(data[,1:3])",
"e": 1127,
"s": 900,
"text": null
},
{
"code": null,
"e": 1135,
"s": 1127,
"text": "Output:"
},
{
"code": null,
"e": 1235,
"s": 1135,
"text": " name subjects marks\n1 akash java 90\n2 kyathi R 98\n3 preethi dbms 78"
},
{
"code": null,
"e": 1315,
"s": 1235,
"text": "We can exclude the index columns by specifying in the c() vector with a β sign."
},
{
"code": null,
"e": 1323,
"s": 1315,
"text": "Syntax:"
},
{
"code": null,
"e": 1354,
"s": 1323,
"text": "dataframe[,-c(column_indexes)]"
},
{
"code": null,
"e": 1363,
"s": 1354,
"text": "Example:"
},
{
"code": null,
"e": 1365,
"s": 1363,
"text": "R"
},
{
"code": "# create a dataframe with 3 rows and 4 columnsdata=data.frame(name=c(\"akash\",\"kyathi\",\"preethi\"), subjects=c(\"java\",\"R\",\"dbms\"), marks=c(90,98,78)) # exclude second and third columnprint(data[,-c(2,3)])",
"e": 1599,
"s": 1365,
"text": null
},
{
"code": null,
"e": 1607,
"s": 1599,
"text": "Output:"
},
{
"code": null,
"e": 1641,
"s": 1607,
"text": "[1] \"akash\" \"kyathi\" \"preethi\""
},
{
"code": null,
"e": 1725,
"s": 1641,
"text": "The select() function from the dplyr package is used for selecting column by index."
},
{
"code": null,
"e": 1733,
"s": 1725,
"text": "Syntax:"
},
{
"code": null,
"e": 1771,
"s": 1733,
"text": "dataframe %>%\n select(column_numbers)"
},
{
"code": null,
"e": 1777,
"s": 1771,
"text": "where"
},
{
"code": null,
"e": 1817,
"s": 1777,
"text": "%>% operator is to load into dataframe"
},
{
"code": null,
"e": 1865,
"s": 1817,
"text": "Syntax to import and install the dpylr package:"
},
{
"code": null,
"e": 1908,
"s": 1865,
"text": "install.packages(\"dplyr\")\nlibrary(\"dplyr\")"
},
{
"code": null,
"e": 1917,
"s": 1908,
"text": "Example:"
},
{
"code": null,
"e": 1919,
"s": 1917,
"text": "R"
},
{
"code": "# loads the packagelibrary(\"dplyr\") # create a dataframe with 3 rows and 4 columnsdata = data.frame(name=c(\"akash\", \"kyathi\", \"preethi\"), subjects=c(\"java\", \"R\", \"dbms\"), marks=c(90, 98, 78)) # select 1 and 3 columnsdata % >%select(1, 3)",
"e": 2195,
"s": 1919,
"text": null
},
{
"code": null,
"e": 2203,
"s": 2195,
"text": "Output:"
},
{
"code": null,
"e": 2267,
"s": 2203,
"text": " name marks\n1 akash 90\n2 kyathi 98\n3 preethi 78"
},
{
"code": null,
"e": 2274,
"s": 2267,
"text": "Picked"
},
{
"code": null,
"e": 2295,
"s": 2274,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 2307,
"s": 2295,
"text": "R-DataFrame"
},
{
"code": null,
"e": 2318,
"s": 2307,
"text": "R Language"
},
{
"code": null,
"e": 2329,
"s": 2318,
"text": "R Programs"
},
{
"code": null,
"e": 2427,
"s": 2329,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2479,
"s": 2427,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 2537,
"s": 2479,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2572,
"s": 2537,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 2610,
"s": 2572,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 2659,
"s": 2610,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2717,
"s": 2659,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2766,
"s": 2717,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2809,
"s": 2766,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 2847,
"s": 2809,
"text": "Merge DataFrames by Column Names in R"
}
] |
Super ASCII String Checker | TCS CodeVita
|
07 Sep, 2021
In the Byteland country, a string S is said to super ASCII string if and only if the count of each character in the string is equal to its ASCII value. In the Byteland country ASCII code of βaβ is 1, βbβ is 2, ..., βzβ is 26. The task is to find out whether the given string is a super ASCII string or not. If true, then print βYesβ otherwise print βNoβ.
Examples:
Input: S = βbbaβ Output: YesExplanation:The count of character βbβ is 2 and the ASCII value of βbβ is also 2.The count of character βaβ is 1. and the ASCII value of βaβ is also 1. Hence, string βbbaβ is super ASCII String.
Input: S = βssbaβOutput: NoExplanation:The count of character βsβ is 2 and the ASCII value of βsβ is 19.The count of character βbβ is 1. and the ASCII value of βbβ is 2.Hence, string βssbaβ is not a super ASCII String.
Approach: The ASCII value of a character βchβ in Byteland can be calculated by the following formula:
The ASCII value of ch = integer equivalent of ch β integer equivalent of βa'(97) + 1
Now, using this formula, the frequency count of each character in the string can be compared with its ASCII value. Follow the below steps to solve the problem:
Initialize an array to store the frequency count of each character of the string.
Traverse the string S and increment the frequency count of each character by 1.
Again, traverse the string S and check if any character has non-zero frequency and is not equal to its ASCII value then print βNoβ.
After the above steps if there doesnβt any such character in the above step then print βYesβ.
Below is the implementation of the above approach:
Python3
C
Java
Python3
C#
import string #for accessing alphabets dicti = {}a = [] #creating a list with the alphabetsfor i in string.ascii_lowercase: a.append(i) #creating a dictionary for the alphabets and correpondind ascii codefor i in string.ascii_lowercase: for j in range (1,27): if (a.index(i)+1) == j: #if the number is equal to the position of the alphabet dicti[i] = j #in the list, then the number will be ascii code for the break #aplhabet in the dictionary s = 'bba't = True #t is initialized as true for i in s: if s.count(i) != dicti[i]: #if any of the alphabet count is not equal to its t = False #corresponding ascii code in the dictionary, t will be false if t: print("Yes") #printing yes if t remains true after checking all alphabetselse: print("No") #code written by jayaselva
// C program for the above approach#include <stdio.h>#include <string.h> // Function to check whether the// string is super ASCII or notvoid checkSuperASCII(char s[]){ // Stores the frequency count // of characters 'a' to 'z' int b[26] = { 0 }; // Traverse the string for (int i = 0; i < strlen(s); i++) { // AscASCIIii value of the // current character int index = (int)s[i] - 97 + 1; // Count frequency of each // character in the string b[index - 1]++; } // Traverse the string for (int i = 0; i < strlen(s); i++) { // ASCII value of the current // character int index = (int)s[i] - 97 + 1; // Check if the frequency of // each character in string // is same as ASCII code or not if (b[index - 1] != index) { printf("No"); return; } } // Else print "Yes" printf("Yes");} // Driver Codeint main(){ // Given string S char s[] = "bba"; // Function Call checkSuperASCII(s); return 0;}
// Java program for the above approachimport java.io.*;import java.util.*; class GFG{ // Function to check whether the// string is super ASCII or notpublic static void checkSuperASCII(String s){ // Stores the frequency count // of characters 'a' to 'z' int b[] = new int[26]; // Traverse the string for(int i = 0; i < s.length(); i++) { // AscASCIIii value of the // current character int index = (int)s.charAt(i) - 97 + 1; // Count frequency of each // character in the string b[index - 1]++; } // Traverse the string for(int i = 0; i < s.length(); i++) { // ASCII value of the current // character int index = (int)s.charAt(i) - 97 + 1; // Check if the frequency of // each character in string // is same as ASCII code or not if (b[index - 1] != index) { System.out.println("No"); return; } } // Else print "Yes" System.out.println("Yes");} // Driver Codepublic static void main(String args[]){ // Given string S String s = "bba"; // Function Call checkSuperASCII(s);}} // This code is contributed by Md Shahbaz Alam
# Python3 program for the above approach # Function to check whether the# string is super ASCII or notdef checkSuperASCII(s): # Stores the frequency count # of characters 'a' to 'z' b = [0 for i in range(26)] # Traverse the string for i in range(len(s)): # AscASCIIii value of the # current character index = ord(s[i]) - 97 + 1; # Count frequency of each # character in the string b[index - 1] += 1 # Traverse the string for i in range(len(s)): # ASCII value of the current # character index = ord(s[i]) - 97 + 1 # Check if the frequency of # each character in string # is same as ASCII code or not if (b[index - 1] != index): print("No") return # Else print "Yes" print("Yes") # Driver Codeif __name__ == '__main__': # Given string S s = "bba" # Function Call checkSuperASCII(s) # This code is contributed by SURENDRA_GANGWAR
// C# program for the above approachusing System;class GFG { // Function to check whether the // string is super ASCII or not static void checkSuperASCII(string s) { // Stores the frequency count // of characters 'a' to 'z' int[] b = new int[26]; // Traverse the string for(int i = 0; i < s.Length; i++) { // AscASCIIii value of the // current character int index = (int)s[i] - 97 + 1; // Count frequency of each // character in the string b[index - 1]++; } // Traverse the string for(int i = 0; i < s.Length; i++) { // ASCII value of the current // character int index = (int)s[i] - 97 + 1; // Check if the frequency of // each character in string // is same as ASCII code or not if (b[index - 1] != index) { Console.WriteLine("No"); return; } } // Else print "Yes" Console.WriteLine("Yes"); } // Driver code static void Main() { // Given string S string s = "bba"; // Function Call checkSuperASCII(s); }} // This code is contributed by divyeshrabadiya07.
Yes
Time Complexity: O(N)Auxiliary Space: O(1)
SURENDRA_GANGWAR
shahbazalam75508
khushboogoyal499
divyeshrabadiya07
jayaselvaravi
interview-preparation
TCS
TCS-coding-questions
TCS-interview-experience
Strings
TCS
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different Methods to Reverse a String in C++
KMP Algorithm for Pattern Searching
Python program to check if a string is palindrome or not
Length of the longest substring without repeating characters
Longest Palindromic Substring | Set 1
Convert string to char array in C++
stringstream in C++ and its Applications
Iterate over characters of a string in C++
Program to add two binary strings
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 409,
"s": 54,
"text": "In the Byteland country, a string S is said to super ASCII string if and only if the count of each character in the string is equal to its ASCII value. In the Byteland country ASCII code of βaβ is 1, βbβ is 2, ..., βzβ is 26. The task is to find out whether the given string is a super ASCII string or not. If true, then print βYesβ otherwise print βNoβ."
},
{
"code": null,
"e": 419,
"s": 409,
"text": "Examples:"
},
{
"code": null,
"e": 642,
"s": 419,
"text": "Input: S = βbbaβ Output: YesExplanation:The count of character βbβ is 2 and the ASCII value of βbβ is also 2.The count of character βaβ is 1. and the ASCII value of βaβ is also 1. Hence, string βbbaβ is super ASCII String."
},
{
"code": null,
"e": 861,
"s": 642,
"text": "Input: S = βssbaβOutput: NoExplanation:The count of character βsβ is 2 and the ASCII value of βsβ is 19.The count of character βbβ is 1. and the ASCII value of βbβ is 2.Hence, string βssbaβ is not a super ASCII String."
},
{
"code": null,
"e": 963,
"s": 861,
"text": "Approach: The ASCII value of a character βchβ in Byteland can be calculated by the following formula:"
},
{
"code": null,
"e": 1048,
"s": 963,
"text": "The ASCII value of ch = integer equivalent of ch β integer equivalent of βa'(97) + 1"
},
{
"code": null,
"e": 1208,
"s": 1048,
"text": "Now, using this formula, the frequency count of each character in the string can be compared with its ASCII value. Follow the below steps to solve the problem:"
},
{
"code": null,
"e": 1290,
"s": 1208,
"text": "Initialize an array to store the frequency count of each character of the string."
},
{
"code": null,
"e": 1370,
"s": 1290,
"text": "Traverse the string S and increment the frequency count of each character by 1."
},
{
"code": null,
"e": 1502,
"s": 1370,
"text": "Again, traverse the string S and check if any character has non-zero frequency and is not equal to its ASCII value then print βNoβ."
},
{
"code": null,
"e": 1596,
"s": 1502,
"text": "After the above steps if there doesnβt any such character in the above step then print βYesβ."
},
{
"code": null,
"e": 1647,
"s": 1596,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1655,
"s": 1647,
"text": "Python3"
},
{
"code": null,
"e": 1657,
"s": 1655,
"text": "C"
},
{
"code": null,
"e": 1662,
"s": 1657,
"text": "Java"
},
{
"code": null,
"e": 1670,
"s": 1662,
"text": "Python3"
},
{
"code": null,
"e": 1673,
"s": 1670,
"text": "C#"
},
{
"code": "import string #for accessing alphabets dicti = {}a = [] #creating a list with the alphabetsfor i in string.ascii_lowercase: a.append(i) #creating a dictionary for the alphabets and correpondind ascii codefor i in string.ascii_lowercase: for j in range (1,27): if (a.index(i)+1) == j: #if the number is equal to the position of the alphabet dicti[i] = j #in the list, then the number will be ascii code for the break #aplhabet in the dictionary s = 'bba't = True #t is initialized as true for i in s: if s.count(i) != dicti[i]: #if any of the alphabet count is not equal to its t = False #corresponding ascii code in the dictionary, t will be false if t: print(\"Yes\") #printing yes if t remains true after checking all alphabetselse: print(\"No\") #code written by jayaselva",
"e": 2545,
"s": 1673,
"text": null
},
{
"code": "// C program for the above approach#include <stdio.h>#include <string.h> // Function to check whether the// string is super ASCII or notvoid checkSuperASCII(char s[]){ // Stores the frequency count // of characters 'a' to 'z' int b[26] = { 0 }; // Traverse the string for (int i = 0; i < strlen(s); i++) { // AscASCIIii value of the // current character int index = (int)s[i] - 97 + 1; // Count frequency of each // character in the string b[index - 1]++; } // Traverse the string for (int i = 0; i < strlen(s); i++) { // ASCII value of the current // character int index = (int)s[i] - 97 + 1; // Check if the frequency of // each character in string // is same as ASCII code or not if (b[index - 1] != index) { printf(\"No\"); return; } } // Else print \"Yes\" printf(\"Yes\");} // Driver Codeint main(){ // Given string S char s[] = \"bba\"; // Function Call checkSuperASCII(s); return 0;}",
"e": 3605,
"s": 2545,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.util.*; class GFG{ // Function to check whether the// string is super ASCII or notpublic static void checkSuperASCII(String s){ // Stores the frequency count // of characters 'a' to 'z' int b[] = new int[26]; // Traverse the string for(int i = 0; i < s.length(); i++) { // AscASCIIii value of the // current character int index = (int)s.charAt(i) - 97 + 1; // Count frequency of each // character in the string b[index - 1]++; } // Traverse the string for(int i = 0; i < s.length(); i++) { // ASCII value of the current // character int index = (int)s.charAt(i) - 97 + 1; // Check if the frequency of // each character in string // is same as ASCII code or not if (b[index - 1] != index) { System.out.println(\"No\"); return; } } // Else print \"Yes\" System.out.println(\"Yes\");} // Driver Codepublic static void main(String args[]){ // Given string S String s = \"bba\"; // Function Call checkSuperASCII(s);}} // This code is contributed by Md Shahbaz Alam",
"e": 4864,
"s": 3605,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to check whether the# string is super ASCII or notdef checkSuperASCII(s): # Stores the frequency count # of characters 'a' to 'z' b = [0 for i in range(26)] # Traverse the string for i in range(len(s)): # AscASCIIii value of the # current character index = ord(s[i]) - 97 + 1; # Count frequency of each # character in the string b[index - 1] += 1 # Traverse the string for i in range(len(s)): # ASCII value of the current # character index = ord(s[i]) - 97 + 1 # Check if the frequency of # each character in string # is same as ASCII code or not if (b[index - 1] != index): print(\"No\") return # Else print \"Yes\" print(\"Yes\") # Driver Codeif __name__ == '__main__': # Given string S s = \"bba\" # Function Call checkSuperASCII(s) # This code is contributed by SURENDRA_GANGWAR",
"e": 5877,
"s": 4864,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG { // Function to check whether the // string is super ASCII or not static void checkSuperASCII(string s) { // Stores the frequency count // of characters 'a' to 'z' int[] b = new int[26]; // Traverse the string for(int i = 0; i < s.Length; i++) { // AscASCIIii value of the // current character int index = (int)s[i] - 97 + 1; // Count frequency of each // character in the string b[index - 1]++; } // Traverse the string for(int i = 0; i < s.Length; i++) { // ASCII value of the current // character int index = (int)s[i] - 97 + 1; // Check if the frequency of // each character in string // is same as ASCII code or not if (b[index - 1] != index) { Console.WriteLine(\"No\"); return; } } // Else print \"Yes\" Console.WriteLine(\"Yes\"); } // Driver code static void Main() { // Given string S string s = \"bba\"; // Function Call checkSuperASCII(s); }} // This code is contributed by divyeshrabadiya07.",
"e": 7255,
"s": 5877,
"text": null
},
{
"code": null,
"e": 7259,
"s": 7255,
"text": "Yes"
},
{
"code": null,
"e": 7304,
"s": 7261,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 7321,
"s": 7304,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 7338,
"s": 7321,
"text": "shahbazalam75508"
},
{
"code": null,
"e": 7355,
"s": 7338,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 7373,
"s": 7355,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 7387,
"s": 7373,
"text": "jayaselvaravi"
},
{
"code": null,
"e": 7409,
"s": 7387,
"text": "interview-preparation"
},
{
"code": null,
"e": 7413,
"s": 7409,
"text": "TCS"
},
{
"code": null,
"e": 7434,
"s": 7413,
"text": "TCS-coding-questions"
},
{
"code": null,
"e": 7459,
"s": 7434,
"text": "TCS-interview-experience"
},
{
"code": null,
"e": 7467,
"s": 7459,
"text": "Strings"
},
{
"code": null,
"e": 7471,
"s": 7467,
"text": "TCS"
},
{
"code": null,
"e": 7479,
"s": 7471,
"text": "Strings"
},
{
"code": null,
"e": 7577,
"s": 7479,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7622,
"s": 7577,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 7658,
"s": 7622,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 7715,
"s": 7658,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 7776,
"s": 7715,
"text": "Length of the longest substring without repeating characters"
},
{
"code": null,
"e": 7814,
"s": 7776,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 7850,
"s": 7814,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 7891,
"s": 7850,
"text": "stringstream in C++ and its Applications"
},
{
"code": null,
"e": 7934,
"s": 7891,
"text": "Iterate over characters of a string in C++"
},
{
"code": null,
"e": 7968,
"s": 7934,
"text": "Program to add two binary strings"
}
] |
Shorthand Syntax for Object Property Value in ES6
|
20 May, 2020
Objects in JavaScript are the most important data-type and forms the building blocks for modern JavaScript. These objects are quite different from JavaScript primitive data-types (Number, String, Boolean, null, undefined, and symbol) in the sense that while these primitive data-types all store a single value each (depending on their types).
The shorthand syntax for object property value is very popular and widely used nowadays. The code looks cleaner and easy to read. The shorthand property makes the code size smaller and simpler.
Example: This example displaying the details of object using shorthand Syntax for object property value in ES6.
// Object property shorthandconst name = 'Raj'const age = 20const location = 'India' // User with ES6 shorthand// property const user = { name, age, location} console.log(user)
Output:
Example: This example displaying the details of the object without using shorthand Syntax for object property value.
// Object property shorthandconst name = 'Raj'const age = 20const location = 'India' // User without ES6 // shorthand property const user = { name: name, age: age, location: location} console.log(user)
Output:
ES6
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How do you run JavaScript script through the Terminal?
Hide or show elements in HTML using display property
Send unlimited Whatsapp messages using JavaScript
Set the value of an input field in JavaScript
Node.js | fs.writeFileSync() Method
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 May, 2020"
},
{
"code": null,
"e": 371,
"s": 28,
"text": "Objects in JavaScript are the most important data-type and forms the building blocks for modern JavaScript. These objects are quite different from JavaScript primitive data-types (Number, String, Boolean, null, undefined, and symbol) in the sense that while these primitive data-types all store a single value each (depending on their types)."
},
{
"code": null,
"e": 565,
"s": 371,
"text": "The shorthand syntax for object property value is very popular and widely used nowadays. The code looks cleaner and easy to read. The shorthand property makes the code size smaller and simpler."
},
{
"code": null,
"e": 677,
"s": 565,
"text": "Example: This example displaying the details of object using shorthand Syntax for object property value in ES6."
},
{
"code": "// Object property shorthandconst name = 'Raj'const age = 20const location = 'India' // User with ES6 shorthand// property const user = { name, age, location} console.log(user) ",
"e": 872,
"s": 677,
"text": null
},
{
"code": null,
"e": 880,
"s": 872,
"text": "Output:"
},
{
"code": null,
"e": 997,
"s": 880,
"text": "Example: This example displaying the details of the object without using shorthand Syntax for object property value."
},
{
"code": "// Object property shorthandconst name = 'Raj'const age = 20const location = 'India' // User without ES6 // shorthand property const user = { name: name, age: age, location: location} console.log(user) ",
"e": 1217,
"s": 997,
"text": null
},
{
"code": null,
"e": 1225,
"s": 1217,
"text": "Output:"
},
{
"code": null,
"e": 1229,
"s": 1225,
"text": "ES6"
},
{
"code": null,
"e": 1245,
"s": 1229,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 1256,
"s": 1245,
"text": "JavaScript"
},
{
"code": null,
"e": 1273,
"s": 1256,
"text": "Web Technologies"
},
{
"code": null,
"e": 1300,
"s": 1273,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1398,
"s": 1300,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1453,
"s": 1398,
"text": "How do you run JavaScript script through the Terminal?"
},
{
"code": null,
"e": 1506,
"s": 1453,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 1556,
"s": 1506,
"text": "Send unlimited Whatsapp messages using JavaScript"
},
{
"code": null,
"e": 1602,
"s": 1556,
"text": "Set the value of an input field in JavaScript"
},
{
"code": null,
"e": 1638,
"s": 1602,
"text": "Node.js | fs.writeFileSync() Method"
},
{
"code": null,
"e": 1700,
"s": 1638,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1733,
"s": 1700,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1794,
"s": 1733,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1844,
"s": 1794,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
HTML <legend> Tag
|
06 Jun, 2022
The legend tag is used to define the title for the child contents. The legend elements are the parent element. This tag is used to define the caption for the <fieldset> element.
Syntax
<legend> Text </legend>
Attribute :
align: It sets the alignment of the legend element.
Example 1:
html
<!DOCTYPE html><html> <head> </head> <body> <h1>GeeksforGeeks</h1> <strong>HTML Legend Tag</strong> <form> <fieldset> <!-- Legend tag using --> <legend>STUDENT::</legend> <label>Name:</label> <input type="text"> <br><br> <label>Email:</label> <input type="text"> <br><br> <label>Date of birth:</label> <input type="text"> <br><br> <label>Address:</label> <input type="text"> <br><br> <label>Enroll No:</label> <input type="text"> </fieldset> </form> </body></html>
Output:
Example 2: Styling the legend tag using CSS properties.
html
<!DOCTYPE html><html> <head> <style> form{ width: 50%; } legend { display: block; padding-left: 10px; padding-right: 10px; border: 3px solid green; background-color:tomato; color:white;; } label { display: inline-block; float: left; clear: left; width: 90px; margin:5px; text-align: left; } input[type="text"] { width:250px; margin:5px 0px; } .gfg { font-size:40px; color:green; font-weight:bold; } </style> </head> <body> <div class = "gfg">GeeksforGeeks</div> <h2>HTML Legend Tag</h2> <form> <fieldset> <!-- Legend tag using --> <legend>STUDENT:</legend> <label>Name:</label> <input type="text"> <br> <label>Email:</label> <input type="text"> <br> <label>Date of birth:</label> <input type="text"> <br> <label>Address:</label> <input type="text"> <br> <label>Enroll No:</label> <input type="text"> </fieldset> </form> </body></html>
Output:
Supported Browsers:
Google Chrome 1 and above
Edge 12 and above
Internet Explorer 6 and above
Firefox 1 and above
Opera 12.1 and above
Safari 3 and above
nidhi_biet
ghoshsuman0129
saurabh1990aror
chhabradhanvi
kumargaurav97520
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n06 Jun, 2022"
},
{
"code": null,
"e": 231,
"s": 53,
"text": "The legend tag is used to define the title for the child contents. The legend elements are the parent element. This tag is used to define the caption for the <fieldset> element."
},
{
"code": null,
"e": 238,
"s": 231,
"text": "Syntax"
},
{
"code": null,
"e": 262,
"s": 238,
"text": "<legend> Text </legend>"
},
{
"code": null,
"e": 275,
"s": 262,
"text": "Attribute : "
},
{
"code": null,
"e": 327,
"s": 275,
"text": "align: It sets the alignment of the legend element."
},
{
"code": null,
"e": 339,
"s": 327,
"text": "Example 1: "
},
{
"code": null,
"e": 344,
"s": 339,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> </head> <body> <h1>GeeksforGeeks</h1> <strong>HTML Legend Tag</strong> <form> <fieldset> <!-- Legend tag using --> <legend>STUDENT::</legend> <label>Name:</label> <input type=\"text\"> <br><br> <label>Email:</label> <input type=\"text\"> <br><br> <label>Date of birth:</label> <input type=\"text\"> <br><br> <label>Address:</label> <input type=\"text\"> <br><br> <label>Enroll No:</label> <input type=\"text\"> </fieldset> </form> </body></html>",
"e": 1111,
"s": 344,
"text": null
},
{
"code": null,
"e": 1120,
"s": 1111,
"text": "Output: "
},
{
"code": null,
"e": 1178,
"s": 1120,
"text": "Example 2: Styling the legend tag using CSS properties. "
},
{
"code": null,
"e": 1183,
"s": 1178,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <style> form{ width: 50%; } legend { display: block; padding-left: 10px; padding-right: 10px; border: 3px solid green; background-color:tomato; color:white;; } label { display: inline-block; float: left; clear: left; width: 90px; margin:5px; text-align: left; } input[type=\"text\"] { width:250px; margin:5px 0px; } .gfg { font-size:40px; color:green; font-weight:bold; } </style> </head> <body> <div class = \"gfg\">GeeksforGeeks</div> <h2>HTML Legend Tag</h2> <form> <fieldset> <!-- Legend tag using --> <legend>STUDENT:</legend> <label>Name:</label> <input type=\"text\"> <br> <label>Email:</label> <input type=\"text\"> <br> <label>Date of birth:</label> <input type=\"text\"> <br> <label>Address:</label> <input type=\"text\"> <br> <label>Enroll No:</label> <input type=\"text\"> </fieldset> </form> </body></html>",
"e": 2710,
"s": 1183,
"text": null
},
{
"code": null,
"e": 2719,
"s": 2710,
"text": "Output: "
},
{
"code": null,
"e": 2740,
"s": 2719,
"text": "Supported Browsers: "
},
{
"code": null,
"e": 2766,
"s": 2740,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 2784,
"s": 2766,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 2814,
"s": 2784,
"text": "Internet Explorer 6 and above"
},
{
"code": null,
"e": 2834,
"s": 2814,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 2855,
"s": 2834,
"text": "Opera 12.1 and above"
},
{
"code": null,
"e": 2874,
"s": 2855,
"text": "Safari 3 and above"
},
{
"code": null,
"e": 2885,
"s": 2874,
"text": "nidhi_biet"
},
{
"code": null,
"e": 2900,
"s": 2885,
"text": "ghoshsuman0129"
},
{
"code": null,
"e": 2916,
"s": 2900,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 2930,
"s": 2916,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 2947,
"s": 2930,
"text": "kumargaurav97520"
},
{
"code": null,
"e": 2957,
"s": 2947,
"text": "HTML-Tags"
},
{
"code": null,
"e": 2962,
"s": 2957,
"text": "HTML"
},
{
"code": null,
"e": 2967,
"s": 2962,
"text": "HTML"
}
] |
Association Rule Mining in R Programming
|
22 Jun, 2020
Association Rule Mining in R Language is an Unsupervised Non-linear algorithm to uncover how the items are associated with each other. In it, frequent Mining shows which items appear together in a transaction or relation. Itβs majorly used by retailers, grocery stores, an online marketplace that has a large transactional database. The same way when any online social media, marketplace, and e-commerce websites know what you buy next using recommendations engines. The recommendations you get on item or variable, while you check out the order is because of Association rule mining boarded on past customer data. There are three common ways to measure association:
Support
Confidence
Lift
In association rule mining, Support, Confidence, and Lift measure association.
Support says how popular an item is, as measured in the proportion of transactions in which an item set appears.
Confidence says how likely item Y is purchased when item X is purchased, expressed as {X -> Y}.Thus it is measured by the proportion of transaction with item X in which item Y also appears. Confidence might misrepresent the importance of association.
Lift says how likely item Y is purchased when item X is purchased while controlling for how popular item Y is.
Apriori Algorithm is also used in association rule mining for discovering frequent itemsets in the transactions database. It was proposed by Agrawal & Srikant in 1993.
Example:A customer does 4 transactions with you. In the first transaction, she buys 1 apple, 1 beer, 1 rice, and 1 chicken. In the second transaction, she buys 1 apple, 1 beer, 1 rice. In the third transaction, she buys 1 apple, 1 beer only. In fourth transactions, she buys 1 apple and 1 orange.
Support(Apple) = 4/4
So, Support of {Apple} is 4 out of 4 or 100%
Confidence(Apple -> Beer) = Support(Apple, Beer)/Support(Apple)
= (3/4)/(4/4)
= 3/4
So, Confidence of {Apple -> Beer} is 3 out of 4 or 75%
Lift(Beer -> Rice) = Support(Beer, Rice)/(Support(Beer) * Support(Rice))
= (2/4)/(3/4) * (2/4)
= 1.33
So, Lift value is greater than 1 implies Rice is likely to be bought if Beer is bought.
Market Basket dataset consists of 15010 observations with Date, Time, Transaction and Item feature or columns. The date variable or column ranges from 30/10/2016 to 09/04/2017. Time is a categorical variable that tells the time. Transaction is a quantitative variable that helps in differentiation of transactions. Item is a categorical variable that links with a product.
# Loading datadataset = read.transactions('Market_Basket_Optimisation.csv', sep = ', ', rm.duplicates = TRUE) # Structure str(dataset)
Using the Association Rule Mining algorithm on the dataset which includes 15010 observations.
# Installing Packagesinstall.packages("arules")install.packages("arulesViz") # Loading packagelibrary(arules)library(arulesViz) # Fitting model# Training Apriori on the datasetset.seed = 220 # Setting seedassocia_rules = apriori(data = dataset, parameter = list(support = 0.004, confidence = 0.2)) # PlotitemFrequencyPlot(dataset, topN = 10) # Visualising the resultsinspect(sort(associa_rules, by = 'lift')[1:10])plot(associa_rules, method = "graph", measure = "confidence", shading = "lift")
Output:
Model associa_rules:The model minimum length is 1, the maximum length is 10, and the target rules with absolute support count 30.
The model minimum length is 1, the maximum length is 10, and the target rules with absolute support count 30.
Item Frequency Plot:So, mineral water is the best selling product followed by eggs, spaghetti, french fries, etc.
So, mineral water is the best selling product followed by eggs, spaghetti, french fries, etc.
Visualizing the model:So, the plot of graphs of 100 is displayed.
So, the plot of graphs of 100 is displayed.
So, Association rule mining is widely used in Recommendation systems in E-Commerce, online marketplace and Social Media websites, etc, and widely used in the industry.
R Machine-Learning
Machine Learning
R Language
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 695,
"s": 28,
"text": "Association Rule Mining in R Language is an Unsupervised Non-linear algorithm to uncover how the items are associated with each other. In it, frequent Mining shows which items appear together in a transaction or relation. Itβs majorly used by retailers, grocery stores, an online marketplace that has a large transactional database. The same way when any online social media, marketplace, and e-commerce websites know what you buy next using recommendations engines. The recommendations you get on item or variable, while you check out the order is because of Association rule mining boarded on past customer data. There are three common ways to measure association:"
},
{
"code": null,
"e": 703,
"s": 695,
"text": "Support"
},
{
"code": null,
"e": 714,
"s": 703,
"text": "Confidence"
},
{
"code": null,
"e": 719,
"s": 714,
"text": "Lift"
},
{
"code": null,
"e": 798,
"s": 719,
"text": "In association rule mining, Support, Confidence, and Lift measure association."
},
{
"code": null,
"e": 911,
"s": 798,
"text": "Support says how popular an item is, as measured in the proportion of transactions in which an item set appears."
},
{
"code": null,
"e": 1162,
"s": 911,
"text": "Confidence says how likely item Y is purchased when item X is purchased, expressed as {X -> Y}.Thus it is measured by the proportion of transaction with item X in which item Y also appears. Confidence might misrepresent the importance of association."
},
{
"code": null,
"e": 1273,
"s": 1162,
"text": "Lift says how likely item Y is purchased when item X is purchased while controlling for how popular item Y is."
},
{
"code": null,
"e": 1441,
"s": 1273,
"text": "Apriori Algorithm is also used in association rule mining for discovering frequent itemsets in the transactions database. It was proposed by Agrawal & Srikant in 1993."
},
{
"code": null,
"e": 1738,
"s": 1441,
"text": "Example:A customer does 4 transactions with you. In the first transaction, she buys 1 apple, 1 beer, 1 rice, and 1 chicken. In the second transaction, she buys 1 apple, 1 beer, 1 rice. In the third transaction, she buys 1 apple, 1 beer only. In fourth transactions, she buys 1 apple and 1 orange."
},
{
"code": null,
"e": 2231,
"s": 1738,
"text": "Support(Apple) = 4/4 \n\nSo, Support of {Apple} is 4 out of 4 or 100%\n\nConfidence(Apple -> Beer) = Support(Apple, Beer)/Support(Apple)\n = (3/4)/(4/4)\n = 3/4\n\nSo, Confidence of {Apple -> Beer} is 3 out of 4 or 75%\n\nLift(Beer -> Rice) = Support(Beer, Rice)/(Support(Beer) * Support(Rice))\n = (2/4)/(3/4) * (2/4)\n = 1.33\n\nSo, Lift value is greater than 1 implies Rice is likely to be bought if Beer is bought.\n"
},
{
"code": null,
"e": 2604,
"s": 2231,
"text": "Market Basket dataset consists of 15010 observations with Date, Time, Transaction and Item feature or columns. The date variable or column ranges from 30/10/2016 to 09/04/2017. Time is a categorical variable that tells the time. Transaction is a quantitative variable that helps in differentiation of transactions. Item is a categorical variable that links with a product."
},
{
"code": "# Loading datadataset = read.transactions('Market_Basket_Optimisation.csv', sep = ', ', rm.duplicates = TRUE) # Structure str(dataset)",
"e": 2767,
"s": 2604,
"text": null
},
{
"code": null,
"e": 2861,
"s": 2767,
"text": "Using the Association Rule Mining algorithm on the dataset which includes 15010 observations."
},
{
"code": "# Installing Packagesinstall.packages(\"arules\")install.packages(\"arulesViz\") # Loading packagelibrary(arules)library(arulesViz) # Fitting model# Training Apriori on the datasetset.seed = 220 # Setting seedassocia_rules = apriori(data = dataset, parameter = list(support = 0.004, confidence = 0.2)) # PlotitemFrequencyPlot(dataset, topN = 10) # Visualising the resultsinspect(sort(associa_rules, by = 'lift')[1:10])plot(associa_rules, method = \"graph\", measure = \"confidence\", shading = \"lift\")",
"e": 3429,
"s": 2861,
"text": null
},
{
"code": null,
"e": 3437,
"s": 3429,
"text": "Output:"
},
{
"code": null,
"e": 3567,
"s": 3437,
"text": "Model associa_rules:The model minimum length is 1, the maximum length is 10, and the target rules with absolute support count 30."
},
{
"code": null,
"e": 3677,
"s": 3567,
"text": "The model minimum length is 1, the maximum length is 10, and the target rules with absolute support count 30."
},
{
"code": null,
"e": 3791,
"s": 3677,
"text": "Item Frequency Plot:So, mineral water is the best selling product followed by eggs, spaghetti, french fries, etc."
},
{
"code": null,
"e": 3885,
"s": 3791,
"text": "So, mineral water is the best selling product followed by eggs, spaghetti, french fries, etc."
},
{
"code": null,
"e": 3951,
"s": 3885,
"text": "Visualizing the model:So, the plot of graphs of 100 is displayed."
},
{
"code": null,
"e": 3995,
"s": 3951,
"text": "So, the plot of graphs of 100 is displayed."
},
{
"code": null,
"e": 4163,
"s": 3995,
"text": "So, Association rule mining is widely used in Recommendation systems in E-Commerce, online marketplace and Social Media websites, etc, and widely used in the industry."
},
{
"code": null,
"e": 4182,
"s": 4163,
"text": "R Machine-Learning"
},
{
"code": null,
"e": 4199,
"s": 4182,
"text": "Machine Learning"
},
{
"code": null,
"e": 4210,
"s": 4199,
"text": "R Language"
},
{
"code": null,
"e": 4227,
"s": 4210,
"text": "Machine Learning"
}
] |
Unicodedata β Unicode Database in Python
|
19 Nov, 2020
Unicode Character Database (UCD) is defined by Unicode Standard Annex #44 which defines the character properties for all unicode characters. This module provides access to UCD and uses the same symbols and names as defined by the Unicode Character Database.
Functions defined by the module :
unicodedata.lookup(name)This function looks up for the character by name. If a character with the given name is found in the database, then, the corresponding character is returned otherwise Keyerror is raised.Example :import unicodedata print (unicodedata.lookup('LEFT CURLY BRACKET'))print (unicodedata.lookup('RIGHT CURLY BRACKET'))print (unicodedata.lookup('ASTERISK')) # gives error as there is # no symbol called ASTER# print (unicodedata.lookup('ASTER'))Output :{
}
*
Example :
import unicodedata print (unicodedata.lookup('LEFT CURLY BRACKET'))print (unicodedata.lookup('RIGHT CURLY BRACKET'))print (unicodedata.lookup('ASTERISK')) # gives error as there is # no symbol called ASTER# print (unicodedata.lookup('ASTER'))
Output :
{
}
*
unicodedata.name(chr[, default])This function returns the name assigned to the given character as a string. If no name is defined, default is returned by the function otherwise ValueError is raised if name is not given.Example :import unicodedata print (unicodedata.name(u'/'))print (unicodedata.name(u'|'))print (unicodedata.name(u':'))Output :SOLIDUS
VERTICAL LINE
COLON
Example :
import unicodedata print (unicodedata.name(u'/'))print (unicodedata.name(u'|'))print (unicodedata.name(u':'))
Output :
SOLIDUS
VERTICAL LINE
COLON
unicodedata.decimal(chr[, default])This function returns the decimal value assigned to the given character as integer. If no value is defined, default is returned by the function otherwise ValueError is raised if value is not given.Example :import unicodedata print (unicodedata.decimal(u'9'))print (unicodedata.decimal(u'a'))Output :9
Traceback (most recent call last):
File "7e736755dd176cd0169eeea6f5d32057.py", line 4, in
print unicodedata.decimal(u'a')
ValueError: not a decimal
Example :
import unicodedata print (unicodedata.decimal(u'9'))print (unicodedata.decimal(u'a'))
Output :
9
Traceback (most recent call last):
File "7e736755dd176cd0169eeea6f5d32057.py", line 4, in
print unicodedata.decimal(u'a')
ValueError: not a decimal
unicodedata.digit(chr[, default])This function returns the digit value assigned to the given character as integer. If no value is defined, default is returned by the function otherwise ValueError is raised if value is not given.Example :import unicodedata print (unicodedata.decimal(u'9'))print (unicodedata.decimal(u'143'))Output :9
Traceback (most recent call last):
File "ad47ae996380a777426cc1431ec4a8cd.py", line 4, in
print unicodedata.decimal(u'143')
TypeError: need a single Unicode character as parameter
Example :
import unicodedata print (unicodedata.decimal(u'9'))print (unicodedata.decimal(u'143'))
Output :
9
Traceback (most recent call last):
File "ad47ae996380a777426cc1431ec4a8cd.py", line 4, in
print unicodedata.decimal(u'143')
TypeError: need a single Unicode character as parameter
unicodedata.numeric(chr[, default])This function returns the numeric value assigned to the given character as integer. If no value is defined, default is returned by the function otherwise ValueError is raised if value is not given.Example :import unicodedata print (unicodedata.decimal(u'9'))print (unicodedata.decimal(u'143'))Output :9
Traceback (most recent call last):
File "ad47ae996380a777426cc1431ec4a8cd.py", line 4, in
print unicodedata.decimal(u'143')
TypeError: need a single Unicode character as parameter
Example :
import unicodedata print (unicodedata.decimal(u'9'))print (unicodedata.decimal(u'143'))
Output :
9
Traceback (most recent call last):
File "ad47ae996380a777426cc1431ec4a8cd.py", line 4, in
print unicodedata.decimal(u'143')
TypeError: need a single Unicode character as parameter
unicodedata.category(chr)This function returns the general category assigned to the given character as string. For example, it returns βLβ for letter and βuβ for uppercase.Example :import unicodedata print (unicodedata.category(u'A'))print (unicodedata.category(u'b'))Output :Lu
Ll
Example :
import unicodedata print (unicodedata.category(u'A'))print (unicodedata.category(u'b'))
Output :
Lu
Ll
unicodedata.bidirectional(chr)This function returns the bidirectional class assigned to the given character as string. For example, it returns βAβ for arabic and βNβ for number. An empty string is returned by this function if no such value is defined.Example :import unicodedata print (unicodedata.bidirectional(u'\u0660'))Output :AN
Example :
import unicodedata print (unicodedata.bidirectional(u'\u0660'))
Output :
AN
unicodedata.normalize(form, unistr)This function returns the normal form for the Unicode string unistr. Valid values for form are βNFCβ, βNFKCβ, βNFDβ, and βNFKDβ.Example :from unicodedata import normalize print ('%r' % normalize('NFD', u'\u00C7'))print ('%r' % normalize('NFC', u'C\u0327'))print ('%r' % normalize('NFKD', u'\u2460'))Output :u'C\u0327'
u'\xc7'
u'1'
Example :
from unicodedata import normalize print ('%r' % normalize('NFD', u'\u00C7'))print ('%r' % normalize('NFC', u'C\u0327'))print ('%r' % normalize('NFKD', u'\u2460'))
Output :
u'C\u0327'
u'\xc7'
u'1'
This article is contributed by Aditi Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. 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.
Python-Library
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
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": 53,
"s": 25,
"text": "\n19 Nov, 2020"
},
{
"code": null,
"e": 311,
"s": 53,
"text": "Unicode Character Database (UCD) is defined by Unicode Standard Annex #44 which defines the character properties for all unicode characters. This module provides access to UCD and uses the same symbols and names as defined by the Unicode Character Database."
},
{
"code": null,
"e": 345,
"s": 311,
"text": "Functions defined by the module :"
},
{
"code": null,
"e": 824,
"s": 345,
"text": "unicodedata.lookup(name)This function looks up for the character by name. If a character with the given name is found in the database, then, the corresponding character is returned otherwise Keyerror is raised.Example :import unicodedata print (unicodedata.lookup('LEFT CURLY BRACKET'))print (unicodedata.lookup('RIGHT CURLY BRACKET'))print (unicodedata.lookup('ASTERISK')) # gives error as there is # no symbol called ASTER# print (unicodedata.lookup('ASTER'))Output :{\n}\n*\n"
},
{
"code": null,
"e": 834,
"s": 824,
"text": "Example :"
},
{
"code": "import unicodedata print (unicodedata.lookup('LEFT CURLY BRACKET'))print (unicodedata.lookup('RIGHT CURLY BRACKET'))print (unicodedata.lookup('ASTERISK')) # gives error as there is # no symbol called ASTER# print (unicodedata.lookup('ASTER'))",
"e": 1080,
"s": 834,
"text": null
},
{
"code": null,
"e": 1089,
"s": 1080,
"text": "Output :"
},
{
"code": null,
"e": 1096,
"s": 1089,
"text": "{\n}\n*\n"
},
{
"code": null,
"e": 1472,
"s": 1096,
"text": "unicodedata.name(chr[, default])This function returns the name assigned to the given character as a string. If no name is defined, default is returned by the function otherwise ValueError is raised if name is not given.Example :import unicodedata print (unicodedata.name(u'/'))print (unicodedata.name(u'|'))print (unicodedata.name(u':'))Output :SOLIDUS\nVERTICAL LINE\nCOLON\n"
},
{
"code": null,
"e": 1482,
"s": 1472,
"text": "Example :"
},
{
"code": "import unicodedata print (unicodedata.name(u'/'))print (unicodedata.name(u'|'))print (unicodedata.name(u':'))",
"e": 1594,
"s": 1482,
"text": null
},
{
"code": null,
"e": 1603,
"s": 1594,
"text": "Output :"
},
{
"code": null,
"e": 1632,
"s": 1603,
"text": "SOLIDUS\nVERTICAL LINE\nCOLON\n"
},
{
"code": null,
"e": 2126,
"s": 1632,
"text": "unicodedata.decimal(chr[, default])This function returns the decimal value assigned to the given character as integer. If no value is defined, default is returned by the function otherwise ValueError is raised if value is not given.Example :import unicodedata print (unicodedata.decimal(u'9'))print (unicodedata.decimal(u'a'))Output :9\nTraceback (most recent call last):\n File \"7e736755dd176cd0169eeea6f5d32057.py\", line 4, in \n print unicodedata.decimal(u'a')\nValueError: not a decimal\n"
},
{
"code": null,
"e": 2136,
"s": 2126,
"text": "Example :"
},
{
"code": "import unicodedata print (unicodedata.decimal(u'9'))print (unicodedata.decimal(u'a'))",
"e": 2224,
"s": 2136,
"text": null
},
{
"code": null,
"e": 2233,
"s": 2224,
"text": "Output :"
},
{
"code": null,
"e": 2391,
"s": 2233,
"text": "9\nTraceback (most recent call last):\n File \"7e736755dd176cd0169eeea6f5d32057.py\", line 4, in \n print unicodedata.decimal(u'a')\nValueError: not a decimal\n"
},
{
"code": null,
"e": 2915,
"s": 2391,
"text": "unicodedata.digit(chr[, default])This function returns the digit value assigned to the given character as integer. If no value is defined, default is returned by the function otherwise ValueError is raised if value is not given.Example :import unicodedata print (unicodedata.decimal(u'9'))print (unicodedata.decimal(u'143'))Output :9\nTraceback (most recent call last):\n File \"ad47ae996380a777426cc1431ec4a8cd.py\", line 4, in \n print unicodedata.decimal(u'143')\nTypeError: need a single Unicode character as parameter\n"
},
{
"code": null,
"e": 2925,
"s": 2915,
"text": "Example :"
},
{
"code": "import unicodedata print (unicodedata.decimal(u'9'))print (unicodedata.decimal(u'143'))",
"e": 3015,
"s": 2925,
"text": null
},
{
"code": null,
"e": 3024,
"s": 3015,
"text": "Output :"
},
{
"code": null,
"e": 3214,
"s": 3024,
"text": "9\nTraceback (most recent call last):\n File \"ad47ae996380a777426cc1431ec4a8cd.py\", line 4, in \n print unicodedata.decimal(u'143')\nTypeError: need a single Unicode character as parameter\n"
},
{
"code": null,
"e": 3742,
"s": 3214,
"text": "unicodedata.numeric(chr[, default])This function returns the numeric value assigned to the given character as integer. If no value is defined, default is returned by the function otherwise ValueError is raised if value is not given.Example :import unicodedata print (unicodedata.decimal(u'9'))print (unicodedata.decimal(u'143'))Output :9\nTraceback (most recent call last):\n File \"ad47ae996380a777426cc1431ec4a8cd.py\", line 4, in \n print unicodedata.decimal(u'143')\nTypeError: need a single Unicode character as parameter\n"
},
{
"code": null,
"e": 3752,
"s": 3742,
"text": "Example :"
},
{
"code": "import unicodedata print (unicodedata.decimal(u'9'))print (unicodedata.decimal(u'143'))",
"e": 3842,
"s": 3752,
"text": null
},
{
"code": null,
"e": 3851,
"s": 3842,
"text": "Output :"
},
{
"code": null,
"e": 4041,
"s": 3851,
"text": "9\nTraceback (most recent call last):\n File \"ad47ae996380a777426cc1431ec4a8cd.py\", line 4, in \n print unicodedata.decimal(u'143')\nTypeError: need a single Unicode character as parameter\n"
},
{
"code": null,
"e": 4326,
"s": 4041,
"text": "unicodedata.category(chr)This function returns the general category assigned to the given character as string. For example, it returns βLβ for letter and βuβ for uppercase.Example :import unicodedata print (unicodedata.category(u'A'))print (unicodedata.category(u'b'))Output :Lu\nLl\n"
},
{
"code": null,
"e": 4336,
"s": 4326,
"text": "Example :"
},
{
"code": "import unicodedata print (unicodedata.category(u'A'))print (unicodedata.category(u'b'))",
"e": 4426,
"s": 4336,
"text": null
},
{
"code": null,
"e": 4435,
"s": 4426,
"text": "Output :"
},
{
"code": null,
"e": 4442,
"s": 4435,
"text": "Lu\nLl\n"
},
{
"code": null,
"e": 4779,
"s": 4442,
"text": "unicodedata.bidirectional(chr)This function returns the bidirectional class assigned to the given character as string. For example, it returns βAβ for arabic and βNβ for number. An empty string is returned by this function if no such value is defined.Example :import unicodedata print (unicodedata.bidirectional(u'\\u0660'))Output :AN\n"
},
{
"code": null,
"e": 4789,
"s": 4779,
"text": "Example :"
},
{
"code": "import unicodedata print (unicodedata.bidirectional(u'\\u0660'))",
"e": 4855,
"s": 4789,
"text": null
},
{
"code": null,
"e": 4864,
"s": 4855,
"text": "Output :"
},
{
"code": null,
"e": 4868,
"s": 4864,
"text": "AN\n"
},
{
"code": null,
"e": 5237,
"s": 4868,
"text": "unicodedata.normalize(form, unistr)This function returns the normal form for the Unicode string unistr. Valid values for form are βNFCβ, βNFKCβ, βNFDβ, and βNFKDβ.Example :from unicodedata import normalize print ('%r' % normalize('NFD', u'\\u00C7'))print ('%r' % normalize('NFC', u'C\\u0327'))print ('%r' % normalize('NFKD', u'\\u2460'))Output :u'C\\u0327'\nu'\\xc7'\nu'1'\n"
},
{
"code": null,
"e": 5247,
"s": 5237,
"text": "Example :"
},
{
"code": "from unicodedata import normalize print ('%r' % normalize('NFD', u'\\u00C7'))print ('%r' % normalize('NFC', u'C\\u0327'))print ('%r' % normalize('NFKD', u'\\u2460'))",
"e": 5412,
"s": 5247,
"text": null
},
{
"code": null,
"e": 5421,
"s": 5412,
"text": "Output :"
},
{
"code": null,
"e": 5446,
"s": 5421,
"text": "u'C\\u0327'\nu'\\xc7'\nu'1'\n"
},
{
"code": null,
"e": 5745,
"s": 5446,
"text": "This article is contributed by Aditi Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 5870,
"s": 5745,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 5885,
"s": 5870,
"text": "Python-Library"
},
{
"code": null,
"e": 5892,
"s": 5885,
"text": "Python"
},
{
"code": null,
"e": 5990,
"s": 5892,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6022,
"s": 5990,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 6049,
"s": 6022,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 6080,
"s": 6049,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 6103,
"s": 6080,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 6124,
"s": 6103,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 6180,
"s": 6124,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 6222,
"s": 6180,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 6264,
"s": 6222,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 6303,
"s": 6264,
"text": "Python | Get unique values from a list"
}
] |
MySQL query to count the number of times a specific integer appears in a column for its corresponding value in another column
|
For this, use aggregate function COUNT(). Let us first create a table β
mysql> create table DemoTable650 (Value1 int,Value2 int);
Query OK, 0 rows affected (0.83 sec)
Insert some records in the table using insert command β
mysql> insert into DemoTable650 values(100,500);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable650 values(100,500);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable650 values(100,500);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable650 values(100,500);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable650 values(200,500);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement β
mysql> select *from DemoTable650;
This will produce the following output β
+--------+--------+
| Value1 | Value2 |
+--------+--------+
| 100 | 500 |
| 100 | 500 |
| 100 | 500 |
| 100 | 500 |
| 200 | 500 |
+--------+--------+
5 rows in set (0.00 sec)
Following is the query to count the number of times a specific integer appears in a column for its corresponding value in another column β
mysql> select Value2,count(Value1) from DemoTable650 where Value1=100 group by Value2;
This will produce the following output β
+--------+---------------+
| Value2 | count(Value1) |
+--------+---------------+
| 500 | 4 |
+--------+---------------+
1 row in set (0.04 sec)
|
[
{
"code": null,
"e": 1259,
"s": 1187,
"text": "For this, use aggregate function COUNT(). Let us first create a table β"
},
{
"code": null,
"e": 1354,
"s": 1259,
"text": "mysql> create table DemoTable650 (Value1 int,Value2 int);\nQuery OK, 0 rows affected (0.83 sec)"
},
{
"code": null,
"e": 1410,
"s": 1354,
"text": "Insert some records in the table using insert command β"
},
{
"code": null,
"e": 1835,
"s": 1410,
"text": "mysql> insert into DemoTable650 values(100,500);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable650 values(100,500);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable650 values(100,500);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable650 values(100,500);\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into DemoTable650 values(200,500);\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 1895,
"s": 1835,
"text": "Display all records from the table using select statement β"
},
{
"code": null,
"e": 1929,
"s": 1895,
"text": "mysql> select *from DemoTable650;"
},
{
"code": null,
"e": 1970,
"s": 1929,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2175,
"s": 1970,
"text": "+--------+--------+\n| Value1 | Value2 |\n+--------+--------+\n| 100 | 500 |\n| 100 | 500 |\n| 100 | 500 |\n| 100 | 500 |\n| 200 | 500 |\n+--------+--------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2314,
"s": 2175,
"text": "Following is the query to count the number of times a specific integer appears in a column for its corresponding value in another column β"
},
{
"code": null,
"e": 2401,
"s": 2314,
"text": "mysql> select Value2,count(Value1) from DemoTable650 where Value1=100 group by Value2;"
},
{
"code": null,
"e": 2442,
"s": 2401,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2601,
"s": 2442,
"text": "+--------+---------------+\n| Value2 | count(Value1) |\n+--------+---------------+\n| 500 | 4 |\n+--------+---------------+\n1 row in set (0.04 sec)"
}
] |
Frequently Asked Questions regarding Placements
|
14 Sep, 2018
Below are some of the most frequently asked questions regarding placements and interviews:
Is competitive programming enough for placements?Competitive Programming plays a very important role in boosting problem-solving skills and ability to perform under time pressure. But obviously, it is not at all enough to get you prepared from placement perspective. This is because companies focus on core data structures and algorithm concepts along with other important CS subjects. You need to have a good grasp of concepts with good problem-solving abilities (as you are required to solve some of the real-life problems during your job), good coding practice.Does writing clean code increases the chance of getting selected?Writing clean code surely creates a good impression of you in front of the recruiter. Recruiters always prefer someone who can write code which is easily understandable and should also be efficient at the same time.How should I prepare for whiteboard interviews?You can practice for Whiteboard coding interview rounds with your friends and colleagues. You can ask your friend to discuss different corner cases of any problem on the whiteboard. This will help you in writing code on the whiteboard parallelly covering different cases. It showcases not only your coding skill but also your presentation skills.What programming languages should I learn?You can learn as many programming languages you want but make sure to master at least any one programming language of your choice. Recruiters only see whether you are able to code a given problem in any language of your choice (C, C++, Java etc.). We recommend you to master any one structured programming language like C and any one of the Object Oriented Programming language like C++, Java etc.Should I mention my competitive profiles in Resume?If you have a good competitive profile then we recommend you to mention it in your resume. This does not mean that recruiters only look for competitive programmers but if you have a good competitive profile then it also reflects that you have good problem-solving abilities. So, if you do not have a good competitive profile then it does not decrease the chance of your selection in any sense at all. All you need is to show the recruiter that you have a good problem-solving ability.How much projects are important to be added in resume?Projects add a pinch of salt to your resume. Try to add 2-3 good projects with somehow description of 1-2 lines. Also, be prepared to deliver detail description of your project and also some of the corner scenarios your project should handle. While applying off-campus, try to include projects according to the technology on which company has vacancies because many companies have a resume filtering option. That is when you apply for a vacancy on their website your resume passes through an initial keyword matching process before it reaches to the hiring team.How should I use GeeksforGeeks for placement preparation?Practice core Data Structures like Stack, Queue, Linked List, Tree, Heap, Graph are few DS which is very common and you should know ins and outs of them irrespective of company you are targeting. Start these topics in the order we have mentioned. Solve few questions of each and then you will start observing patterns. For example, Most of the tree questions boils down to solving it in three parts, Solve left subtree, solve right subtree, combine the results.Problem solving: Based on some interview experiences, we found that Problem solving and strong coding skills are the two major areas top MNCs look for. You know DS and coding. Great! But how and where to use these are more important. Here comes the Algorithms part. So go for practicing below topics:Divide and Conquer Archives β GeeksforGeeksGreedy Algorithm Archives β GeeksforGeeksBacktracking Archives β GeeksforGeeksDynamic Programming Archives β GeeksforGeeksPattern Searching Archives β GeeksforGeeksOut of all, Dynamic Programming is one of the toughest topic which is most challenging to master upon. And also you should expect to face at least one DP problem in each round of Tech Giants (specially in Google) interview.Practice Advanced Data Structures: Once you are comfortable with Core DS, itβs time to move to Advanced Data Structure Archives β GeeksforGeeks. TRIE, TST, Interval Tree, K Dimensional Tree are also important.
Is competitive programming enough for placements?Competitive Programming plays a very important role in boosting problem-solving skills and ability to perform under time pressure. But obviously, it is not at all enough to get you prepared from placement perspective. This is because companies focus on core data structures and algorithm concepts along with other important CS subjects. You need to have a good grasp of concepts with good problem-solving abilities (as you are required to solve some of the real-life problems during your job), good coding practice.
Does writing clean code increases the chance of getting selected?Writing clean code surely creates a good impression of you in front of the recruiter. Recruiters always prefer someone who can write code which is easily understandable and should also be efficient at the same time.
How should I prepare for whiteboard interviews?You can practice for Whiteboard coding interview rounds with your friends and colleagues. You can ask your friend to discuss different corner cases of any problem on the whiteboard. This will help you in writing code on the whiteboard parallelly covering different cases. It showcases not only your coding skill but also your presentation skills.
What programming languages should I learn?You can learn as many programming languages you want but make sure to master at least any one programming language of your choice. Recruiters only see whether you are able to code a given problem in any language of your choice (C, C++, Java etc.). We recommend you to master any one structured programming language like C and any one of the Object Oriented Programming language like C++, Java etc.
Should I mention my competitive profiles in Resume?If you have a good competitive profile then we recommend you to mention it in your resume. This does not mean that recruiters only look for competitive programmers but if you have a good competitive profile then it also reflects that you have good problem-solving abilities. So, if you do not have a good competitive profile then it does not decrease the chance of your selection in any sense at all. All you need is to show the recruiter that you have a good problem-solving ability.
How much projects are important to be added in resume?Projects add a pinch of salt to your resume. Try to add 2-3 good projects with somehow description of 1-2 lines. Also, be prepared to deliver detail description of your project and also some of the corner scenarios your project should handle. While applying off-campus, try to include projects according to the technology on which company has vacancies because many companies have a resume filtering option. That is when you apply for a vacancy on their website your resume passes through an initial keyword matching process before it reaches to the hiring team.
How should I use GeeksforGeeks for placement preparation?Practice core Data Structures like Stack, Queue, Linked List, Tree, Heap, Graph are few DS which is very common and you should know ins and outs of them irrespective of company you are targeting. Start these topics in the order we have mentioned. Solve few questions of each and then you will start observing patterns. For example, Most of the tree questions boils down to solving it in three parts, Solve left subtree, solve right subtree, combine the results.Problem solving: Based on some interview experiences, we found that Problem solving and strong coding skills are the two major areas top MNCs look for. You know DS and coding. Great! But how and where to use these are more important. Here comes the Algorithms part. So go for practicing below topics:Divide and Conquer Archives β GeeksforGeeksGreedy Algorithm Archives β GeeksforGeeksBacktracking Archives β GeeksforGeeksDynamic Programming Archives β GeeksforGeeksPattern Searching Archives β GeeksforGeeksOut of all, Dynamic Programming is one of the toughest topic which is most challenging to master upon. And also you should expect to face at least one DP problem in each round of Tech Giants (specially in Google) interview.Practice Advanced Data Structures: Once you are comfortable with Core DS, itβs time to move to Advanced Data Structure Archives β GeeksforGeeks. TRIE, TST, Interval Tree, K Dimensional Tree are also important.
Practice core Data Structures like Stack, Queue, Linked List, Tree, Heap, Graph are few DS which is very common and you should know ins and outs of them irrespective of company you are targeting. Start these topics in the order we have mentioned. Solve few questions of each and then you will start observing patterns. For example, Most of the tree questions boils down to solving it in three parts, Solve left subtree, solve right subtree, combine the results.
Problem solving: Based on some interview experiences, we found that Problem solving and strong coding skills are the two major areas top MNCs look for. You know DS and coding. Great! But how and where to use these are more important. Here comes the Algorithms part. So go for practicing below topics:Divide and Conquer Archives β GeeksforGeeksGreedy Algorithm Archives β GeeksforGeeksBacktracking Archives β GeeksforGeeksDynamic Programming Archives β GeeksforGeeksPattern Searching Archives β GeeksforGeeksOut of all, Dynamic Programming is one of the toughest topic which is most challenging to master upon. And also you should expect to face at least one DP problem in each round of Tech Giants (specially in Google) interview.
Divide and Conquer Archives β GeeksforGeeks
Greedy Algorithm Archives β GeeksforGeeks
Backtracking Archives β GeeksforGeeks
Dynamic Programming Archives β GeeksforGeeks
Pattern Searching Archives β GeeksforGeeks
Out of all, Dynamic Programming is one of the toughest topic which is most challenging to master upon. And also you should expect to face at least one DP problem in each round of Tech Giants (specially in Google) interview.
Practice Advanced Data Structures: Once you are comfortable with Core DS, itβs time to move to Advanced Data Structure Archives β GeeksforGeeks. TRIE, TST, Interval Tree, K Dimensional Tree are also important.
Career-Advices
Interview Tips
interview-preparation
placement preparation
Placements
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Sep, 2018"
},
{
"code": null,
"e": 143,
"s": 52,
"text": "Below are some of the most frequently asked questions regarding placements and interviews:"
},
{
"code": null,
"e": 4428,
"s": 143,
"text": "Is competitive programming enough for placements?Competitive Programming plays a very important role in boosting problem-solving skills and ability to perform under time pressure. But obviously, it is not at all enough to get you prepared from placement perspective. This is because companies focus on core data structures and algorithm concepts along with other important CS subjects. You need to have a good grasp of concepts with good problem-solving abilities (as you are required to solve some of the real-life problems during your job), good coding practice.Does writing clean code increases the chance of getting selected?Writing clean code surely creates a good impression of you in front of the recruiter. Recruiters always prefer someone who can write code which is easily understandable and should also be efficient at the same time.How should I prepare for whiteboard interviews?You can practice for Whiteboard coding interview rounds with your friends and colleagues. You can ask your friend to discuss different corner cases of any problem on the whiteboard. This will help you in writing code on the whiteboard parallelly covering different cases. It showcases not only your coding skill but also your presentation skills.What programming languages should I learn?You can learn as many programming languages you want but make sure to master at least any one programming language of your choice. Recruiters only see whether you are able to code a given problem in any language of your choice (C, C++, Java etc.). We recommend you to master any one structured programming language like C and any one of the Object Oriented Programming language like C++, Java etc.Should I mention my competitive profiles in Resume?If you have a good competitive profile then we recommend you to mention it in your resume. This does not mean that recruiters only look for competitive programmers but if you have a good competitive profile then it also reflects that you have good problem-solving abilities. So, if you do not have a good competitive profile then it does not decrease the chance of your selection in any sense at all. All you need is to show the recruiter that you have a good problem-solving ability.How much projects are important to be added in resume?Projects add a pinch of salt to your resume. Try to add 2-3 good projects with somehow description of 1-2 lines. Also, be prepared to deliver detail description of your project and also some of the corner scenarios your project should handle. While applying off-campus, try to include projects according to the technology on which company has vacancies because many companies have a resume filtering option. That is when you apply for a vacancy on their website your resume passes through an initial keyword matching process before it reaches to the hiring team.How should I use GeeksforGeeks for placement preparation?Practice core Data Structures like Stack, Queue, Linked List, Tree, Heap, Graph are few DS which is very common and you should know ins and outs of them irrespective of company you are targeting. Start these topics in the order we have mentioned. Solve few questions of each and then you will start observing patterns. For example, Most of the tree questions boils down to solving it in three parts, Solve left subtree, solve right subtree, combine the results.Problem solving: Based on some interview experiences, we found that Problem solving and strong coding skills are the two major areas top MNCs look for. You know DS and coding. Great! But how and where to use these are more important. Here comes the Algorithms part. So go for practicing below topics:Divide and Conquer Archives β GeeksforGeeksGreedy Algorithm Archives β GeeksforGeeksBacktracking Archives β GeeksforGeeksDynamic Programming Archives β GeeksforGeeksPattern Searching Archives β GeeksforGeeksOut of all, Dynamic Programming is one of the toughest topic which is most challenging to master upon. And also you should expect to face at least one DP problem in each round of Tech Giants (specially in Google) interview.Practice Advanced Data Structures: Once you are comfortable with Core DS, itβs time to move to Advanced Data Structure Archives β GeeksforGeeks. TRIE, TST, Interval Tree, K Dimensional Tree are also important."
},
{
"code": null,
"e": 4993,
"s": 4428,
"text": "Is competitive programming enough for placements?Competitive Programming plays a very important role in boosting problem-solving skills and ability to perform under time pressure. But obviously, it is not at all enough to get you prepared from placement perspective. This is because companies focus on core data structures and algorithm concepts along with other important CS subjects. You need to have a good grasp of concepts with good problem-solving abilities (as you are required to solve some of the real-life problems during your job), good coding practice."
},
{
"code": null,
"e": 5274,
"s": 4993,
"text": "Does writing clean code increases the chance of getting selected?Writing clean code surely creates a good impression of you in front of the recruiter. Recruiters always prefer someone who can write code which is easily understandable and should also be efficient at the same time."
},
{
"code": null,
"e": 5668,
"s": 5274,
"text": "How should I prepare for whiteboard interviews?You can practice for Whiteboard coding interview rounds with your friends and colleagues. You can ask your friend to discuss different corner cases of any problem on the whiteboard. This will help you in writing code on the whiteboard parallelly covering different cases. It showcases not only your coding skill but also your presentation skills."
},
{
"code": null,
"e": 6108,
"s": 5668,
"text": "What programming languages should I learn?You can learn as many programming languages you want but make sure to master at least any one programming language of your choice. Recruiters only see whether you are able to code a given problem in any language of your choice (C, C++, Java etc.). We recommend you to master any one structured programming language like C and any one of the Object Oriented Programming language like C++, Java etc."
},
{
"code": null,
"e": 6644,
"s": 6108,
"text": "Should I mention my competitive profiles in Resume?If you have a good competitive profile then we recommend you to mention it in your resume. This does not mean that recruiters only look for competitive programmers but if you have a good competitive profile then it also reflects that you have good problem-solving abilities. So, if you do not have a good competitive profile then it does not decrease the chance of your selection in any sense at all. All you need is to show the recruiter that you have a good problem-solving ability."
},
{
"code": null,
"e": 7261,
"s": 6644,
"text": "How much projects are important to be added in resume?Projects add a pinch of salt to your resume. Try to add 2-3 good projects with somehow description of 1-2 lines. Also, be prepared to deliver detail description of your project and also some of the corner scenarios your project should handle. While applying off-campus, try to include projects according to the technology on which company has vacancies because many companies have a resume filtering option. That is when you apply for a vacancy on their website your resume passes through an initial keyword matching process before it reaches to the hiring team."
},
{
"code": null,
"e": 8719,
"s": 7261,
"text": "How should I use GeeksforGeeks for placement preparation?Practice core Data Structures like Stack, Queue, Linked List, Tree, Heap, Graph are few DS which is very common and you should know ins and outs of them irrespective of company you are targeting. Start these topics in the order we have mentioned. Solve few questions of each and then you will start observing patterns. For example, Most of the tree questions boils down to solving it in three parts, Solve left subtree, solve right subtree, combine the results.Problem solving: Based on some interview experiences, we found that Problem solving and strong coding skills are the two major areas top MNCs look for. You know DS and coding. Great! But how and where to use these are more important. Here comes the Algorithms part. So go for practicing below topics:Divide and Conquer Archives β GeeksforGeeksGreedy Algorithm Archives β GeeksforGeeksBacktracking Archives β GeeksforGeeksDynamic Programming Archives β GeeksforGeeksPattern Searching Archives β GeeksforGeeksOut of all, Dynamic Programming is one of the toughest topic which is most challenging to master upon. And also you should expect to face at least one DP problem in each round of Tech Giants (specially in Google) interview.Practice Advanced Data Structures: Once you are comfortable with Core DS, itβs time to move to Advanced Data Structure Archives β GeeksforGeeks. TRIE, TST, Interval Tree, K Dimensional Tree are also important."
},
{
"code": null,
"e": 9181,
"s": 8719,
"text": "Practice core Data Structures like Stack, Queue, Linked List, Tree, Heap, Graph are few DS which is very common and you should know ins and outs of them irrespective of company you are targeting. Start these topics in the order we have mentioned. Solve few questions of each and then you will start observing patterns. For example, Most of the tree questions boils down to solving it in three parts, Solve left subtree, solve right subtree, combine the results."
},
{
"code": null,
"e": 9912,
"s": 9181,
"text": "Problem solving: Based on some interview experiences, we found that Problem solving and strong coding skills are the two major areas top MNCs look for. You know DS and coding. Great! But how and where to use these are more important. Here comes the Algorithms part. So go for practicing below topics:Divide and Conquer Archives β GeeksforGeeksGreedy Algorithm Archives β GeeksforGeeksBacktracking Archives β GeeksforGeeksDynamic Programming Archives β GeeksforGeeksPattern Searching Archives β GeeksforGeeksOut of all, Dynamic Programming is one of the toughest topic which is most challenging to master upon. And also you should expect to face at least one DP problem in each round of Tech Giants (specially in Google) interview."
},
{
"code": null,
"e": 9956,
"s": 9912,
"text": "Divide and Conquer Archives β GeeksforGeeks"
},
{
"code": null,
"e": 9998,
"s": 9956,
"text": "Greedy Algorithm Archives β GeeksforGeeks"
},
{
"code": null,
"e": 10036,
"s": 9998,
"text": "Backtracking Archives β GeeksforGeeks"
},
{
"code": null,
"e": 10081,
"s": 10036,
"text": "Dynamic Programming Archives β GeeksforGeeks"
},
{
"code": null,
"e": 10124,
"s": 10081,
"text": "Pattern Searching Archives β GeeksforGeeks"
},
{
"code": null,
"e": 10348,
"s": 10124,
"text": "Out of all, Dynamic Programming is one of the toughest topic which is most challenging to master upon. And also you should expect to face at least one DP problem in each round of Tech Giants (specially in Google) interview."
},
{
"code": null,
"e": 10558,
"s": 10348,
"text": "Practice Advanced Data Structures: Once you are comfortable with Core DS, itβs time to move to Advanced Data Structure Archives β GeeksforGeeks. TRIE, TST, Interval Tree, K Dimensional Tree are also important."
},
{
"code": null,
"e": 10573,
"s": 10558,
"text": "Career-Advices"
},
{
"code": null,
"e": 10588,
"s": 10573,
"text": "Interview Tips"
},
{
"code": null,
"e": 10610,
"s": 10588,
"text": "interview-preparation"
},
{
"code": null,
"e": 10632,
"s": 10610,
"text": "placement preparation"
},
{
"code": null,
"e": 10643,
"s": 10632,
"text": "Placements"
}
] |
C++ program for Solving Cryptarithmetic Puzzles
|
16 Jan, 2018
Newspapers and magazines often have crypt-arithmetic puzzles of the form:Examples:
Input : s1 = SEND, s2 = "MORE", s3 = "MONEY"
Output : One of the possible solution is:
D=1 E=5 M=0 N=3 O=8 R=2 S=7 Y=6
Explanation:
The above values satisfy below equation :
SEND
+ MORE
--------
MONEY
--------
It is strongly recommended to refer Backtracking | Set 8 (Solving Cryptarithmetic Puzzles) for approach of this problem.
The idea is to assign each letter a digit from 0 to 9 so that the arithmetic works out correctly. A permutation is a recursive function which calls a check function for every possible permutation of integers.Check function checks whether the sum of first two numbers corresponding to first two string is equal to the third number corresponding to third string. If the solution is found then print the solution.
// CPP program for solving cryptographic puzzles#include <bits/stdc++.h>using namespace std; // vector stores 1 corresponding to index// number which is already assigned// to any char, otherwise stores 0vector<int> use(10); // structure to store char and its corresponding integerstruct node{ char c; int v;}; // function check for correct solutionint check(node* nodeArr, const int count, string s1, string s2, string s3){ int val1 = 0, val2 = 0, val3 = 0, m = 1, j, i; // calculate number corresponding to first string for (i = s1.length() - 1; i >= 0; i--) { char ch = s1[i]; for (j = 0; j < count; j++) if (nodeArr[j].c == ch) break; val1 += m * nodeArr[j].v; m *= 10; } m = 1; // calculate number corresponding to second string for (i = s2.length() - 1; i >= 0; i--) { char ch = s2[i]; for (j = 0; j < count; j++) if (nodeArr[j].c == ch) break; val2 += m * nodeArr[j].v; m *= 10; } m = 1; // calculate number corresponding to third string for (i = s3.length() - 1; i >= 0; i--) { char ch = s3[i]; for (j = 0; j < count; j++) if (nodeArr[j].c == ch) break; val3 += m * nodeArr[j].v; m *= 10; } // sum of first two number equal to third return true if (val3 == (val1 + val2)) return 1; // else return false return 0;} // Recursive function to check solution for all permutationsbool permutation(const int count, node* nodeArr, int n, string s1, string s2, string s3){ // Base case if (n == count - 1) { // check for all numbers not used yet for (int i = 0; i < 10; i++) { // if not used if (use[i] == 0) { // assign char at index n integer i nodeArr[n].v = i; // if solution found if (check(nodeArr, count, s1, s2, s3) == 1) { cout << "\nSolution found: "; for (int j = 0; j < count; j++) cout << " " << nodeArr[j].c << " = " << nodeArr[j].v; return true; } } } return false; } for (int i = 0; i < 10; i++) { // if ith integer not used yet if (use[i] == 0) { // assign char at index n integer i nodeArr[n].v = i; // mark it as not available for other char use[i] = 1; // call recursive function if (permutation(count, nodeArr, n + 1, s1, s2, s3)) return true; // backtrack for all other possible solutions use[i] = 0; } } return false;} bool solveCryptographic(string s1, string s2, string s3){ // count to store number of unique char int count = 0; // Length of all three strings int l1 = s1.length(); int l2 = s2.length(); int l3 = s3.length(); // vector to store frequency of each char vector<int> freq(26); for (int i = 0; i < l1; i++) ++freq[s1[i] - 'A']; for (int i = 0; i < l2; i++) ++freq[s2[i] - 'A']; for (int i = 0; i < l3; i++) ++freq[s3[i] - 'A']; // count number of unique char for (int i = 0; i < 26; i++) if (freq[i] > 0) count++; // solution not possible for count greater than 10 if (count > 10) { cout << "Invalid strings"; return 0; } // array of nodes node nodeArr[count]; // store all unique char in nodeArr for (int i = 0, j = 0; i < 26; i++) { if (freq[i] > 0) { nodeArr[j].c = char(i + 'A'); j++; } } return permutation(count, nodeArr, 0, s1, s2, s3);} // Driver functionint main(){ string s1 = "SEND"; string s2 = "MORE"; string s3 = "MONEY"; if (solveCryptographic(s1, s2, s3) == false) cout << "No solution"; return 0;}
Output:
Solution found: D=1 E=5 M=0 N=3 O=8 R=2 S=7 Y=6
Backtracking
C++ Programs
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path of more than k length from a source
Find shortest safe route in a path with landmines
Longest Possible Route in a Matrix with Hurdles
Difference between Backtracking and Branch-N-Bound technique
Top 20 Backtracking Algorithm Interview Questions
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Jan, 2018"
},
{
"code": null,
"e": 135,
"s": 52,
"text": "Newspapers and magazines often have crypt-arithmetic puzzles of the form:Examples:"
},
{
"code": null,
"e": 362,
"s": 135,
"text": "Input : s1 = SEND, s2 = \"MORE\", s3 = \"MONEY\"\nOutput : One of the possible solution is:\n D=1 E=5 M=0 N=3 O=8 R=2 S=7 Y=6 \nExplanation:\nThe above values satisfy below equation : \n SEND\n+ MORE\n--------\n MONEY\n-------- \n"
},
{
"code": null,
"e": 483,
"s": 362,
"text": "It is strongly recommended to refer Backtracking | Set 8 (Solving Cryptarithmetic Puzzles) for approach of this problem."
},
{
"code": null,
"e": 894,
"s": 483,
"text": "The idea is to assign each letter a digit from 0 to 9 so that the arithmetic works out correctly. A permutation is a recursive function which calls a check function for every possible permutation of integers.Check function checks whether the sum of first two numbers corresponding to first two string is equal to the third number corresponding to third string. If the solution is found then print the solution."
},
{
"code": "// CPP program for solving cryptographic puzzles#include <bits/stdc++.h>using namespace std; // vector stores 1 corresponding to index// number which is already assigned// to any char, otherwise stores 0vector<int> use(10); // structure to store char and its corresponding integerstruct node{ char c; int v;}; // function check for correct solutionint check(node* nodeArr, const int count, string s1, string s2, string s3){ int val1 = 0, val2 = 0, val3 = 0, m = 1, j, i; // calculate number corresponding to first string for (i = s1.length() - 1; i >= 0; i--) { char ch = s1[i]; for (j = 0; j < count; j++) if (nodeArr[j].c == ch) break; val1 += m * nodeArr[j].v; m *= 10; } m = 1; // calculate number corresponding to second string for (i = s2.length() - 1; i >= 0; i--) { char ch = s2[i]; for (j = 0; j < count; j++) if (nodeArr[j].c == ch) break; val2 += m * nodeArr[j].v; m *= 10; } m = 1; // calculate number corresponding to third string for (i = s3.length() - 1; i >= 0; i--) { char ch = s3[i]; for (j = 0; j < count; j++) if (nodeArr[j].c == ch) break; val3 += m * nodeArr[j].v; m *= 10; } // sum of first two number equal to third return true if (val3 == (val1 + val2)) return 1; // else return false return 0;} // Recursive function to check solution for all permutationsbool permutation(const int count, node* nodeArr, int n, string s1, string s2, string s3){ // Base case if (n == count - 1) { // check for all numbers not used yet for (int i = 0; i < 10; i++) { // if not used if (use[i] == 0) { // assign char at index n integer i nodeArr[n].v = i; // if solution found if (check(nodeArr, count, s1, s2, s3) == 1) { cout << \"\\nSolution found: \"; for (int j = 0; j < count; j++) cout << \" \" << nodeArr[j].c << \" = \" << nodeArr[j].v; return true; } } } return false; } for (int i = 0; i < 10; i++) { // if ith integer not used yet if (use[i] == 0) { // assign char at index n integer i nodeArr[n].v = i; // mark it as not available for other char use[i] = 1; // call recursive function if (permutation(count, nodeArr, n + 1, s1, s2, s3)) return true; // backtrack for all other possible solutions use[i] = 0; } } return false;} bool solveCryptographic(string s1, string s2, string s3){ // count to store number of unique char int count = 0; // Length of all three strings int l1 = s1.length(); int l2 = s2.length(); int l3 = s3.length(); // vector to store frequency of each char vector<int> freq(26); for (int i = 0; i < l1; i++) ++freq[s1[i] - 'A']; for (int i = 0; i < l2; i++) ++freq[s2[i] - 'A']; for (int i = 0; i < l3; i++) ++freq[s3[i] - 'A']; // count number of unique char for (int i = 0; i < 26; i++) if (freq[i] > 0) count++; // solution not possible for count greater than 10 if (count > 10) { cout << \"Invalid strings\"; return 0; } // array of nodes node nodeArr[count]; // store all unique char in nodeArr for (int i = 0, j = 0; i < 26; i++) { if (freq[i] > 0) { nodeArr[j].c = char(i + 'A'); j++; } } return permutation(count, nodeArr, 0, s1, s2, s3);} // Driver functionint main(){ string s1 = \"SEND\"; string s2 = \"MORE\"; string s3 = \"MONEY\"; if (solveCryptographic(s1, s2, s3) == false) cout << \"No solution\"; return 0;}",
"e": 5041,
"s": 894,
"text": null
},
{
"code": null,
"e": 5049,
"s": 5041,
"text": "Output:"
},
{
"code": null,
"e": 5100,
"s": 5049,
"text": "Solution found: D=1 E=5 M=0 N=3 O=8 R=2 S=7 Y=6\n\n"
},
{
"code": null,
"e": 5113,
"s": 5100,
"text": "Backtracking"
},
{
"code": null,
"e": 5126,
"s": 5113,
"text": "C++ Programs"
},
{
"code": null,
"e": 5139,
"s": 5126,
"text": "Backtracking"
},
{
"code": null,
"e": 5237,
"s": 5139,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5297,
"s": 5237,
"text": "Find if there is a path of more than k length from a source"
},
{
"code": null,
"e": 5347,
"s": 5297,
"text": "Find shortest safe route in a path with landmines"
},
{
"code": null,
"e": 5395,
"s": 5347,
"text": "Longest Possible Route in a Matrix with Hurdles"
},
{
"code": null,
"e": 5456,
"s": 5395,
"text": "Difference between Backtracking and Branch-N-Bound technique"
},
{
"code": null,
"e": 5506,
"s": 5456,
"text": "Top 20 Backtracking Algorithm Interview Questions"
},
{
"code": null,
"e": 5541,
"s": 5506,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 5575,
"s": 5541,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 5619,
"s": 5575,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 5678,
"s": 5619,
"text": "How to return multiple values from a function in C or C++?"
}
] |
Dunder or magic methods in Python
|
14 Mar, 2018
Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. Dunder here means βDouble Under (Underscores)β. These are commonly used for operator overloading. Few examples for magic methods are: __init__, __add__, __len__, __repr__ etc.
The __init__ method for initialization is invoked without any call, when an instance of a class is created, like constructors in certain other programming languages such as C++, Java, C#, PHP etc. These methods are the reason we can add two strings with β+β operator without any explicit typecasting.
Hereβs a simple implementation :
# declare our own string classclass String: # magic method to initiate object def __init__(self, string): self.string = string # Driver Codeif __name__ == '__main__': # object creation string1 = String('Hello') # print object location print(string1)
Output :
<__main__.String object at 0x7fe992215390>
The above snippet of code prints only the memory address of the string object. Letβs add a __repr__ method to represent our object.
# declare our own string classclass String: # magic method to initiate object def __init__(self, string): self.string = string # print our string object def __repr__(self): return 'Object: {}'.format(self.string) # Driver Codeif __name__ == '__main__': # object creation string1 = String('Hello') # print object location print(string1)
Output :
Object: Hello
If we try to add a string to it :
# declare our own string classclass String: # magic method to initiate object def __init__(self, string): self.string = string # print our string object def __repr__(self): return 'Object: {}'.format(self.string) # Driver Codeif __name__ == '__main__': # object creation string1 = String('Hello') # concatenate String object and a string print(string1 +' world')
Output :
TypeError: unsupported operand type(s) for +: 'String' and 'str'
Now add __add__ method to String class :
# declare our own string classclass String: # magic method to initiate object def __init__(self, string): self.string = string # print our string object def __repr__(self): return 'Object: {}'.format(self.string) def __add__(self, other): return self.string + other # Driver Codeif __name__ == '__main__': # object creation string1 = String('Hello') # concatenate String object and a string print(string1 +' Geeks')
Output :
Hello Geeks
Reference : docs.python.org.
python-oop-concepts
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Enumerate() in Python
Python Dictionary
Python OOPs Concepts
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Python Classes and Objects
Introduction To PYTHON
Stack in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Mar, 2018"
},
{
"code": null,
"e": 339,
"s": 52,
"text": "Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. Dunder here means βDouble Under (Underscores)β. These are commonly used for operator overloading. Few examples for magic methods are: __init__, __add__, __len__, __repr__ etc."
},
{
"code": null,
"e": 640,
"s": 339,
"text": "The __init__ method for initialization is invoked without any call, when an instance of a class is created, like constructors in certain other programming languages such as C++, Java, C#, PHP etc. These methods are the reason we can add two strings with β+β operator without any explicit typecasting."
},
{
"code": null,
"e": 673,
"s": 640,
"text": "Hereβs a simple implementation :"
},
{
"code": "# declare our own string classclass String: # magic method to initiate object def __init__(self, string): self.string = string # Driver Codeif __name__ == '__main__': # object creation string1 = String('Hello') # print object location print(string1)",
"e": 971,
"s": 673,
"text": null
},
{
"code": null,
"e": 980,
"s": 971,
"text": "Output :"
},
{
"code": null,
"e": 1024,
"s": 980,
"text": "<__main__.String object at 0x7fe992215390>\n"
},
{
"code": null,
"e": 1157,
"s": 1024,
"text": " The above snippet of code prints only the memory address of the string object. Letβs add a __repr__ method to represent our object."
},
{
"code": "# declare our own string classclass String: # magic method to initiate object def __init__(self, string): self.string = string # print our string object def __repr__(self): return 'Object: {}'.format(self.string) # Driver Codeif __name__ == '__main__': # object creation string1 = String('Hello') # print object location print(string1)",
"e": 1556,
"s": 1157,
"text": null
},
{
"code": null,
"e": 1565,
"s": 1556,
"text": "Output :"
},
{
"code": null,
"e": 1580,
"s": 1565,
"text": "Object: Hello\n"
},
{
"code": null,
"e": 1615,
"s": 1580,
"text": " If we try to add a string to it :"
},
{
"code": "# declare our own string classclass String: # magic method to initiate object def __init__(self, string): self.string = string # print our string object def __repr__(self): return 'Object: {}'.format(self.string) # Driver Codeif __name__ == '__main__': # object creation string1 = String('Hello') # concatenate String object and a string print(string1 +' world')",
"e": 2045,
"s": 1615,
"text": null
},
{
"code": null,
"e": 2054,
"s": 2045,
"text": "Output :"
},
{
"code": null,
"e": 2120,
"s": 2054,
"text": "TypeError: unsupported operand type(s) for +: 'String' and 'str'\n"
},
{
"code": null,
"e": 2162,
"s": 2120,
"text": " Now add __add__ method to String class :"
},
{
"code": "# declare our own string classclass String: # magic method to initiate object def __init__(self, string): self.string = string # print our string object def __repr__(self): return 'Object: {}'.format(self.string) def __add__(self, other): return self.string + other # Driver Codeif __name__ == '__main__': # object creation string1 = String('Hello') # concatenate String object and a string print(string1 +' Geeks')",
"e": 2666,
"s": 2162,
"text": null
},
{
"code": null,
"e": 2675,
"s": 2666,
"text": "Output :"
},
{
"code": null,
"e": 2688,
"s": 2675,
"text": "Hello Geeks\n"
},
{
"code": null,
"e": 2719,
"s": 2690,
"text": "Reference : docs.python.org."
},
{
"code": null,
"e": 2739,
"s": 2719,
"text": "python-oop-concepts"
},
{
"code": null,
"e": 2746,
"s": 2739,
"text": "Python"
},
{
"code": null,
"e": 2844,
"s": 2746,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2874,
"s": 2844,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2919,
"s": 2874,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 2941,
"s": 2919,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2959,
"s": 2941,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2980,
"s": 2959,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3022,
"s": 2980,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3051,
"s": 3022,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3078,
"s": 3051,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3101,
"s": 3078,
"text": "Introduction To PYTHON"
}
] |
C Program to count number of lines in a file
|
11 Jul, 2022
C
/* C Program to count the Number of Lines in a Text File */#include <stdio.h>#define MAX_FILE_NAME 100 int main(){ FILE *fp; int count = 0; // Line counter (result) char filename[MAX_FILE_NAME]; char c; // To store a character read from file // Get file name from user. The file should be // either in current folder or complete path should be provided printf("Enter file name: "); scanf("%s", filename); // Open the file fp = fopen(filename, "r"); // Check if file exists if (fp == NULL) { printf("Could not open file %s", filename); return 0; } // Extract characters from file and store in character c for (c = getc(fp); c != EOF; c = getc(fp)) if (c == '\n') // Increment count if this character is newline count = count + 1; // Close the file fclose(fp); printf("The file %s has %d lines\n ", filename, count); return 0;}
Output:
Enter file name: countLines.c
The file countLines.c has 41 lines
Time complexity: O(N) where N is total number of characters in given file
Please write comments if you find anything incorrect or want to share more information about the topic discussed above.
kumargaurav97520
cpp-file-handling
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Jul, 2022"
},
{
"code": null,
"e": 56,
"s": 54,
"text": "C"
},
{
"code": "/* C Program to count the Number of Lines in a Text File */#include <stdio.h>#define MAX_FILE_NAME 100 int main(){ FILE *fp; int count = 0; // Line counter (result) char filename[MAX_FILE_NAME]; char c; // To store a character read from file // Get file name from user. The file should be // either in current folder or complete path should be provided printf(\"Enter file name: \"); scanf(\"%s\", filename); // Open the file fp = fopen(filename, \"r\"); // Check if file exists if (fp == NULL) { printf(\"Could not open file %s\", filename); return 0; } // Extract characters from file and store in character c for (c = getc(fp); c != EOF; c = getc(fp)) if (c == '\\n') // Increment count if this character is newline count = count + 1; // Close the file fclose(fp); printf(\"The file %s has %d lines\\n \", filename, count); return 0;}",
"e": 983,
"s": 56,
"text": null
},
{
"code": null,
"e": 991,
"s": 983,
"text": "Output:"
},
{
"code": null,
"e": 1056,
"s": 991,
"text": "Enter file name: countLines.c\nThe file countLines.c has 41 lines"
},
{
"code": null,
"e": 1130,
"s": 1056,
"text": "Time complexity: O(N) where N is total number of characters in given file"
},
{
"code": null,
"e": 1250,
"s": 1130,
"text": "Please write comments if you find anything incorrect or want to share more information about the topic discussed above."
},
{
"code": null,
"e": 1267,
"s": 1250,
"text": "kumargaurav97520"
},
{
"code": null,
"e": 1285,
"s": 1267,
"text": "cpp-file-handling"
},
{
"code": null,
"e": 1296,
"s": 1285,
"text": "C Language"
}
] |
Extract last N rows of dataframe in R
|
16 Mar, 2021
The last n rows of the data frame can be accessed by using the in-built tail() method in R. Supposedly, N is the total number of rows in the data frame, then n <=N last rows can be extracted from the structure.
Syntax:
tail(dataframe, n = )
Parameter :
dataframe β The data frame to extract rows from the end
n β integer which indicates the number of rows to extract.
The changes are not retained to the original data frame. The time complexity is polynomial in terms of the number of rows to be extracted, that is the value n.
Create dataframe
Pass required number of rows to tail()
Extract rows
Display result
Example 1:
R
# declaring data framedata_frame = data.frame(col1 = c(1:6),col2 = c(7:12),col3 = c(13:24)) # printing original data frameprint ("Original Data Frame")print(data_frame) # extracting last row from the data framelast_row = tail(data_frame, n =1) # printing the last row of the data frameprint ("Extracting last row from data frame")print (last_row)
Output
[1] "Original Data Frame"
col1 col2 col3
1 1 7 13
2 2 8 14
3 3 9 15
4 4 10 16
5 5 11 17
6 6 12 18
7 1 7 19
8 2 8 20
9 3 9 21
10 4 10 22
11 5 11 23
12 6 12 24
[1] "Extracting last row from data frame"
col1 col2 col3
12 6 12 24
Example 2:
R
# declaring data framedata_frame = data.frame(col1 = c(1:6),col2 = c(7:12),col3 = c(13:24)) # printing original data frameprint ("Original Data Frame")print(data_frame) # extracting last row from the data framelast_4row = tail(data_frame, n = 4) # printing the last row of the data frameprint ("Extracting last 4 rows from data frame")print (last_4row)
Output
[1] "Original Data Frame"
col1 col2 col3
1 1 7 13
2 2 8 14
3 3 9 15
4 4 10 16
5 5 11 17
6 6 12 18
7 1 7 19
8 2 8 20
9 3 9 21
10 4 10 22
11 5 11 23
12 6 12 24
[1] "Extracting last 4 rows from data frame"
col1 col2 col3
9 3 9 21
10 4 10 22
11 5 11 23
12 6 12 24
nrow() method can be used to extract the number of total rows in the data frame. When we pass this as the argument value of n, then all the rows are extracted.
Example 3:
R
# declaring data framedata_frame = data.frame(col1 = c(1:3),col2 = c(7:9),col3 = c(13:15)) # printing original data frameprint ("Original Data Frame")print(data_frame) # extracting all rows from the data frame using nrow() methoddf = tail(data_frame, n = nrow(data_frame)) # printing the last row of the data frameprint ("Extracting last rows from data frame")print (df)
Output
[1] "Original Data Frame"
col1 col2 col3
1 1 7 13
2 2 8 14
3 3 9 15
[1] "Extracting last rows from data frame"
col1 col2 col3
1 1 7 13
2 2 8 14
3 3 9 15
Picked
R-DataFrame
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
R - if statement
How to filter R DataFrame by values in a column?
Remove rows with NA in one column of R DataFrame
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Mar, 2021"
},
{
"code": null,
"e": 240,
"s": 28,
"text": "The last n rows of the data frame can be accessed by using the in-built tail() method in R. Supposedly, N is the total number of rows in the data frame, then n <=N last rows can be extracted from the structure. "
},
{
"code": null,
"e": 248,
"s": 240,
"text": "Syntax:"
},
{
"code": null,
"e": 271,
"s": 248,
"text": "tail(dataframe, n = ) "
},
{
"code": null,
"e": 284,
"s": 271,
"text": "Parameter : "
},
{
"code": null,
"e": 340,
"s": 284,
"text": "dataframe β The data frame to extract rows from the end"
},
{
"code": null,
"e": 399,
"s": 340,
"text": "n β integer which indicates the number of rows to extract."
},
{
"code": null,
"e": 560,
"s": 399,
"text": "The changes are not retained to the original data frame. The time complexity is polynomial in terms of the number of rows to be extracted, that is the value n. "
},
{
"code": null,
"e": 577,
"s": 560,
"text": "Create dataframe"
},
{
"code": null,
"e": 616,
"s": 577,
"text": "Pass required number of rows to tail()"
},
{
"code": null,
"e": 629,
"s": 616,
"text": "Extract rows"
},
{
"code": null,
"e": 644,
"s": 629,
"text": "Display result"
},
{
"code": null,
"e": 655,
"s": 644,
"text": "Example 1:"
},
{
"code": null,
"e": 657,
"s": 655,
"text": "R"
},
{
"code": "# declaring data framedata_frame = data.frame(col1 = c(1:6),col2 = c(7:12),col3 = c(13:24)) # printing original data frameprint (\"Original Data Frame\")print(data_frame) # extracting last row from the data framelast_row = tail(data_frame, n =1) # printing the last row of the data frameprint (\"Extracting last row from data frame\")print (last_row)",
"e": 1007,
"s": 657,
"text": null
},
{
"code": null,
"e": 1014,
"s": 1007,
"text": "Output"
},
{
"code": null,
"e": 1350,
"s": 1014,
"text": "[1] \"Original Data Frame\"\n col1 col2 col3\n1 1 7 13\n2 2 8 14\n3 3 9 15\n4 4 10 16\n5 5 11 17\n6 6 12 18\n7 1 7 19\n8 2 8 20\n9 3 9 21\n10 4 10 22\n11 5 11 23\n12 6 12 24\n[1] \"Extracting last row from data frame\"\n col1 col2 col3\n12 6 12 24"
},
{
"code": null,
"e": 1361,
"s": 1350,
"text": "Example 2:"
},
{
"code": null,
"e": 1363,
"s": 1361,
"text": "R"
},
{
"code": "# declaring data framedata_frame = data.frame(col1 = c(1:6),col2 = c(7:12),col3 = c(13:24)) # printing original data frameprint (\"Original Data Frame\")print(data_frame) # extracting last row from the data framelast_4row = tail(data_frame, n = 4) # printing the last row of the data frameprint (\"Extracting last 4 rows from data frame\")print (last_4row)",
"e": 1719,
"s": 1363,
"text": null
},
{
"code": null,
"e": 1726,
"s": 1719,
"text": "Output"
},
{
"code": null,
"e": 2119,
"s": 1726,
"text": "[1] \"Original Data Frame\"\n col1 col2 col3\n1 1 7 13\n2 2 8 14\n3 3 9 15\n4 4 10 16\n5 5 11 17\n6 6 12 18\n7 1 7 19\n8 2 8 20\n9 3 9 21\n10 4 10 22\n11 5 11 23\n12 6 12 24\n[1] \"Extracting last 4 rows from data frame\"\n col1 col2 col3\n9 3 9 21\n10 4 10 22\n11 5 11 23\n12 6 12 24"
},
{
"code": null,
"e": 2280,
"s": 2119,
"text": "nrow() method can be used to extract the number of total rows in the data frame. When we pass this as the argument value of n, then all the rows are extracted. "
},
{
"code": null,
"e": 2291,
"s": 2280,
"text": "Example 3:"
},
{
"code": null,
"e": 2293,
"s": 2291,
"text": "R"
},
{
"code": "# declaring data framedata_frame = data.frame(col1 = c(1:3),col2 = c(7:9),col3 = c(13:15)) # printing original data frameprint (\"Original Data Frame\")print(data_frame) # extracting all rows from the data frame using nrow() methoddf = tail(data_frame, n = nrow(data_frame)) # printing the last row of the data frameprint (\"Extracting last rows from data frame\")print (df)",
"e": 2667,
"s": 2293,
"text": null
},
{
"code": null,
"e": 2674,
"s": 2667,
"text": "Output"
},
{
"code": null,
"e": 2877,
"s": 2674,
"text": "[1] \"Original Data Frame\"\n col1 col2 col3\n1 1 7 13\n2 2 8 14\n3 3 9 15\n[1] \"Extracting last rows from data frame\"\n col1 col2 col3\n1 1 7 13\n2 2 8 14\n3 3 9 15"
},
{
"code": null,
"e": 2884,
"s": 2877,
"text": "Picked"
},
{
"code": null,
"e": 2896,
"s": 2884,
"text": "R-DataFrame"
},
{
"code": null,
"e": 2907,
"s": 2896,
"text": "R Language"
},
{
"code": null,
"e": 3005,
"s": 2907,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3057,
"s": 3005,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 3109,
"s": 3057,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 3167,
"s": 3109,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3199,
"s": 3167,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 3234,
"s": 3199,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 3278,
"s": 3234,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 3316,
"s": 3278,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 3333,
"s": 3316,
"text": "R - if statement"
},
{
"code": null,
"e": 3382,
"s": 3333,
"text": "How to filter R DataFrame by values in a column?"
}
] |
Wave Array | Practice | GeeksforGeeks
|
Given a sorted array arr[] of distinct integers. Sort the array into a wave-like array and return it
In other words, arrange the elements into a sequence such that arr[1] >= arr[2] <= arr[3] >= arr[4] <= arr[5].....
If there are multiple solutions, find the lexicographically smallest one.
Example 1:
Input:
n = 5
arr[] = {1,2,3,4,5}
Output: 2 1 4 3 5
Explanation: Array elements after
sorting it in wave form are
2 1 4 3 5.
Example 2:
Input:
n = 6
arr[] = {2,4,7,8,9,10}
Output: 4 2 8 7 10 9
Explanation: Array elements after
sorting it in wave form are
4 2 8 7 10 9.
Your Task:
The task is to complete the function convertToWave(), which converts the given array to a wave array.
Expected Time Complexity: O(n).
Expected Auxiliary Space: O(1).
Constraints:
1 β€ n β€ 106
0 β€ arr[i] β€107
0
rahulvishwas26024 days ago
// Your code here int j=1; for(int i=0;i<n;i+=2){ if(i==n-1 && n%2==1) { break; } int temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; }
0
heynileshkapoor6 days ago
C++ | EASY | 0.1/1.41
void convertToWave(vector<int>& arr, int n){
// Your code here
int k;
if(arr.size()%2==0)
{
k = arr.size();
}
else
{
k = arr.size()-1;
}
for(int i=0;i<k;i+=2)
{
arr[i] = arr[i]^arr[i+1];
arr[i+1] = arr[i]^arr[i+1];//Using XOR to swap elements
arr[i] = arr[i]^arr[i+1];
}
}
0
shekharankur46 days ago
class Solution{
public:
void convertToWave(vector<int>& arr, int n){
// Your code here
for(int i=0;i<n-1;i+=2){
if(arr[i] < arr[i+1]){
int x = arr[i];
arr[i]=arr[i+1];
arr[i+1]=x;
}
}
}
};
+1
user_qmho6 days ago
// Your code here for(int i=0;i<n-1;i=i+2) { swap(arr[i],arr[i+1]); }
0
chhetriarjun555551 week ago
C++
void convertToWave(vector<int>& arr, int n){ int i=0, j=0; while(i < n/2){ swap(arr[j], arr[j+1]); i++; j += 2; } }
0
kushwaharajshree231 week ago
C++ solution just same approach as REVERSE ARRAY IN GROUPS...
void convertToWave(vector<int>& arr, int n){
// Your code here
int k= 2;
for(int i=0; i<n; i+=k)
{
int l=i;
int r=min(i+k-1, n-1);
while(l<=r)
{
int temp= arr[l];
arr[l]=arr[r];
arr[r]= temp;
l++;
r--;
}
}
}
0
riyaraip081 week ago
// Your code here int i=0,j=1; for(i=0;i<n;i+=2) { if(j>=n){ break; } if(arr[i]<arr[j]){ swap(arr[i], arr[j]); } j += 2; } }
0
codewithshoaib191 week ago
public static void convertToWave(int arr[], int n){ // Your code here for(int i=0;i<n-1;i+=2){ swap(arr,i,i+1); } } public static void swap(int[]arr,int s,int e){ int temp=arr[s]; arr[s]=arr[e]; arr[e]=temp; }
0
jayrambagal002 weeks ago
Python Solution:
def convertToWave(self,arr,N): for i in range(0,N-1,2): arr[i],arr[i+1]=arr[i+1],arr[i] return arr
0
mayank180919992 weeks ago
void convertToWave(vector<int>& arr, int n){
// Your code here
for(int i=0;i<n-1;i+=2){
if(arr[i]<arr[i+1]){
swap(arr[i],arr[i+1]);
}
}
}
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": 454,
"s": 238,
"text": "Given a sorted array arr[] of distinct integers. Sort the array into a wave-like array and return it\nIn other words, arrange the elements into a sequence such that arr[1] >= arr[2] <= arr[3] >= arr[4] <= arr[5]....."
},
{
"code": null,
"e": 528,
"s": 454,
"text": "If there are multiple solutions, find the lexicographically smallest one."
},
{
"code": null,
"e": 539,
"s": 528,
"text": "Example 1:"
},
{
"code": null,
"e": 665,
"s": 539,
"text": "Input:\nn = 5\narr[] = {1,2,3,4,5}\nOutput: 2 1 4 3 5\nExplanation: Array elements after \nsorting it in wave form are \n2 1 4 3 5."
},
{
"code": null,
"e": 676,
"s": 665,
"text": "Example 2:"
},
{
"code": null,
"e": 811,
"s": 676,
"text": "Input:\nn = 6\narr[] = {2,4,7,8,9,10}\nOutput: 4 2 8 7 10 9\nExplanation: Array elements after \nsorting it in wave form are \n4 2 8 7 10 9."
},
{
"code": null,
"e": 924,
"s": 811,
"text": "Your Task:\nThe task is to complete the function convertToWave(), which converts the given array to a wave array."
},
{
"code": null,
"e": 988,
"s": 924,
"text": "Expected Time Complexity: O(n).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 1029,
"s": 988,
"text": "Constraints:\n1 β€ n β€ 106\n0 β€ arr[i] β€107"
},
{
"code": null,
"e": 1031,
"s": 1029,
"text": "0"
},
{
"code": null,
"e": 1058,
"s": 1031,
"text": "rahulvishwas26024 days ago"
},
{
"code": null,
"e": 1281,
"s": 1058,
"text": " // Your code here int j=1; for(int i=0;i<n;i+=2){ if(i==n-1 && n%2==1) { break; } int temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; }"
},
{
"code": null,
"e": 1283,
"s": 1281,
"text": "0"
},
{
"code": null,
"e": 1309,
"s": 1283,
"text": "heynileshkapoor6 days ago"
},
{
"code": null,
"e": 1332,
"s": 1309,
"text": "C++ | EASY | 0.1/1.41 "
},
{
"code": null,
"e": 1798,
"s": 1336,
"text": " void convertToWave(vector<int>& arr, int n){\n \n // Your code here\n int k;\n if(arr.size()%2==0)\n {\n k = arr.size();\n }\n else\n {\n k = arr.size()-1;\n }\n for(int i=0;i<k;i+=2)\n {\n arr[i] = arr[i]^arr[i+1];\n arr[i+1] = arr[i]^arr[i+1];//Using XOR to swap elements\n arr[i] = arr[i]^arr[i+1];\n \n }\n \n }\n"
},
{
"code": null,
"e": 1800,
"s": 1798,
"text": "0"
},
{
"code": null,
"e": 1824,
"s": 1800,
"text": "shekharankur46 days ago"
},
{
"code": null,
"e": 2133,
"s": 1824,
"text": "\nclass Solution{\n public:\n void convertToWave(vector<int>& arr, int n){\n \n // Your code here\n for(int i=0;i<n-1;i+=2){\n if(arr[i] < arr[i+1]){\n int x = arr[i];\n arr[i]=arr[i+1];\n arr[i+1]=x;\n }\n }\n }\n};\n\n"
},
{
"code": null,
"e": 2136,
"s": 2133,
"text": "+1"
},
{
"code": null,
"e": 2156,
"s": 2136,
"text": "user_qmho6 days ago"
},
{
"code": null,
"e": 2254,
"s": 2156,
"text": "// Your code here for(int i=0;i<n-1;i=i+2) { swap(arr[i],arr[i+1]); }"
},
{
"code": null,
"e": 2256,
"s": 2254,
"text": "0"
},
{
"code": null,
"e": 2284,
"s": 2256,
"text": "chhetriarjun555551 week ago"
},
{
"code": null,
"e": 2288,
"s": 2284,
"text": "C++"
},
{
"code": null,
"e": 2449,
"s": 2288,
"text": "void convertToWave(vector<int>& arr, int n){ int i=0, j=0; while(i < n/2){ swap(arr[j], arr[j+1]); i++; j += 2; } }"
},
{
"code": null,
"e": 2451,
"s": 2449,
"text": "0"
},
{
"code": null,
"e": 2480,
"s": 2451,
"text": "kushwaharajshree231 week ago"
},
{
"code": null,
"e": 2542,
"s": 2480,
"text": "C++ solution just same approach as REVERSE ARRAY IN GROUPS..."
},
{
"code": null,
"e": 2955,
"s": 2544,
"text": " void convertToWave(vector<int>& arr, int n){\n \n // Your code here\n int k= 2;\n for(int i=0; i<n; i+=k)\n {\n int l=i;\n int r=min(i+k-1, n-1);\n while(l<=r)\n {\n int temp= arr[l];\n arr[l]=arr[r];\n arr[r]= temp;\n l++;\n r--;\n }\n }\n \n }"
},
{
"code": null,
"e": 2957,
"s": 2955,
"text": "0"
},
{
"code": null,
"e": 2978,
"s": 2957,
"text": "riyaraip081 week ago"
},
{
"code": null,
"e": 3207,
"s": 2978,
"text": "// Your code here int i=0,j=1; for(i=0;i<n;i+=2) { if(j>=n){ break; } if(arr[i]<arr[j]){ swap(arr[i], arr[j]); } j += 2; } }"
},
{
"code": null,
"e": 3209,
"s": 3207,
"text": "0"
},
{
"code": null,
"e": 3236,
"s": 3209,
"text": "codewithshoaib191 week ago"
},
{
"code": null,
"e": 3498,
"s": 3236,
"text": "public static void convertToWave(int arr[], int n){ // Your code here for(int i=0;i<n-1;i+=2){ swap(arr,i,i+1); } } public static void swap(int[]arr,int s,int e){ int temp=arr[s]; arr[s]=arr[e]; arr[e]=temp; }"
},
{
"code": null,
"e": 3500,
"s": 3498,
"text": "0"
},
{
"code": null,
"e": 3525,
"s": 3500,
"text": "jayrambagal002 weeks ago"
},
{
"code": null,
"e": 3542,
"s": 3525,
"text": "Python Solution:"
},
{
"code": null,
"e": 3665,
"s": 3544,
"text": "def convertToWave(self,arr,N): for i in range(0,N-1,2): arr[i],arr[i+1]=arr[i+1],arr[i] return arr"
},
{
"code": null,
"e": 3667,
"s": 3665,
"text": "0"
},
{
"code": null,
"e": 3693,
"s": 3667,
"text": "mayank180919992 weeks ago"
},
{
"code": null,
"e": 3918,
"s": 3693,
"text": " void convertToWave(vector<int>& arr, int n){\n \n // Your code here\n for(int i=0;i<n-1;i+=2){\n if(arr[i]<arr[i+1]){\n swap(arr[i],arr[i+1]);\n }\n }\n \n }"
},
{
"code": null,
"e": 4064,
"s": 3918,
"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": 4100,
"s": 4064,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4110,
"s": 4100,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4120,
"s": 4110,
"text": "\nContest\n"
},
{
"code": null,
"e": 4183,
"s": 4120,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4331,
"s": 4183,
"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": 4539,
"s": 4331,
"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": 4645,
"s": 4539,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Alternating Numbers - GeeksforGeeks
|
31 Mar, 2021
Given a number N, the task is to check if N is an Alternating Number or not. If N is an Alternating Number then print βYesβ else print βNoβ.
Alternating Number is a positive integer for which, in base-10, the parity of its digits are alternates i.e., the digits in number N is followed by odd, even, odd, ... or even, odd, even, ... order.
Examples:
Input: N = 129 Output: Yes Explanation: 129 has digits which is in alternate odd even odd form.
Input: N = 28 Output: No Explanation: 28 has digits which is not in alternate odd even odd form.
Approach: The idea is to convert the number into a string and check if any digit is followed by the digit of the same parity then N is not an Alternating Numbers, else N is an Alternating Numbers.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if a string is// of the form even odd even odd...bool isEvenOddForm(string s){ int n = s.length(); for (int i = 0; i < n; i++) { if (i % 2 == 0 && s[i] % 2 != 0) return false; if (i % 2 == 1 && s[i] % 2 != 1) return false; } return true;} // Function to check if a string is// of the form odd even odd even ...bool isOddEvenForm(string s){ int n = s.length(); for (int i = 0; i < n; i++) { if (i % 2 == 0 && s[i] % 2 != 1) return false; if (i % 2 == 1 && s[i] % 2 != 0) return false; } return true;} // Function to check if n is an// alternating numberbool isAlternating(int n){ string str = to_string(n); return (isEvenOddForm(str) || isOddEvenForm(str));} // Driver Codeint main(){ // Given Number N int N = 129; // Function Call if (isAlternating(N)) cout << "Yes"; else cout << "No"; return 0;}
// Java program for the above approachclass GFG{ // Function to check if a string is// of the form even odd even odd...static boolean isEvenOddForm(String s){ int n = s.length(); for(int i = 0; i < n; i++) { if (i % 2 == 0 && s.charAt(i) % 2 != 0) return false; if (i % 2 == 1 && s.charAt(i) % 2 != 1) return false; } return true;} // Function to check if a string is// of the form odd even odd even ...static boolean isOddEvenForm(String s){ int n = s.length(); for(int i = 0; i < n; i++) { if (i % 2 == 0 && s.charAt(i) % 2 != 1) return false; if (i % 2 == 1 && s.charAt(i) % 2 != 0) return false; } return true;} // Function to check if n is an// alternating numberstatic boolean isAlternating(int n){ String str = Integer.toString(n); return (isEvenOddForm(str) || isOddEvenForm(str));} // Driver Codepublic static void main(String[] args){ // Given number N int N = 129; // Function call if (isAlternating(N)) System.out.println("Yes"); else System.out.println("No");}} // This Code is contributed by rock_cool
# Python3 program for the above approach # Function to check if a string is# of the form even odd even odd...def isEvenOddForm(s): n = len(s) for i in range(n): if (i % 2 == 0 and int(s[i]) % 2 != 0): return False if (i % 2 == 1 and int(s[i]) % 2 != 1): return False return True # Function to check if a string is# of the form odd even odd even ...def isOddEvenForm(s): n = len(s) for i in range(n): if (i % 2 == 0 and int(s[i]) % 2 != 1): return False if (i % 2 == 1 and int(s[i]) % 2 != 0): return False return True # Function to check if n is an# alternating numberdef isAlternating(n): s = str(n) return (isEvenOddForm(s) or isOddEvenForm(s)) # Driver Code # Given Number NN = 129 # Function Callif (isAlternating(N)): print("Yes")else: print("No") # This code is contributed by Vishal Maurya
// C# program for the above approachusing System;class GFG{ // Function to check if a string is// of the form even odd even odd...static bool isEvenOddForm(String s){ int n = s.Length; for(int i = 0; i < n; i++) { if (i % 2 == 0 && s[i] % 2 != 0) return false; if (i % 2 == 1 && s[i] % 2 != 1) return false; } return true;} // Function to check if a string is// of the form odd even odd even ...static bool isOddEvenForm(String s){ int n = s.Length; for(int i = 0; i < n; i++) { if (i % 2 == 0 && s[i] % 2 != 1) return false; if (i % 2 == 1 && s[i] % 2 != 0) return false; } return true;} // Function to check if n is an// alternating numberstatic bool isAlternating(int n){ String str = n.ToString(); return (isEvenOddForm(str) || isOddEvenForm(str));} // Driver Codepublic static void Main(String[] args){ // Given number N int N = 129; // Function call if (isAlternating(N)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by Princi Singh
<script> // Javascript program for the above approach // Function to check if a string is// of the form even odd even odd...function isEvenOddForm(s){ let n = s.length; for(let i = 0; i < n; i++) { if (i % 2 == 0 && s[i] % 2 != 0) return false; if (i % 2 == 1 && s[i] % 2 != 1) return false; } return true;} // Function to check if a string is// of the form odd even odd even ...function isOddEvenForm(s){ let n = s.length; for(let i = 0; i < n; i++) { if (i % 2 == 0 && s[i] % 2 != 1) return false; if (i % 2 == 1 && s[i] % 2 != 0) return false; } return true;} // Function to check if n is an// alternating numberfunction isAlternating(n){ let str = n.toString(); return (isEvenOddForm(str) || isOddEvenForm(str));} // Driver code // Given number Nlet N = 129; // Function callif (isAlternating(N)) document.write("Yes");else document.write("No"); // This code is contributed by divyesh072019 </script>
Yes
Time Complexity: O(log10N)
vishu2908
rock_cool
princi singh
divyesh072019
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
Program for Decimal to Binary Conversion
Program for factorial of a number
Operators in C / C++
Euclidean algorithms (Basic and Extended)
The Knight's tour problem | Backtracking-1
Efficient program to print all prime factors of a given number
|
[
{
"code": null,
"e": 24742,
"s": 24714,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 24883,
"s": 24742,
"text": "Given a number N, the task is to check if N is an Alternating Number or not. If N is an Alternating Number then print βYesβ else print βNoβ."
},
{
"code": null,
"e": 25084,
"s": 24883,
"text": "Alternating Number is a positive integer for which, in base-10, the parity of its digits are alternates i.e., the digits in number N is followed by odd, even, odd, ... or even, odd, even, ... order. "
},
{
"code": null,
"e": 25095,
"s": 25084,
"text": "Examples: "
},
{
"code": null,
"e": 25191,
"s": 25095,
"text": "Input: N = 129 Output: Yes Explanation: 129 has digits which is in alternate odd even odd form."
},
{
"code": null,
"e": 25289,
"s": 25191,
"text": "Input: N = 28 Output: No Explanation: 28 has digits which is not in alternate odd even odd form. "
},
{
"code": null,
"e": 25486,
"s": 25289,
"text": "Approach: The idea is to convert the number into a string and check if any digit is followed by the digit of the same parity then N is not an Alternating Numbers, else N is an Alternating Numbers."
},
{
"code": null,
"e": 25538,
"s": 25486,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25542,
"s": 25538,
"text": "C++"
},
{
"code": null,
"e": 25547,
"s": 25542,
"text": "Java"
},
{
"code": null,
"e": 25555,
"s": 25547,
"text": "Python3"
},
{
"code": null,
"e": 25558,
"s": 25555,
"text": "C#"
},
{
"code": null,
"e": 25569,
"s": 25558,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if a string is// of the form even odd even odd...bool isEvenOddForm(string s){ int n = s.length(); for (int i = 0; i < n; i++) { if (i % 2 == 0 && s[i] % 2 != 0) return false; if (i % 2 == 1 && s[i] % 2 != 1) return false; } return true;} // Function to check if a string is// of the form odd even odd even ...bool isOddEvenForm(string s){ int n = s.length(); for (int i = 0; i < n; i++) { if (i % 2 == 0 && s[i] % 2 != 1) return false; if (i % 2 == 1 && s[i] % 2 != 0) return false; } return true;} // Function to check if n is an// alternating numberbool isAlternating(int n){ string str = to_string(n); return (isEvenOddForm(str) || isOddEvenForm(str));} // Driver Codeint main(){ // Given Number N int N = 129; // Function Call if (isAlternating(N)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 26620,
"s": 25569,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function to check if a string is// of the form even odd even odd...static boolean isEvenOddForm(String s){ int n = s.length(); for(int i = 0; i < n; i++) { if (i % 2 == 0 && s.charAt(i) % 2 != 0) return false; if (i % 2 == 1 && s.charAt(i) % 2 != 1) return false; } return true;} // Function to check if a string is// of the form odd even odd even ...static boolean isOddEvenForm(String s){ int n = s.length(); for(int i = 0; i < n; i++) { if (i % 2 == 0 && s.charAt(i) % 2 != 1) return false; if (i % 2 == 1 && s.charAt(i) % 2 != 0) return false; } return true;} // Function to check if n is an// alternating numberstatic boolean isAlternating(int n){ String str = Integer.toString(n); return (isEvenOddForm(str) || isOddEvenForm(str));} // Driver Codepublic static void main(String[] args){ // Given number N int N = 129; // Function call if (isAlternating(N)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This Code is contributed by rock_cool",
"e": 27786,
"s": 26620,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to check if a string is# of the form even odd even odd...def isEvenOddForm(s): n = len(s) for i in range(n): if (i % 2 == 0 and int(s[i]) % 2 != 0): return False if (i % 2 == 1 and int(s[i]) % 2 != 1): return False return True # Function to check if a string is# of the form odd even odd even ...def isOddEvenForm(s): n = len(s) for i in range(n): if (i % 2 == 0 and int(s[i]) % 2 != 1): return False if (i % 2 == 1 and int(s[i]) % 2 != 0): return False return True # Function to check if n is an# alternating numberdef isAlternating(n): s = str(n) return (isEvenOddForm(s) or isOddEvenForm(s)) # Driver Code # Given Number NN = 129 # Function Callif (isAlternating(N)): print(\"Yes\")else: print(\"No\") # This code is contributed by Vishal Maurya",
"e": 28744,
"s": 27786,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function to check if a string is// of the form even odd even odd...static bool isEvenOddForm(String s){ int n = s.Length; for(int i = 0; i < n; i++) { if (i % 2 == 0 && s[i] % 2 != 0) return false; if (i % 2 == 1 && s[i] % 2 != 1) return false; } return true;} // Function to check if a string is// of the form odd even odd even ...static bool isOddEvenForm(String s){ int n = s.Length; for(int i = 0; i < n; i++) { if (i % 2 == 0 && s[i] % 2 != 1) return false; if (i % 2 == 1 && s[i] % 2 != 0) return false; } return true;} // Function to check if n is an// alternating numberstatic bool isAlternating(int n){ String str = n.ToString(); return (isEvenOddForm(str) || isOddEvenForm(str));} // Driver Codepublic static void Main(String[] args){ // Given number N int N = 129; // Function call if (isAlternating(N)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by Princi Singh",
"e": 29882,
"s": 28744,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to check if a string is// of the form even odd even odd...function isEvenOddForm(s){ let n = s.length; for(let i = 0; i < n; i++) { if (i % 2 == 0 && s[i] % 2 != 0) return false; if (i % 2 == 1 && s[i] % 2 != 1) return false; } return true;} // Function to check if a string is// of the form odd even odd even ...function isOddEvenForm(s){ let n = s.length; for(let i = 0; i < n; i++) { if (i % 2 == 0 && s[i] % 2 != 1) return false; if (i % 2 == 1 && s[i] % 2 != 0) return false; } return true;} // Function to check if n is an// alternating numberfunction isAlternating(n){ let str = n.toString(); return (isEvenOddForm(str) || isOddEvenForm(str));} // Driver code // Given number Nlet N = 129; // Function callif (isAlternating(N)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by divyesh072019 </script>",
"e": 30923,
"s": 29882,
"text": null
},
{
"code": null,
"e": 30927,
"s": 30923,
"text": "Yes"
},
{
"code": null,
"e": 30957,
"s": 30929,
"text": "Time Complexity: O(log10N) "
},
{
"code": null,
"e": 30967,
"s": 30957,
"text": "vishu2908"
},
{
"code": null,
"e": 30977,
"s": 30967,
"text": "rock_cool"
},
{
"code": null,
"e": 30990,
"s": 30977,
"text": "princi singh"
},
{
"code": null,
"e": 31004,
"s": 30990,
"text": "divyesh072019"
},
{
"code": null,
"e": 31011,
"s": 31004,
"text": "series"
},
{
"code": null,
"e": 31024,
"s": 31011,
"text": "Mathematical"
},
{
"code": null,
"e": 31037,
"s": 31024,
"text": "Mathematical"
},
{
"code": null,
"e": 31044,
"s": 31037,
"text": "series"
},
{
"code": null,
"e": 31142,
"s": 31044,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31166,
"s": 31142,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 31209,
"s": 31166,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 31223,
"s": 31209,
"text": "Prime Numbers"
},
{
"code": null,
"e": 31272,
"s": 31223,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 31313,
"s": 31272,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 31347,
"s": 31313,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 31368,
"s": 31347,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 31410,
"s": 31368,
"text": "Euclidean algorithms (Basic and Extended)"
},
{
"code": null,
"e": 31453,
"s": 31410,
"text": "The Knight's tour problem | Backtracking-1"
}
] |
WPF - Window
|
Window is the root window of XAML applications which provides minimize/maximize option, title bar, border, and close button. It also provides the ability to create, configure, show, and manage the lifetime of windows and dialog boxes. The hierarchical inheritance of Window class is as follows β
AllowsTransparency
Gets or sets a value that indicates whether a window's client area supports transparency.
DialogResult
Gets or sets the dialog result value, which is the value that is returned from the ShowDialog method.
Icon
Gets or sets a window's icon.
IsActive
Gets a value that indicates whether the window is active.
Left
Gets or sets the position of the window's left edge, in relation to the desktop.
OwnedWindows
Gets a collection of windows for which this window is the owner.
Owner
Gets or sets the Window that owns this Window.
ResizeMode
Gets or sets the resize mode.
RestoreBounds
Gets the size and location of a window before being either minimized or maximized.
ShowActivated
Gets or sets a value that indicates whether a window is activated when first shown.
ShowInTaskbar
Gets or sets a value that indicates whether the window has a task bar button.
SizeToContent
Gets or sets a value that indicates whether a window will automatically size itself to fit the size of its content.
TaskbarItemInfo
Gets or sets the Windows 7 taskbar thumbnail for the Window.
Title
Gets or sets a window's title.
Top
Gets or sets the position of the window's top edge, in relation to the desktop.
Topmost
Gets or sets a value that indicates whether a window appears in the topmost z-order.
WindowStartupLocation
Gets or sets the position of the window when first shown.
WindowState
Gets or sets a value that indicates whether a window is restored, minimized, or maximized.
WindowStyle
Gets or sets a window's border style.
Activated
Occurs when a window becomes the foreground window.
Closed
Occurs when the window is about to close.
Closing
Occurs directly after Close is called, and can be handled to cancel window closure.
ContentRendered
Occurs after a window's content has been rendered.
Deactivated
Occurs when a window becomes a background window.
LocationChanged
Occurs when the window's location changes.
SourceInitialized
This event is raised to support interoperation with Win32. See HwndSource.
StateChanged
Occurs when the window's WindowState property changes.
Activate
Attempts to bring the window to the foreground and activates it.
Close
Manually closes a Window.
DragMove
Allows a window to be dragged by a mouse with its left button down over an exposed area of the window's client area.
GetWindow
Returns a reference to the Window object that hosts the content tree within which the dependency object is located.
Hide
Makes a window invisible.
Show
Opens a window and returns without waiting for the newly opened window to close.
ShowDialog
Opens a window and returns only when the newly opened window is closed.
When you create a new WPF project, then by default, the Window control is present. Letβs have a look at the following example.
When you create a new WPF project, then by default, the Window control is present. Letβs have a look at the following example.
The following XAML code starts with a <Window> Tag and ends with a </Window> tag. The code sets some properties for the window and creates some other controls like text blocks, button, etc.
The following XAML code starts with a <Window> Tag and ends with a </Window> tag. The code sets some properties for the window and creates some other controls like text blocks, button, etc.
<Window x:Class = "WPFToolTipControl.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local = "clr-namespace:WPFToolTipControl"
mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604">
<Grid>
<TextBlock x:Name = "textBlock" HorizontalAlignment = "Left"
Margin = "101,75,0,0" TextWrapping = "Wrap"
Text = "User Name" VerticalAlignment = "Top" />
<TextBlock x:Name = "textBlock1" HorizontalAlignment = "Left"
Margin = "101,125,0,0" TextWrapping = "Wrap"
Text = "Password" VerticalAlignment = "Top" />
<TextBox x:Name = "textBox" HorizontalAlignment = "Left"
Height = "24" Margin = "199,75,0,0" TextWrapping = "Wrap"
VerticalAlignment = "Top" Width = "219"
ToolTipService.ToolTip = "Enter User Name" />
<PasswordBox x:Name = "passwordBox" HorizontalAlignment = "Left"
Margin = "199,125,0,0" VerticalAlignment = "Top" Width = "219"
Height = "24" ToolTipService.ToolTip = "Enter Password" />
<Button x:Name = "button" Content = "Log in" HorizontalAlignment = "Left"
Margin = "199,189,0,0" VerticalAlignment = "Top" Width = "75"
ToolTipService.ToolTip = "Log in" />
</Grid>
</Window>
When you compile and execute the above code, it will display the following output. When the mouse enters the region of the Button or the Textboxes, it will show a tooltip.
We recommend that you execute the above example code and try some other properties and events of this class.
31 Lectures
2.5 hours
Anadi Sharma
30 Lectures
2.5 hours
Taurius Litvinavicius
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2316,
"s": 2020,
"text": "Window is the root window of XAML applications which provides minimize/maximize option, title bar, border, and close button. It also provides the ability to create, configure, show, and manage the lifetime of windows and dialog boxes. The hierarchical inheritance of Window class is as follows β"
},
{
"code": null,
"e": 2335,
"s": 2316,
"text": "AllowsTransparency"
},
{
"code": null,
"e": 2425,
"s": 2335,
"text": "Gets or sets a value that indicates whether a window's client area supports transparency."
},
{
"code": null,
"e": 2438,
"s": 2425,
"text": "DialogResult"
},
{
"code": null,
"e": 2540,
"s": 2438,
"text": "Gets or sets the dialog result value, which is the value that is returned from the ShowDialog method."
},
{
"code": null,
"e": 2545,
"s": 2540,
"text": "Icon"
},
{
"code": null,
"e": 2575,
"s": 2545,
"text": "Gets or sets a window's icon."
},
{
"code": null,
"e": 2584,
"s": 2575,
"text": "IsActive"
},
{
"code": null,
"e": 2642,
"s": 2584,
"text": "Gets a value that indicates whether the window is active."
},
{
"code": null,
"e": 2647,
"s": 2642,
"text": "Left"
},
{
"code": null,
"e": 2728,
"s": 2647,
"text": "Gets or sets the position of the window's left edge, in relation to the desktop."
},
{
"code": null,
"e": 2741,
"s": 2728,
"text": "OwnedWindows"
},
{
"code": null,
"e": 2806,
"s": 2741,
"text": "Gets a collection of windows for which this window is the owner."
},
{
"code": null,
"e": 2812,
"s": 2806,
"text": "Owner"
},
{
"code": null,
"e": 2859,
"s": 2812,
"text": "Gets or sets the Window that owns this Window."
},
{
"code": null,
"e": 2870,
"s": 2859,
"text": "ResizeMode"
},
{
"code": null,
"e": 2900,
"s": 2870,
"text": "Gets or sets the resize mode."
},
{
"code": null,
"e": 2914,
"s": 2900,
"text": "RestoreBounds"
},
{
"code": null,
"e": 2997,
"s": 2914,
"text": "Gets the size and location of a window before being either minimized or maximized."
},
{
"code": null,
"e": 3011,
"s": 2997,
"text": "ShowActivated"
},
{
"code": null,
"e": 3095,
"s": 3011,
"text": "Gets or sets a value that indicates whether a window is activated when first shown."
},
{
"code": null,
"e": 3109,
"s": 3095,
"text": "ShowInTaskbar"
},
{
"code": null,
"e": 3187,
"s": 3109,
"text": "Gets or sets a value that indicates whether the window has a task bar button."
},
{
"code": null,
"e": 3201,
"s": 3187,
"text": "SizeToContent"
},
{
"code": null,
"e": 3317,
"s": 3201,
"text": "Gets or sets a value that indicates whether a window will automatically size itself to fit the size of its content."
},
{
"code": null,
"e": 3333,
"s": 3317,
"text": "TaskbarItemInfo"
},
{
"code": null,
"e": 3394,
"s": 3333,
"text": "Gets or sets the Windows 7 taskbar thumbnail for the Window."
},
{
"code": null,
"e": 3400,
"s": 3394,
"text": "Title"
},
{
"code": null,
"e": 3431,
"s": 3400,
"text": "Gets or sets a window's title."
},
{
"code": null,
"e": 3435,
"s": 3431,
"text": "Top"
},
{
"code": null,
"e": 3515,
"s": 3435,
"text": "Gets or sets the position of the window's top edge, in relation to the desktop."
},
{
"code": null,
"e": 3523,
"s": 3515,
"text": "Topmost"
},
{
"code": null,
"e": 3608,
"s": 3523,
"text": "Gets or sets a value that indicates whether a window appears in the topmost z-order."
},
{
"code": null,
"e": 3630,
"s": 3608,
"text": "WindowStartupLocation"
},
{
"code": null,
"e": 3688,
"s": 3630,
"text": "Gets or sets the position of the window when first shown."
},
{
"code": null,
"e": 3700,
"s": 3688,
"text": "WindowState"
},
{
"code": null,
"e": 3791,
"s": 3700,
"text": "Gets or sets a value that indicates whether a window is restored, minimized, or maximized."
},
{
"code": null,
"e": 3803,
"s": 3791,
"text": "WindowStyle"
},
{
"code": null,
"e": 3841,
"s": 3803,
"text": "Gets or sets a window's border style."
},
{
"code": null,
"e": 3851,
"s": 3841,
"text": "Activated"
},
{
"code": null,
"e": 3903,
"s": 3851,
"text": "Occurs when a window becomes the foreground window."
},
{
"code": null,
"e": 3910,
"s": 3903,
"text": "Closed"
},
{
"code": null,
"e": 3952,
"s": 3910,
"text": "Occurs when the window is about to close."
},
{
"code": null,
"e": 3960,
"s": 3952,
"text": "Closing"
},
{
"code": null,
"e": 4044,
"s": 3960,
"text": "Occurs directly after Close is called, and can be handled to cancel window closure."
},
{
"code": null,
"e": 4060,
"s": 4044,
"text": "ContentRendered"
},
{
"code": null,
"e": 4111,
"s": 4060,
"text": "Occurs after a window's content has been rendered."
},
{
"code": null,
"e": 4123,
"s": 4111,
"text": "Deactivated"
},
{
"code": null,
"e": 4173,
"s": 4123,
"text": "Occurs when a window becomes a background window."
},
{
"code": null,
"e": 4189,
"s": 4173,
"text": "LocationChanged"
},
{
"code": null,
"e": 4232,
"s": 4189,
"text": "Occurs when the window's location changes."
},
{
"code": null,
"e": 4250,
"s": 4232,
"text": "SourceInitialized"
},
{
"code": null,
"e": 4325,
"s": 4250,
"text": "This event is raised to support interoperation with Win32. See HwndSource."
},
{
"code": null,
"e": 4338,
"s": 4325,
"text": "StateChanged"
},
{
"code": null,
"e": 4393,
"s": 4338,
"text": "Occurs when the window's WindowState property changes."
},
{
"code": null,
"e": 4402,
"s": 4393,
"text": "Activate"
},
{
"code": null,
"e": 4467,
"s": 4402,
"text": "Attempts to bring the window to the foreground and activates it."
},
{
"code": null,
"e": 4473,
"s": 4467,
"text": "Close"
},
{
"code": null,
"e": 4499,
"s": 4473,
"text": "Manually closes a Window."
},
{
"code": null,
"e": 4508,
"s": 4499,
"text": "DragMove"
},
{
"code": null,
"e": 4625,
"s": 4508,
"text": "Allows a window to be dragged by a mouse with its left button down over an exposed area of the window's client area."
},
{
"code": null,
"e": 4635,
"s": 4625,
"text": "GetWindow"
},
{
"code": null,
"e": 4751,
"s": 4635,
"text": "Returns a reference to the Window object that hosts the content tree within which the dependency object is located."
},
{
"code": null,
"e": 4756,
"s": 4751,
"text": "Hide"
},
{
"code": null,
"e": 4782,
"s": 4756,
"text": "Makes a window invisible."
},
{
"code": null,
"e": 4787,
"s": 4782,
"text": "Show"
},
{
"code": null,
"e": 4868,
"s": 4787,
"text": "Opens a window and returns without waiting for the newly opened window to close."
},
{
"code": null,
"e": 4879,
"s": 4868,
"text": "ShowDialog"
},
{
"code": null,
"e": 4951,
"s": 4879,
"text": "Opens a window and returns only when the newly opened window is closed."
},
{
"code": null,
"e": 5078,
"s": 4951,
"text": "When you create a new WPF project, then by default, the Window control is present. Letβs have a look at the following example."
},
{
"code": null,
"e": 5205,
"s": 5078,
"text": "When you create a new WPF project, then by default, the Window control is present. Letβs have a look at the following example."
},
{
"code": null,
"e": 5395,
"s": 5205,
"text": "The following XAML code starts with a <Window> Tag and ends with a </Window> tag. The code sets some properties for the window and creates some other controls like text blocks, button, etc."
},
{
"code": null,
"e": 5585,
"s": 5395,
"text": "The following XAML code starts with a <Window> Tag and ends with a </Window> tag. The code sets some properties for the window and creates some other controls like text blocks, button, etc."
},
{
"code": null,
"e": 7118,
"s": 5585,
"text": "<Window x:Class = \"WPFToolTipControl.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:WPFToolTipControl\" \n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid> \n <TextBlock x:Name = \"textBlock\" HorizontalAlignment = \"Left\" \n Margin = \"101,75,0,0\" TextWrapping = \"Wrap\" \n Text = \"User Name\" VerticalAlignment = \"Top\" /> \n\t\t\t\n <TextBlock x:Name = \"textBlock1\" HorizontalAlignment = \"Left\"\n Margin = \"101,125,0,0\" TextWrapping = \"Wrap\" \n Text = \"Password\" VerticalAlignment = \"Top\" /> \n\t\t\t\n <TextBox x:Name = \"textBox\" HorizontalAlignment = \"Left\" \n Height = \"24\" Margin = \"199,75,0,0\" TextWrapping = \"Wrap\" \n VerticalAlignment = \"Top\" Width = \"219\" \n ToolTipService.ToolTip = \"Enter User Name\" /> \n\t\t\t\n <PasswordBox x:Name = \"passwordBox\" HorizontalAlignment = \"Left\" \n Margin = \"199,125,0,0\" VerticalAlignment = \"Top\" Width = \"219\" \n Height = \"24\" ToolTipService.ToolTip = \"Enter Password\" /> \n\t\t\t\n <Button x:Name = \"button\" Content = \"Log in\" HorizontalAlignment = \"Left\" \n Margin = \"199,189,0,0\" VerticalAlignment = \"Top\" Width = \"75\" \n ToolTipService.ToolTip = \"Log in\" /> \n </Grid> \n\t\n</Window> "
},
{
"code": null,
"e": 7290,
"s": 7118,
"text": "When you compile and execute the above code, it will display the following output. When the mouse enters the region of the Button or the Textboxes, it will show a tooltip."
},
{
"code": null,
"e": 7399,
"s": 7290,
"text": "We recommend that you execute the above example code and try some other properties and events of this class."
},
{
"code": null,
"e": 7434,
"s": 7399,
"text": "\n 31 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7448,
"s": 7434,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7483,
"s": 7448,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7506,
"s": 7483,
"text": " Taurius Litvinavicius"
},
{
"code": null,
"e": 7513,
"s": 7506,
"text": " Print"
},
{
"code": null,
"e": 7524,
"s": 7513,
"text": " Add Notes"
}
] |
Market Basket Analysis β Multiple Support Frequent Item set Mining | by Srinivas Paturu | Towards Data Science
|
The problem of generating Association Rules from a database of transactions (market baskets) is of interest for many retailers. An association rule is of the form X β Y where X, Y are subsets of I (the universal set of all products (or items) and X β© Y = β
.
One can understand the meaning of above association rule as, if the customer has purchased items in the set X then he is likely to purchase items in the set Y. Some well-known examples of association rules can be {Milk} -> {Bread}, {Milk} -> {Bread, Eggs}, {Bread, Butter} -> {Jam} and the humorous {Diapers} -> {Beer}. Please note that association rules are not commutative, .i.e. X β Y does not equal Y β X.
The problem of finding association rules for a given transaction database (market baskets) is defined as follows:
a. Given a transaction database of size Z with N distinct items and an input support and confidence, find all the rules X β Y that satisfy the given support and confidence constraints.
b. A support is a threshold that would determine if the items in X are frequent enough to be considered for association rule generation. More specifically if {X}.count / Z >= support, then X is considered a frequent item set.
c. A confidence is a threshold that would determine the conditional probability of buying Y. More specifically if {XβY}.count / {X}.count >= confidence, then X β Y is considered a valid association rule.
Suppose if there are βNβ distinct items/products sold by the retailer, then a brute force approach of counting and generating association rules has the complexity of O(N!).
Apriori algorithm is an improvement over the brute force method based on the observations that a set of items X is a frequent item set only if all the proper subsets of X are also frequent item sets. This would reduce the no of states/rules need to explore for generating all possible association rules. The Apriori algorithm works by this principle and is executed in two steps
a. Find all the frequent item sets in the transaction database of size 1, 2, 3...k.
b. Generate all valid association rules from the frequent item sets 2, 3, 4...k.
c. Stop if no further frequent item sets of size k + 1 can be generated.
The Apriori algorithm requires at least βkβ scans of the transaction database.
MSApriori, which stands for Multiple Support Apriori, is a more constrained definition of the Apriori algorithm for real life scenarios. The Apriori algorithm considers only one support value for all the items in the transactions, irrespective of whether an item is a frequently selling item (such as groceries) or a less frequently selling item (high priced items such as Home decors). So, to establish a weighing scheme for the frequently/rarely sold items, each item is given an individual support. The problem definition for MSApriori algorithm is modified as follows:
a. Given a transaction database and different minimum input supportβs (MIS) for each item and confidence, find all the rules X β Y that satisfy the given support and confidence constraints.
b. A support is a threshold that would determine if the items in X are frequent enough to be considered for association rule generation. Because there are different supports for different items in MSApriori, any item set that satisfies the minimum MIS of items in its set is considered frequent. More specifically if
a. |X| = 1,
{X}.count / n >= MIS(X), then X is considered a frequent item set.
b. |X| >= 1,
{X}.count / n >= MIN (MIS(X1), MIS(X2), MIS(X3) ... MIS(Xk)); Xi β X, i=1 to k.
c. To discourage very frequently and less frequently items appearing together in any frequent item set, a support difference constraint Ξ¦ is enforced on the candidate item set X
a. |X| >= 1,
MAX(Supp(X1), Supp(X2) ... Supp(Xk))βMIN(Supp(X1), Supp(X2) ... Supp(Xk)) <= Ξ¦
The task of assigning MIS to items must be done in a meticulous manner. For highly moving items such as daily groceries, a high value of MIS is desired. For not so frequently sold items such as high end electronics, a less value of MIS is desired. One such assignment of MIS can be done using the following approximation.
MIS (item) = Ξ΄ * Supp (item); Ξ΄ β [0, 1]
The above assignment is discussed in WebMining by Bing Liu et al. An algorithm for solving MSApriori is also proposed in the above book by Bing Liu, letβs call it the default MSApriori algorithm. The default MSApriori algorithm does a scan of transaction database for each candidate item set Ck; k >=2 to compute the frequent item set Fk.
Considering there are βZβ number of total transactions in the database and βNβ unique items, the default MSApriori algorithm requires calculation of support for all C2; C2 would have N*(N-1)/2 item sets if the MIS of each item is defined as above equation.
Total time complexity = N*(N-1)/2 * Z ~ O(n3).
Similarly, C3, C4... Ck would have corresponding complexities based on the size of item set multiplied by the number of transactions in the database.
The proposed improvement to the default MSApriori is to use a look forward strategy of computing the supports of each Ck in the first pass of the transaction database scan, storing them in a Hash Table (Hk) and retrieving them when required. In the first pass of the transaction database scan, for each transaction of length βLβ, each Ck (k <= L) is generated locally and the count of its support increased in Hk. So, for C2, the proposed modification would work as follows,
/* modified MSApriori Algorithm form Bing et al */Modificaiton-1: init-pass()For each item(i) in Transaction T:a. Compute/increment the support of item(i)b. For each item(j) in Transaction T: // (j>i) Compute the hashcode of itemset(i,j) Retrieve the support of itemset(i,j) from the hash table(H2) Initialize/Increment the support of itemset(i,j).Modificaiton-2: CandidateGen2() //Candidate generation function for 2-itemsetFor each item(i) in list L/C2: For each item(j) in list L: // (j>i) Compute the hashcode of itemset(i,j) Retrieve the support of itemset(i,j) from the hash table(H2) If support > MIS(item(i)) // and other constrains like Ξ¦ Return itemset(i,j) into F2.
NOTE: CandidateGen2() directly returns the items into F2, no need for scanning the transaction database again!
In the Modificaiton-1, an extra sub-loop is added for each transaction to compute the support for 2-itemsets, assuming the average length of transaction is βLβ then this step would add further processing time of L*(L-1)/2 for each transaction in the database. Assuming, there are βZβ transactions in the database, the time required to complete the init-pass() is
Time complexity (init-pass) = L*(L-1)/2 * Z
~= c * Z ~ O(Z) //for all practical reasons L << Z
In the Modificaiton-2, I am adding an extra step for accessing the hash table (H2) which can be done in constant time (TH) in most library implementations. The time required to complete CandidateGen2() is given as
Time complexity = N*(N-1)/2*TH ~ O(n2).
Combining both modifications, total time complexity = O(Z) + O(n2) < O(n3)! (from the default algorithm).
The default MSApirioi algorithm is implemented by Phillipe et al in the open-sourced java data mining library SPMF. I have modified the default MSApriori algorithm in SPMF library with my proposed alteration in the program MSAprori_H.java. The results of the execution of the MSApriori and MSApriori_H is as follows:
Dataset considered: retail1.txt
No of distinct items in the dataset: N = 2603.
No of transactions in the dataset: Z = 541909.
A note on the Hash function requirements for this algorithm. We would ideally require a hash function that would give a unique hash value for a set of integers, irrespective of the order of the integers in the given set. Generating such a hash function is definitely not a simple task, so I have relaxed the hash value to be a Java object in my implementation. I have chosen a BitSet object to implement in MSApriori_H.java. Consider a java BitSet object as a long array of Booleans that can hold ON/OFF values in required positions.
Hash function in MSApriori_H.java:
/* Input k-item set in Integer[] items */BitSet hashcode = new BitSet(Integer.MAX_VALUE);for(int i=0; i<items.length; i++) {hashcode.set(items[i])};return hashcode;
Some rights reserved
|
[
{
"code": null,
"e": 430,
"s": 172,
"text": "The problem of generating Association Rules from a database of transactions (market baskets) is of interest for many retailers. An association rule is of the form X β Y where X, Y are subsets of I (the universal set of all products (or items) and X β© Y = β
."
},
{
"code": null,
"e": 840,
"s": 430,
"text": "One can understand the meaning of above association rule as, if the customer has purchased items in the set X then he is likely to purchase items in the set Y. Some well-known examples of association rules can be {Milk} -> {Bread}, {Milk} -> {Bread, Eggs}, {Bread, Butter} -> {Jam} and the humorous {Diapers} -> {Beer}. Please note that association rules are not commutative, .i.e. X β Y does not equal Y β X."
},
{
"code": null,
"e": 954,
"s": 840,
"text": "The problem of finding association rules for a given transaction database (market baskets) is defined as follows:"
},
{
"code": null,
"e": 1139,
"s": 954,
"text": "a. Given a transaction database of size Z with N distinct items and an input support and confidence, find all the rules X β Y that satisfy the given support and confidence constraints."
},
{
"code": null,
"e": 1365,
"s": 1139,
"text": "b. A support is a threshold that would determine if the items in X are frequent enough to be considered for association rule generation. More specifically if {X}.count / Z >= support, then X is considered a frequent item set."
},
{
"code": null,
"e": 1569,
"s": 1365,
"text": "c. A confidence is a threshold that would determine the conditional probability of buying Y. More specifically if {XβY}.count / {X}.count >= confidence, then X β Y is considered a valid association rule."
},
{
"code": null,
"e": 1742,
"s": 1569,
"text": "Suppose if there are βNβ distinct items/products sold by the retailer, then a brute force approach of counting and generating association rules has the complexity of O(N!)."
},
{
"code": null,
"e": 2121,
"s": 1742,
"text": "Apriori algorithm is an improvement over the brute force method based on the observations that a set of items X is a frequent item set only if all the proper subsets of X are also frequent item sets. This would reduce the no of states/rules need to explore for generating all possible association rules. The Apriori algorithm works by this principle and is executed in two steps"
},
{
"code": null,
"e": 2205,
"s": 2121,
"text": "a. Find all the frequent item sets in the transaction database of size 1, 2, 3...k."
},
{
"code": null,
"e": 2286,
"s": 2205,
"text": "b. Generate all valid association rules from the frequent item sets 2, 3, 4...k."
},
{
"code": null,
"e": 2359,
"s": 2286,
"text": "c. Stop if no further frequent item sets of size k + 1 can be generated."
},
{
"code": null,
"e": 2438,
"s": 2359,
"text": "The Apriori algorithm requires at least βkβ scans of the transaction database."
},
{
"code": null,
"e": 3011,
"s": 2438,
"text": "MSApriori, which stands for Multiple Support Apriori, is a more constrained definition of the Apriori algorithm for real life scenarios. The Apriori algorithm considers only one support value for all the items in the transactions, irrespective of whether an item is a frequently selling item (such as groceries) or a less frequently selling item (high priced items such as Home decors). So, to establish a weighing scheme for the frequently/rarely sold items, each item is given an individual support. The problem definition for MSApriori algorithm is modified as follows:"
},
{
"code": null,
"e": 3201,
"s": 3011,
"text": "a. Given a transaction database and different minimum input supportβs (MIS) for each item and confidence, find all the rules X β Y that satisfy the given support and confidence constraints."
},
{
"code": null,
"e": 3518,
"s": 3201,
"text": "b. A support is a threshold that would determine if the items in X are frequent enough to be considered for association rule generation. Because there are different supports for different items in MSApriori, any item set that satisfies the minimum MIS of items in its set is considered frequent. More specifically if"
},
{
"code": null,
"e": 3530,
"s": 3518,
"text": "a. |X| = 1,"
},
{
"code": null,
"e": 3597,
"s": 3530,
"text": "{X}.count / n >= MIS(X), then X is considered a frequent item set."
},
{
"code": null,
"e": 3610,
"s": 3597,
"text": "b. |X| >= 1,"
},
{
"code": null,
"e": 3690,
"s": 3610,
"text": "{X}.count / n >= MIN (MIS(X1), MIS(X2), MIS(X3) ... MIS(Xk)); Xi β X, i=1 to k."
},
{
"code": null,
"e": 3868,
"s": 3690,
"text": "c. To discourage very frequently and less frequently items appearing together in any frequent item set, a support difference constraint Ξ¦ is enforced on the candidate item set X"
},
{
"code": null,
"e": 3881,
"s": 3868,
"text": "a. |X| >= 1,"
},
{
"code": null,
"e": 3960,
"s": 3881,
"text": "MAX(Supp(X1), Supp(X2) ... Supp(Xk))βMIN(Supp(X1), Supp(X2) ... Supp(Xk)) <= Ξ¦"
},
{
"code": null,
"e": 4282,
"s": 3960,
"text": "The task of assigning MIS to items must be done in a meticulous manner. For highly moving items such as daily groceries, a high value of MIS is desired. For not so frequently sold items such as high end electronics, a less value of MIS is desired. One such assignment of MIS can be done using the following approximation."
},
{
"code": null,
"e": 4323,
"s": 4282,
"text": "MIS (item) = Ξ΄ * Supp (item); Ξ΄ β [0, 1]"
},
{
"code": null,
"e": 4662,
"s": 4323,
"text": "The above assignment is discussed in WebMining by Bing Liu et al. An algorithm for solving MSApriori is also proposed in the above book by Bing Liu, letβs call it the default MSApriori algorithm. The default MSApriori algorithm does a scan of transaction database for each candidate item set Ck; k >=2 to compute the frequent item set Fk."
},
{
"code": null,
"e": 4919,
"s": 4662,
"text": "Considering there are βZβ number of total transactions in the database and βNβ unique items, the default MSApriori algorithm requires calculation of support for all C2; C2 would have N*(N-1)/2 item sets if the MIS of each item is defined as above equation."
},
{
"code": null,
"e": 4966,
"s": 4919,
"text": "Total time complexity = N*(N-1)/2 * Z ~ O(n3)."
},
{
"code": null,
"e": 5116,
"s": 4966,
"text": "Similarly, C3, C4... Ck would have corresponding complexities based on the size of item set multiplied by the number of transactions in the database."
},
{
"code": null,
"e": 5591,
"s": 5116,
"text": "The proposed improvement to the default MSApriori is to use a look forward strategy of computing the supports of each Ck in the first pass of the transaction database scan, storing them in a Hash Table (Hk) and retrieving them when required. In the first pass of the transaction database scan, for each transaction of length βLβ, each Ck (k <= L) is generated locally and the count of its support increased in Hk. So, for C2, the proposed modification would work as follows,"
},
{
"code": null,
"e": 6321,
"s": 5591,
"text": "/* modified MSApriori Algorithm form Bing et al */Modificaiton-1: init-pass()For each item(i) in Transaction T:a. Compute/increment the support of item(i)b. For each item(j) in Transaction T: // (j>i) Compute the hashcode of itemset(i,j) Retrieve the support of itemset(i,j) from the hash table(H2) Initialize/Increment the support of itemset(i,j).Modificaiton-2: CandidateGen2() //Candidate generation function for 2-itemsetFor each item(i) in list L/C2: For each item(j) in list L: // (j>i) Compute the hashcode of itemset(i,j) Retrieve the support of itemset(i,j) from the hash table(H2) If support > MIS(item(i)) // and other constrains like Ξ¦ Return itemset(i,j) into F2."
},
{
"code": null,
"e": 6432,
"s": 6321,
"text": "NOTE: CandidateGen2() directly returns the items into F2, no need for scanning the transaction database again!"
},
{
"code": null,
"e": 6795,
"s": 6432,
"text": "In the Modificaiton-1, an extra sub-loop is added for each transaction to compute the support for 2-itemsets, assuming the average length of transaction is βLβ then this step would add further processing time of L*(L-1)/2 for each transaction in the database. Assuming, there are βZβ transactions in the database, the time required to complete the init-pass() is"
},
{
"code": null,
"e": 6839,
"s": 6795,
"text": "Time complexity (init-pass) = L*(L-1)/2 * Z"
},
{
"code": null,
"e": 6890,
"s": 6839,
"text": "~= c * Z ~ O(Z) //for all practical reasons L << Z"
},
{
"code": null,
"e": 7104,
"s": 6890,
"text": "In the Modificaiton-2, I am adding an extra step for accessing the hash table (H2) which can be done in constant time (TH) in most library implementations. The time required to complete CandidateGen2() is given as"
},
{
"code": null,
"e": 7144,
"s": 7104,
"text": "Time complexity = N*(N-1)/2*TH ~ O(n2)."
},
{
"code": null,
"e": 7250,
"s": 7144,
"text": "Combining both modifications, total time complexity = O(Z) + O(n2) < O(n3)! (from the default algorithm)."
},
{
"code": null,
"e": 7567,
"s": 7250,
"text": "The default MSApirioi algorithm is implemented by Phillipe et al in the open-sourced java data mining library SPMF. I have modified the default MSApriori algorithm in SPMF library with my proposed alteration in the program MSAprori_H.java. The results of the execution of the MSApriori and MSApriori_H is as follows:"
},
{
"code": null,
"e": 7599,
"s": 7567,
"text": "Dataset considered: retail1.txt"
},
{
"code": null,
"e": 7646,
"s": 7599,
"text": "No of distinct items in the dataset: N = 2603."
},
{
"code": null,
"e": 7693,
"s": 7646,
"text": "No of transactions in the dataset: Z = 541909."
},
{
"code": null,
"e": 8227,
"s": 7693,
"text": "A note on the Hash function requirements for this algorithm. We would ideally require a hash function that would give a unique hash value for a set of integers, irrespective of the order of the integers in the given set. Generating such a hash function is definitely not a simple task, so I have relaxed the hash value to be a Java object in my implementation. I have chosen a BitSet object to implement in MSApriori_H.java. Consider a java BitSet object as a long array of Booleans that can hold ON/OFF values in required positions."
},
{
"code": null,
"e": 8262,
"s": 8227,
"text": "Hash function in MSApriori_H.java:"
},
{
"code": null,
"e": 8427,
"s": 8262,
"text": "/* Input k-item set in Integer[] items */BitSet hashcode = new BitSet(Integer.MAX_VALUE);for(int i=0; i<items.length; i++) {hashcode.set(items[i])};return hashcode;"
}
] |
Gaussian Mixture Models for Clustering | by Vivienne DiFrancesco | Towards Data Science
|
Recently I was using K-Means in a project and decided to see what other options were out there for clustering algorithms. I always find it enjoyable to sink my teeth into expanding my data science skillset. I decided to write this article to share the experience of what I discovered on my quest to broaden my clustering knowledge to include using Gaussian Mixture Models.
When hearing of this technique you may have thought about the Gaussian distribution (also called normal distribution). Thatβs exactly what this clustering technique is based on. It assumes that the data points come from multi-dimensional Gaussian distributions that could have varying parameters of covariance, mean, and density.
Gaussian Mixture models work based on an algorithm called Expectation-Maximization, or EM. When given the number of clusters for a Gaussian Mixture model, the EM algorithm tries to figure out the parameters of these Gaussian distributions in two basic steps.
The E-step makes a guess of the parameters based on available data. Data points are assigned to a Gaussian cluster and probabilities are calculated that they belong to that cluster.
The M-step updates the cluster parameters based on the calculations from the E-step. The mean, covariance, and density are calculated for clusters based on the data points in the E step.
The process is repeated with the calculated values continuing to be updated until convergence is reached.
If you are familiar with K-Means, this process at a high level is really the same. The similar flow being to make a guess, calculate values, and readjust until convergence.
With a basic understanding of how Gaussian Mixture works, the fun part is to start coding and experimenting. You can implement a clustering model in just a few lines of code using Python and Scikit-Learn. I encourage you to look at the Scikit-Learn documentation page for the Gaussian Mixture class.
from sklearn.mixture import GaussianMixturegm = GaussianMixture(n_components=n, random_state=123, n_init=10)preds = gm.fit_predict(X)
The n_components parameter is where you specify the number of clusters. The n_init parameter allows you to control how many times the algorithm is initialized. The initial placement of where clusters are located at the start can set the algorithm up for picking bad cluster parameters. By initializing multiple times, you decrease the chance of converging on bad clusters simply because of bad luck on initial placement. Finally, the fitting and predicting can be done in one step from calling the fit_predict() method on your data represented as X in the example.
But how many clusters are in my data? You may have noticed that in order to apply the model to your data, you have to have a value chosen for the number of clusters. How do you know what cluster number best represents your data? You have a couple of options that I will go over.
Often, the best way to find an appropriate cluster number is to try different cluster numbers and see which fits your data appropriately. The two most popular evaluation metrics for picking cluster numbers for fitting Gaussian Mixture models are BIC and AIC. BIC stands for Bayesian information criterion and AIC stands for Akaike information criterion. The intuition in the calculation of both of these metrics is that they favor the simplest model that maximize the likelihood function of the model.
Calculating the AIC and BIC is easy because they are built in as a method on the Scikit-Learn Gaussian Mixture class. By setting up a loop to try different cluster numbers and calculate the AIC and BIC, you can then plot the metrics together to pick your cluster number.
You can see that the AIC and BIC mirror each other pretty closely. BIC and AIC are meant to be minimized so pick the low spot in the chart. The two measures will usually pick the same number for clusters, but if they differ then know that BIC more heavily favors simple models than AIC, but AIC models tend the fit the data a little better. In this example, I would pick 5 as the most appropriate cluster number for the data as the chart really levels off after that.
Another method for picking the cluster number that I came across is by using the Bayesian Gaussian Mixture Models class in Scikit-Learn. When you fit this model it has an attribute to return the weights of clusters with erroneous clusters being weighted at or near zero and basically removing those clusters automatically. Once again you can fit this model in only a couple lines of code.
from sklearn.mixture import BayesianGaussianMixtureimport numpy as npbgm = BayesianGaussianMixture(n_components=10, n_init=10)bgm.fit(X)np.round(bgm.weights_, 2)
The model is created and fit the same as before but now we can return an array of cluster weights. My own experiment returned this array:
array([0.09, 0.25, 0.16, 0.07, 0.06, 0.24, 0.13, 0., 0., 0. ])
This allows me to see that the model has basically picked the appropriate number of clusters automatically, as the ones that are not needed are weighted as 0.
One positive about these models is that they can handle a greater variety of shapes, primarily clusters that form ellipsis shapes. Something like K-Means is really only good at clusters that are roughly spherical. There is a covariance_type parameter that allows for adjusting for different shapes of the clusters. However, something like crescent shaped clusters will still be difficult for a Gaussian Mixture model to accurately identify.
Another positive is that these models allow for soft classification. K-Means is a hard classification model where each data point is assigned to a single cluster. The Gaussian Mixture method, however, calculates probabilities of data points belonging to clusters. These probabilities can be obtained using the predict_proba() method after fitting the model.
A caveat I found when playing with Gaussian Mixture models is that they take a lot longer to run than a K-Means model because they take a lot longer to converge. Be mindful of the amount of data you are using and how many features are involved. When experimenting with the Bayesian Gaussian Mixture class specifically, it often gave errors about how convergence couldnβt be reached. When this happens you can increase the max_iter parameter, but that also means it will take longer to run. Keep in mind that it also may mean that your data is not well suited to a Gaussian Mixture clustering style.
There is so much more to explore with this style of clustering. I tried to have this be a guide that explained concepts in plain English to get you started, but I encourage you to look up formulas and dig into the math behind what is happening. The Scikit-Learn clustering user guide is a great place to start.
|
[
{
"code": null,
"e": 545,
"s": 172,
"text": "Recently I was using K-Means in a project and decided to see what other options were out there for clustering algorithms. I always find it enjoyable to sink my teeth into expanding my data science skillset. I decided to write this article to share the experience of what I discovered on my quest to broaden my clustering knowledge to include using Gaussian Mixture Models."
},
{
"code": null,
"e": 875,
"s": 545,
"text": "When hearing of this technique you may have thought about the Gaussian distribution (also called normal distribution). Thatβs exactly what this clustering technique is based on. It assumes that the data points come from multi-dimensional Gaussian distributions that could have varying parameters of covariance, mean, and density."
},
{
"code": null,
"e": 1134,
"s": 875,
"text": "Gaussian Mixture models work based on an algorithm called Expectation-Maximization, or EM. When given the number of clusters for a Gaussian Mixture model, the EM algorithm tries to figure out the parameters of these Gaussian distributions in two basic steps."
},
{
"code": null,
"e": 1316,
"s": 1134,
"text": "The E-step makes a guess of the parameters based on available data. Data points are assigned to a Gaussian cluster and probabilities are calculated that they belong to that cluster."
},
{
"code": null,
"e": 1503,
"s": 1316,
"text": "The M-step updates the cluster parameters based on the calculations from the E-step. The mean, covariance, and density are calculated for clusters based on the data points in the E step."
},
{
"code": null,
"e": 1609,
"s": 1503,
"text": "The process is repeated with the calculated values continuing to be updated until convergence is reached."
},
{
"code": null,
"e": 1782,
"s": 1609,
"text": "If you are familiar with K-Means, this process at a high level is really the same. The similar flow being to make a guess, calculate values, and readjust until convergence."
},
{
"code": null,
"e": 2082,
"s": 1782,
"text": "With a basic understanding of how Gaussian Mixture works, the fun part is to start coding and experimenting. You can implement a clustering model in just a few lines of code using Python and Scikit-Learn. I encourage you to look at the Scikit-Learn documentation page for the Gaussian Mixture class."
},
{
"code": null,
"e": 2216,
"s": 2082,
"text": "from sklearn.mixture import GaussianMixturegm = GaussianMixture(n_components=n, random_state=123, n_init=10)preds = gm.fit_predict(X)"
},
{
"code": null,
"e": 2781,
"s": 2216,
"text": "The n_components parameter is where you specify the number of clusters. The n_init parameter allows you to control how many times the algorithm is initialized. The initial placement of where clusters are located at the start can set the algorithm up for picking bad cluster parameters. By initializing multiple times, you decrease the chance of converging on bad clusters simply because of bad luck on initial placement. Finally, the fitting and predicting can be done in one step from calling the fit_predict() method on your data represented as X in the example."
},
{
"code": null,
"e": 3060,
"s": 2781,
"text": "But how many clusters are in my data? You may have noticed that in order to apply the model to your data, you have to have a value chosen for the number of clusters. How do you know what cluster number best represents your data? You have a couple of options that I will go over."
},
{
"code": null,
"e": 3562,
"s": 3060,
"text": "Often, the best way to find an appropriate cluster number is to try different cluster numbers and see which fits your data appropriately. The two most popular evaluation metrics for picking cluster numbers for fitting Gaussian Mixture models are BIC and AIC. BIC stands for Bayesian information criterion and AIC stands for Akaike information criterion. The intuition in the calculation of both of these metrics is that they favor the simplest model that maximize the likelihood function of the model."
},
{
"code": null,
"e": 3833,
"s": 3562,
"text": "Calculating the AIC and BIC is easy because they are built in as a method on the Scikit-Learn Gaussian Mixture class. By setting up a loop to try different cluster numbers and calculate the AIC and BIC, you can then plot the metrics together to pick your cluster number."
},
{
"code": null,
"e": 4301,
"s": 3833,
"text": "You can see that the AIC and BIC mirror each other pretty closely. BIC and AIC are meant to be minimized so pick the low spot in the chart. The two measures will usually pick the same number for clusters, but if they differ then know that BIC more heavily favors simple models than AIC, but AIC models tend the fit the data a little better. In this example, I would pick 5 as the most appropriate cluster number for the data as the chart really levels off after that."
},
{
"code": null,
"e": 4690,
"s": 4301,
"text": "Another method for picking the cluster number that I came across is by using the Bayesian Gaussian Mixture Models class in Scikit-Learn. When you fit this model it has an attribute to return the weights of clusters with erroneous clusters being weighted at or near zero and basically removing those clusters automatically. Once again you can fit this model in only a couple lines of code."
},
{
"code": null,
"e": 4852,
"s": 4690,
"text": "from sklearn.mixture import BayesianGaussianMixtureimport numpy as npbgm = BayesianGaussianMixture(n_components=10, n_init=10)bgm.fit(X)np.round(bgm.weights_, 2)"
},
{
"code": null,
"e": 4990,
"s": 4852,
"text": "The model is created and fit the same as before but now we can return an array of cluster weights. My own experiment returned this array:"
},
{
"code": null,
"e": 5053,
"s": 4990,
"text": "array([0.09, 0.25, 0.16, 0.07, 0.06, 0.24, 0.13, 0., 0., 0. ])"
},
{
"code": null,
"e": 5212,
"s": 5053,
"text": "This allows me to see that the model has basically picked the appropriate number of clusters automatically, as the ones that are not needed are weighted as 0."
},
{
"code": null,
"e": 5653,
"s": 5212,
"text": "One positive about these models is that they can handle a greater variety of shapes, primarily clusters that form ellipsis shapes. Something like K-Means is really only good at clusters that are roughly spherical. There is a covariance_type parameter that allows for adjusting for different shapes of the clusters. However, something like crescent shaped clusters will still be difficult for a Gaussian Mixture model to accurately identify."
},
{
"code": null,
"e": 6011,
"s": 5653,
"text": "Another positive is that these models allow for soft classification. K-Means is a hard classification model where each data point is assigned to a single cluster. The Gaussian Mixture method, however, calculates probabilities of data points belonging to clusters. These probabilities can be obtained using the predict_proba() method after fitting the model."
},
{
"code": null,
"e": 6610,
"s": 6011,
"text": "A caveat I found when playing with Gaussian Mixture models is that they take a lot longer to run than a K-Means model because they take a lot longer to converge. Be mindful of the amount of data you are using and how many features are involved. When experimenting with the Bayesian Gaussian Mixture class specifically, it often gave errors about how convergence couldnβt be reached. When this happens you can increase the max_iter parameter, but that also means it will take longer to run. Keep in mind that it also may mean that your data is not well suited to a Gaussian Mixture clustering style."
}
] |
Construct the smallest possible Array with given Sum and XOR - GeeksforGeeks
|
07 Apr, 2021
Given two positive integers S and X which represents the sum and Bitwise XOR of all the elements of an array arr[]. The task is to find the elements of the array arr[]. If no such array can be generated, print -1.Examples:
Input: Sum = 4, Xor = 2 Output: {3, 1} Explanation: Sum of 1 and 3 is 4. Bitwise XOR of 1 and 3 is 2.Input: Sum = 5, Xor = 8 Output: -1 Explanation: There is no such array exists.
Approach: It can be proven that the maximum length of the array will be at most 3. Let us consider the following cases:
Case 1: If the given Sum and Bitwise XOR are equal and non-zero, then, that element will be the only element of the required array.
Case 2: For unequal Sum and Bitwise XOR, the shortest array length can be either 2 or 3. If the given Bitwise XOR and Sum is a and b respectively, then the shortest array can be {a, (b β a)/2, (b-a)/2 } by using the following two properties of XOR: a Xor 0 = aa Xor a = 0
a Xor 0 = a
a Xor a = 0
Case 3: When length of array can be 2.The array we took in the previous case can be reduced to two elements if it is possible.
One important formula helpful here is:-
p + q = (p ^ q) + 2*(p & q)
Substituting values of sum and xor in the above formula we get a very helpful relation.
b = a + 2*(p & q) (p & q) = (b-a)/2 From previous case, x = (b-a)/2 = (p & q)
So, now letβs see some relation between a (given xor) and x ((b-a)/2).
p q a=(p^q) x=(p&q) a&x
0 0 0 0 0
0 1 1 0 0
1 0 1 0 0
1 1 0 1 0
Note: p and q represents all corresponding 32 bits of two numbers in array.
It is important to note that if a & x becomes zero then a + x = a ^ x which means the array will be reduced to {a+x, x} because a+x = a^x. From the above formula, which can still lead to overall XOR as a, and sum will still be b as x is (b-a)/2.
Case 4: The only case left is to check whether array exists or not. In this case, there are only two condition to check as: If Bitwise XOR is greater than the sum.If sum and xor have different parities i.e., one is even and other is odd.
If Bitwise XOR is greater than the sum.If sum and xor have different parities i.e., one is even and other is odd.
If Bitwise XOR is greater than the sum.
If sum and xor have different parities i.e., one is even and other is odd.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find arrayvoid findArray(int sum, int xorr){ // array not possible if (xorr > sum || sum % 2 != xorr % 2) { cout << "No Array Possible\n"; return; } // Array possible with exactly 1 // or no element if (sum == xorr) { if (sum == 0) cout << "Array is empty" << " with size 0\n"; else cout << "Array size is " << 1 << "\n Array is " << sum << "\n"; return; } int mid = (sum - xorr) / 2; // Checking array with two // elements possible or not. if (xorr & mid == 1) { cout << "Array size is " << 3 << "\n"; cout << "Array is " << xorr << " " << mid << " " << mid << "\n"; } else { cout << "Array size is " << 2 << "\n"; cout << "Array is " << (xorr + mid) << " " << mid << "\n"; }} // Driver Codeint main(){ // Given sum and value // of Bitwise XOR int sum = 4, xorr = 2; // Function Call findArray(sum, xorr); cout << "\n"; return 0;}
// Java program implementation// of the approachimport java.util.*;import java.io.*; class GFG{ // Function to find arraystatic void findArray(int sum, int xorr){ // Array not possible if (xorr > sum || sum % 2 != xorr % 2) { System.out.println("No Array Possible"); return; } // Array possible with exactly 1 // or no element if (sum == xorr) { if (sum == 0) System.out.println("Array is empty " + "with size 0"); else System.out.println("Array size is " + 1); System.out.println("Array is " + sum); return; } int mid = (sum - xorr) / 2; // Checking array with two // elements possible or not. if (xorr == 1 && mid == 1) { System.out.println("Array size is " + 3); System.out.println("Array is " + xorr + " " + mid + " " + mid); } else { System.out.println("Array size is " + 2); System.out.println("Array is " + (xorr + mid) + " " + mid); }} // Driver codepublic static void main(String[] args){ // Given sum and value // of Bitwise XOR int sum = 4, xorr = 2; // Function call findArray(sum, xorr);}} // This code is contributed by sanjoy_62
# Python3 program for the above approach # Function to find arraydef findArray(_sum, xorr): # Array not possible if (xorr > _sum or _sum % 2 != xorr % 2): print("No Array Possible") return # Array possible with exactly 1 # or no element if (_sum == xorr): if (_sum == 0): print("Array is empty", " with size 0") else: print("Array size is", 1) print("Array is", _sum) return mid = (_sum - xorr) // 2 # Checking array with two # elements possible or not. if (xorr & mid == 1): print("Array size is", 3) print("Array is", xorr, mid, mid) else: print("Array size is", 2) print("Array is" ,(xorr + mid), mid) # Driver Code # Given sum and value# of Bitwise XOR_sum = 4xorr = 2 # Function CallfindArray(_sum, xorr) # This code is contributed by divyamohan123
// C# program implementation// of the approachusing System; class GFG{ // Function to find arraystatic void findArray(int sum, int xorr){ // Array not possible if (xorr > sum || sum % 2 != xorr % 2) { Console.WriteLine("No Array Possible"); return; } // Array possible with exactly 1 // or no element if (sum == xorr) { if (sum == 0) Console.WriteLine("Array is empty " + "with size 0"); else Console.WriteLine("Array size is " + 1); Console.WriteLine("Array is " + sum); return; } int mid = (sum - xorr) / 2; // Checking array with two // elements possible or not. if (xorr == 1 && mid == 1) { Console.WriteLine("Array size is " + 3); Console.WriteLine("Array is " + xorr + " " + mid + " " + mid); } else { Console.WriteLine("Array size is " + 2); Console.WriteLine("Array is " + (xorr + mid) + " " + mid); }} // Driver codepublic static void Main(){ // Given sum and value // of Bitwise XOR int sum = 4, xorr = 2; // Function call findArray(sum, xorr);}} // This code is contributed by sanjoy_62
<script> // Javascript program implementation// of the approach // Function to find arrayfunction findArray(sum, xorr){ // Array not possible if (xorr > sum || sum % 2 != xorr % 2) { System.out.println("No Array Possible"); return; } // Array possible with exactly 1 // or no element if (sum == xorr) { if (sum == 0) document.write("Array is empty " + "with size 0"); else document.write("Array size is " + 1); document.write(" Array is " + sum); return; } var mid = (sum - xorr) / 2; // Checking array with two // elements possible or not. if (xorr == 1 && mid == 1) { document.write("Array size is " + 3); document.write("Array is " + xorr + " " + mid + " " + mid); } else { document.write("Array size is " + 2); document.write("<br>") document.write("Array is " + (xorr + mid) + " " + mid); }} // Driver code // Given sum and value// of Bitwise XORvar sum = 4, xorr = 2; // Function callfindArray(sum, xorr); // This code is contributed by Khushboogoyal499 </script>
Array size is 2
Array is 3 1
Time Complexity: O(1) Auxiliary Space: O(1)
divyamohan123
sanjoy_62
khushboogoyal499
Bitwise-XOR
Algorithms
Arrays
Bit Magic
Competitive Programming
Greedy
Arrays
Greedy
Bit Magic
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Quadratic Probing in Hashing
Difference between Informed and Uninformed Search in AI
K means Clustering - Introduction
SCAN (Elevator) Disk Scheduling Algorithms
Arrays in Java
Arrays in C/C++
Stack Data Structure (Introduction and Program)
Program for array rotation
Largest Sum Contiguous Subarray
|
[
{
"code": null,
"e": 24299,
"s": 24271,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 24524,
"s": 24299,
"text": "Given two positive integers S and X which represents the sum and Bitwise XOR of all the elements of an array arr[]. The task is to find the elements of the array arr[]. If no such array can be generated, print -1.Examples: "
},
{
"code": null,
"e": 24706,
"s": 24524,
"text": "Input: Sum = 4, Xor = 2 Output: {3, 1} Explanation: Sum of 1 and 3 is 4. Bitwise XOR of 1 and 3 is 2.Input: Sum = 5, Xor = 8 Output: -1 Explanation: There is no such array exists. "
},
{
"code": null,
"e": 24830,
"s": 24708,
"text": "Approach: It can be proven that the maximum length of the array will be at most 3. Let us consider the following cases: "
},
{
"code": null,
"e": 24964,
"s": 24830,
"text": "Case 1: If the given Sum and Bitwise XOR are equal and non-zero, then, that element will be the only element of the required array. "
},
{
"code": null,
"e": 25236,
"s": 24964,
"text": "Case 2: For unequal Sum and Bitwise XOR, the shortest array length can be either 2 or 3. If the given Bitwise XOR and Sum is a and b respectively, then the shortest array can be {a, (b β a)/2, (b-a)/2 } by using the following two properties of XOR: a Xor 0 = aa Xor a = 0"
},
{
"code": null,
"e": 25248,
"s": 25236,
"text": "a Xor 0 = a"
},
{
"code": null,
"e": 25260,
"s": 25248,
"text": "a Xor a = 0"
},
{
"code": null,
"e": 25388,
"s": 25260,
"text": "Case 3: When length of array can be 2.The array we took in the previous case can be reduced to two elements if it is possible. "
},
{
"code": null,
"e": 25429,
"s": 25388,
"text": "One important formula helpful here is:- "
},
{
"code": null,
"e": 25461,
"s": 25431,
"text": "p + q = (p ^ q) + 2*(p & q) "
},
{
"code": null,
"e": 25552,
"s": 25463,
"text": "Substituting values of sum and xor in the above formula we get a very helpful relation. "
},
{
"code": null,
"e": 25634,
"s": 25554,
"text": "b = a + 2*(p & q) (p & q) = (b-a)/2 From previous case, x = (b-a)/2 = (p & q) "
},
{
"code": null,
"e": 25708,
"s": 25636,
"text": "So, now letβs see some relation between a (given xor) and x ((b-a)/2). "
},
{
"code": null,
"e": 25846,
"s": 25710,
"text": "p q a=(p^q) x=(p&q) a&x\n0 0 0 0 0\n0 1 1 0 0\n1 0 1 0 0\n1 1 0 1 0"
},
{
"code": null,
"e": 25923,
"s": 25846,
"text": "Note: p and q represents all corresponding 32 bits of two numbers in array. "
},
{
"code": null,
"e": 26171,
"s": 25923,
"text": "It is important to note that if a & x becomes zero then a + x = a ^ x which means the array will be reduced to {a+x, x} because a+x = a^x. From the above formula, which can still lead to overall XOR as a, and sum will still be b as x is (b-a)/2. "
},
{
"code": null,
"e": 26409,
"s": 26171,
"text": "Case 4: The only case left is to check whether array exists or not. In this case, there are only two condition to check as: If Bitwise XOR is greater than the sum.If sum and xor have different parities i.e., one is even and other is odd."
},
{
"code": null,
"e": 26523,
"s": 26409,
"text": "If Bitwise XOR is greater than the sum.If sum and xor have different parities i.e., one is even and other is odd."
},
{
"code": null,
"e": 26563,
"s": 26523,
"text": "If Bitwise XOR is greater than the sum."
},
{
"code": null,
"e": 26638,
"s": 26563,
"text": "If sum and xor have different parities i.e., one is even and other is odd."
},
{
"code": null,
"e": 26690,
"s": 26638,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26694,
"s": 26690,
"text": "C++"
},
{
"code": null,
"e": 26699,
"s": 26694,
"text": "Java"
},
{
"code": null,
"e": 26707,
"s": 26699,
"text": "Python3"
},
{
"code": null,
"e": 26710,
"s": 26707,
"text": "C#"
},
{
"code": null,
"e": 26721,
"s": 26710,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find arrayvoid findArray(int sum, int xorr){ // array not possible if (xorr > sum || sum % 2 != xorr % 2) { cout << \"No Array Possible\\n\"; return; } // Array possible with exactly 1 // or no element if (sum == xorr) { if (sum == 0) cout << \"Array is empty\" << \" with size 0\\n\"; else cout << \"Array size is \" << 1 << \"\\n Array is \" << sum << \"\\n\"; return; } int mid = (sum - xorr) / 2; // Checking array with two // elements possible or not. if (xorr & mid == 1) { cout << \"Array size is \" << 3 << \"\\n\"; cout << \"Array is \" << xorr << \" \" << mid << \" \" << mid << \"\\n\"; } else { cout << \"Array size is \" << 2 << \"\\n\"; cout << \"Array is \" << (xorr + mid) << \" \" << mid << \"\\n\"; }} // Driver Codeint main(){ // Given sum and value // of Bitwise XOR int sum = 4, xorr = 2; // Function Call findArray(sum, xorr); cout << \"\\n\"; return 0;}",
"e": 27972,
"s": 26721,
"text": null
},
{
"code": "// Java program implementation// of the approachimport java.util.*;import java.io.*; class GFG{ // Function to find arraystatic void findArray(int sum, int xorr){ // Array not possible if (xorr > sum || sum % 2 != xorr % 2) { System.out.println(\"No Array Possible\"); return; } // Array possible with exactly 1 // or no element if (sum == xorr) { if (sum == 0) System.out.println(\"Array is empty \" + \"with size 0\"); else System.out.println(\"Array size is \" + 1); System.out.println(\"Array is \" + sum); return; } int mid = (sum - xorr) / 2; // Checking array with two // elements possible or not. if (xorr == 1 && mid == 1) { System.out.println(\"Array size is \" + 3); System.out.println(\"Array is \" + xorr + \" \" + mid + \" \" + mid); } else { System.out.println(\"Array size is \" + 2); System.out.println(\"Array is \" + (xorr + mid) + \" \" + mid); }} // Driver codepublic static void main(String[] args){ // Given sum and value // of Bitwise XOR int sum = 4, xorr = 2; // Function call findArray(sum, xorr);}} // This code is contributed by sanjoy_62",
"e": 29317,
"s": 27972,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find arraydef findArray(_sum, xorr): # Array not possible if (xorr > _sum or _sum % 2 != xorr % 2): print(\"No Array Possible\") return # Array possible with exactly 1 # or no element if (_sum == xorr): if (_sum == 0): print(\"Array is empty\", \" with size 0\") else: print(\"Array size is\", 1) print(\"Array is\", _sum) return mid = (_sum - xorr) // 2 # Checking array with two # elements possible or not. if (xorr & mid == 1): print(\"Array size is\", 3) print(\"Array is\", xorr, mid, mid) else: print(\"Array size is\", 2) print(\"Array is\" ,(xorr + mid), mid) # Driver Code # Given sum and value# of Bitwise XOR_sum = 4xorr = 2 # Function CallfindArray(_sum, xorr) # This code is contributed by divyamohan123",
"e": 30250,
"s": 29317,
"text": null
},
{
"code": "// C# program implementation// of the approachusing System; class GFG{ // Function to find arraystatic void findArray(int sum, int xorr){ // Array not possible if (xorr > sum || sum % 2 != xorr % 2) { Console.WriteLine(\"No Array Possible\"); return; } // Array possible with exactly 1 // or no element if (sum == xorr) { if (sum == 0) Console.WriteLine(\"Array is empty \" + \"with size 0\"); else Console.WriteLine(\"Array size is \" + 1); Console.WriteLine(\"Array is \" + sum); return; } int mid = (sum - xorr) / 2; // Checking array with two // elements possible or not. if (xorr == 1 && mid == 1) { Console.WriteLine(\"Array size is \" + 3); Console.WriteLine(\"Array is \" + xorr + \" \" + mid + \" \" + mid); } else { Console.WriteLine(\"Array size is \" + 2); Console.WriteLine(\"Array is \" + (xorr + mid) + \" \" + mid); }} // Driver codepublic static void Main(){ // Given sum and value // of Bitwise XOR int sum = 4, xorr = 2; // Function call findArray(sum, xorr);}} // This code is contributed by sanjoy_62",
"e": 31528,
"s": 30250,
"text": null
},
{
"code": "<script> // Javascript program implementation// of the approach // Function to find arrayfunction findArray(sum, xorr){ // Array not possible if (xorr > sum || sum % 2 != xorr % 2) { System.out.println(\"No Array Possible\"); return; } // Array possible with exactly 1 // or no element if (sum == xorr) { if (sum == 0) document.write(\"Array is empty \" + \"with size 0\"); else document.write(\"Array size is \" + 1); document.write(\" Array is \" + sum); return; } var mid = (sum - xorr) / 2; // Checking array with two // elements possible or not. if (xorr == 1 && mid == 1) { document.write(\"Array size is \" + 3); document.write(\"Array is \" + xorr + \" \" + mid + \" \" + mid); } else { document.write(\"Array size is \" + 2); document.write(\"<br>\") document.write(\"Array is \" + (xorr + mid) + \" \" + mid); }} // Driver code // Given sum and value// of Bitwise XORvar sum = 4, xorr = 2; // Function callfindArray(sum, xorr); // This code is contributed by Khushboogoyal499 </script>",
"e": 32775,
"s": 31528,
"text": null
},
{
"code": null,
"e": 32804,
"s": 32775,
"text": "Array size is 2\nArray is 3 1"
},
{
"code": null,
"e": 32851,
"s": 32806,
"text": "Time Complexity: O(1) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 32865,
"s": 32851,
"text": "divyamohan123"
},
{
"code": null,
"e": 32875,
"s": 32865,
"text": "sanjoy_62"
},
{
"code": null,
"e": 32892,
"s": 32875,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 32904,
"s": 32892,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 32915,
"s": 32904,
"text": "Algorithms"
},
{
"code": null,
"e": 32922,
"s": 32915,
"text": "Arrays"
},
{
"code": null,
"e": 32932,
"s": 32922,
"text": "Bit Magic"
},
{
"code": null,
"e": 32956,
"s": 32932,
"text": "Competitive Programming"
},
{
"code": null,
"e": 32963,
"s": 32956,
"text": "Greedy"
},
{
"code": null,
"e": 32970,
"s": 32963,
"text": "Arrays"
},
{
"code": null,
"e": 32977,
"s": 32970,
"text": "Greedy"
},
{
"code": null,
"e": 32987,
"s": 32977,
"text": "Bit Magic"
},
{
"code": null,
"e": 32998,
"s": 32987,
"text": "Algorithms"
},
{
"code": null,
"e": 33096,
"s": 32998,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33105,
"s": 33096,
"text": "Comments"
},
{
"code": null,
"e": 33118,
"s": 33105,
"text": "Old Comments"
},
{
"code": null,
"e": 33143,
"s": 33118,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 33172,
"s": 33143,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 33228,
"s": 33172,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 33262,
"s": 33228,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 33305,
"s": 33262,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 33320,
"s": 33305,
"text": "Arrays in Java"
},
{
"code": null,
"e": 33336,
"s": 33320,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 33384,
"s": 33336,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 33411,
"s": 33384,
"text": "Program for array rotation"
}
] |
Attributes in PHP 8
|
Attributes are kinds of classes that can be used to add metadata to other classes, functions, class methods, class properties, constants, and parameters. Attributes do nothing during runtime.
Attributes have no impact on the code, but available for the reflection API. Attributes in PHP 8 allow other code to examine the class properties and methods.
We can have more than one attribute to a declaration.
We can have more than one attribute to a declaration.
It may resolve the class name.
It may resolve the class name.
Attributes can be namespaced.
Attributes can be namespaced.
It may have zero or more parameters
It may have zero or more parameters
In PHP 8, #[ ] (# and square brackets) is used for an attribute declaration.
In PHP 8, #[ ] (# and square brackets) is used for an attribute declaration.
We can declare multiple attributes inside #[ ], separated by a comma.
We can declare multiple attributes inside #[ ], separated by a comma.
Arguments are optional to use but need to be enclosed inside parenthesis ().
Arguments are optional to use but need to be enclosed inside parenthesis ().
Arguments can be literals values or constant expressions.
Arguments can be literals values or constant expressions.
Attribute: Syntax
#[attribute]
We can use an attribute to a class for instance.
#[Attribute]
Final class EmpClass{
}
Example: Attribute Function
#[Attr('param')]
function Exam(){}
Example: Attribute Classes
#[Attr('param')]
class Exam{}
Example: Attribute Class Properties
class Emp{
#[Attribute('param')]
public $name;
}
Example: Attribute Class Constants
Class Emp{
#[Attribute('emp')]
private const EMP = 'emp';
}
Example: Attribute Function
#[Attribute('emp')]
function exam(){}
Example: Attribute Method Arguments
Function emp(#[Attribute('param')]$name){
}
<?php
#[MyAttribute]
class Emp
{
#[MyAttribute]
public const EMP = 'emp';
#[MyAttribute]
public $a;
#[MyAttribute]
public function foo(#[MyAttribute] $dept){}
}
$object = new #[MyAttribute] class(){};
#[MyAttribute]
function f() {}
$f1 = #[MyAttribute] function(){};
$f2 = #[MyAttribute] fn() => 1;
print_r($f1);
?>
Closure Object ( )
|
[
{
"code": null,
"e": 1254,
"s": 1062,
"text": "Attributes are kinds of classes that can be used to add metadata to other classes, functions, class methods, class properties, constants, and parameters. Attributes do nothing during runtime."
},
{
"code": null,
"e": 1413,
"s": 1254,
"text": "Attributes have no impact on the code, but available for the reflection API. Attributes in PHP 8 allow other code to examine the class properties and methods."
},
{
"code": null,
"e": 1467,
"s": 1413,
"text": "We can have more than one attribute to a declaration."
},
{
"code": null,
"e": 1521,
"s": 1467,
"text": "We can have more than one attribute to a declaration."
},
{
"code": null,
"e": 1552,
"s": 1521,
"text": "It may resolve the class name."
},
{
"code": null,
"e": 1583,
"s": 1552,
"text": "It may resolve the class name."
},
{
"code": null,
"e": 1613,
"s": 1583,
"text": "Attributes can be namespaced."
},
{
"code": null,
"e": 1643,
"s": 1613,
"text": "Attributes can be namespaced."
},
{
"code": null,
"e": 1679,
"s": 1643,
"text": "It may have zero or more parameters"
},
{
"code": null,
"e": 1715,
"s": 1679,
"text": "It may have zero or more parameters"
},
{
"code": null,
"e": 1792,
"s": 1715,
"text": "In PHP 8, #[ ] (# and square brackets) is used for an attribute declaration."
},
{
"code": null,
"e": 1869,
"s": 1792,
"text": "In PHP 8, #[ ] (# and square brackets) is used for an attribute declaration."
},
{
"code": null,
"e": 1939,
"s": 1869,
"text": "We can declare multiple attributes inside #[ ], separated by a comma."
},
{
"code": null,
"e": 2009,
"s": 1939,
"text": "We can declare multiple attributes inside #[ ], separated by a comma."
},
{
"code": null,
"e": 2086,
"s": 2009,
"text": "Arguments are optional to use but need to be enclosed inside parenthesis ()."
},
{
"code": null,
"e": 2163,
"s": 2086,
"text": "Arguments are optional to use but need to be enclosed inside parenthesis ()."
},
{
"code": null,
"e": 2221,
"s": 2163,
"text": "Arguments can be literals values or constant expressions."
},
{
"code": null,
"e": 2279,
"s": 2221,
"text": "Arguments can be literals values or constant expressions."
},
{
"code": null,
"e": 2297,
"s": 2279,
"text": "Attribute: Syntax"
},
{
"code": null,
"e": 2310,
"s": 2297,
"text": "#[attribute]"
},
{
"code": null,
"e": 2359,
"s": 2310,
"text": "We can use an attribute to a class for instance."
},
{
"code": null,
"e": 2396,
"s": 2359,
"text": "#[Attribute]\nFinal class EmpClass{\n}"
},
{
"code": null,
"e": 2424,
"s": 2396,
"text": "Example: Attribute Function"
},
{
"code": null,
"e": 2459,
"s": 2424,
"text": "#[Attr('param')]\nfunction Exam(){}"
},
{
"code": null,
"e": 2486,
"s": 2459,
"text": "Example: Attribute Classes"
},
{
"code": null,
"e": 2516,
"s": 2486,
"text": "#[Attr('param')]\nclass Exam{}"
},
{
"code": null,
"e": 2552,
"s": 2516,
"text": "Example: Attribute Class Properties"
},
{
"code": null,
"e": 2607,
"s": 2552,
"text": "class Emp{\n #[Attribute('param')]\n public $name;\n}"
},
{
"code": null,
"e": 2642,
"s": 2607,
"text": "Example: Attribute Class Constants"
},
{
"code": null,
"e": 2708,
"s": 2642,
"text": "Class Emp{\n #[Attribute('emp')]\n private const EMP = 'emp';\n}"
},
{
"code": null,
"e": 2736,
"s": 2708,
"text": "Example: Attribute Function"
},
{
"code": null,
"e": 2774,
"s": 2736,
"text": "#[Attribute('emp')]\nfunction exam(){}"
},
{
"code": null,
"e": 2810,
"s": 2774,
"text": "Example: Attribute Method Arguments"
},
{
"code": null,
"e": 2854,
"s": 2810,
"text": "Function emp(#[Attribute('param')]$name){\n}"
},
{
"code": null,
"e": 3190,
"s": 2854,
"text": "<?php\n#[MyAttribute]\nclass Emp\n{\n #[MyAttribute]\n public const EMP = 'emp';\n #[MyAttribute]\n public $a;\n #[MyAttribute]\n public function foo(#[MyAttribute] $dept){}\n}\n\n$object = new #[MyAttribute] class(){};\n#[MyAttribute]\nfunction f() {}\n\n$f1 = #[MyAttribute] function(){};\n$f2 = #[MyAttribute] fn() => 1;\nprint_r($f1);\n?>"
},
{
"code": null,
"e": 3209,
"s": 3190,
"text": "Closure Object ( )"
}
] |
Attention Craving RNNS: Building Up To Transformer Networks | by William Falcon | Towards Data Science
|
Adding attention to your neural networks is a bit like wanting to take an afternoon nap at work. You know itβs better for you, everyone wants to do it, but everyoneβs too scared to.
My goal today is to assume nothing, explain the details with animations, and make math great again (MMGA? ugh...)
Here weβll cover:
Short RNN review.Short sequence to sequence model review.Attention in RNNs.Improvements to attention.Transformer network introduction.
Short RNN review.
Short sequence to sequence model review.
Attention in RNNs.
Improvements to attention.
Transformer network introduction.
RNNs let us model sequences in neural networks. While there are other ways of modeling sequences, RNNs are particularly useful. RNNs come in two flavors, LSTMs (Hochreiter et al, 1997) and GRUs (Cho et al, 2014). For a deep tutorial, check out Chris Colahβs tutorial.
Letβs look at machine translation for a concrete example of an RNN.
Imagine we have an RNN with 56 hidden units.
Imagine we have an RNN with 56 hidden units.
rnn_cell = rnn_cell(input_dim=100, output_dim=56)
2. We have a word βNYUβ which is represented by the integer 12 meaning itβs the 12th word in the vocab I created.
# 'NYU' is the 12th word in my vocabword = 'NYU'word = VOCAB[word]print(word)# 11
Except we donβt feed an integer into the RNN, we use a higher dimensional representation which we currently obtain through embeddings. An embedding lets us map a sequence of discrete tokens into continuous space (Bengio et al, 2003).
embedding_layer = Embedding(vocab_size=120, embedding_dim=10)# project our word to 10 dimensionsx = embedding_layer(x)
An RNN cell takes in two inputs, a word x, and a hidden state from the previous time step h. At every time step, it outputs a new h.
*Tip: For the first step h is normally just zeros.
# 1 word, RNN has 56 hidden units h_0 = np.zeros(1, 56)
This is important: RNN cell is DIFFERENT from an RNN.
Thereβs a MAJOR point of confusion in RNN terminology. In deep learning frameworks like Pytorch and Tensorflow, the RNN CELL is the unit that performs this computation:
h1 = rnn_cell(x, h0)
the RNN NETWORK for loops the cell over the time steps
def RNN(sentence): current_h = h_0 all_h = [] for word in sentence: # use the RNN CELL at each time step current_h = rnn_cell(embed(word), current_h) all_h.append(current_h) # RNNs output a hidden vector h at each time step return all_h
Hereβs an illustration of an RNN moving the same RNN cell over time:
Now youβre a pro at RNNs, but letβs take it easy for a minute.
RNNs can be used as blocks into larger deep learning systems.
One such system is a Seq2Seq model introduced by Bengioβs group (Cho et al, 2014) and Google (Sutskever et al, 2014), which can be used to translate a sequence to another. You can frame a lot of problems as translation:
Translate English to Spanish.Translate a video sequence into another sequence.Translate a sequence of instructions into programming code.Translate user behavior into future user behavior...The only limit is your creativity!
Translate English to Spanish.
Translate a video sequence into another sequence.
Translate a sequence of instructions into programming code.
Translate user behavior into future user behavior
...
The only limit is your creativity!
A seq2seq model is nothing more than 2 RNNs, an encoder (E), and decoder (D).
class Seq2Seq(object): def __init__(): self.encoder = RNN(...) self.decoder = RNN(...)
The seq2seq model has 2 major steps:
Step 1: Encode a sequence:
sentence = ["NYU", "NLP", "rocks", "!"]all_h = Seq2Seq.encoder(sentence)# all_h now has 4 h (activations)
Step 2: Decode to generate aβtranslation.β
This part gets really involved. The encoder in the previous step processed the full sequence at once (ie: it was a vanilla RNN).
In this second step, we run the decoder RNN one step at a time to generate predictions autoregressively (this is fancy for using the output of the previous step as the input to the next step).
There are two major ways of doing the decoding:
Option 1: Greedy Decoding
Run 1 step of the decoder.Pick the highest probability output.Use this output as the input to the next step
Run 1 step of the decoder.
Pick the highest probability output.
Use this output as the input to the next step
# you have to seed the first x since there are no predictions yet# SOS means start of sentencecurrent_X_token = '<SOS>'# we also use the last hidden output of the encoder (or set to zero)h_option_1 = hs[-1]h_option_2 = zeros(...)# let's use option 1 where it's the last h produced by the encoderdec_h = h_option_1# run greedy search until the RNN generates an End-of-Sentence tokenwhile current_X_token != 'EOS': # keep the output h for next step next_h = decoder(dec_h, current_X_token) # use new h to find most probable next word using classifier next_token = max(softmax(fully_connected_layer(next_h))) # *KEY* prepare for next pass by updating pointers current_X_token = next_token dec_h = next_h
Itβs called greedy because we always go with the highest probability next word.
Option 2: Beam Search
Thereβs a better technique called Beam Search, which considers multiple paths through the decoding process. Colloquially, a beam search of width 5 means we consider 5 possible sequences with the maximum log likelihood (math talk for 5 most probable sequences).
At a high-level, instead of taking the highest probability prediction, we keep the top k (beam size = k). Notice below, at each step we have 5 options (5 with the highest probability).
This youtube video has a detailed beam search tutorial!
So, the full seq2seq process with greedy decoding as an animation to translate βNYU NLP is awesomeβ into Spanish looks like this:
This model has various parts:
Blue RNN is the encoder.Red RNN is the decoderThe blue rectangle on top of the decoder is a fully connected layer with a softmax. This picks the most likely next word.
Blue RNN is the encoder.
Red RNN is the decoder
The blue rectangle on top of the decoder is a fully connected layer with a softmax. This picks the most likely next word.
Ok, now that weβve covered all the prereqs, letβs get to the good stuff.
If you noticed on the previous animation, the decoder only looked at the last hidden vector generated by the encoder.
Turns out, itβs hard for the RNN to remember everything that happened over the sequence in this single vector (Bahdanau et al, 2015). For example, the word βNYUβ could have been forgotten by the encoder by the time it finishes processing the input sequence.
Attention tries to solve this problem.
When you give a model an attention mechanism you allow it to look at ALL the hβs produced by the encoder at EACH decoding step.
To do this, we use a separate network, usually 1 fully connected layer which calculates how much of all the hβs the decoder wants to look at. This is called the attention mechanism.
So imagine that for all the hβs we generated, weβre actually only going to take a bit of each. Their sum is called a context vector c.
The scalars 0.3, 0.2, 0.4, 0.1 are called attention weights. In the original paper, youβll find the same equation on page 3:
those weights are generated by a small neural network in this way:
# attention is just a fully connected layer and a final projectionattention_mechanism = nn.Linear(input=h_size+x_size, attn_dim=20)final_proj_V = weight_matrix(attn_dim)# encode the full input sentence to get the hs we want to attend toall_h = encoder(["NYU", "NLP", "is", "awesome"]# greedy decoding 1 step at a time until end of sentence tokencurrent_token = '<SOS>'while current_token != '<EOS>': # attend to the hs first attn_energies = [] for h in all_h: attn_score = attention_mechanism([h,current_token]) attn_score = tanh(attn_score) attn_score = final_proj_V.dot(attn_score) # attn_score is now a scalar (called an attn energy) attn_energies.append(attn_score) # turn the attention energies into weights by normalizing attn_weights = softmax(attn_energies) # attn_weights = [0.3, 0.2, 0.4, 0.1]
Now that we have the weights, we use them to pull out the hβs which might be relevant for that particular token being decoded
context_vector = attn_weights.dot(all_h)# this is now a vector which mixes a bit of all the h's
Letβs break it down into steps:
We encoded the full input sequence and generated a list of hβs.We started decoding with the decoder using greedy search.Instead of giving the decoder h4, we gave it a context vector.To generate the context vector, we used another network and learnable weights V to score how relevant each h was to the current token being decoded.We normalized those attention energies and used them to mix all the hβs into 1 h which hopefully captures the relevant parts of all the hs, ie: a context vector.Now we perform the decoding step again, but this time, using the context vector instead of h4.
We encoded the full input sequence and generated a list of hβs.
We started decoding with the decoder using greedy search.
Instead of giving the decoder h4, we gave it a context vector.
To generate the context vector, we used another network and learnable weights V to score how relevant each h was to the current token being decoded.
We normalized those attention energies and used them to mix all the hβs into 1 h which hopefully captures the relevant parts of all the hs, ie: a context vector.
Now we perform the decoding step again, but this time, using the context vector instead of h4.
Visualizing Attention
The attention weights tell us how important each h is. This means we can also visualize the weights at each decoding step. Hereβs an example from the original attention paper:
In the first row, to translate βLββ the network used an alpha on the word βTheβ and zeroed the rest out.
To generate the word βeconomiqueβ the network actually put some weight of the alphas at βEuropean Economicβ and zeroed out the rest. This shows attentionβs usefulness when the translation relationship is many-to-one or one-to-many.
Types of Attention
This type of attention used only the hβs generated by the encoder. Thereβs a ton of research on improving on that process. For example:
Use only some of the hβs, maybe the hβs around the time step youβre currently decoding (local attention).In addition to the hβs also use the hβs being generated by the decoder which we were throwing away before....
Use only some of the hβs, maybe the hβs around the time step youβre currently decoding (local attention).
In addition to the hβs also use the hβs being generated by the decoder which we were throwing away before.
...
How to calculate attention energies
Another research area deals with how to calculate the attention scores. Instead of a dot product with V, researchers have also tried:
Scaling dot products.Cosine(s, h)Not using the V matrix and applying the softmax to the fully connected layer....
Scaling dot products.
Cosine(s, h)
Not using the V matrix and applying the softmax to the fully connected layer.
...
What to use when calculating attention energies
This final area of research looked at what exactly should go into comparing with the h vectors.
To build some intuition about what I mean, think about calculating attention like a key-value dictionary. The key is what you give the attention network to βlook upβ the most relevant context. The value is the most relevant context.
The method I described here only uses the current token and each h to compute the attention score. That is:
# calculate how relevant that h isscore_1 = attn_network([embed("<SOS"), h1])score_2 = attn_network([embed("<SOS"), h2])score_3 = attn_network([embed("<SOS"), h3])score_4 = attn_network([embed("<SOS"), h4])
But really we could give it anything we might think is useful to help the attention network make the best decision. Maybe we give it the last context vector also!
score_1 = attn_network([embed("<SOS>"), h1, last_context])
or maybe we give it something different, maybe a token to let it know itβs decoding Spanish
score_1 = attn_network([embed("<SOS>"), h1, last_context, embed('<SPA>')])
The possibilities are endless!
Here are some tips to think about if you decide to implement your own.
Use Facebookβs implementation which is already really optimized.
Use Facebookβs implementation which is already really optimized.
Ok, fine that was a cop-out. Here are actual tips.
Remember the seq2seq has two parts a decoder RNN and encoder RNN. These two are separate.The bulk of the work goes into building the decoder. The encoder is simply running the encoder over the full input sequence.Remember the decoder RNN operates one step at a time. This is key!Remember the decoder RNN operates one step at a time. Worth saying twice ;)You have two options for decoding algorithms, greedy or beam search. Greedy is easier to implement, but beam search will give you better results most of the time.Attention is optional! BUT... the impact is huge when you have it...Attention is a separate network... Think about the network as the dictionary, where the key is a collection of things you want the network to use in deciding how relevant each particular h is.Remember you are calculating attention for each h. That means you have a for loop for [h1, ..., hn].The attention network embedding dim can be made arbitrarily high. This WILL blow up your RAM. Make sure to put it on a separate GPU or keep the dim small.A trick to get large models going is to put the encoder on 1 gpu, decoder on a second gpu and the attention network on a third gpu. This way you keep the memory footprint low.If you actually deploy this model, youβll need to implement it batched. Everything I explained here was for batch size=1, but you can scale to bigger batches by changing to tensor products and being smart about your linear algebra. I explain this in detail here.
Remember the seq2seq has two parts a decoder RNN and encoder RNN. These two are separate.
The bulk of the work goes into building the decoder. The encoder is simply running the encoder over the full input sequence.
Remember the decoder RNN operates one step at a time. This is key!
Remember the decoder RNN operates one step at a time. Worth saying twice ;)
You have two options for decoding algorithms, greedy or beam search. Greedy is easier to implement, but beam search will give you better results most of the time.
Attention is optional! BUT... the impact is huge when you have it...
Attention is a separate network... Think about the network as the dictionary, where the key is a collection of things you want the network to use in deciding how relevant each particular h is.
Remember you are calculating attention for each h. That means you have a for loop for [h1, ..., hn].
The attention network embedding dim can be made arbitrarily high. This WILL blow up your RAM. Make sure to put it on a separate GPU or keep the dim small.
A trick to get large models going is to put the encoder on 1 gpu, decoder on a second gpu and the attention network on a third gpu. This way you keep the memory footprint low.
If you actually deploy this model, youβll need to implement it batched. Everything I explained here was for batch size=1, but you can scale to bigger batches by changing to tensor products and being smart about your linear algebra. I explain this in detail here.
Again, most of the time, you should just use an open source implementation, but itβs a great learning experience to do your own!
Turns out... the attention network by itself was shown to be really powerful.
So much so, that researchers decided to get rid of the RNNs and the sequence to sequence approach. They instead created something called a Transformer model.
At a high-level, a transformer still has an encoder and decoder except the layers are fully connected and look at the full input at once. Then as the input moves through the network, attention heads are applied to focus on whatβs important.
This model has largely replaced seq2seq models in translation and is behind the currently most powerful models, BERT and OpenAIβs GPT.
|
[
{
"code": null,
"e": 353,
"s": 171,
"text": "Adding attention to your neural networks is a bit like wanting to take an afternoon nap at work. You know itβs better for you, everyone wants to do it, but everyoneβs too scared to."
},
{
"code": null,
"e": 467,
"s": 353,
"text": "My goal today is to assume nothing, explain the details with animations, and make math great again (MMGA? ugh...)"
},
{
"code": null,
"e": 485,
"s": 467,
"text": "Here weβll cover:"
},
{
"code": null,
"e": 620,
"s": 485,
"text": "Short RNN review.Short sequence to sequence model review.Attention in RNNs.Improvements to attention.Transformer network introduction."
},
{
"code": null,
"e": 638,
"s": 620,
"text": "Short RNN review."
},
{
"code": null,
"e": 679,
"s": 638,
"text": "Short sequence to sequence model review."
},
{
"code": null,
"e": 698,
"s": 679,
"text": "Attention in RNNs."
},
{
"code": null,
"e": 725,
"s": 698,
"text": "Improvements to attention."
},
{
"code": null,
"e": 759,
"s": 725,
"text": "Transformer network introduction."
},
{
"code": null,
"e": 1027,
"s": 759,
"text": "RNNs let us model sequences in neural networks. While there are other ways of modeling sequences, RNNs are particularly useful. RNNs come in two flavors, LSTMs (Hochreiter et al, 1997) and GRUs (Cho et al, 2014). For a deep tutorial, check out Chris Colahβs tutorial."
},
{
"code": null,
"e": 1095,
"s": 1027,
"text": "Letβs look at machine translation for a concrete example of an RNN."
},
{
"code": null,
"e": 1140,
"s": 1095,
"text": "Imagine we have an RNN with 56 hidden units."
},
{
"code": null,
"e": 1185,
"s": 1140,
"text": "Imagine we have an RNN with 56 hidden units."
},
{
"code": null,
"e": 1235,
"s": 1185,
"text": "rnn_cell = rnn_cell(input_dim=100, output_dim=56)"
},
{
"code": null,
"e": 1349,
"s": 1235,
"text": "2. We have a word βNYUβ which is represented by the integer 12 meaning itβs the 12th word in the vocab I created."
},
{
"code": null,
"e": 1431,
"s": 1349,
"text": "# 'NYU' is the 12th word in my vocabword = 'NYU'word = VOCAB[word]print(word)# 11"
},
{
"code": null,
"e": 1665,
"s": 1431,
"text": "Except we donβt feed an integer into the RNN, we use a higher dimensional representation which we currently obtain through embeddings. An embedding lets us map a sequence of discrete tokens into continuous space (Bengio et al, 2003)."
},
{
"code": null,
"e": 1784,
"s": 1665,
"text": "embedding_layer = Embedding(vocab_size=120, embedding_dim=10)# project our word to 10 dimensionsx = embedding_layer(x)"
},
{
"code": null,
"e": 1917,
"s": 1784,
"text": "An RNN cell takes in two inputs, a word x, and a hidden state from the previous time step h. At every time step, it outputs a new h."
},
{
"code": null,
"e": 1968,
"s": 1917,
"text": "*Tip: For the first step h is normally just zeros."
},
{
"code": null,
"e": 2024,
"s": 1968,
"text": "# 1 word, RNN has 56 hidden units h_0 = np.zeros(1, 56)"
},
{
"code": null,
"e": 2078,
"s": 2024,
"text": "This is important: RNN cell is DIFFERENT from an RNN."
},
{
"code": null,
"e": 2247,
"s": 2078,
"text": "Thereβs a MAJOR point of confusion in RNN terminology. In deep learning frameworks like Pytorch and Tensorflow, the RNN CELL is the unit that performs this computation:"
},
{
"code": null,
"e": 2268,
"s": 2247,
"text": "h1 = rnn_cell(x, h0)"
},
{
"code": null,
"e": 2323,
"s": 2268,
"text": "the RNN NETWORK for loops the cell over the time steps"
},
{
"code": null,
"e": 2576,
"s": 2323,
"text": "def RNN(sentence): current_h = h_0 all_h = [] for word in sentence: # use the RNN CELL at each time step current_h = rnn_cell(embed(word), current_h) all_h.append(current_h) # RNNs output a hidden vector h at each time step return all_h"
},
{
"code": null,
"e": 2645,
"s": 2576,
"text": "Hereβs an illustration of an RNN moving the same RNN cell over time:"
},
{
"code": null,
"e": 2708,
"s": 2645,
"text": "Now youβre a pro at RNNs, but letβs take it easy for a minute."
},
{
"code": null,
"e": 2770,
"s": 2708,
"text": "RNNs can be used as blocks into larger deep learning systems."
},
{
"code": null,
"e": 2990,
"s": 2770,
"text": "One such system is a Seq2Seq model introduced by Bengioβs group (Cho et al, 2014) and Google (Sutskever et al, 2014), which can be used to translate a sequence to another. You can frame a lot of problems as translation:"
},
{
"code": null,
"e": 3214,
"s": 2990,
"text": "Translate English to Spanish.Translate a video sequence into another sequence.Translate a sequence of instructions into programming code.Translate user behavior into future user behavior...The only limit is your creativity!"
},
{
"code": null,
"e": 3244,
"s": 3214,
"text": "Translate English to Spanish."
},
{
"code": null,
"e": 3294,
"s": 3244,
"text": "Translate a video sequence into another sequence."
},
{
"code": null,
"e": 3354,
"s": 3294,
"text": "Translate a sequence of instructions into programming code."
},
{
"code": null,
"e": 3404,
"s": 3354,
"text": "Translate user behavior into future user behavior"
},
{
"code": null,
"e": 3408,
"s": 3404,
"text": "..."
},
{
"code": null,
"e": 3443,
"s": 3408,
"text": "The only limit is your creativity!"
},
{
"code": null,
"e": 3521,
"s": 3443,
"text": "A seq2seq model is nothing more than 2 RNNs, an encoder (E), and decoder (D)."
},
{
"code": null,
"e": 3619,
"s": 3521,
"text": "class Seq2Seq(object): def __init__(): self.encoder = RNN(...) self.decoder = RNN(...)"
},
{
"code": null,
"e": 3656,
"s": 3619,
"text": "The seq2seq model has 2 major steps:"
},
{
"code": null,
"e": 3683,
"s": 3656,
"text": "Step 1: Encode a sequence:"
},
{
"code": null,
"e": 3789,
"s": 3683,
"text": "sentence = [\"NYU\", \"NLP\", \"rocks\", \"!\"]all_h = Seq2Seq.encoder(sentence)# all_h now has 4 h (activations)"
},
{
"code": null,
"e": 3832,
"s": 3789,
"text": "Step 2: Decode to generate aβtranslation.β"
},
{
"code": null,
"e": 3961,
"s": 3832,
"text": "This part gets really involved. The encoder in the previous step processed the full sequence at once (ie: it was a vanilla RNN)."
},
{
"code": null,
"e": 4154,
"s": 3961,
"text": "In this second step, we run the decoder RNN one step at a time to generate predictions autoregressively (this is fancy for using the output of the previous step as the input to the next step)."
},
{
"code": null,
"e": 4202,
"s": 4154,
"text": "There are two major ways of doing the decoding:"
},
{
"code": null,
"e": 4228,
"s": 4202,
"text": "Option 1: Greedy Decoding"
},
{
"code": null,
"e": 4336,
"s": 4228,
"text": "Run 1 step of the decoder.Pick the highest probability output.Use this output as the input to the next step"
},
{
"code": null,
"e": 4363,
"s": 4336,
"text": "Run 1 step of the decoder."
},
{
"code": null,
"e": 4400,
"s": 4363,
"text": "Pick the highest probability output."
},
{
"code": null,
"e": 4446,
"s": 4400,
"text": "Use this output as the input to the next step"
},
{
"code": null,
"e": 5161,
"s": 4446,
"text": "# you have to seed the first x since there are no predictions yet# SOS means start of sentencecurrent_X_token = '<SOS>'# we also use the last hidden output of the encoder (or set to zero)h_option_1 = hs[-1]h_option_2 = zeros(...)# let's use option 1 where it's the last h produced by the encoderdec_h = h_option_1# run greedy search until the RNN generates an End-of-Sentence tokenwhile current_X_token != 'EOS': # keep the output h for next step next_h = decoder(dec_h, current_X_token) # use new h to find most probable next word using classifier next_token = max(softmax(fully_connected_layer(next_h))) # *KEY* prepare for next pass by updating pointers current_X_token = next_token dec_h = next_h"
},
{
"code": null,
"e": 5241,
"s": 5161,
"text": "Itβs called greedy because we always go with the highest probability next word."
},
{
"code": null,
"e": 5263,
"s": 5241,
"text": "Option 2: Beam Search"
},
{
"code": null,
"e": 5524,
"s": 5263,
"text": "Thereβs a better technique called Beam Search, which considers multiple paths through the decoding process. Colloquially, a beam search of width 5 means we consider 5 possible sequences with the maximum log likelihood (math talk for 5 most probable sequences)."
},
{
"code": null,
"e": 5709,
"s": 5524,
"text": "At a high-level, instead of taking the highest probability prediction, we keep the top k (beam size = k). Notice below, at each step we have 5 options (5 with the highest probability)."
},
{
"code": null,
"e": 5765,
"s": 5709,
"text": "This youtube video has a detailed beam search tutorial!"
},
{
"code": null,
"e": 5895,
"s": 5765,
"text": "So, the full seq2seq process with greedy decoding as an animation to translate βNYU NLP is awesomeβ into Spanish looks like this:"
},
{
"code": null,
"e": 5925,
"s": 5895,
"text": "This model has various parts:"
},
{
"code": null,
"e": 6093,
"s": 5925,
"text": "Blue RNN is the encoder.Red RNN is the decoderThe blue rectangle on top of the decoder is a fully connected layer with a softmax. This picks the most likely next word."
},
{
"code": null,
"e": 6118,
"s": 6093,
"text": "Blue RNN is the encoder."
},
{
"code": null,
"e": 6141,
"s": 6118,
"text": "Red RNN is the decoder"
},
{
"code": null,
"e": 6263,
"s": 6141,
"text": "The blue rectangle on top of the decoder is a fully connected layer with a softmax. This picks the most likely next word."
},
{
"code": null,
"e": 6336,
"s": 6263,
"text": "Ok, now that weβve covered all the prereqs, letβs get to the good stuff."
},
{
"code": null,
"e": 6454,
"s": 6336,
"text": "If you noticed on the previous animation, the decoder only looked at the last hidden vector generated by the encoder."
},
{
"code": null,
"e": 6712,
"s": 6454,
"text": "Turns out, itβs hard for the RNN to remember everything that happened over the sequence in this single vector (Bahdanau et al, 2015). For example, the word βNYUβ could have been forgotten by the encoder by the time it finishes processing the input sequence."
},
{
"code": null,
"e": 6751,
"s": 6712,
"text": "Attention tries to solve this problem."
},
{
"code": null,
"e": 6879,
"s": 6751,
"text": "When you give a model an attention mechanism you allow it to look at ALL the hβs produced by the encoder at EACH decoding step."
},
{
"code": null,
"e": 7061,
"s": 6879,
"text": "To do this, we use a separate network, usually 1 fully connected layer which calculates how much of all the hβs the decoder wants to look at. This is called the attention mechanism."
},
{
"code": null,
"e": 7196,
"s": 7061,
"text": "So imagine that for all the hβs we generated, weβre actually only going to take a bit of each. Their sum is called a context vector c."
},
{
"code": null,
"e": 7321,
"s": 7196,
"text": "The scalars 0.3, 0.2, 0.4, 0.1 are called attention weights. In the original paper, youβll find the same equation on page 3:"
},
{
"code": null,
"e": 7388,
"s": 7321,
"text": "those weights are generated by a small neural network in this way:"
},
{
"code": null,
"e": 8231,
"s": 7388,
"text": "# attention is just a fully connected layer and a final projectionattention_mechanism = nn.Linear(input=h_size+x_size, attn_dim=20)final_proj_V = weight_matrix(attn_dim)# encode the full input sentence to get the hs we want to attend toall_h = encoder([\"NYU\", \"NLP\", \"is\", \"awesome\"]# greedy decoding 1 step at a time until end of sentence tokencurrent_token = '<SOS>'while current_token != '<EOS>': # attend to the hs first attn_energies = [] for h in all_h: attn_score = attention_mechanism([h,current_token]) attn_score = tanh(attn_score) attn_score = final_proj_V.dot(attn_score) # attn_score is now a scalar (called an attn energy) attn_energies.append(attn_score) # turn the attention energies into weights by normalizing attn_weights = softmax(attn_energies) # attn_weights = [0.3, 0.2, 0.4, 0.1]"
},
{
"code": null,
"e": 8357,
"s": 8231,
"text": "Now that we have the weights, we use them to pull out the hβs which might be relevant for that particular token being decoded"
},
{
"code": null,
"e": 8453,
"s": 8357,
"text": "context_vector = attn_weights.dot(all_h)# this is now a vector which mixes a bit of all the h's"
},
{
"code": null,
"e": 8485,
"s": 8453,
"text": "Letβs break it down into steps:"
},
{
"code": null,
"e": 9071,
"s": 8485,
"text": "We encoded the full input sequence and generated a list of hβs.We started decoding with the decoder using greedy search.Instead of giving the decoder h4, we gave it a context vector.To generate the context vector, we used another network and learnable weights V to score how relevant each h was to the current token being decoded.We normalized those attention energies and used them to mix all the hβs into 1 h which hopefully captures the relevant parts of all the hs, ie: a context vector.Now we perform the decoding step again, but this time, using the context vector instead of h4."
},
{
"code": null,
"e": 9135,
"s": 9071,
"text": "We encoded the full input sequence and generated a list of hβs."
},
{
"code": null,
"e": 9193,
"s": 9135,
"text": "We started decoding with the decoder using greedy search."
},
{
"code": null,
"e": 9256,
"s": 9193,
"text": "Instead of giving the decoder h4, we gave it a context vector."
},
{
"code": null,
"e": 9405,
"s": 9256,
"text": "To generate the context vector, we used another network and learnable weights V to score how relevant each h was to the current token being decoded."
},
{
"code": null,
"e": 9567,
"s": 9405,
"text": "We normalized those attention energies and used them to mix all the hβs into 1 h which hopefully captures the relevant parts of all the hs, ie: a context vector."
},
{
"code": null,
"e": 9662,
"s": 9567,
"text": "Now we perform the decoding step again, but this time, using the context vector instead of h4."
},
{
"code": null,
"e": 9684,
"s": 9662,
"text": "Visualizing Attention"
},
{
"code": null,
"e": 9860,
"s": 9684,
"text": "The attention weights tell us how important each h is. This means we can also visualize the weights at each decoding step. Hereβs an example from the original attention paper:"
},
{
"code": null,
"e": 9965,
"s": 9860,
"text": "In the first row, to translate βLββ the network used an alpha on the word βTheβ and zeroed the rest out."
},
{
"code": null,
"e": 10197,
"s": 9965,
"text": "To generate the word βeconomiqueβ the network actually put some weight of the alphas at βEuropean Economicβ and zeroed out the rest. This shows attentionβs usefulness when the translation relationship is many-to-one or one-to-many."
},
{
"code": null,
"e": 10216,
"s": 10197,
"text": "Types of Attention"
},
{
"code": null,
"e": 10352,
"s": 10216,
"text": "This type of attention used only the hβs generated by the encoder. Thereβs a ton of research on improving on that process. For example:"
},
{
"code": null,
"e": 10567,
"s": 10352,
"text": "Use only some of the hβs, maybe the hβs around the time step youβre currently decoding (local attention).In addition to the hβs also use the hβs being generated by the decoder which we were throwing away before...."
},
{
"code": null,
"e": 10673,
"s": 10567,
"text": "Use only some of the hβs, maybe the hβs around the time step youβre currently decoding (local attention)."
},
{
"code": null,
"e": 10780,
"s": 10673,
"text": "In addition to the hβs also use the hβs being generated by the decoder which we were throwing away before."
},
{
"code": null,
"e": 10784,
"s": 10780,
"text": "..."
},
{
"code": null,
"e": 10820,
"s": 10784,
"text": "How to calculate attention energies"
},
{
"code": null,
"e": 10954,
"s": 10820,
"text": "Another research area deals with how to calculate the attention scores. Instead of a dot product with V, researchers have also tried:"
},
{
"code": null,
"e": 11068,
"s": 10954,
"text": "Scaling dot products.Cosine(s, h)Not using the V matrix and applying the softmax to the fully connected layer...."
},
{
"code": null,
"e": 11090,
"s": 11068,
"text": "Scaling dot products."
},
{
"code": null,
"e": 11103,
"s": 11090,
"text": "Cosine(s, h)"
},
{
"code": null,
"e": 11181,
"s": 11103,
"text": "Not using the V matrix and applying the softmax to the fully connected layer."
},
{
"code": null,
"e": 11185,
"s": 11181,
"text": "..."
},
{
"code": null,
"e": 11233,
"s": 11185,
"text": "What to use when calculating attention energies"
},
{
"code": null,
"e": 11329,
"s": 11233,
"text": "This final area of research looked at what exactly should go into comparing with the h vectors."
},
{
"code": null,
"e": 11562,
"s": 11329,
"text": "To build some intuition about what I mean, think about calculating attention like a key-value dictionary. The key is what you give the attention network to βlook upβ the most relevant context. The value is the most relevant context."
},
{
"code": null,
"e": 11670,
"s": 11562,
"text": "The method I described here only uses the current token and each h to compute the attention score. That is:"
},
{
"code": null,
"e": 11877,
"s": 11670,
"text": "# calculate how relevant that h isscore_1 = attn_network([embed(\"<SOS\"), h1])score_2 = attn_network([embed(\"<SOS\"), h2])score_3 = attn_network([embed(\"<SOS\"), h3])score_4 = attn_network([embed(\"<SOS\"), h4])"
},
{
"code": null,
"e": 12040,
"s": 11877,
"text": "But really we could give it anything we might think is useful to help the attention network make the best decision. Maybe we give it the last context vector also!"
},
{
"code": null,
"e": 12099,
"s": 12040,
"text": "score_1 = attn_network([embed(\"<SOS>\"), h1, last_context])"
},
{
"code": null,
"e": 12191,
"s": 12099,
"text": "or maybe we give it something different, maybe a token to let it know itβs decoding Spanish"
},
{
"code": null,
"e": 12266,
"s": 12191,
"text": "score_1 = attn_network([embed(\"<SOS>\"), h1, last_context, embed('<SPA>')])"
},
{
"code": null,
"e": 12297,
"s": 12266,
"text": "The possibilities are endless!"
},
{
"code": null,
"e": 12368,
"s": 12297,
"text": "Here are some tips to think about if you decide to implement your own."
},
{
"code": null,
"e": 12433,
"s": 12368,
"text": "Use Facebookβs implementation which is already really optimized."
},
{
"code": null,
"e": 12498,
"s": 12433,
"text": "Use Facebookβs implementation which is already really optimized."
},
{
"code": null,
"e": 12549,
"s": 12498,
"text": "Ok, fine that was a cop-out. Here are actual tips."
},
{
"code": null,
"e": 14017,
"s": 12549,
"text": "Remember the seq2seq has two parts a decoder RNN and encoder RNN. These two are separate.The bulk of the work goes into building the decoder. The encoder is simply running the encoder over the full input sequence.Remember the decoder RNN operates one step at a time. This is key!Remember the decoder RNN operates one step at a time. Worth saying twice ;)You have two options for decoding algorithms, greedy or beam search. Greedy is easier to implement, but beam search will give you better results most of the time.Attention is optional! BUT... the impact is huge when you have it...Attention is a separate network... Think about the network as the dictionary, where the key is a collection of things you want the network to use in deciding how relevant each particular h is.Remember you are calculating attention for each h. That means you have a for loop for [h1, ..., hn].The attention network embedding dim can be made arbitrarily high. This WILL blow up your RAM. Make sure to put it on a separate GPU or keep the dim small.A trick to get large models going is to put the encoder on 1 gpu, decoder on a second gpu and the attention network on a third gpu. This way you keep the memory footprint low.If you actually deploy this model, youβll need to implement it batched. Everything I explained here was for batch size=1, but you can scale to bigger batches by changing to tensor products and being smart about your linear algebra. I explain this in detail here."
},
{
"code": null,
"e": 14107,
"s": 14017,
"text": "Remember the seq2seq has two parts a decoder RNN and encoder RNN. These two are separate."
},
{
"code": null,
"e": 14232,
"s": 14107,
"text": "The bulk of the work goes into building the decoder. The encoder is simply running the encoder over the full input sequence."
},
{
"code": null,
"e": 14299,
"s": 14232,
"text": "Remember the decoder RNN operates one step at a time. This is key!"
},
{
"code": null,
"e": 14375,
"s": 14299,
"text": "Remember the decoder RNN operates one step at a time. Worth saying twice ;)"
},
{
"code": null,
"e": 14538,
"s": 14375,
"text": "You have two options for decoding algorithms, greedy or beam search. Greedy is easier to implement, but beam search will give you better results most of the time."
},
{
"code": null,
"e": 14607,
"s": 14538,
"text": "Attention is optional! BUT... the impact is huge when you have it..."
},
{
"code": null,
"e": 14800,
"s": 14607,
"text": "Attention is a separate network... Think about the network as the dictionary, where the key is a collection of things you want the network to use in deciding how relevant each particular h is."
},
{
"code": null,
"e": 14901,
"s": 14800,
"text": "Remember you are calculating attention for each h. That means you have a for loop for [h1, ..., hn]."
},
{
"code": null,
"e": 15056,
"s": 14901,
"text": "The attention network embedding dim can be made arbitrarily high. This WILL blow up your RAM. Make sure to put it on a separate GPU or keep the dim small."
},
{
"code": null,
"e": 15232,
"s": 15056,
"text": "A trick to get large models going is to put the encoder on 1 gpu, decoder on a second gpu and the attention network on a third gpu. This way you keep the memory footprint low."
},
{
"code": null,
"e": 15495,
"s": 15232,
"text": "If you actually deploy this model, youβll need to implement it batched. Everything I explained here was for batch size=1, but you can scale to bigger batches by changing to tensor products and being smart about your linear algebra. I explain this in detail here."
},
{
"code": null,
"e": 15624,
"s": 15495,
"text": "Again, most of the time, you should just use an open source implementation, but itβs a great learning experience to do your own!"
},
{
"code": null,
"e": 15702,
"s": 15624,
"text": "Turns out... the attention network by itself was shown to be really powerful."
},
{
"code": null,
"e": 15860,
"s": 15702,
"text": "So much so, that researchers decided to get rid of the RNNs and the sequence to sequence approach. They instead created something called a Transformer model."
},
{
"code": null,
"e": 16101,
"s": 15860,
"text": "At a high-level, a transformer still has an encoder and decoder except the layers are fully connected and look at the full input at once. Then as the input moves through the network, attention heads are applied to focus on whatβs important."
}
] |
CNN Transfer Learning & Fine Tuning | by Victor Roman | Towards Data Science
|
Learn how to apply these powerful techniques to take your Deep Learning models to a whole new level!
As we have seen in previous articles, we can use the architectures developed by research teams and leverage their power to make predictions and obtain better results in our Deep Learning models.
Training a neural network takes time, luckily nowadays there are ways to avoid having to:
Define the architecture of a neural network
Train her from the beginning
We already have seen ways to avoid having to define the architecture here, and it consists of using predefined architectures that are known to work well: ResNet, AlexNet, VGG, Inception, DenseNet, etc.
And what about avoiding training it from scratch? What do I mean by that?
Neural networks are initialized with random weights (usually) that after a series of epochs reach some values that allow us to properly classify our input images.
What would happen if we could initialize those weights to certain values that we know beforehand that are already good to classify a certain dataset?
In this way, we would not need a dataset as big as if we were to train a network from zero (from hundreds of thousands or even millions of images we could go to a few thousands) nor would we need to wait a good number of epochs for the weights to take good values for the classification, they would have it much easier due to their initialization.
Letβs explore how to do this with the techniques of transfer learning and fine-tuning:
Letβs take the VGG16 network trained on the ImageNet dataset as an example. Letβs see its architecture:
We know that ImageNet consists of a dataset of about 1.2 million images for training, 50,000 for validation and 100,000 for testing, belonging to 1000 categories.
Now imagine that what we want is to apply the VGG16 trained on ImageNet to another dataset, letβs say that we choose the CIFAR-10. How could we do it?
Remembering the general scheme of a CNN, we have a feature extractor in the first stage and then a classifier:
What if we removed the last layer of the VGG16, which simply takes a probability for each of the 1000 classes in the ImageNet and replaces it with a layer that takes 10 probabilities? This way, we could take all the knowledge that VGG16 has trained on the ImageNet and apply it to our problem!
As we have seen, what we will do is change the classification stage, so that the last layer is one of 10 neurons (our CIFAR 10 has 10 classes) and then we will retrain the network allowing the weights of the fully connected layers to be changed, that is, the classification stage.
For this, we would initialize our network with the weights from the ImageNet, and then freeze all the convolutional and max-pooling layers so that they do not modify their weights, leaving only the fully connected ones free.
Once this is done, we would start retraining. In this way, we manage to take advantage of the feature extraction stage of our network and only tune the final classifier to work better with our dataset. This is what is known as Transfer Learning because we take advantage of the knowledge of another problem to solve the one we are dealing with.
This approach can also be done by saving the characteristics given by the last layer of max pooling and then putting that data into any classifier (SVM, logreg, etc).
Letβs see how we could do it:
# We first load the necessary libraries, the dataset and reshape its dimensons to the minimum allowed by the VGG16 --> (48,48,3)import tensorflow as tffrom keras import callbacksfrom keras import optimizersfrom keras.engine import Modelfrom keras.layers import Dropout, Flatten, Densefrom keras.optimizers import Adamfrom keras.applications import VGG16from keras.datasets import cifar10from keras.utils import to_categoricalimport numpy as npinput_shape = (48, 48, 3)(X_train, y_train), (X_test, y_test) = cifar10.load_data()Y_train = to_categorical(y_train)Y_test = to_categorical(y_test)# resize train setX_train_resized = []for img in X_train: X_train_resized.append(np.resize(img, input_shape) / 255) X_train_resized = np.array(X_train_resized)print(X_train_resized.shape)# resize test setX_test_resized = []for img in X_test: X_test_resized.append(np.resize(img, input_shape) / 255) X_test_resized = np.array(X_test_resized)print(X_test_resized.shape)
# We build the base modelbase_model = VGG16(weights='imagenet', include_top=False, input_shape=input_shape)base_model.summary()
# We freeze every layer in our base model so that they do not train, we want that our feature extractor stays as before --> transfer learningfor layer in base_model.layers: layer.trainable = False print('Layer ' + layer.name + ' frozen.')# We take the last layer of our the model and add it to our classifierlast = base_model.layers[-1].outputx = Flatten()(last)x = Dense(1000, activation='relu', name='fc1')(x)x = Dropout(0.3)(x)x = Dense(10, activation='softmax', name='predictions')(x)model = Model(base_model.input, x)# We compile the modelmodel.compile(optimizer=Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])-model.summary()
# We start the trainingepochs = 10batch_size = 256# We train itmodel.fit(X_train_resized, Y_train, batch_size=batch_size, validation_data=(X_test_resized, Y_test), epochs=epochs)
# We evaluate the accuracy and the loss in the test setscores = model.evaluate(X_test_resized, Y_test, verbose=1)print('Test loss:', scores[0])print('Test accuracy:', scores[1])
We havenβt had to train at all, and weβve had not bad results! Keep in mind that if we did it randomly the probability of getting it right would be 1/10=0.1 or 10%, since we have 10 classes.
The more similar the dataset on which the network was originally trained and the dataset of our problem are, the better results we get.
And if our dataset has nothing to do with the one of ImageNet or we want to improve the results even more?
Well, for that, we use fine-tuning.
With fine-tuning, we first change the last layer to match the classes in our dataset, as we have done before with transfer learning. But besides, we also retrain the layers of the network that we want.
Remember again the architecture of the VGG16:
What we did in the previous example was to change only the layers of the classification stage, keeping the knowledge that the network obtained when extracting characteristics (patterns) in the previous task, from which we are loading the weights (ImageNet).
With fine-tuning we are not limited to retraining only the classifier stage (i.e. the fully connected layers), but what we will do is retrain also the feature extraction stage, i.e. the convolutional and pooling layers.
Itβs important to keep in mind that in a neural network, the first layers detect simpler and more general patterns, and the more we advance in the architecture, the more specific to the dataset and the more complicated the patterns they detect.
Therefore, we could allow the last block of convolution and pooling layers to be retrained.
When do I do fine-tuning and transfer learning? How do I choose which layer to retrain from?
Well, as a general rule, the first thing we will do is transfer learning, i.e. we will not retrain our network. That will give us a baseline that we will have to overcome. Then, we will retrain only the classification stage, and then we can try to retrain some convolutional block as well.
Make transfer learning, that is, modify only the last layer so that it has the same number of outputs as our classes (baseline)
Try to retrain the sorting stage, i.e. the dense layers
Trying to retrain some convolutional stage
Following these steps most of the time you will reach a suitable result for your problem
It also depends on the type of problem you have. If:
The new dataset is small and similar to the original one: be careful when fine-tuning, maybe it is better to choose the characteristics of the last layer of the convolutional stage and use an SVM or linear classifier.
The new dataset is large and similar to the original: having more data we probably wonβt over-fit, so we can fine-tune with more confidence.
The new dataset is small and very different from the original: it would be best to use features of an earlier layer of the convolutional stage, as this will be set in more general patterns than the later layers, and then use a linear classifier.
The new dataset is big and very different from the original: we will train it from scratch! However, it is still recommended that you initialize the weights with those of the ImageNet.
When using any of these techniques, you must take into account the possible restrictions of the pre-trained models. For example, they may require a minimum image size.
Besides, when retraining networks, we usually choose lower learning rates than if we do it from scratch since we start from the initialization of weights that is assumed to be good.
# Fine Tuning Example, classification VGG16 with CIFAR 10, we import the necessary librariesimport tensorflow as tffrom keras import callbacksfrom keras import optimizersfrom keras.engine import Modelfrom keras.layers import Dropout, Flatten, Densefrom keras.optimizers import Adamfrom keras.preprocessing.image import ImageDataGeneratorfrom keras.applications import VGG16from keras.datasets import cifar10from keras.utils import to_categoricalimport numpy as np# We first load the dataset and reshape its dimensions to the minimum allowed by VGG16 --> (48, 48, 3)input_shape = (48, 48, 3)(X_train, y_train), (X_test, y_test) = cifar10.load_data()Y_train = to_categorical(y_train)Y_test = to_categorical(y_test)# resize train setX_train_resized = []for img in X_train: X_train_resized.append(np.resize(img, input_shape) / 255) X_train_resized = np.array(X_train_resized)print(X_train_resized.shape)# resize test setX_test_resized = []for img in X_test: X_test_resized.append(np.resize(img, input_shape) / 255) X_test_resized = np.array(X_test_resized)print(X_test_resized.shape)
# We build the base modelbase_model = VGG16(weights='imagenet', include_top=False, input_shape=input_shape)base_model.summary()
# We allow to the last convolutional andthe classification stages to trainfor layer in base_model.layers: if layer.name == 'block5_conv1': break layer.trainable = False print('Layer ' + layer.name + ' frozen.')# We add our classificator (top_model) to the last layer of the modellast = base_model.layers[-1].outputx = Flatten()(last)x = Dense(1000, activation='relu', name='fc1')(x)x = Dropout(0.3)(x)x = Dense(10, activation='softmax', name='predictions')(x)model = Model(base_model.input, x)# We compile the modelmodel.compile(optimizer=Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])# We see the new structure of the modelmodel.summary()
# We start the trainingepochs = 15batch_size = 256# We train the modelmodel.fit(X_train_resized, Y_train, batch_size=batch_size, validation_data=(X_test_resized, Y_test), epochs=epochs)
# We evaluate the accuracy and the loss in the test setscores = model.evaluate(X_test_resized, Y_test, verbose=1)print('Test loss:', scores[0])print('Test accuracy:', scores[1])
So,the way to go when we face a Deep Learning problem would be to star always using fine-tunning and building a baseline model which we will try to improve later.
As always, I hope you enjoyed the post, and that you gained an intuition about how to implement and develop a convolutional neural network with transfer learning and fine-tuning!
If you liked this post then you can take a look at my other posts on Data Science and Machine Learning here.
If you want to learn more about Machine Learning, Data Science and Artificial Intelligence follow me on Medium, and stay tuned for my next posts!
|
[
{
"code": null,
"e": 273,
"s": 172,
"text": "Learn how to apply these powerful techniques to take your Deep Learning models to a whole new level!"
},
{
"code": null,
"e": 468,
"s": 273,
"text": "As we have seen in previous articles, we can use the architectures developed by research teams and leverage their power to make predictions and obtain better results in our Deep Learning models."
},
{
"code": null,
"e": 558,
"s": 468,
"text": "Training a neural network takes time, luckily nowadays there are ways to avoid having to:"
},
{
"code": null,
"e": 602,
"s": 558,
"text": "Define the architecture of a neural network"
},
{
"code": null,
"e": 631,
"s": 602,
"text": "Train her from the beginning"
},
{
"code": null,
"e": 833,
"s": 631,
"text": "We already have seen ways to avoid having to define the architecture here, and it consists of using predefined architectures that are known to work well: ResNet, AlexNet, VGG, Inception, DenseNet, etc."
},
{
"code": null,
"e": 907,
"s": 833,
"text": "And what about avoiding training it from scratch? What do I mean by that?"
},
{
"code": null,
"e": 1070,
"s": 907,
"text": "Neural networks are initialized with random weights (usually) that after a series of epochs reach some values that allow us to properly classify our input images."
},
{
"code": null,
"e": 1220,
"s": 1070,
"text": "What would happen if we could initialize those weights to certain values that we know beforehand that are already good to classify a certain dataset?"
},
{
"code": null,
"e": 1568,
"s": 1220,
"text": "In this way, we would not need a dataset as big as if we were to train a network from zero (from hundreds of thousands or even millions of images we could go to a few thousands) nor would we need to wait a good number of epochs for the weights to take good values for the classification, they would have it much easier due to their initialization."
},
{
"code": null,
"e": 1655,
"s": 1568,
"text": "Letβs explore how to do this with the techniques of transfer learning and fine-tuning:"
},
{
"code": null,
"e": 1759,
"s": 1655,
"text": "Letβs take the VGG16 network trained on the ImageNet dataset as an example. Letβs see its architecture:"
},
{
"code": null,
"e": 1922,
"s": 1759,
"text": "We know that ImageNet consists of a dataset of about 1.2 million images for training, 50,000 for validation and 100,000 for testing, belonging to 1000 categories."
},
{
"code": null,
"e": 2073,
"s": 1922,
"text": "Now imagine that what we want is to apply the VGG16 trained on ImageNet to another dataset, letβs say that we choose the CIFAR-10. How could we do it?"
},
{
"code": null,
"e": 2184,
"s": 2073,
"text": "Remembering the general scheme of a CNN, we have a feature extractor in the first stage and then a classifier:"
},
{
"code": null,
"e": 2478,
"s": 2184,
"text": "What if we removed the last layer of the VGG16, which simply takes a probability for each of the 1000 classes in the ImageNet and replaces it with a layer that takes 10 probabilities? This way, we could take all the knowledge that VGG16 has trained on the ImageNet and apply it to our problem!"
},
{
"code": null,
"e": 2759,
"s": 2478,
"text": "As we have seen, what we will do is change the classification stage, so that the last layer is one of 10 neurons (our CIFAR 10 has 10 classes) and then we will retrain the network allowing the weights of the fully connected layers to be changed, that is, the classification stage."
},
{
"code": null,
"e": 2984,
"s": 2759,
"text": "For this, we would initialize our network with the weights from the ImageNet, and then freeze all the convolutional and max-pooling layers so that they do not modify their weights, leaving only the fully connected ones free."
},
{
"code": null,
"e": 3329,
"s": 2984,
"text": "Once this is done, we would start retraining. In this way, we manage to take advantage of the feature extraction stage of our network and only tune the final classifier to work better with our dataset. This is what is known as Transfer Learning because we take advantage of the knowledge of another problem to solve the one we are dealing with."
},
{
"code": null,
"e": 3496,
"s": 3329,
"text": "This approach can also be done by saving the characteristics given by the last layer of max pooling and then putting that data into any classifier (SVM, logreg, etc)."
},
{
"code": null,
"e": 3526,
"s": 3496,
"text": "Letβs see how we could do it:"
},
{
"code": null,
"e": 4488,
"s": 3526,
"text": "# We first load the necessary libraries, the dataset and reshape its dimensons to the minimum allowed by the VGG16 --> (48,48,3)import tensorflow as tffrom keras import callbacksfrom keras import optimizersfrom keras.engine import Modelfrom keras.layers import Dropout, Flatten, Densefrom keras.optimizers import Adamfrom keras.applications import VGG16from keras.datasets import cifar10from keras.utils import to_categoricalimport numpy as npinput_shape = (48, 48, 3)(X_train, y_train), (X_test, y_test) = cifar10.load_data()Y_train = to_categorical(y_train)Y_test = to_categorical(y_test)# resize train setX_train_resized = []for img in X_train: X_train_resized.append(np.resize(img, input_shape) / 255) X_train_resized = np.array(X_train_resized)print(X_train_resized.shape)# resize test setX_test_resized = []for img in X_test: X_test_resized.append(np.resize(img, input_shape) / 255) X_test_resized = np.array(X_test_resized)print(X_test_resized.shape)"
},
{
"code": null,
"e": 4616,
"s": 4488,
"text": "# We build the base modelbase_model = VGG16(weights='imagenet', include_top=False, input_shape=input_shape)base_model.summary()"
},
{
"code": null,
"e": 5274,
"s": 4616,
"text": "# We freeze every layer in our base model so that they do not train, we want that our feature extractor stays as before --> transfer learningfor layer in base_model.layers: layer.trainable = False print('Layer ' + layer.name + ' frozen.')# We take the last layer of our the model and add it to our classifierlast = base_model.layers[-1].outputx = Flatten()(last)x = Dense(1000, activation='relu', name='fc1')(x)x = Dropout(0.3)(x)x = Dense(10, activation='softmax', name='predictions')(x)model = Model(base_model.input, x)# We compile the modelmodel.compile(optimizer=Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])-model.summary()"
},
{
"code": null,
"e": 5480,
"s": 5274,
"text": "# We start the trainingepochs = 10batch_size = 256# We train itmodel.fit(X_train_resized, Y_train, batch_size=batch_size, validation_data=(X_test_resized, Y_test), epochs=epochs)"
},
{
"code": null,
"e": 5658,
"s": 5480,
"text": "# We evaluate the accuracy and the loss in the test setscores = model.evaluate(X_test_resized, Y_test, verbose=1)print('Test loss:', scores[0])print('Test accuracy:', scores[1])"
},
{
"code": null,
"e": 5849,
"s": 5658,
"text": "We havenβt had to train at all, and weβve had not bad results! Keep in mind that if we did it randomly the probability of getting it right would be 1/10=0.1 or 10%, since we have 10 classes."
},
{
"code": null,
"e": 5985,
"s": 5849,
"text": "The more similar the dataset on which the network was originally trained and the dataset of our problem are, the better results we get."
},
{
"code": null,
"e": 6092,
"s": 5985,
"text": "And if our dataset has nothing to do with the one of ImageNet or we want to improve the results even more?"
},
{
"code": null,
"e": 6128,
"s": 6092,
"text": "Well, for that, we use fine-tuning."
},
{
"code": null,
"e": 6330,
"s": 6128,
"text": "With fine-tuning, we first change the last layer to match the classes in our dataset, as we have done before with transfer learning. But besides, we also retrain the layers of the network that we want."
},
{
"code": null,
"e": 6376,
"s": 6330,
"text": "Remember again the architecture of the VGG16:"
},
{
"code": null,
"e": 6634,
"s": 6376,
"text": "What we did in the previous example was to change only the layers of the classification stage, keeping the knowledge that the network obtained when extracting characteristics (patterns) in the previous task, from which we are loading the weights (ImageNet)."
},
{
"code": null,
"e": 6854,
"s": 6634,
"text": "With fine-tuning we are not limited to retraining only the classifier stage (i.e. the fully connected layers), but what we will do is retrain also the feature extraction stage, i.e. the convolutional and pooling layers."
},
{
"code": null,
"e": 7099,
"s": 6854,
"text": "Itβs important to keep in mind that in a neural network, the first layers detect simpler and more general patterns, and the more we advance in the architecture, the more specific to the dataset and the more complicated the patterns they detect."
},
{
"code": null,
"e": 7191,
"s": 7099,
"text": "Therefore, we could allow the last block of convolution and pooling layers to be retrained."
},
{
"code": null,
"e": 7284,
"s": 7191,
"text": "When do I do fine-tuning and transfer learning? How do I choose which layer to retrain from?"
},
{
"code": null,
"e": 7574,
"s": 7284,
"text": "Well, as a general rule, the first thing we will do is transfer learning, i.e. we will not retrain our network. That will give us a baseline that we will have to overcome. Then, we will retrain only the classification stage, and then we can try to retrain some convolutional block as well."
},
{
"code": null,
"e": 7702,
"s": 7574,
"text": "Make transfer learning, that is, modify only the last layer so that it has the same number of outputs as our classes (baseline)"
},
{
"code": null,
"e": 7758,
"s": 7702,
"text": "Try to retrain the sorting stage, i.e. the dense layers"
},
{
"code": null,
"e": 7801,
"s": 7758,
"text": "Trying to retrain some convolutional stage"
},
{
"code": null,
"e": 7890,
"s": 7801,
"text": "Following these steps most of the time you will reach a suitable result for your problem"
},
{
"code": null,
"e": 7943,
"s": 7890,
"text": "It also depends on the type of problem you have. If:"
},
{
"code": null,
"e": 8161,
"s": 7943,
"text": "The new dataset is small and similar to the original one: be careful when fine-tuning, maybe it is better to choose the characteristics of the last layer of the convolutional stage and use an SVM or linear classifier."
},
{
"code": null,
"e": 8302,
"s": 8161,
"text": "The new dataset is large and similar to the original: having more data we probably wonβt over-fit, so we can fine-tune with more confidence."
},
{
"code": null,
"e": 8548,
"s": 8302,
"text": "The new dataset is small and very different from the original: it would be best to use features of an earlier layer of the convolutional stage, as this will be set in more general patterns than the later layers, and then use a linear classifier."
},
{
"code": null,
"e": 8733,
"s": 8548,
"text": "The new dataset is big and very different from the original: we will train it from scratch! However, it is still recommended that you initialize the weights with those of the ImageNet."
},
{
"code": null,
"e": 8901,
"s": 8733,
"text": "When using any of these techniques, you must take into account the possible restrictions of the pre-trained models. For example, they may require a minimum image size."
},
{
"code": null,
"e": 9083,
"s": 8901,
"text": "Besides, when retraining networks, we usually choose lower learning rates than if we do it from scratch since we start from the initialization of weights that is assumed to be good."
},
{
"code": null,
"e": 10167,
"s": 9083,
"text": "# Fine Tuning Example, classification VGG16 with CIFAR 10, we import the necessary librariesimport tensorflow as tffrom keras import callbacksfrom keras import optimizersfrom keras.engine import Modelfrom keras.layers import Dropout, Flatten, Densefrom keras.optimizers import Adamfrom keras.preprocessing.image import ImageDataGeneratorfrom keras.applications import VGG16from keras.datasets import cifar10from keras.utils import to_categoricalimport numpy as np# We first load the dataset and reshape its dimensions to the minimum allowed by VGG16 --> (48, 48, 3)input_shape = (48, 48, 3)(X_train, y_train), (X_test, y_test) = cifar10.load_data()Y_train = to_categorical(y_train)Y_test = to_categorical(y_test)# resize train setX_train_resized = []for img in X_train: X_train_resized.append(np.resize(img, input_shape) / 255) X_train_resized = np.array(X_train_resized)print(X_train_resized.shape)# resize test setX_test_resized = []for img in X_test: X_test_resized.append(np.resize(img, input_shape) / 255) X_test_resized = np.array(X_test_resized)print(X_test_resized.shape)"
},
{
"code": null,
"e": 10295,
"s": 10167,
"text": "# We build the base modelbase_model = VGG16(weights='imagenet', include_top=False, input_shape=input_shape)base_model.summary()"
},
{
"code": null,
"e": 10966,
"s": 10295,
"text": "# We allow to the last convolutional andthe classification stages to trainfor layer in base_model.layers: if layer.name == 'block5_conv1': break layer.trainable = False print('Layer ' + layer.name + ' frozen.')# We add our classificator (top_model) to the last layer of the modellast = base_model.layers[-1].outputx = Flatten()(last)x = Dense(1000, activation='relu', name='fc1')(x)x = Dropout(0.3)(x)x = Dense(10, activation='softmax', name='predictions')(x)model = Model(base_model.input, x)# We compile the modelmodel.compile(optimizer=Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])# We see the new structure of the modelmodel.summary()"
},
{
"code": null,
"e": 11179,
"s": 10966,
"text": "# We start the trainingepochs = 15batch_size = 256# We train the modelmodel.fit(X_train_resized, Y_train, batch_size=batch_size, validation_data=(X_test_resized, Y_test), epochs=epochs)"
},
{
"code": null,
"e": 11357,
"s": 11179,
"text": "# We evaluate the accuracy and the loss in the test setscores = model.evaluate(X_test_resized, Y_test, verbose=1)print('Test loss:', scores[0])print('Test accuracy:', scores[1])"
},
{
"code": null,
"e": 11520,
"s": 11357,
"text": "So,the way to go when we face a Deep Learning problem would be to star always using fine-tunning and building a baseline model which we will try to improve later."
},
{
"code": null,
"e": 11699,
"s": 11520,
"text": "As always, I hope you enjoyed the post, and that you gained an intuition about how to implement and develop a convolutional neural network with transfer learning and fine-tuning!"
},
{
"code": null,
"e": 11808,
"s": 11699,
"text": "If you liked this post then you can take a look at my other posts on Data Science and Machine Learning here."
}
] |
Proxy Design Pattern
|
01 Sep, 2021
Proxy means βin place ofβ, representingβ or βin place ofβ or βon behalf ofβ are literal meanings of proxy and that directly explains Proxy Design Pattern.Proxies are also called surrogates, handles, and wrappers. They are closely related in structure, but not purpose, to Adapters and Decorators.
A real world example can be a cheque or credit card is a proxy for what is in our bank account. It can be used in place of cash, and provides a means of accessing that cash when required. And thatβs exactly what the Proxy pattern does β βControls and manage access to the object they are protectingβ.
Behavior
As in the decorator pattern, proxies can be chained together. The client, and each proxy, believes it is delegating messages to the real server:
When to use this pattern?
Proxy pattern is used when we need to create a wrapper to cover the main objectβs complexity from the client.
Types of proxies
Remote proxy:They are responsible for representing the object located remotely. Talking to the real object might involve marshalling and unmarshalling of data and talking to the remote object. All that logic is encapsulated in these proxies and the client application need not worry about them.
Virtual proxy:
These proxies will provide some default and instant results if the real object is supposed to take some time to produce results. These proxies initiate the operation on real objects and provide a default result to the application. Once the real object is done, these proxies push the actual data to the client where it has provided dummy data earlier.
Protection proxy:
If an application does not have access to some resource then such proxies will talk to the objects in applications that have access to that resource and then get the result back.
Smart Proxy:
A smart proxy provides additional layer of security by interposing specific actions when the object is accessed. An example can be to check if the real object is locked before it is accessed to ensure that no other object can change it.
Some Examples
A very simple real life scenario is our college internet, which restricts few site access. The proxy first checks the host you are connecting to, if it is not part of restricted site list, then it connects to the real internet. This example is based on Protection proxies.
Lets see how it works :
Interface of Internet
package com.saket.demo.proxy; public interface Internet{ public void connectTo(String serverhost) throws Exception;}
RealInternet.java
package com.saket.demo.proxy; public class RealInternet implements Internet{ @Override public void connectTo(String serverhost) { System.out.println("Connecting to "+ serverhost); }}
ProxyInternet.java
package com.saket.demo.proxy; import java.util.ArrayList;import java.util.List; public class ProxyInternet implements Internet{ private Internet internet = new RealInternet(); private static List<String> bannedSites; static { bannedSites = new ArrayList<String>(); bannedSites.add("abc.com"); bannedSites.add("def.com"); bannedSites.add("ijk.com"); bannedSites.add("lnm.com"); } @Override public void connectTo(String serverhost) throws Exception { if(bannedSites.contains(serverhost.toLowerCase())) { throw new Exception("Access Denied"); } internet.connectTo(serverhost); } }
Client.java
package com.saket.demo.proxy; public class Client{ public static void main (String[] args) { Internet internet = new ProxyInternet(); try { internet.connectTo("geeksforgeeks.org"); internet.connectTo("abc.com"); } catch (Exception e) { System.out.println(e.getMessage()); } }}
As one of the site is mentioned in the banned sites, SoRunning the program will give the output :
Connecting to geeksforgeeks.org
Access Denied
Benefits:
One of the advantages of Proxy pattern is security.
This pattern avoids duplication of objects which might be huge size and memory intensive. This in turn increases the performance of the application.
The remote proxy also ensures about security by installing the local code proxy (stub) in the client machine and then accessing the server with help of the remote code.
Drawbacks/Consequences:
This pattern introduces another layer of abstraction which sometimes may be an issue if the RealSubject code is accessed by some of the clients directly and some of them might access the Proxy classes. This might cause disparate behaviour.
Interesting points:
There are few differences between the related patterns. Like Adapter pattern gives a different interface to its subject, while Proxy patterns provides the same interface from the original object but the decorator provides an enhanced interface. Decorator pattern adds additional behaviour at runtime.
Proxy used in Java API: java.rmi.*;
Further Read: Proxy Method in Python
This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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.
Design Pattern
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 349,
"s": 52,
"text": "Proxy means βin place ofβ, representingβ or βin place ofβ or βon behalf ofβ are literal meanings of proxy and that directly explains Proxy Design Pattern.Proxies are also called surrogates, handles, and wrappers. They are closely related in structure, but not purpose, to Adapters and Decorators."
},
{
"code": null,
"e": 650,
"s": 349,
"text": "A real world example can be a cheque or credit card is a proxy for what is in our bank account. It can be used in place of cash, and provides a means of accessing that cash when required. And thatβs exactly what the Proxy pattern does β βControls and manage access to the object they are protectingβ."
},
{
"code": null,
"e": 659,
"s": 650,
"text": "Behavior"
},
{
"code": null,
"e": 804,
"s": 659,
"text": "As in the decorator pattern, proxies can be chained together. The client, and each proxy, believes it is delegating messages to the real server:"
},
{
"code": null,
"e": 830,
"s": 804,
"text": "When to use this pattern?"
},
{
"code": null,
"e": 940,
"s": 830,
"text": "Proxy pattern is used when we need to create a wrapper to cover the main objectβs complexity from the client."
},
{
"code": null,
"e": 957,
"s": 940,
"text": "Types of proxies"
},
{
"code": null,
"e": 1252,
"s": 957,
"text": "Remote proxy:They are responsible for representing the object located remotely. Talking to the real object might involve marshalling and unmarshalling of data and talking to the remote object. All that logic is encapsulated in these proxies and the client application need not worry about them."
},
{
"code": null,
"e": 1267,
"s": 1252,
"text": "Virtual proxy:"
},
{
"code": null,
"e": 1619,
"s": 1267,
"text": "These proxies will provide some default and instant results if the real object is supposed to take some time to produce results. These proxies initiate the operation on real objects and provide a default result to the application. Once the real object is done, these proxies push the actual data to the client where it has provided dummy data earlier."
},
{
"code": null,
"e": 1637,
"s": 1619,
"text": "Protection proxy:"
},
{
"code": null,
"e": 1816,
"s": 1637,
"text": "If an application does not have access to some resource then such proxies will talk to the objects in applications that have access to that resource and then get the result back."
},
{
"code": null,
"e": 1829,
"s": 1816,
"text": "Smart Proxy:"
},
{
"code": null,
"e": 2066,
"s": 1829,
"text": "A smart proxy provides additional layer of security by interposing specific actions when the object is accessed. An example can be to check if the real object is locked before it is accessed to ensure that no other object can change it."
},
{
"code": null,
"e": 2080,
"s": 2066,
"text": "Some Examples"
},
{
"code": null,
"e": 2353,
"s": 2080,
"text": "A very simple real life scenario is our college internet, which restricts few site access. The proxy first checks the host you are connecting to, if it is not part of restricted site list, then it connects to the real internet. This example is based on Protection proxies."
},
{
"code": null,
"e": 2377,
"s": 2353,
"text": "Lets see how it works :"
},
{
"code": null,
"e": 2399,
"s": 2377,
"text": "Interface of Internet"
},
{
"code": "package com.saket.demo.proxy; public interface Internet{ public void connectTo(String serverhost) throws Exception;}",
"e": 2520,
"s": 2399,
"text": null
},
{
"code": null,
"e": 2538,
"s": 2520,
"text": "RealInternet.java"
},
{
"code": "package com.saket.demo.proxy; public class RealInternet implements Internet{ @Override public void connectTo(String serverhost) { System.out.println(\"Connecting to \"+ serverhost); }}",
"e": 2741,
"s": 2538,
"text": null
},
{
"code": null,
"e": 2760,
"s": 2741,
"text": "ProxyInternet.java"
},
{
"code": "package com.saket.demo.proxy; import java.util.ArrayList;import java.util.List; public class ProxyInternet implements Internet{ private Internet internet = new RealInternet(); private static List<String> bannedSites; static { bannedSites = new ArrayList<String>(); bannedSites.add(\"abc.com\"); bannedSites.add(\"def.com\"); bannedSites.add(\"ijk.com\"); bannedSites.add(\"lnm.com\"); } @Override public void connectTo(String serverhost) throws Exception { if(bannedSites.contains(serverhost.toLowerCase())) { throw new Exception(\"Access Denied\"); } internet.connectTo(serverhost); } }",
"e": 3466,
"s": 2760,
"text": null
},
{
"code": null,
"e": 3478,
"s": 3466,
"text": "Client.java"
},
{
"code": "package com.saket.demo.proxy; public class Client{ public static void main (String[] args) { Internet internet = new ProxyInternet(); try { internet.connectTo(\"geeksforgeeks.org\"); internet.connectTo(\"abc.com\"); } catch (Exception e) { System.out.println(e.getMessage()); } }}",
"e": 3847,
"s": 3478,
"text": null
},
{
"code": null,
"e": 3945,
"s": 3847,
"text": "As one of the site is mentioned in the banned sites, SoRunning the program will give the output :"
},
{
"code": null,
"e": 3992,
"s": 3945,
"text": "Connecting to geeksforgeeks.org\nAccess Denied\n"
},
{
"code": null,
"e": 4002,
"s": 3992,
"text": "Benefits:"
},
{
"code": null,
"e": 4054,
"s": 4002,
"text": "One of the advantages of Proxy pattern is security."
},
{
"code": null,
"e": 4203,
"s": 4054,
"text": "This pattern avoids duplication of objects which might be huge size and memory intensive. This in turn increases the performance of the application."
},
{
"code": null,
"e": 4372,
"s": 4203,
"text": "The remote proxy also ensures about security by installing the local code proxy (stub) in the client machine and then accessing the server with help of the remote code."
},
{
"code": null,
"e": 4396,
"s": 4372,
"text": "Drawbacks/Consequences:"
},
{
"code": null,
"e": 4636,
"s": 4396,
"text": "This pattern introduces another layer of abstraction which sometimes may be an issue if the RealSubject code is accessed by some of the clients directly and some of them might access the Proxy classes. This might cause disparate behaviour."
},
{
"code": null,
"e": 4656,
"s": 4636,
"text": "Interesting points:"
},
{
"code": null,
"e": 4957,
"s": 4656,
"text": "There are few differences between the related patterns. Like Adapter pattern gives a different interface to its subject, while Proxy patterns provides the same interface from the original object but the decorator provides an enhanced interface. Decorator pattern adds additional behaviour at runtime."
},
{
"code": null,
"e": 4993,
"s": 4957,
"text": "Proxy used in Java API: java.rmi.*;"
},
{
"code": null,
"e": 5030,
"s": 4993,
"text": "Further Read: Proxy Method in Python"
},
{
"code": null,
"e": 5325,
"s": 5030,
"text": "This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 5450,
"s": 5325,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 5465,
"s": 5450,
"text": "Design Pattern"
}
] |
GATE | GATE-CS-2007 | Question 10
|
19 Nov, 2018
Consider a 4-way set associative cache consisting of 128 lines with a line size of 64 words. The CPU generates a 20-bit address of a word in main memory. The number of bits in the TAG, LINE and WORD fields arerespectively:
(A) 9,6,5(B) 7, 7, 6(C) 7, 5, 8(D) 9, 5, 6Answer: (D)Explanation:
Here the number of sets = 128/4 = 32 (as it is 4 say set associative)
We have total 64 words then we need 6 bits to identify the word
So the line offset is 5 bits and the word offset is 6 bits
and the TAG = 20-(5+6) =9 bits
so it should be 9,5,6
Quiz of this Question
beherasarthak75
GATE-CS-2007
GATE-GATE-CS-2007
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Nov, 2018"
},
{
"code": null,
"e": 251,
"s": 28,
"text": "Consider a 4-way set associative cache consisting of 128 lines with a line size of 64 words. The CPU generates a 20-bit address of a word in main memory. The number of bits in the TAG, LINE and WORD fields arerespectively:"
},
{
"code": null,
"e": 317,
"s": 251,
"text": "(A) 9,6,5(B) 7, 7, 6(C) 7, 5, 8(D) 9, 5, 6Answer: (D)Explanation:"
},
{
"code": null,
"e": 567,
"s": 317,
"text": "Here the number of sets = 128/4 = 32 (as it is 4 say set associative)\n\nWe have total 64 words then we need 6 bits to identify the word\n\nSo the line offset is 5 bits and the word offset is 6 bits\n\nand the TAG = 20-(5+6) =9 bits\n\nso it should be 9,5,6"
},
{
"code": null,
"e": 589,
"s": 567,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 605,
"s": 589,
"text": "beherasarthak75"
},
{
"code": null,
"e": 618,
"s": 605,
"text": "GATE-CS-2007"
},
{
"code": null,
"e": 636,
"s": 618,
"text": "GATE-GATE-CS-2007"
},
{
"code": null,
"e": 641,
"s": 636,
"text": "GATE"
}
] |
Theming of Material Design EditText in Android with Example
|
05 Nov, 2020
Prerequisite: Material Design EditText in Android with Examples
In the previous article Material Design EditText in Android with Examples Material design Text Fields offers more customization and makes the user experience better than the normal text fields. For example, Icon to clear the entire EditText field, helper text, etc. In this article, itβs been discussed how we can customize Material design edit text fields. Have a look at the following image to get an idea of how Material design EditTexts can themed.
Note: Now in this article we will only customize the Material design EditText and about implementation refer to the prerequisite article above. The Material design EditText comes under the Small Components.
Working with the activity_main.xml file
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="64dp" android:text="Material Design Filled EditText" /> <!--this is the material design filled EditText with helper text--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/filled_edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:hint="Enter Something" app:helperText="Enter in text format only"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" /> </com.google.android.material.textfield.TextInputLayout> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="64dp" android:text="Material Design Outlined EditText" /> <!--this is the material design outlined EditText with helper text--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/outline_edit_text" style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:hint="Enter Something" app:helperText="Enter in text format only"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" /> </com.google.android.material.textfield.TextInputLayout> </LinearLayout>
As we have seen there are three types shaping the Material design components in the article Introduction to Material Design in Android. Those are Triangle edge, Cut corner, and Rounded corner.
Working with the styles.xml. Invoke the following code to customize the MDC EditText. Comments are added inside the code for better understanding.
XML
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <!--this changes the filled colour of the MDC Filled EditText--> <!--this also changes the color of the hint font and helper text too--> <item name="colorOnSurface">@color/colorPrimaryDark</item> <!--this customizes the hint font of the EditText--> <item name="textAppearanceSubtitle1">@style/TextAppearance.App.Subtitle1</item> <!--this changes the helper text font--> <item name="textAppearanceCaption">@style/TextAppearance.App.Caption</item> <!--this is to change the shape of the MDC EditText--> <item name="shapeAppearanceSmallComponent">@style/ShapeAppearance.App.SmallComponent</item> </style> <style name="TextAppearance.App.Subtitle1" parent="TextAppearance.MaterialComponents.Subtitle1"> <!--this changes the font face of the hint text--> <item name="fontFamily">sans-serif-condensed</item> <item name="android:fontFamily">sans-serif-condensed</item> </style> <style name="TextAppearance.App.Caption" parent="TextAppearance.MaterialComponents.Caption"> <!--this changes the font face of the helper text--> <item name="fontFamily">sans-serif-black</item> <item name="android:fontFamily">sans-serif-black</item> </style> <style name="ShapeAppearance.App.SmallComponent" parent="ShapeAppearance.MaterialComponents.SmallComponent"> <!--this makes the 10 dp of cut corners of the MDC EditText--> <item name="cornerFamily">cut</item> <item name="cornerSize">10dp</item> </style> </resources>
There are more attributes to set the radius for particular corners.
boxCornerRadiusTopStartboxCornerRadiusTopEnd
boxCornerRadiusBottomStartboxCornerRadiusBottomEnd
Following code and output is an example of the same. The code needs to be invoked inside styles.xml.
XML
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <!--this changes the filled colour of the MDC Filled EditText--> <!--this also changes the color of the hint font and helper text too--> <item name="colorOnSurface">@color/colorPrimaryDark</item> <!--this customizes the hint font of the EditText--> <item name="textAppearanceSubtitle1">@style/TextAppearance.App.Subtitle1</item> <!--this changes the helper text font--> <item name="textAppearanceCaption">@style/TextAppearance.App.Caption</item> <!--this is to change the shape of the MDC EditText--> <item name="shapeAppearanceSmallComponent">@style/ShapeAppearance.App.SmallComponent</item> </style> <style name="TextAppearance.App.Subtitle1" parent="TextAppearance.MaterialComponents.Subtitle1"> <!--this changes the font face of the hint text--> <item name="fontFamily">sans-serif-condensed</item> <item name="android:fontFamily">sans-serif-condensed</item> </style> <style name="TextAppearance.App.Caption" parent="TextAppearance.MaterialComponents.Caption"> <!--this changes the font face of the helper text--> <item name="fontFamily">sans-serif-black</item> <item name="android:fontFamily">sans-serif-black</item> </style> <style name="ShapeAppearance.App.SmallComponent" parent="ShapeAppearance.MaterialComponents.SmallComponent"> <!--this makes the 10 dp of cut corners of the MDC EditText--> <item name="cornerFamily">rounded</item> <!--this attribute makes changes to the Bottom Right corner of the EditText according to the value--> <item name="cornerSizeBottomRight">24dp</item> <!--this attribute makes changes to the Top Left corner of the EditText according to the value--> <item name="cornerSizeTopLeft">24dp</item> </style> </resources>
android
Technical Scripter 2020
Android
Technical Scripter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Nov, 2020"
},
{
"code": null,
"e": 92,
"s": 28,
"text": "Prerequisite: Material Design EditText in Android with Examples"
},
{
"code": null,
"e": 545,
"s": 92,
"text": "In the previous article Material Design EditText in Android with Examples Material design Text Fields offers more customization and makes the user experience better than the normal text fields. For example, Icon to clear the entire EditText field, helper text, etc. In this article, itβs been discussed how we can customize Material design edit text fields. Have a look at the following image to get an idea of how Material design EditTexts can themed."
},
{
"code": null,
"e": 752,
"s": 545,
"text": "Note: Now in this article we will only customize the Material design EditText and about implementation refer to the prerequisite article above. The Material design EditText comes under the Small Components."
},
{
"code": null,
"e": 792,
"s": 752,
"text": "Working with the activity_main.xml file"
},
{
"code": null,
"e": 796,
"s": 792,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"64dp\" android:text=\"Material Design Filled EditText\" /> <!--this is the material design filled EditText with helper text--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/filled_edit_text\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:hint=\"Enter Something\" app:helperText=\"Enter in text format only\"> <com.google.android.material.textfield.TextInputEditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" /> </com.google.android.material.textfield.TextInputLayout> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"64dp\" android:text=\"Material Design Outlined EditText\" /> <!--this is the material design outlined EditText with helper text--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/outline_edit_text\" style=\"@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:hint=\"Enter Something\" app:helperText=\"Enter in text format only\"> <com.google.android.material.textfield.TextInputEditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" /> </com.google.android.material.textfield.TextInputLayout> </LinearLayout>",
"e": 3159,
"s": 796,
"text": null
},
{
"code": null,
"e": 3352,
"s": 3159,
"text": "As we have seen there are three types shaping the Material design components in the article Introduction to Material Design in Android. Those are Triangle edge, Cut corner, and Rounded corner."
},
{
"code": null,
"e": 3499,
"s": 3352,
"text": "Working with the styles.xml. Invoke the following code to customize the MDC EditText. Comments are added inside the code for better understanding."
},
{
"code": null,
"e": 3503,
"s": 3499,
"text": "XML"
},
{
"code": "<resources> <!-- Base application theme. --> <style name=\"AppTheme\" parent=\"Theme.MaterialComponents.Light.DarkActionBar\"> <!-- Customize your theme here. --> <item name=\"colorPrimary\">@color/colorPrimary</item> <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item> <item name=\"colorAccent\">@color/colorAccent</item> <!--this changes the filled colour of the MDC Filled EditText--> <!--this also changes the color of the hint font and helper text too--> <item name=\"colorOnSurface\">@color/colorPrimaryDark</item> <!--this customizes the hint font of the EditText--> <item name=\"textAppearanceSubtitle1\">@style/TextAppearance.App.Subtitle1</item> <!--this changes the helper text font--> <item name=\"textAppearanceCaption\">@style/TextAppearance.App.Caption</item> <!--this is to change the shape of the MDC EditText--> <item name=\"shapeAppearanceSmallComponent\">@style/ShapeAppearance.App.SmallComponent</item> </style> <style name=\"TextAppearance.App.Subtitle1\" parent=\"TextAppearance.MaterialComponents.Subtitle1\"> <!--this changes the font face of the hint text--> <item name=\"fontFamily\">sans-serif-condensed</item> <item name=\"android:fontFamily\">sans-serif-condensed</item> </style> <style name=\"TextAppearance.App.Caption\" parent=\"TextAppearance.MaterialComponents.Caption\"> <!--this changes the font face of the helper text--> <item name=\"fontFamily\">sans-serif-black</item> <item name=\"android:fontFamily\">sans-serif-black</item> </style> <style name=\"ShapeAppearance.App.SmallComponent\" parent=\"ShapeAppearance.MaterialComponents.SmallComponent\"> <!--this makes the 10 dp of cut corners of the MDC EditText--> <item name=\"cornerFamily\">cut</item> <item name=\"cornerSize\">10dp</item> </style> </resources>",
"e": 5424,
"s": 3503,
"text": null
},
{
"code": null,
"e": 5492,
"s": 5424,
"text": "There are more attributes to set the radius for particular corners."
},
{
"code": null,
"e": 5537,
"s": 5492,
"text": "boxCornerRadiusTopStartboxCornerRadiusTopEnd"
},
{
"code": null,
"e": 5588,
"s": 5537,
"text": "boxCornerRadiusBottomStartboxCornerRadiusBottomEnd"
},
{
"code": null,
"e": 5689,
"s": 5588,
"text": "Following code and output is an example of the same. The code needs to be invoked inside styles.xml."
},
{
"code": null,
"e": 5693,
"s": 5689,
"text": "XML"
},
{
"code": "<resources> <!-- Base application theme. --> <style name=\"AppTheme\" parent=\"Theme.MaterialComponents.Light.DarkActionBar\"> <!-- Customize your theme here. --> <item name=\"colorPrimary\">@color/colorPrimary</item> <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item> <item name=\"colorAccent\">@color/colorAccent</item> <!--this changes the filled colour of the MDC Filled EditText--> <!--this also changes the color of the hint font and helper text too--> <item name=\"colorOnSurface\">@color/colorPrimaryDark</item> <!--this customizes the hint font of the EditText--> <item name=\"textAppearanceSubtitle1\">@style/TextAppearance.App.Subtitle1</item> <!--this changes the helper text font--> <item name=\"textAppearanceCaption\">@style/TextAppearance.App.Caption</item> <!--this is to change the shape of the MDC EditText--> <item name=\"shapeAppearanceSmallComponent\">@style/ShapeAppearance.App.SmallComponent</item> </style> <style name=\"TextAppearance.App.Subtitle1\" parent=\"TextAppearance.MaterialComponents.Subtitle1\"> <!--this changes the font face of the hint text--> <item name=\"fontFamily\">sans-serif-condensed</item> <item name=\"android:fontFamily\">sans-serif-condensed</item> </style> <style name=\"TextAppearance.App.Caption\" parent=\"TextAppearance.MaterialComponents.Caption\"> <!--this changes the font face of the helper text--> <item name=\"fontFamily\">sans-serif-black</item> <item name=\"android:fontFamily\">sans-serif-black</item> </style> <style name=\"ShapeAppearance.App.SmallComponent\" parent=\"ShapeAppearance.MaterialComponents.SmallComponent\"> <!--this makes the 10 dp of cut corners of the MDC EditText--> <item name=\"cornerFamily\">rounded</item> <!--this attribute makes changes to the Bottom Right corner of the EditText according to the value--> <item name=\"cornerSizeBottomRight\">24dp</item> <!--this attribute makes changes to the Top Left corner of the EditText according to the value--> <item name=\"cornerSizeTopLeft\">24dp</item> </style> </resources>",
"e": 7897,
"s": 5693,
"text": null
},
{
"code": null,
"e": 7905,
"s": 7897,
"text": "android"
},
{
"code": null,
"e": 7929,
"s": 7905,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 7937,
"s": 7929,
"text": "Android"
},
{
"code": null,
"e": 7956,
"s": 7937,
"text": "Technical Scripter"
},
{
"code": null,
"e": 7964,
"s": 7956,
"text": "Android"
}
] |
Python Program for Counting Sort
|
22 Jun, 2022
Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then do some arithmetic to calculate the position of each object in the output sequence.
Python3
# Python program for counting sort # The main function that sort the given string arr[] in# alphabetical orderdef countSort(arr): # The output character array that will have sorted arr output = [0 for i in range(256)] # Create a count array to store count of individual # characters and initialize count array as 0 count = [0 for i in range(256)] # For storing the resulting answer since the # string is immutable ans = ["" for _ in arr] # Store count of each character for i in arr: count[ord(i)] += 1 # Change count[i] so that count[i] now contains actual # position of this character in output array for i in range(256): count[i] += count[i-1] # Build the output character array for i in range(len(arr)): output[count[ord(arr[i])]-1] = arr[i] count[ord(arr[i])] -= 1 # Copy the output array to arr, so that arr now # contains sorted characters for i in range(len(arr)): ans[i] = output[i] return ans # Driver program to test above functionarr = "geeksforgeeks"ans = countSort(arr)print ("Sorted character array is %s" %("".join(ans))) # This code is contributed by Nikhil Kumar Singh
Output:
Sorted character array is eeeefggkkorss
Time Complexity: O(n)
Space Complexity: O(n)
Please refer complete article on Counting Sort for more details!
surindertarika1234
amartyaghoshgfg
harshmaster07705
python sorting-exercises
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 309,
"s": 52,
"text": "Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then do some arithmetic to calculate the position of each object in the output sequence. "
},
{
"code": null,
"e": 317,
"s": 309,
"text": "Python3"
},
{
"code": "# Python program for counting sort # The main function that sort the given string arr[] in# alphabetical orderdef countSort(arr): # The output character array that will have sorted arr output = [0 for i in range(256)] # Create a count array to store count of individual # characters and initialize count array as 0 count = [0 for i in range(256)] # For storing the resulting answer since the # string is immutable ans = [\"\" for _ in arr] # Store count of each character for i in arr: count[ord(i)] += 1 # Change count[i] so that count[i] now contains actual # position of this character in output array for i in range(256): count[i] += count[i-1] # Build the output character array for i in range(len(arr)): output[count[ord(arr[i])]-1] = arr[i] count[ord(arr[i])] -= 1 # Copy the output array to arr, so that arr now # contains sorted characters for i in range(len(arr)): ans[i] = output[i] return ans # Driver program to test above functionarr = \"geeksforgeeks\"ans = countSort(arr)print (\"Sorted character array is %s\" %(\"\".join(ans))) # This code is contributed by Nikhil Kumar Singh",
"e": 1504,
"s": 317,
"text": null
},
{
"code": null,
"e": 1514,
"s": 1504,
"text": "Output: "
},
{
"code": null,
"e": 1554,
"s": 1514,
"text": "Sorted character array is eeeefggkkorss"
},
{
"code": null,
"e": 1576,
"s": 1554,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 1599,
"s": 1576,
"text": "Space Complexity: O(n)"
},
{
"code": null,
"e": 1665,
"s": 1599,
"text": "Please refer complete article on Counting Sort for more details! "
},
{
"code": null,
"e": 1684,
"s": 1665,
"text": "surindertarika1234"
},
{
"code": null,
"e": 1700,
"s": 1684,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 1717,
"s": 1700,
"text": "harshmaster07705"
},
{
"code": null,
"e": 1742,
"s": 1717,
"text": "python sorting-exercises"
},
{
"code": null,
"e": 1758,
"s": 1742,
"text": "Python Programs"
}
] |
GATE | GATE CS 2011 | Question 65
|
28 Jun, 2021
Consider a relational table with a single record for each registered student with the following attributes.
1. Registration_Num: Unique registration number
of each registered student
2. UID: Unique identity number, unique at the
national level for each citizen
3. BankAccount_Num: Unique account number at
the bank. A student can have multiple accounts
or join accounts. This attribute stores the
primary account number.
4. Name: Name of the student
5. Hostel_Room: Room number of the hostel
Which one of the following option is INCORRECT?(A) BankAccount_Num is candidate key(B) Registration_Num can be a primary key(C) UID is candidate key if all students are from the same country(D) If S is a superkey such that Sβ©UID is NULL then SβͺUID is also a superkeyAnswer: (A)Explanation: A Candidate Key value must uniquely identify the corresponding row in table. BankAccount_Number is not a candidate key. As per the question βA student can have multiple accounts or joint accounts. This attributes stores the primary account numberβ. If two students have a joint account and if the joint account is their primary account, then BankAccount_Number value cannot uniquely identify a row.Quiz of this Question
GATE-CS-2011
GATE-GATE CS 2011
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 136,
"s": 28,
"text": "Consider a relational table with a single record for each registered student with the following attributes."
},
{
"code": null,
"e": 538,
"s": 136,
"text": "1. Registration_Num: Unique registration number\n of each registered student\n2. UID: Unique identity number, unique at the \n national level for each citizen\n3. BankAccount_Num: Unique account number at\n the bank. A student can have multiple accounts\n or join accounts. This attribute stores the \n primary account number.\n4. Name: Name of the student\n5. Hostel_Room: Room number of the hostel "
},
{
"code": null,
"e": 1248,
"s": 538,
"text": "Which one of the following option is INCORRECT?(A) BankAccount_Num is candidate key(B) Registration_Num can be a primary key(C) UID is candidate key if all students are from the same country(D) If S is a superkey such that Sβ©UID is NULL then SβͺUID is also a superkeyAnswer: (A)Explanation: A Candidate Key value must uniquely identify the corresponding row in table. BankAccount_Number is not a candidate key. As per the question βA student can have multiple accounts or joint accounts. This attributes stores the primary account numberβ. If two students have a joint account and if the joint account is their primary account, then BankAccount_Number value cannot uniquely identify a row.Quiz of this Question"
},
{
"code": null,
"e": 1261,
"s": 1248,
"text": "GATE-CS-2011"
},
{
"code": null,
"e": 1279,
"s": 1261,
"text": "GATE-GATE CS 2011"
},
{
"code": null,
"e": 1284,
"s": 1279,
"text": "GATE"
}
] |
Semaphores in Process Synchronization
|
17 Jun, 2022
Semaphore was proposed by Dijkstra in 1965 which is a very significant technique to manage concurrent processes by using a simple integer value, which is known as a semaphore. Semaphore is simply an integer variable that is shared between threads. This variable is used to solve the critical section problem and to achieve process synchronization in the multiprocessing environment. Semaphores are of two types:
Binary Semaphore β This is also known as mutex lock. It can have only two values β 0 and 1. Its value is initialized to 1. It is used to implement the solution of critical section problems with multiple processes.Counting Semaphore β Its value can range over an unrestricted domain. It is used to control access to a resource that has multiple instances.
Binary Semaphore β This is also known as mutex lock. It can have only two values β 0 and 1. Its value is initialized to 1. It is used to implement the solution of critical section problems with multiple processes.
Counting Semaphore β Its value can range over an unrestricted domain. It is used to control access to a resource that has multiple instances.
Now let us see how it does so.
First, look at two operations that can be used to access and change the value of the semaphore variable.
Some point regarding P and V operation :
P operation is also called wait, sleep, or down operation, and V operation is also called signal, wake-up, or up operation.Both operations are atomic and semaphore(s) is always initialized to one. Here atomic means that variable on which read, modify and update happens at the same time/moment with no pre-emption i.e. in-between read, modify and update no other operation is performed that may change the variable.A critical section is surrounded by both operations to implement process synchronization. See the below image. The critical section of Process P is in between P and V operation.
P operation is also called wait, sleep, or down operation, and V operation is also called signal, wake-up, or up operation.
Both operations are atomic and semaphore(s) is always initialized to one. Here atomic means that variable on which read, modify and update happens at the same time/moment with no pre-emption i.e. in-between read, modify and update no other operation is performed that may change the variable.
A critical section is surrounded by both operations to implement process synchronization. See the below image. The critical section of Process P is in between P and V operation.
Now, let us see how it implements mutual exclusion. Let there be two processes P1 and P2 and a semaphore s is initialized as 1. Now if suppose P1 enters in its critical section then the value of semaphore s becomes 0. Now if P2 wants to enter its critical section then it will wait until s > 0, this can only happen when P1 finishes its critical section and calls V operation on semaphore s.
This way mutual exclusion is achieved. Look at the below image for details which is Binary semaphore.
Implementation of binary semaphores :
C++
struct semaphore { enum value(0, 1); // q contains all Process Control Blocks (PCBs) // corresponding to processes got blocked // while performing down operation. Queue<process> q; } P(semaphore s){ if (s.value == 1) { s.value = 0; } else { // add the process to the waiting queue q.push(P) sleep(); }}V(Semaphore s){ if (s.q is empty) { s.value = 1; } else { // select a process from waiting queue Process p=q.front(); // remove the process from wating as it has been sent for CS q.pop(); wakeup(p); }}
The description above is for binary semaphore which can take only two values 0 and 1 and ensure mutual exclusion. There is one other type of semaphore called counting semaphore which can take values greater than one.
Now suppose there is a resource whose number of instances is 4. Now we initialize S = 4 and the rest is the same as for binary semaphore. Whenever the process wants that resource it calls P or waits for function and when it is done it calls V or signal function. If the value of S becomes zero then a process has to wait until S becomes positive. For example, Suppose there are 4 processes P1, P2, P3, P4, and they all call wait operation on S(initialized with 4). If another process P5 wants the resource then it should wait until one of the four processes calls the signal function and the value of semaphore becomes positive.
Limitations :
One of the biggest limitations of semaphore is priority inversion.Deadlock, suppose a process is trying to wake up another process which is not in a sleep state. Therefore, a deadlock may block indefinitely.The operating system has to keep track of all calls to wait and to signal the semaphore.
One of the biggest limitations of semaphore is priority inversion.
Deadlock, suppose a process is trying to wake up another process which is not in a sleep state. Therefore, a deadlock may block indefinitely.
The operating system has to keep track of all calls to wait and to signal the semaphore.
Problem in this implementation of semaphore :The main problem with semaphores is that they require busy waiting, If a process is in the critical section, then other processes trying to enter critical section will be waiting until the critical section is not occupied by any process.Whenever any process waits then it continuously checks for semaphore value (look at this line while (s==0); in P operation) and waste CPU cycle.
There is also a chance of βspinlockβ as the processes keep on spins while waiting for the lock.
To avoid this another implementation is provided below.
Implementation of counting semaphore :
CPP
struct Semaphore { int value; // q contains all Process Control Blocks(PCBs) // corresponding to processes got blocked // while performing down operation. Queue<process> q; } P(Semaphore s){ s.value = s.value - 1; if (s.value < 0) { // add process to queue // here p is a process which is currently executing q.push(p); block(); } else return;} V(Semaphore s){ s.value = s.value + 1; if (s.value >= 0) { // remove process p from queue Process p=q.pop(); wakeup(p); } else return;}
In this implementation whenever the process waits it is added to a waiting queue of processes associated with that semaphore. This is done through system call block() on that process. When a process is completed it calls the signal function and one process in the queue is resumed. It uses wakeup() system call.
Sam_Sparrow
HarshalChavan
Hasanul Islam
soumya7
tushargupta09
ap173777
secret_giggle
abhishekpal97854368
ankithreddy2001
bengerisanjeev
phoniex
ganeshdhumal2020
geeky01adarsh
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Jun, 2022"
},
{
"code": null,
"e": 464,
"s": 52,
"text": "Semaphore was proposed by Dijkstra in 1965 which is a very significant technique to manage concurrent processes by using a simple integer value, which is known as a semaphore. Semaphore is simply an integer variable that is shared between threads. This variable is used to solve the critical section problem and to achieve process synchronization in the multiprocessing environment. Semaphores are of two types:"
},
{
"code": null,
"e": 819,
"s": 464,
"text": "Binary Semaphore β This is also known as mutex lock. It can have only two values β 0 and 1. Its value is initialized to 1. It is used to implement the solution of critical section problems with multiple processes.Counting Semaphore β Its value can range over an unrestricted domain. It is used to control access to a resource that has multiple instances."
},
{
"code": null,
"e": 1033,
"s": 819,
"text": "Binary Semaphore β This is also known as mutex lock. It can have only two values β 0 and 1. Its value is initialized to 1. It is used to implement the solution of critical section problems with multiple processes."
},
{
"code": null,
"e": 1175,
"s": 1033,
"text": "Counting Semaphore β Its value can range over an unrestricted domain. It is used to control access to a resource that has multiple instances."
},
{
"code": null,
"e": 1206,
"s": 1175,
"text": "Now let us see how it does so."
},
{
"code": null,
"e": 1312,
"s": 1206,
"text": "First, look at two operations that can be used to access and change the value of the semaphore variable. "
},
{
"code": null,
"e": 1353,
"s": 1312,
"text": "Some point regarding P and V operation :"
},
{
"code": null,
"e": 1947,
"s": 1353,
"text": "P operation is also called wait, sleep, or down operation, and V operation is also called signal, wake-up, or up operation.Both operations are atomic and semaphore(s) is always initialized to one. Here atomic means that variable on which read, modify and update happens at the same time/moment with no pre-emption i.e. in-between read, modify and update no other operation is performed that may change the variable.A critical section is surrounded by both operations to implement process synchronization. See the below image. The critical section of Process P is in between P and V operation. "
},
{
"code": null,
"e": 2071,
"s": 1947,
"text": "P operation is also called wait, sleep, or down operation, and V operation is also called signal, wake-up, or up operation."
},
{
"code": null,
"e": 2364,
"s": 2071,
"text": "Both operations are atomic and semaphore(s) is always initialized to one. Here atomic means that variable on which read, modify and update happens at the same time/moment with no pre-emption i.e. in-between read, modify and update no other operation is performed that may change the variable."
},
{
"code": null,
"e": 2543,
"s": 2364,
"text": "A critical section is surrounded by both operations to implement process synchronization. See the below image. The critical section of Process P is in between P and V operation. "
},
{
"code": null,
"e": 2936,
"s": 2543,
"text": "Now, let us see how it implements mutual exclusion. Let there be two processes P1 and P2 and a semaphore s is initialized as 1. Now if suppose P1 enters in its critical section then the value of semaphore s becomes 0. Now if P2 wants to enter its critical section then it will wait until s > 0, this can only happen when P1 finishes its critical section and calls V operation on semaphore s. "
},
{
"code": null,
"e": 3039,
"s": 2936,
"text": "This way mutual exclusion is achieved. Look at the below image for details which is Binary semaphore. "
},
{
"code": null,
"e": 3077,
"s": 3039,
"text": "Implementation of binary semaphores :"
},
{
"code": null,
"e": 3081,
"s": 3077,
"text": "C++"
},
{
"code": "struct semaphore { enum value(0, 1); // q contains all Process Control Blocks (PCBs) // corresponding to processes got blocked // while performing down operation. Queue<process> q; } P(semaphore s){ if (s.value == 1) { s.value = 0; } else { // add the process to the waiting queue q.push(P) sleep(); }}V(Semaphore s){ if (s.q is empty) { s.value = 1; } else { // select a process from waiting queue Process p=q.front(); // remove the process from wating as it has been sent for CS q.pop(); wakeup(p); }}",
"e": 3718,
"s": 3081,
"text": null
},
{
"code": null,
"e": 3935,
"s": 3718,
"text": "The description above is for binary semaphore which can take only two values 0 and 1 and ensure mutual exclusion. There is one other type of semaphore called counting semaphore which can take values greater than one."
},
{
"code": null,
"e": 4564,
"s": 3935,
"text": "Now suppose there is a resource whose number of instances is 4. Now we initialize S = 4 and the rest is the same as for binary semaphore. Whenever the process wants that resource it calls P or waits for function and when it is done it calls V or signal function. If the value of S becomes zero then a process has to wait until S becomes positive. For example, Suppose there are 4 processes P1, P2, P3, P4, and they all call wait operation on S(initialized with 4). If another process P5 wants the resource then it should wait until one of the four processes calls the signal function and the value of semaphore becomes positive."
},
{
"code": null,
"e": 4578,
"s": 4564,
"text": "Limitations :"
},
{
"code": null,
"e": 4874,
"s": 4578,
"text": "One of the biggest limitations of semaphore is priority inversion.Deadlock, suppose a process is trying to wake up another process which is not in a sleep state. Therefore, a deadlock may block indefinitely.The operating system has to keep track of all calls to wait and to signal the semaphore."
},
{
"code": null,
"e": 4941,
"s": 4874,
"text": "One of the biggest limitations of semaphore is priority inversion."
},
{
"code": null,
"e": 5083,
"s": 4941,
"text": "Deadlock, suppose a process is trying to wake up another process which is not in a sleep state. Therefore, a deadlock may block indefinitely."
},
{
"code": null,
"e": 5172,
"s": 5083,
"text": "The operating system has to keep track of all calls to wait and to signal the semaphore."
},
{
"code": null,
"e": 5599,
"s": 5172,
"text": "Problem in this implementation of semaphore :The main problem with semaphores is that they require busy waiting, If a process is in the critical section, then other processes trying to enter critical section will be waiting until the critical section is not occupied by any process.Whenever any process waits then it continuously checks for semaphore value (look at this line while (s==0); in P operation) and waste CPU cycle."
},
{
"code": null,
"e": 5695,
"s": 5599,
"text": "There is also a chance of βspinlockβ as the processes keep on spins while waiting for the lock."
},
{
"code": null,
"e": 5752,
"s": 5695,
"text": " To avoid this another implementation is provided below."
},
{
"code": null,
"e": 5792,
"s": 5752,
"text": "Implementation of counting semaphore : "
},
{
"code": null,
"e": 5796,
"s": 5792,
"text": "CPP"
},
{
"code": "struct Semaphore { int value; // q contains all Process Control Blocks(PCBs) // corresponding to processes got blocked // while performing down operation. Queue<process> q; } P(Semaphore s){ s.value = s.value - 1; if (s.value < 0) { // add process to queue // here p is a process which is currently executing q.push(p); block(); } else return;} V(Semaphore s){ s.value = s.value + 1; if (s.value >= 0) { // remove process p from queue Process p=q.pop(); wakeup(p); } else return;}",
"e": 6382,
"s": 5796,
"text": null
},
{
"code": null,
"e": 6694,
"s": 6382,
"text": "In this implementation whenever the process waits it is added to a waiting queue of processes associated with that semaphore. This is done through system call block() on that process. When a process is completed it calls the signal function and one process in the queue is resumed. It uses wakeup() system call."
},
{
"code": null,
"e": 6706,
"s": 6694,
"text": "Sam_Sparrow"
},
{
"code": null,
"e": 6720,
"s": 6706,
"text": "HarshalChavan"
},
{
"code": null,
"e": 6734,
"s": 6720,
"text": "Hasanul Islam"
},
{
"code": null,
"e": 6742,
"s": 6734,
"text": "soumya7"
},
{
"code": null,
"e": 6756,
"s": 6742,
"text": "tushargupta09"
},
{
"code": null,
"e": 6765,
"s": 6756,
"text": "ap173777"
},
{
"code": null,
"e": 6779,
"s": 6765,
"text": "secret_giggle"
},
{
"code": null,
"e": 6799,
"s": 6779,
"text": "abhishekpal97854368"
},
{
"code": null,
"e": 6815,
"s": 6799,
"text": "ankithreddy2001"
},
{
"code": null,
"e": 6830,
"s": 6815,
"text": "bengerisanjeev"
},
{
"code": null,
"e": 6838,
"s": 6830,
"text": "phoniex"
},
{
"code": null,
"e": 6855,
"s": 6838,
"text": "ganeshdhumal2020"
},
{
"code": null,
"e": 6869,
"s": 6855,
"text": "geeky01adarsh"
},
{
"code": null,
"e": 6877,
"s": 6869,
"text": "GATE CS"
},
{
"code": null,
"e": 6895,
"s": 6877,
"text": "Operating Systems"
},
{
"code": null,
"e": 6913,
"s": 6895,
"text": "Operating Systems"
}
] |
Split a comma delimited string into an array in PHP
|
31 Jul, 2021
Given a long string separated with comma delimiter. The task is to split the given string with comma delimiter and store the result in an array.
Examples:
Input : geeks,for,geeks
Output : Array ( [0] => geeks [1] => for [2] => geeks )
Input : practice, code
Output : Array ( [0] => practice [1] => code )
Use explode() or preg_split() function to split the string in php with given delimiter.
PHP | explode() Function: The explode() function is an inbuilt function in PHP which is used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.Syntax:
array explode( separator, OriginalString, NoOfElements )
PHP | preg_split() Function: The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
Syntax:
array preg_split( string $pattern, string
$subject [, int $limit = -1 [, int $flags = 0 ]] )
Example:
<?php // Use preg_split() function$string = "123,456,78,000"; $str_arr = preg_split ("/\,/", $string); print_r($str_arr); // use of explode$string = "123,46,78,000";$str_arr = explode (",", $string); print_r($str_arr);?>
Array
(
[0] => 123
[1] => 456
[2] => 78
[3] => 000
)
Array
(
[0] => 123
[1] => 46
[2] => 78
[3] => 000
)
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 Jul, 2021"
},
{
"code": null,
"e": 197,
"s": 52,
"text": "Given a long string separated with comma delimiter. The task is to split the given string with comma delimiter and store the result in an array."
},
{
"code": null,
"e": 207,
"s": 197,
"text": "Examples:"
},
{
"code": null,
"e": 359,
"s": 207,
"text": "Input : geeks,for,geeks\nOutput : Array ( [0] => geeks [1] => for [2] => geeks )\n\nInput : practice, code\nOutput : Array ( [0] => practice [1] => code )\n"
},
{
"code": null,
"e": 447,
"s": 359,
"text": "Use explode() or preg_split() function to split the string in php with given delimiter."
},
{
"code": null,
"e": 818,
"s": 447,
"text": "PHP | explode() Function: The explode() function is an inbuilt function in PHP which is used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.Syntax:"
},
{
"code": null,
"e": 875,
"s": 818,
"text": "array explode( separator, OriginalString, NoOfElements )"
},
{
"code": null,
"e": 1039,
"s": 875,
"text": "PHP | preg_split() Function: The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern."
},
{
"code": null,
"e": 1047,
"s": 1039,
"text": "Syntax:"
},
{
"code": null,
"e": 1141,
"s": 1047,
"text": "array preg_split( string $pattern, string \n$subject [, int $limit = -1 [, int $flags = 0 ]] )"
},
{
"code": null,
"e": 1150,
"s": 1141,
"text": "Example:"
},
{
"code": "<?php // Use preg_split() function$string = \"123,456,78,000\"; $str_arr = preg_split (\"/\\,/\", $string); print_r($str_arr); // use of explode$string = \"123,46,78,000\";$str_arr = explode (\",\", $string); print_r($str_arr);?>",
"e": 1377,
"s": 1150,
"text": null
},
{
"code": null,
"e": 1515,
"s": 1377,
"text": "Array\n(\n [0] => 123\n [1] => 456\n [2] => 78\n [3] => 000\n)\nArray\n(\n [0] => 123\n [1] => 46\n [2] => 78\n [3] => 000\n)\n"
},
{
"code": null,
"e": 1684,
"s": 1515,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 1688,
"s": 1684,
"text": "PHP"
},
{
"code": null,
"e": 1701,
"s": 1688,
"text": "PHP Programs"
},
{
"code": null,
"e": 1718,
"s": 1701,
"text": "Web Technologies"
},
{
"code": null,
"e": 1722,
"s": 1718,
"text": "PHP"
}
] |
Java AWT | FlowLayout
|
25 Jun, 2018
FlowLayout is used to arrange components in a sequence one after the other. The default layout of applet and panel is FlowLayout.
Constructors :
FlowLayout(): It will Construct a new FlowLayout with centered alignment.The horizontal and vertical gap will be 5 pixels.FlowLayout(int align) : It will Construct a new FlowLayout with given alignment.The horizontal and vertical gap will be 5 pixels.FlowLayout(int align, int HorizontalGap, int VerticalGap ): It will Construct a new FlowLayout with given alignment, the given horizontal and vertical gap between the components.JLabel(String text): It will create a JLabel instance with the specified text.
FlowLayout(): It will Construct a new FlowLayout with centered alignment.The horizontal and vertical gap will be 5 pixels.
FlowLayout(int align) : It will Construct a new FlowLayout with given alignment.The horizontal and vertical gap will be 5 pixels.
FlowLayout(int align, int HorizontalGap, int VerticalGap ): It will Construct a new FlowLayout with given alignment, the given horizontal and vertical gap between the components.
JLabel(String text): It will create a JLabel instance with the specified text.
Commonly used methods:
setTitle(String Text): This Method is used to set Title of JFrame. The title you want to set is passed as a string.getAlignment(): Returns the alignment for this layout.setAlignment(int align): used to set the alignment for this layout.removeLayoutComponent(Component comp): Used to remove the component passed as argument from the layout.
setTitle(String Text): This Method is used to set Title of JFrame. The title you want to set is passed as a string.
getAlignment(): Returns the alignment for this layout.
setAlignment(int align): used to set the alignment for this layout.
removeLayoutComponent(Component comp): Used to remove the component passed as argument from the layout.
Below programs will illustrate the Example of FlowLayout in java.
Program 1: The following program illustrates the use of FlowLayout by arranging several JLabel components in a JFrame, whose instance class is named as βExampleβ. We create 5 JLabel components named βl1β, βl2β²β²... βl5β and then add them to the JFrame by the method this.add(). We set the title and bounds of the frame by method setTitle and setBounds.The layout is set by the method setLayout();// Java program to show Example of FlowLayout.// in java. Importing different Package.import java.awt.*;import java.awt.event.*;import javax.swing.*; class Example extends JFrame { // Declaration of objects of JLabel class. JLabel l1, l2, l3, l4, l5; // Constructor of Example class. public Example() { // Creating Object of "FlowLayout" class FlowLayout layout = new FlowLayout(); // this Keyword refers to current object. // Function to set Layout of JFrame. this.setLayout(layout); // Initialization of object "l1" of JLabel class. l1 = new JLabel("Label 1 "); // Initialization of object "l2" of JLabel class. l2 = new JLabel("Label 2 "); // Initialization of object "l3" of JLabel class. l3 = new JLabel("Label 3 "); // Initialization of object "l4" of JLabel class. l4 = new JLabel("Label 4 "); // Initialization of object "l5" of JLabel class. l5 = new JLabel("Label 5 "); // this Keyword refers to current object. // Adding Jlabel "l1" on JFrame. this.add(l1); // Adding Jlabel "l2" on JFrame. this.add(l2); // Adding Jlabel "l3" on JFrame. this.add(l3); // Adding Jlabel "l4" on JFrame. this.add(l4); // Adding Jlabel "l5" on JFrame. this.add(l5); }} class MainFrame { // Driver code public static void main(String[] args) { // Creating Object of Example class. Example f = new Example(); // Function to set title of JFrame. f.setTitle("Example of FlowLayout"); // Function to set Bounds of JFrame. f.setBounds(200, 100, 600, 400); // Function to set visible status of JFrame. f.setVisible(true); }}Output:We can control the alignment of components in a flow layout arrangement, by using these FlowLayout Fields.1) RIGHT :- Each row of component shifts towards right.2) LEFT :- Each row of component shifts towards left.Program 2: The following program illustrates the use of FlowLayout using Right alignment by passing the argument FlowLayout.RIGHT in the constructor of FLowLayout. We create 5 JLabel components named βl1β, βl2β²β²... βl5β and then add them to the JFrame by the method this.add(). We set the title and bounds of the frame by method setTitle and setBounds.The layout is set by the method setLayout();// Java program to show example of// FlowLayout and using RIGHT alignmentimport java.awt.*;import java.awt.event.*;import javax.swing.*; class Example extends JFrame { // Declaration of objects of JLabel class. JLabel l1, l2, l3, l4, l5; // Constructor of Example class. public Example() { // Creating Object of "FlowLayout" class, passing // RIGHT alignment through constructor. FlowLayout layout = new FlowLayout(FlowLayout.RIGHT); // this Keyword refers to current object. // Function to set Layout of JFrame. this.setLayout(layout); // Initialization of object "l1" of JLabel class. l1 = new JLabel("Label 1 "); // Initialization of object "l2" of JLabel class. l2 = new JLabel("Label 2 "); // Initialization of object "l3" of JLabel class. l3 = new JLabel("Label 3 "); // Initialization of object "l4" of JLabel class. l4 = new JLabel("Label 4 "); // Initialization of object "l5" of JLabel class. l5 = new JLabel("Label 5 "); // this Keyword refers to current object. // Adding Jlabel "l1" on JFrame. this.add(l1); // Adding Jlabel "l2" on JFrame. this.add(l2); // Adding Jlabel "l3" on JFrame. this.add(l3); // Adding Jlabel "l4" on JFrame. this.add(l4); // Adding Jlabel "l5" on JFrame. this.add(l5); }} class MainFrame { // Driver code public static void main(String[] args) { // Creating Object of Example class. Example f = new Example(); // Function to set title of JFrame. f.setTitle("Example of FlowLayout"); // Function to set Bounds of JFrame. f.setBounds(200, 100, 600, 400); // Function to set visible status of JFrame. f.setVisible(true); }}Output:
Program 1: The following program illustrates the use of FlowLayout by arranging several JLabel components in a JFrame, whose instance class is named as βExampleβ. We create 5 JLabel components named βl1β, βl2β²β²... βl5β and then add them to the JFrame by the method this.add(). We set the title and bounds of the frame by method setTitle and setBounds.The layout is set by the method setLayout();// Java program to show Example of FlowLayout.// in java. Importing different Package.import java.awt.*;import java.awt.event.*;import javax.swing.*; class Example extends JFrame { // Declaration of objects of JLabel class. JLabel l1, l2, l3, l4, l5; // Constructor of Example class. public Example() { // Creating Object of "FlowLayout" class FlowLayout layout = new FlowLayout(); // this Keyword refers to current object. // Function to set Layout of JFrame. this.setLayout(layout); // Initialization of object "l1" of JLabel class. l1 = new JLabel("Label 1 "); // Initialization of object "l2" of JLabel class. l2 = new JLabel("Label 2 "); // Initialization of object "l3" of JLabel class. l3 = new JLabel("Label 3 "); // Initialization of object "l4" of JLabel class. l4 = new JLabel("Label 4 "); // Initialization of object "l5" of JLabel class. l5 = new JLabel("Label 5 "); // this Keyword refers to current object. // Adding Jlabel "l1" on JFrame. this.add(l1); // Adding Jlabel "l2" on JFrame. this.add(l2); // Adding Jlabel "l3" on JFrame. this.add(l3); // Adding Jlabel "l4" on JFrame. this.add(l4); // Adding Jlabel "l5" on JFrame. this.add(l5); }} class MainFrame { // Driver code public static void main(String[] args) { // Creating Object of Example class. Example f = new Example(); // Function to set title of JFrame. f.setTitle("Example of FlowLayout"); // Function to set Bounds of JFrame. f.setBounds(200, 100, 600, 400); // Function to set visible status of JFrame. f.setVisible(true); }}Output:We can control the alignment of components in a flow layout arrangement, by using these FlowLayout Fields.1) RIGHT :- Each row of component shifts towards right.2) LEFT :- Each row of component shifts towards left.
// Java program to show Example of FlowLayout.// in java. Importing different Package.import java.awt.*;import java.awt.event.*;import javax.swing.*; class Example extends JFrame { // Declaration of objects of JLabel class. JLabel l1, l2, l3, l4, l5; // Constructor of Example class. public Example() { // Creating Object of "FlowLayout" class FlowLayout layout = new FlowLayout(); // this Keyword refers to current object. // Function to set Layout of JFrame. this.setLayout(layout); // Initialization of object "l1" of JLabel class. l1 = new JLabel("Label 1 "); // Initialization of object "l2" of JLabel class. l2 = new JLabel("Label 2 "); // Initialization of object "l3" of JLabel class. l3 = new JLabel("Label 3 "); // Initialization of object "l4" of JLabel class. l4 = new JLabel("Label 4 "); // Initialization of object "l5" of JLabel class. l5 = new JLabel("Label 5 "); // this Keyword refers to current object. // Adding Jlabel "l1" on JFrame. this.add(l1); // Adding Jlabel "l2" on JFrame. this.add(l2); // Adding Jlabel "l3" on JFrame. this.add(l3); // Adding Jlabel "l4" on JFrame. this.add(l4); // Adding Jlabel "l5" on JFrame. this.add(l5); }} class MainFrame { // Driver code public static void main(String[] args) { // Creating Object of Example class. Example f = new Example(); // Function to set title of JFrame. f.setTitle("Example of FlowLayout"); // Function to set Bounds of JFrame. f.setBounds(200, 100, 600, 400); // Function to set visible status of JFrame. f.setVisible(true); }}
Output:
We can control the alignment of components in a flow layout arrangement, by using these FlowLayout Fields.1) RIGHT :- Each row of component shifts towards right.2) LEFT :- Each row of component shifts towards left.
Program 2: The following program illustrates the use of FlowLayout using Right alignment by passing the argument FlowLayout.RIGHT in the constructor of FLowLayout. We create 5 JLabel components named βl1β, βl2β²β²... βl5β and then add them to the JFrame by the method this.add(). We set the title and bounds of the frame by method setTitle and setBounds.The layout is set by the method setLayout();// Java program to show example of// FlowLayout and using RIGHT alignmentimport java.awt.*;import java.awt.event.*;import javax.swing.*; class Example extends JFrame { // Declaration of objects of JLabel class. JLabel l1, l2, l3, l4, l5; // Constructor of Example class. public Example() { // Creating Object of "FlowLayout" class, passing // RIGHT alignment through constructor. FlowLayout layout = new FlowLayout(FlowLayout.RIGHT); // this Keyword refers to current object. // Function to set Layout of JFrame. this.setLayout(layout); // Initialization of object "l1" of JLabel class. l1 = new JLabel("Label 1 "); // Initialization of object "l2" of JLabel class. l2 = new JLabel("Label 2 "); // Initialization of object "l3" of JLabel class. l3 = new JLabel("Label 3 "); // Initialization of object "l4" of JLabel class. l4 = new JLabel("Label 4 "); // Initialization of object "l5" of JLabel class. l5 = new JLabel("Label 5 "); // this Keyword refers to current object. // Adding Jlabel "l1" on JFrame. this.add(l1); // Adding Jlabel "l2" on JFrame. this.add(l2); // Adding Jlabel "l3" on JFrame. this.add(l3); // Adding Jlabel "l4" on JFrame. this.add(l4); // Adding Jlabel "l5" on JFrame. this.add(l5); }} class MainFrame { // Driver code public static void main(String[] args) { // Creating Object of Example class. Example f = new Example(); // Function to set title of JFrame. f.setTitle("Example of FlowLayout"); // Function to set Bounds of JFrame. f.setBounds(200, 100, 600, 400); // Function to set visible status of JFrame. f.setVisible(true); }}Output:
// Java program to show example of// FlowLayout and using RIGHT alignmentimport java.awt.*;import java.awt.event.*;import javax.swing.*; class Example extends JFrame { // Declaration of objects of JLabel class. JLabel l1, l2, l3, l4, l5; // Constructor of Example class. public Example() { // Creating Object of "FlowLayout" class, passing // RIGHT alignment through constructor. FlowLayout layout = new FlowLayout(FlowLayout.RIGHT); // this Keyword refers to current object. // Function to set Layout of JFrame. this.setLayout(layout); // Initialization of object "l1" of JLabel class. l1 = new JLabel("Label 1 "); // Initialization of object "l2" of JLabel class. l2 = new JLabel("Label 2 "); // Initialization of object "l3" of JLabel class. l3 = new JLabel("Label 3 "); // Initialization of object "l4" of JLabel class. l4 = new JLabel("Label 4 "); // Initialization of object "l5" of JLabel class. l5 = new JLabel("Label 5 "); // this Keyword refers to current object. // Adding Jlabel "l1" on JFrame. this.add(l1); // Adding Jlabel "l2" on JFrame. this.add(l2); // Adding Jlabel "l3" on JFrame. this.add(l3); // Adding Jlabel "l4" on JFrame. this.add(l4); // Adding Jlabel "l5" on JFrame. this.add(l5); }} class MainFrame { // Driver code public static void main(String[] args) { // Creating Object of Example class. Example f = new Example(); // Function to set title of JFrame. f.setTitle("Example of FlowLayout"); // Function to set Bounds of JFrame. f.setBounds(200, 100, 600, 400); // Function to set visible status of JFrame. f.setVisible(true); }}
Output:
Reference: https://www.geeksforgeeks.org/message-dialogs-java-gui/
Java-AWT
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Jun, 2018"
},
{
"code": null,
"e": 158,
"s": 28,
"text": "FlowLayout is used to arrange components in a sequence one after the other. The default layout of applet and panel is FlowLayout."
},
{
"code": null,
"e": 173,
"s": 158,
"text": "Constructors :"
},
{
"code": null,
"e": 681,
"s": 173,
"text": "FlowLayout(): It will Construct a new FlowLayout with centered alignment.The horizontal and vertical gap will be 5 pixels.FlowLayout(int align) : It will Construct a new FlowLayout with given alignment.The horizontal and vertical gap will be 5 pixels.FlowLayout(int align, int HorizontalGap, int VerticalGap ): It will Construct a new FlowLayout with given alignment, the given horizontal and vertical gap between the components.JLabel(String text): It will create a JLabel instance with the specified text."
},
{
"code": null,
"e": 804,
"s": 681,
"text": "FlowLayout(): It will Construct a new FlowLayout with centered alignment.The horizontal and vertical gap will be 5 pixels."
},
{
"code": null,
"e": 934,
"s": 804,
"text": "FlowLayout(int align) : It will Construct a new FlowLayout with given alignment.The horizontal and vertical gap will be 5 pixels."
},
{
"code": null,
"e": 1113,
"s": 934,
"text": "FlowLayout(int align, int HorizontalGap, int VerticalGap ): It will Construct a new FlowLayout with given alignment, the given horizontal and vertical gap between the components."
},
{
"code": null,
"e": 1192,
"s": 1113,
"text": "JLabel(String text): It will create a JLabel instance with the specified text."
},
{
"code": null,
"e": 1215,
"s": 1192,
"text": "Commonly used methods:"
},
{
"code": null,
"e": 1555,
"s": 1215,
"text": "setTitle(String Text): This Method is used to set Title of JFrame. The title you want to set is passed as a string.getAlignment(): Returns the alignment for this layout.setAlignment(int align): used to set the alignment for this layout.removeLayoutComponent(Component comp): Used to remove the component passed as argument from the layout."
},
{
"code": null,
"e": 1671,
"s": 1555,
"text": "setTitle(String Text): This Method is used to set Title of JFrame. The title you want to set is passed as a string."
},
{
"code": null,
"e": 1726,
"s": 1671,
"text": "getAlignment(): Returns the alignment for this layout."
},
{
"code": null,
"e": 1794,
"s": 1726,
"text": "setAlignment(int align): used to set the alignment for this layout."
},
{
"code": null,
"e": 1898,
"s": 1794,
"text": "removeLayoutComponent(Component comp): Used to remove the component passed as argument from the layout."
},
{
"code": null,
"e": 1964,
"s": 1898,
"text": "Below programs will illustrate the Example of FlowLayout in java."
},
{
"code": null,
"e": 6669,
"s": 1964,
"text": "Program 1: The following program illustrates the use of FlowLayout by arranging several JLabel components in a JFrame, whose instance class is named as βExampleβ. We create 5 JLabel components named βl1β, βl2β²β²... βl5β and then add them to the JFrame by the method this.add(). We set the title and bounds of the frame by method setTitle and setBounds.The layout is set by the method setLayout();// Java program to show Example of FlowLayout.// in java. Importing different Package.import java.awt.*;import java.awt.event.*;import javax.swing.*; class Example extends JFrame { // Declaration of objects of JLabel class. JLabel l1, l2, l3, l4, l5; // Constructor of Example class. public Example() { // Creating Object of \"FlowLayout\" class FlowLayout layout = new FlowLayout(); // this Keyword refers to current object. // Function to set Layout of JFrame. this.setLayout(layout); // Initialization of object \"l1\" of JLabel class. l1 = new JLabel(\"Label 1 \"); // Initialization of object \"l2\" of JLabel class. l2 = new JLabel(\"Label 2 \"); // Initialization of object \"l3\" of JLabel class. l3 = new JLabel(\"Label 3 \"); // Initialization of object \"l4\" of JLabel class. l4 = new JLabel(\"Label 4 \"); // Initialization of object \"l5\" of JLabel class. l5 = new JLabel(\"Label 5 \"); // this Keyword refers to current object. // Adding Jlabel \"l1\" on JFrame. this.add(l1); // Adding Jlabel \"l2\" on JFrame. this.add(l2); // Adding Jlabel \"l3\" on JFrame. this.add(l3); // Adding Jlabel \"l4\" on JFrame. this.add(l4); // Adding Jlabel \"l5\" on JFrame. this.add(l5); }} class MainFrame { // Driver code public static void main(String[] args) { // Creating Object of Example class. Example f = new Example(); // Function to set title of JFrame. f.setTitle(\"Example of FlowLayout\"); // Function to set Bounds of JFrame. f.setBounds(200, 100, 600, 400); // Function to set visible status of JFrame. f.setVisible(true); }}Output:We can control the alignment of components in a flow layout arrangement, by using these FlowLayout Fields.1) RIGHT :- Each row of component shifts towards right.2) LEFT :- Each row of component shifts towards left.Program 2: The following program illustrates the use of FlowLayout using Right alignment by passing the argument FlowLayout.RIGHT in the constructor of FLowLayout. We create 5 JLabel components named βl1β, βl2β²β²... βl5β and then add them to the JFrame by the method this.add(). We set the title and bounds of the frame by method setTitle and setBounds.The layout is set by the method setLayout();// Java program to show example of// FlowLayout and using RIGHT alignmentimport java.awt.*;import java.awt.event.*;import javax.swing.*; class Example extends JFrame { // Declaration of objects of JLabel class. JLabel l1, l2, l3, l4, l5; // Constructor of Example class. public Example() { // Creating Object of \"FlowLayout\" class, passing // RIGHT alignment through constructor. FlowLayout layout = new FlowLayout(FlowLayout.RIGHT); // this Keyword refers to current object. // Function to set Layout of JFrame. this.setLayout(layout); // Initialization of object \"l1\" of JLabel class. l1 = new JLabel(\"Label 1 \"); // Initialization of object \"l2\" of JLabel class. l2 = new JLabel(\"Label 2 \"); // Initialization of object \"l3\" of JLabel class. l3 = new JLabel(\"Label 3 \"); // Initialization of object \"l4\" of JLabel class. l4 = new JLabel(\"Label 4 \"); // Initialization of object \"l5\" of JLabel class. l5 = new JLabel(\"Label 5 \"); // this Keyword refers to current object. // Adding Jlabel \"l1\" on JFrame. this.add(l1); // Adding Jlabel \"l2\" on JFrame. this.add(l2); // Adding Jlabel \"l3\" on JFrame. this.add(l3); // Adding Jlabel \"l4\" on JFrame. this.add(l4); // Adding Jlabel \"l5\" on JFrame. this.add(l5); }} class MainFrame { // Driver code public static void main(String[] args) { // Creating Object of Example class. Example f = new Example(); // Function to set title of JFrame. f.setTitle(\"Example of FlowLayout\"); // Function to set Bounds of JFrame. f.setBounds(200, 100, 600, 400); // Function to set visible status of JFrame. f.setVisible(true); }}Output:"
},
{
"code": null,
"e": 9099,
"s": 6669,
"text": "Program 1: The following program illustrates the use of FlowLayout by arranging several JLabel components in a JFrame, whose instance class is named as βExampleβ. We create 5 JLabel components named βl1β, βl2β²β²... βl5β and then add them to the JFrame by the method this.add(). We set the title and bounds of the frame by method setTitle and setBounds.The layout is set by the method setLayout();// Java program to show Example of FlowLayout.// in java. Importing different Package.import java.awt.*;import java.awt.event.*;import javax.swing.*; class Example extends JFrame { // Declaration of objects of JLabel class. JLabel l1, l2, l3, l4, l5; // Constructor of Example class. public Example() { // Creating Object of \"FlowLayout\" class FlowLayout layout = new FlowLayout(); // this Keyword refers to current object. // Function to set Layout of JFrame. this.setLayout(layout); // Initialization of object \"l1\" of JLabel class. l1 = new JLabel(\"Label 1 \"); // Initialization of object \"l2\" of JLabel class. l2 = new JLabel(\"Label 2 \"); // Initialization of object \"l3\" of JLabel class. l3 = new JLabel(\"Label 3 \"); // Initialization of object \"l4\" of JLabel class. l4 = new JLabel(\"Label 4 \"); // Initialization of object \"l5\" of JLabel class. l5 = new JLabel(\"Label 5 \"); // this Keyword refers to current object. // Adding Jlabel \"l1\" on JFrame. this.add(l1); // Adding Jlabel \"l2\" on JFrame. this.add(l2); // Adding Jlabel \"l3\" on JFrame. this.add(l3); // Adding Jlabel \"l4\" on JFrame. this.add(l4); // Adding Jlabel \"l5\" on JFrame. this.add(l5); }} class MainFrame { // Driver code public static void main(String[] args) { // Creating Object of Example class. Example f = new Example(); // Function to set title of JFrame. f.setTitle(\"Example of FlowLayout\"); // Function to set Bounds of JFrame. f.setBounds(200, 100, 600, 400); // Function to set visible status of JFrame. f.setVisible(true); }}Output:We can control the alignment of components in a flow layout arrangement, by using these FlowLayout Fields.1) RIGHT :- Each row of component shifts towards right.2) LEFT :- Each row of component shifts towards left."
},
{
"code": "// Java program to show Example of FlowLayout.// in java. Importing different Package.import java.awt.*;import java.awt.event.*;import javax.swing.*; class Example extends JFrame { // Declaration of objects of JLabel class. JLabel l1, l2, l3, l4, l5; // Constructor of Example class. public Example() { // Creating Object of \"FlowLayout\" class FlowLayout layout = new FlowLayout(); // this Keyword refers to current object. // Function to set Layout of JFrame. this.setLayout(layout); // Initialization of object \"l1\" of JLabel class. l1 = new JLabel(\"Label 1 \"); // Initialization of object \"l2\" of JLabel class. l2 = new JLabel(\"Label 2 \"); // Initialization of object \"l3\" of JLabel class. l3 = new JLabel(\"Label 3 \"); // Initialization of object \"l4\" of JLabel class. l4 = new JLabel(\"Label 4 \"); // Initialization of object \"l5\" of JLabel class. l5 = new JLabel(\"Label 5 \"); // this Keyword refers to current object. // Adding Jlabel \"l1\" on JFrame. this.add(l1); // Adding Jlabel \"l2\" on JFrame. this.add(l2); // Adding Jlabel \"l3\" on JFrame. this.add(l3); // Adding Jlabel \"l4\" on JFrame. this.add(l4); // Adding Jlabel \"l5\" on JFrame. this.add(l5); }} class MainFrame { // Driver code public static void main(String[] args) { // Creating Object of Example class. Example f = new Example(); // Function to set title of JFrame. f.setTitle(\"Example of FlowLayout\"); // Function to set Bounds of JFrame. f.setBounds(200, 100, 600, 400); // Function to set visible status of JFrame. f.setVisible(true); }}",
"e": 10913,
"s": 9099,
"text": null
},
{
"code": null,
"e": 10921,
"s": 10913,
"text": "Output:"
},
{
"code": null,
"e": 11136,
"s": 10921,
"text": "We can control the alignment of components in a flow layout arrangement, by using these FlowLayout Fields.1) RIGHT :- Each row of component shifts towards right.2) LEFT :- Each row of component shifts towards left."
},
{
"code": null,
"e": 13412,
"s": 11136,
"text": "Program 2: The following program illustrates the use of FlowLayout using Right alignment by passing the argument FlowLayout.RIGHT in the constructor of FLowLayout. We create 5 JLabel components named βl1β, βl2β²β²... βl5β and then add them to the JFrame by the method this.add(). We set the title and bounds of the frame by method setTitle and setBounds.The layout is set by the method setLayout();// Java program to show example of// FlowLayout and using RIGHT alignmentimport java.awt.*;import java.awt.event.*;import javax.swing.*; class Example extends JFrame { // Declaration of objects of JLabel class. JLabel l1, l2, l3, l4, l5; // Constructor of Example class. public Example() { // Creating Object of \"FlowLayout\" class, passing // RIGHT alignment through constructor. FlowLayout layout = new FlowLayout(FlowLayout.RIGHT); // this Keyword refers to current object. // Function to set Layout of JFrame. this.setLayout(layout); // Initialization of object \"l1\" of JLabel class. l1 = new JLabel(\"Label 1 \"); // Initialization of object \"l2\" of JLabel class. l2 = new JLabel(\"Label 2 \"); // Initialization of object \"l3\" of JLabel class. l3 = new JLabel(\"Label 3 \"); // Initialization of object \"l4\" of JLabel class. l4 = new JLabel(\"Label 4 \"); // Initialization of object \"l5\" of JLabel class. l5 = new JLabel(\"Label 5 \"); // this Keyword refers to current object. // Adding Jlabel \"l1\" on JFrame. this.add(l1); // Adding Jlabel \"l2\" on JFrame. this.add(l2); // Adding Jlabel \"l3\" on JFrame. this.add(l3); // Adding Jlabel \"l4\" on JFrame. this.add(l4); // Adding Jlabel \"l5\" on JFrame. this.add(l5); }} class MainFrame { // Driver code public static void main(String[] args) { // Creating Object of Example class. Example f = new Example(); // Function to set title of JFrame. f.setTitle(\"Example of FlowLayout\"); // Function to set Bounds of JFrame. f.setBounds(200, 100, 600, 400); // Function to set visible status of JFrame. f.setVisible(true); }}Output:"
},
{
"code": "// Java program to show example of// FlowLayout and using RIGHT alignmentimport java.awt.*;import java.awt.event.*;import javax.swing.*; class Example extends JFrame { // Declaration of objects of JLabel class. JLabel l1, l2, l3, l4, l5; // Constructor of Example class. public Example() { // Creating Object of \"FlowLayout\" class, passing // RIGHT alignment through constructor. FlowLayout layout = new FlowLayout(FlowLayout.RIGHT); // this Keyword refers to current object. // Function to set Layout of JFrame. this.setLayout(layout); // Initialization of object \"l1\" of JLabel class. l1 = new JLabel(\"Label 1 \"); // Initialization of object \"l2\" of JLabel class. l2 = new JLabel(\"Label 2 \"); // Initialization of object \"l3\" of JLabel class. l3 = new JLabel(\"Label 3 \"); // Initialization of object \"l4\" of JLabel class. l4 = new JLabel(\"Label 4 \"); // Initialization of object \"l5\" of JLabel class. l5 = new JLabel(\"Label 5 \"); // this Keyword refers to current object. // Adding Jlabel \"l1\" on JFrame. this.add(l1); // Adding Jlabel \"l2\" on JFrame. this.add(l2); // Adding Jlabel \"l3\" on JFrame. this.add(l3); // Adding Jlabel \"l4\" on JFrame. this.add(l4); // Adding Jlabel \"l5\" on JFrame. this.add(l5); }} class MainFrame { // Driver code public static void main(String[] args) { // Creating Object of Example class. Example f = new Example(); // Function to set title of JFrame. f.setTitle(\"Example of FlowLayout\"); // Function to set Bounds of JFrame. f.setBounds(200, 100, 600, 400); // Function to set visible status of JFrame. f.setVisible(true); }}",
"e": 15285,
"s": 13412,
"text": null
},
{
"code": null,
"e": 15293,
"s": 15285,
"text": "Output:"
},
{
"code": null,
"e": 15360,
"s": 15293,
"text": "Reference: https://www.geeksforgeeks.org/message-dialogs-java-gui/"
},
{
"code": null,
"e": 15369,
"s": 15360,
"text": "Java-AWT"
},
{
"code": null,
"e": 15374,
"s": 15369,
"text": "Java"
},
{
"code": null,
"e": 15379,
"s": 15374,
"text": "Java"
}
] |
Randomly select n elements from list in Python
|
21 Aug, 2020
In this article, we will discuss how to randomly select n elements from the list in Python. Before moving on to the approaches letβs discuss Random Module which we are going to use in our approaches.Random Module:Random module is the predefined Module in Python, It contains methods to return random values. This module is useful when we want to generate random values. Some of the methods of Random module are:-seed(), getstate(), choice(), sample() etc.
Letβs discuss different approaches to implement this.Approach 1 : Using sample() Method. sample() method is used to return required list of items from a given sequence. This method do not allow duplicate elements in a sequence.
# importing random moduleimport random # declaring listlist = [2, 2, 4, 6, 6, 8] # initializing the value of nn = 4 # printing n elements from listprint(random.sample(list, n))
Output :
[8, 6, 6, 4]
Approach 2 : Using choice() Method. choice() method is used to return a random number from given sequence. The sequence can be a list or a tuple. This returns a single value from available data that considers duplicate values in the sequence(list).
# importing random moduleimport random # declaring listlist = [2, 2, 4, 6, 6, 8] # initializing the value of nn = 4 # traversing and printing random elementsfor i in range(n): # end = " " so that we get output in single line print(random.choice(list), end = " ")
Output :
8 2 4 6
Python list-programs
python-list
Python-random
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python OOPs Concepts
Python Classes and Objects
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 - Pandas dataframe.append()
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Aug, 2020"
},
{
"code": null,
"e": 484,
"s": 28,
"text": "In this article, we will discuss how to randomly select n elements from the list in Python. Before moving on to the approaches letβs discuss Random Module which we are going to use in our approaches.Random Module:Random module is the predefined Module in Python, It contains methods to return random values. This module is useful when we want to generate random values. Some of the methods of Random module are:-seed(), getstate(), choice(), sample() etc."
},
{
"code": null,
"e": 712,
"s": 484,
"text": "Letβs discuss different approaches to implement this.Approach 1 : Using sample() Method. sample() method is used to return required list of items from a given sequence. This method do not allow duplicate elements in a sequence."
},
{
"code": "# importing random moduleimport random # declaring listlist = [2, 2, 4, 6, 6, 8] # initializing the value of nn = 4 # printing n elements from listprint(random.sample(list, n))",
"e": 892,
"s": 712,
"text": null
},
{
"code": null,
"e": 901,
"s": 892,
"text": "Output :"
},
{
"code": null,
"e": 915,
"s": 901,
"text": "[8, 6, 6, 4]\n"
},
{
"code": null,
"e": 1164,
"s": 915,
"text": "Approach 2 : Using choice() Method. choice() method is used to return a random number from given sequence. The sequence can be a list or a tuple. This returns a single value from available data that considers duplicate values in the sequence(list)."
},
{
"code": "# importing random moduleimport random # declaring listlist = [2, 2, 4, 6, 6, 8] # initializing the value of nn = 4 # traversing and printing random elementsfor i in range(n): # end = \" \" so that we get output in single line print(random.choice(list), end = \" \")",
"e": 1442,
"s": 1164,
"text": null
},
{
"code": null,
"e": 1451,
"s": 1442,
"text": "Output :"
},
{
"code": null,
"e": 1461,
"s": 1451,
"text": "8 2 4 6 \n"
},
{
"code": null,
"e": 1482,
"s": 1461,
"text": "Python list-programs"
},
{
"code": null,
"e": 1494,
"s": 1482,
"text": "python-list"
},
{
"code": null,
"e": 1508,
"s": 1494,
"text": "Python-random"
},
{
"code": null,
"e": 1515,
"s": 1508,
"text": "Python"
},
{
"code": null,
"e": 1527,
"s": 1515,
"text": "python-list"
},
{
"code": null,
"e": 1625,
"s": 1527,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1657,
"s": 1625,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1678,
"s": 1657,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1705,
"s": 1678,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1728,
"s": 1705,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1759,
"s": 1728,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1815,
"s": 1759,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1857,
"s": 1815,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1899,
"s": 1857,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1934,
"s": 1899,
"text": "Python - Pandas dataframe.append()"
}
] |
How to Install Scrapy on MacOS?
|
22 Sep, 2021
In this article, we will learn how to install Scrapy in Python on MacOS.
Scrapy is a fast high-level web crawling and web scraping framework used to crawl websites and extract structured data from their pages. It can be used for a wide range of purposes, from data mining to monitoring and automated testing.
Follow the below steps to install the SCrapy package on macOS using pip:
Step 1: Install the latest Python3 in MacOS
Step 2: Check if pip3 and python3 are correctly installed.
python3 --version
pip3 --version
Step 3: Upgrade your pip to avoid errors during installation.
pip3 install --upgrade pip
Step 4: Enter the following command to install Scrapy using pip3.
pip3 install Scrapy
Follow the below steps to install the Scrapy package on macOS using the setup.py file:
Step 1: Download the latest source package of Scrapy for python3 from here.
curl https://files.pythonhosted.org/packages/e9/dc/b2f41d802f548fba35c2d7c443ab0ab3df358eebd261f4d30d19ad39658a/Scrapy-2.5.0.tar.gz > scrapy.tar.gz
Step 2: Extract the downloaded package using the following command.
tar -xzvf scrapy.tar.gz
Step 3: Go inside the folder and Enter the following command to install the package.
Note: You must have developer tools for XCode MacOS installed in your system
cd Scrapy-2.5.0
python3 setup.py install
Make the following import in your python terminal to verify if the installation has been done properly:
import scrapy
If there is any error while importing the module then is not installed properly.
Blogathon-2021
how-to-install
Picked
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 102,
"s": 28,
"text": "In this article, we will learn how to install Scrapy in Python on MacOS. "
},
{
"code": null,
"e": 338,
"s": 102,
"text": "Scrapy is a fast high-level web crawling and web scraping framework used to crawl websites and extract structured data from their pages. It can be used for a wide range of purposes, from data mining to monitoring and automated testing."
},
{
"code": null,
"e": 411,
"s": 338,
"text": "Follow the below steps to install the SCrapy package on macOS using pip:"
},
{
"code": null,
"e": 455,
"s": 411,
"text": "Step 1: Install the latest Python3 in MacOS"
},
{
"code": null,
"e": 514,
"s": 455,
"text": "Step 2: Check if pip3 and python3 are correctly installed."
},
{
"code": null,
"e": 547,
"s": 514,
"text": "python3 --version\npip3 --version"
},
{
"code": null,
"e": 609,
"s": 547,
"text": "Step 3: Upgrade your pip to avoid errors during installation."
},
{
"code": null,
"e": 636,
"s": 609,
"text": "pip3 install --upgrade pip"
},
{
"code": null,
"e": 702,
"s": 636,
"text": "Step 4: Enter the following command to install Scrapy using pip3."
},
{
"code": null,
"e": 722,
"s": 702,
"text": "pip3 install Scrapy"
},
{
"code": null,
"e": 809,
"s": 722,
"text": "Follow the below steps to install the Scrapy package on macOS using the setup.py file:"
},
{
"code": null,
"e": 885,
"s": 809,
"text": "Step 1: Download the latest source package of Scrapy for python3 from here."
},
{
"code": null,
"e": 1033,
"s": 885,
"text": "curl https://files.pythonhosted.org/packages/e9/dc/b2f41d802f548fba35c2d7c443ab0ab3df358eebd261f4d30d19ad39658a/Scrapy-2.5.0.tar.gz > scrapy.tar.gz"
},
{
"code": null,
"e": 1101,
"s": 1033,
"text": "Step 2: Extract the downloaded package using the following command."
},
{
"code": null,
"e": 1125,
"s": 1101,
"text": "tar -xzvf scrapy.tar.gz"
},
{
"code": null,
"e": 1210,
"s": 1125,
"text": "Step 3: Go inside the folder and Enter the following command to install the package."
},
{
"code": null,
"e": 1287,
"s": 1210,
"text": "Note: You must have developer tools for XCode MacOS installed in your system"
},
{
"code": null,
"e": 1328,
"s": 1287,
"text": "cd Scrapy-2.5.0\npython3 setup.py install"
},
{
"code": null,
"e": 1432,
"s": 1328,
"text": "Make the following import in your python terminal to verify if the installation has been done properly:"
},
{
"code": null,
"e": 1446,
"s": 1432,
"text": "import scrapy"
},
{
"code": null,
"e": 1527,
"s": 1446,
"text": "If there is any error while importing the module then is not installed properly."
},
{
"code": null,
"e": 1542,
"s": 1527,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 1557,
"s": 1542,
"text": "how-to-install"
},
{
"code": null,
"e": 1564,
"s": 1557,
"text": "Picked"
},
{
"code": null,
"e": 1574,
"s": 1564,
"text": "Blogathon"
},
{
"code": null,
"e": 1581,
"s": 1574,
"text": "How To"
},
{
"code": null,
"e": 1600,
"s": 1581,
"text": "Installation Guide"
}
] |
How to print Python dictionary into JSON format?
|
JSON stands for Javascript Standard Object Notation. Python module called json is a JSON encoder/decoder. The dumps() function in this module returns a JSON string representation of Python dictionary object.
D1={"pen":25, "pencil":10, "book":100, "sharpner":5, "eraser":5}
>>> import json
>>> j=json.dumps(D1)
>>> j
'{"pen": 25, "pencil": 10, "book": 100, "sharpner": 5, "eraser": 5}'
|
[
{
"code": null,
"e": 1270,
"s": 1062,
"text": "JSON stands for Javascript Standard Object Notation. Python module called json is a JSON encoder/decoder. The dumps() function in this module returns a JSON string representation of Python dictionary object."
},
{
"code": null,
"e": 1447,
"s": 1270,
"text": "D1={\"pen\":25, \"pencil\":10, \"book\":100, \"sharpner\":5, \"eraser\":5}\n>>> import json\n>>> j=json.dumps(D1)\n>>> j\n'{\"pen\": 25, \"pencil\": 10, \"book\": 100, \"sharpner\": 5, \"eraser\": 5}'"
}
] |
How to create a listView with a checkBox in Kotlin?
|
This example demonstrates how to Create a listView with a checkBox in Kotlin.
Step 1 β Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project.
Step 2 β Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
tools:context=".MainActivity">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
Step 3 β Add the following code to src/MainActivity.kt
import android.view.View
import android.widget.AdapterView.OnItemClickListener
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
import java.util.*
class MainActivity : AppCompatActivity() {
private var dataModel: ArrayList<DataModel>? = null
private lateinit var listView: ListView
private lateinit var adapter: CustomAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
listView = findViewById<View>(R.id.listView) as ListView
dataModel = ArrayList<DataModel>()
dataModel!!.add(DataModel("Apple Pie", false))
dataModel!!.add(DataModel("Banana Bread", false))
dataModel!!.add(DataModel("Cupcake", false))
dataModel!!.add(DataModel("Donut", true))
dataModel!!.add(DataModel("Eclair", true))
dataModel!!.add(DataModel("Froyo", true))
dataModel!!.add(DataModel("Gingerbread", true))
dataModel!!.add(DataModel("Honeycomb", false))
dataModel!!.add(DataModel("Ice Cream Sandwich", false))
dataModel!!.add(DataModel("Jelly Bean", false))
dataModel!!.add(DataModel("Kitkat", false))
dataModel!!.add(DataModel("Lollipop", false))
dataModel!!.add(DataModel("Marshmallow", false))
dataModel!!.add(DataModel("Nougat", false))
adapter = CustomAdapter(dataModel!!, applicationContext)
listView.adapter = adapter
listView.onItemClickListener = OnItemClickListener { _, _, position, _ ->
val dataModel: DataModel = dataModel!![position] as DataModel
dataModel.checked = !dataModel.checked
adapter.notifyDataSetChanged()
}
}
}
Step 4 β Create a new Kotlin class (CustomAdapter.kt) and add the following code to src/CustomAdapter.kt
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.CheckBox
import android.widget.TextView
import java.util.*
class CustomAdapter(private val dataSet: ArrayList<*>, mContext: Context) :
ArrayAdapter<Any?>(mContext, R.layout.row_item, dataSet) {
private class ViewHolder {
lateinit var txtName: TextView
lateinit var checkBox: CheckBox
}
override fun getCount(): Int {
return dataSet.size
}
override fun getItem(position: Int): DataModel {
return dataSet[position] as DataModel
}
override fun getView(
position: Int,
convertView: View?,
parent: ViewGroup
): View {
var convertView = convertView
val viewHolder: ViewHolder
val result: View
if (convertView == null) {
viewHolder = ViewHolder()
convertView =
LayoutInflater.from(parent.context).inflate(R.layout.row_item, parent, false)
viewHolder.txtName =
convertView.findViewById(R.id.txtName)
viewHolder.checkBox =
convertView.findViewById(R.id.checkBox)
result = convertView
convertView.tag = viewHolder
} else {
viewHolder = convertView.tag as ViewHolder
result = convertView
}
val item: DataModel = getItem(position)
viewHolder.txtName.text = item.name
viewHolder.checkBox.isChecked = item.checked
return result
}
}
Step 5 β Create a new Kotlin class (DataModel.kit) and add the following code to src/DataModel.kt
package app.com.q3
class DataModel internal constructor(var name: String?, var checked: Boolean)
Step 6 β Create a Layout resource file (row_item.xml) and add the following code β
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="2dp">
<TextView
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:textColor="@android:color/background_dark"
android:textSize="16sp" />
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Step 7 β Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q1">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the 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": 1140,
"s": 1062,
"text": "This example demonstrates how to Create a listView with a checkBox in Kotlin."
},
{
"code": null,
"e": 1270,
"s": 1140,
"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": 1335,
"s": 1270,
"text": "Step 2 β Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1780,
"s": 1335,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n<ListView\n android:id=\"@+id/listView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1835,
"s": 1780,
"text": "Step 3 β Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3557,
"s": 1835,
"text": "import android.view.View\nimport android.widget.AdapterView.OnItemClickListener\nimport android.widget.ListView\nimport androidx.appcompat.app.AppCompatActivity\nimport java.util.*\nclass MainActivity : AppCompatActivity() {\n private var dataModel: ArrayList<DataModel>? = null\n private lateinit var listView: ListView\n private lateinit var adapter: CustomAdapter\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n listView = findViewById<View>(R.id.listView) as ListView\n dataModel = ArrayList<DataModel>()\n dataModel!!.add(DataModel(\"Apple Pie\", false))\n dataModel!!.add(DataModel(\"Banana Bread\", false))\n dataModel!!.add(DataModel(\"Cupcake\", false))\n dataModel!!.add(DataModel(\"Donut\", true))\n dataModel!!.add(DataModel(\"Eclair\", true))\n dataModel!!.add(DataModel(\"Froyo\", true))\n dataModel!!.add(DataModel(\"Gingerbread\", true))\n dataModel!!.add(DataModel(\"Honeycomb\", false))\n dataModel!!.add(DataModel(\"Ice Cream Sandwich\", false))\n dataModel!!.add(DataModel(\"Jelly Bean\", false))\n dataModel!!.add(DataModel(\"Kitkat\", false))\n dataModel!!.add(DataModel(\"Lollipop\", false))\n dataModel!!.add(DataModel(\"Marshmallow\", false))\n dataModel!!.add(DataModel(\"Nougat\", false))\n adapter = CustomAdapter(dataModel!!, applicationContext)\n listView.adapter = adapter\n listView.onItemClickListener = OnItemClickListener { _, _, position, _ ->\n val dataModel: DataModel = dataModel!![position] as DataModel\n dataModel.checked = !dataModel.checked\n adapter.notifyDataSetChanged()\n }\n }\n}"
},
{
"code": null,
"e": 3663,
"s": 3557,
"text": "Step 4 β Create a new Kotlin class (CustomAdapter.kt) and add the following code to src/CustomAdapter.kt"
},
{
"code": null,
"e": 5178,
"s": 3663,
"text": "import android.content.Context\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport android.widget.ArrayAdapter\nimport android.widget.CheckBox\nimport android.widget.TextView\nimport java.util.*\nclass CustomAdapter(private val dataSet: ArrayList<*>, mContext: Context) :\nArrayAdapter<Any?>(mContext, R.layout.row_item, dataSet) {\n private class ViewHolder {\n lateinit var txtName: TextView\n lateinit var checkBox: CheckBox\n }\n override fun getCount(): Int {\n return dataSet.size\n }\n override fun getItem(position: Int): DataModel {\n return dataSet[position] as DataModel\n }\n override fun getView(\n position: Int,\n convertView: View?,\n parent: ViewGroup\n ): View {\n var convertView = convertView\n val viewHolder: ViewHolder\n val result: View\n if (convertView == null) {\n viewHolder = ViewHolder()\n convertView =\n LayoutInflater.from(parent.context).inflate(R.layout.row_item, parent, false)\n viewHolder.txtName =\n convertView.findViewById(R.id.txtName)\n viewHolder.checkBox =\n convertView.findViewById(R.id.checkBox)\n result = convertView\n convertView.tag = viewHolder\n } else {\n viewHolder = convertView.tag as ViewHolder\n result = convertView\n }\n val item: DataModel = getItem(position)\n viewHolder.txtName.text = item.name\n viewHolder.checkBox.isChecked = item.checked\n return result\n }\n}"
},
{
"code": null,
"e": 5276,
"s": 5178,
"text": "Step 5 β Create a new Kotlin class (DataModel.kit) and add the following code to src/DataModel.kt"
},
{
"code": null,
"e": 5373,
"s": 5276,
"text": "package app.com.q3\nclass DataModel internal constructor(var name: String?, var checked: Boolean)"
},
{
"code": null,
"e": 5456,
"s": 5373,
"text": "Step 6 β Create a Layout resource file (row_item.xml) and add the following code β"
},
{
"code": null,
"e": 6221,
"s": 5456,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"2dp\">\n <TextView\n android:id=\"@+id/txtName\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentStart=\"true\"\n android:layout_centerVertical=\"true\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"16sp\" />\n <CheckBox\n android:id=\"@+id/checkBox\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentTop=\"true\"\n android:layout_alignParentEnd=\"true\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 6276,
"s": 6221,
"text": "Step 7 β Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 6942,
"s": 6276,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.q1\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 7290,
"s": 6942,
"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 the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
How to Vibrate a Device Programmatically in Android? - GeeksforGeeks
|
23 Feb, 2021
Hepatic feedbacks are also considered when it comes to user experience. So in this discussion, itβs been discussed various types of haptics or the types of vibration of the device. For example, click haptics or long-press button haptics. There five different types of vibration modes in haptic feedback discussed are:
Default vibration of the deviceClick effect vibrationDouble click effect vibrationHeavy click effect vibrationTick effect vibration
Default vibration of the device
Click effect vibration
Double click effect vibration
Heavy click effect vibration
Tick effect vibration
Note that we are going to implement this project using the Java language.
Step 1: Create an empty activity Android studio project
Create an empty activity android studio project.
Refer to Android | How to Create/Start a New Project in Android Studio?
Note that select Java as the programming language.
Step 2: Working with the activity_main.xml
In this discussion, four different types of haptics are discussed.
So to generate that haptics there are four different buttons are included in the layout. Invoke the following code inside the activity_main.xml file.
Make sure to give appropriate IDs for all the buttons to handle them in the MainActivity.java file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--Button to generate normal vibration--> <Button android:id="@+id/normalVibrationButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="64dp" android:backgroundTint="@color/colorPrimary" android:text="NORMAL VIBRATION" android:textColor="@android:color/white" /> <!--Button to generate click vibration--> <Button android:id="@+id/clickVibrationButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/normalVibrationButton" android:layout_centerHorizontal="true" android:layout_marginTop="8dp" android:backgroundTint="@color/colorPrimary" android:text="CLICK VIBRATION" android:textColor="@android:color/white" /> <!--Button to generate double click vibration--> <Button android:id="@+id/doubleClickVibrationButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/clickVibrationButton" android:layout_centerHorizontal="true" android:layout_marginTop="8dp" android:backgroundTint="@color/colorPrimary" android:text="DOUBLE CLICK VIBRATION" android:textColor="@android:color/white" /> <!--Button to generate tick vibration--> <Button android:id="@+id/tickVibrationButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/doubleClickVibrationButton" android:layout_centerHorizontal="true" android:layout_marginTop="8dp" android:backgroundTint="@color/colorPrimary" android:text="TICK VIBRATION" android:textColor="@android:color/white" /> <!--Button to generate heavy click vibration--> <Button android:id="@+id/heavyClickVibrationButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/tickVibrationButton" android:layout_centerHorizontal="true" android:layout_marginTop="8dp" android:backgroundTint="@color/colorPrimary" android:text="HEAVY CLICK EFFECT VIBRATION" android:textColor="@android:color/white" /> </RelativeLayout>
Output UI:
Step 3: Invoking Vibrate permission in AndroidManifest file
The vibration of the device needs permissions. To invoke the following code inside the AndroidManifest file.
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.adityamshidlyali.vibrationsinandroid"> <!--vibrate permission which needs to be invoked as we hard accessing the vibrator hardware of the device--> <uses-permission android:name="android.permission.VIBRATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Step 4: Working with the MainActivity.java file
As it is said that there are five different kinds of vibrations. For those five kinds of vibrations, there are constants for each of them. Those are:
DEFAULT_AMPLITUDE -> for default vibration of the device
EFFECT_CLICK -> for single click haptic
EFFECT_DOUBLE_CLICK -> for double click of the view
EFFECT_HEAVY_CLICK -> for heavy click effect of the view
EFFECT_TICK -> for tick effect vibration
Invoke the following code inside the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import androidx.appcompat.app.AppCompatActivity;import android.content.Context;import android.os.Bundle;import android.os.VibrationEffect;import android.os.Vibrator;import android.view.View;import android.widget.Button; public class MainActivity extends AppCompatActivity { // buttons for all the types of the vibration effects Button bNormalVibration, bClickVibration, bDoubleClickVibration, bTickVibration, bHeavyClickVibration; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // get the VIBRATOR_SERVICE system service final Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); // register all of the buttons with their IDs bNormalVibration = findViewById(R.id.normalVibrationButton); bClickVibration = findViewById(R.id.clickVibrationButton); bDoubleClickVibration = findViewById(R.id.doubleClickVibrationButton); bTickVibration = findViewById(R.id.tickVibrationButton); bHeavyClickVibration = findViewById(R.id.heavyClickVibrationButton); // handle normal vibration button bNormalVibration.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final VibrationEffect vibrationEffect1; // this is the only type of the vibration which requires system version Oreo (API 26) if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { // this effect creates the vibration of default amplitude for 1000ms(1 sec) vibrationEffect1 = VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE); // it is safe to cancel other vibrations currently taking place vibrator.cancel(); vibrator.vibrate(vibrationEffect1); } } }); // handle click vibration button bClickVibration.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // this type of vibration requires API 29 final VibrationEffect vibrationEffect2; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) { // create vibrator effect with the constant EFFECT_CLICK vibrationEffect2 = VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK); // it is safe to cancel other vibrations currently taking place vibrator.cancel(); vibrator.vibrate(vibrationEffect2); } } }); // handle double click vibration button bDoubleClickVibration.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final VibrationEffect vibrationEffect3; // this type of vibration requires API 29 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) { // create vibrator effect with the constant EFFECT_DOUBLE_CLICK vibrationEffect3 = VibrationEffect.createPredefined(VibrationEffect.EFFECT_DOUBLE_CLICK); // it is safe to cancel other vibrations currently taking place vibrator.cancel(); vibrator.vibrate(vibrationEffect3); } } }); // handle tick effect vibration button bTickVibration.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final VibrationEffect vibrationEffect4; // this type of vibration requires API 29 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) { // create vibrator effect with the constant EFFECT_TICK vibrationEffect4 = VibrationEffect.createPredefined(VibrationEffect.EFFECT_TICK); // it is safe to cancel other vibrations currently taking place vibrator.cancel(); vibrator.vibrate(vibrationEffect4); } } }); // handle heavy click vibration button bHeavyClickVibration.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final VibrationEffect vibrationEffect5; // this type of vibration requires API 29 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) { // create vibrator effect with the constant EFFECT_HEAVY_CLICK vibrationEffect5 = VibrationEffect.createPredefined(VibrationEffect.EFFECT_HEAVY_CLICK); // it is safe to cancel other vibrations currently taking place vibrator.cancel(); vibrator.vibrate(vibrationEffect5); } } }); }}
The output should be tested on the physical android device. To know how to set up a physical android studio refer to How to Run the Android App on a Real Device?
Android-Misc
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Retrofit with Kotlin Coroutine in Android
Flutter - Custom Bottom Navigation Bar
How to Post Data to API using Retrofit in Android?
How to Read Data from SQLite Database in Android?
Android Listview in Java with Example
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
HashMap in Java with Examples
|
[
{
"code": null,
"e": 25036,
"s": 25008,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 25354,
"s": 25036,
"text": "Hepatic feedbacks are also considered when it comes to user experience. So in this discussion, itβs been discussed various types of haptics or the types of vibration of the device. For example, click haptics or long-press button haptics. There five different types of vibration modes in haptic feedback discussed are:"
},
{
"code": null,
"e": 25486,
"s": 25354,
"text": "Default vibration of the deviceClick effect vibrationDouble click effect vibrationHeavy click effect vibrationTick effect vibration"
},
{
"code": null,
"e": 25518,
"s": 25486,
"text": "Default vibration of the device"
},
{
"code": null,
"e": 25541,
"s": 25518,
"text": "Click effect vibration"
},
{
"code": null,
"e": 25571,
"s": 25541,
"text": "Double click effect vibration"
},
{
"code": null,
"e": 25600,
"s": 25571,
"text": "Heavy click effect vibration"
},
{
"code": null,
"e": 25622,
"s": 25600,
"text": "Tick effect vibration"
},
{
"code": null,
"e": 25697,
"s": 25622,
"text": "Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 25753,
"s": 25697,
"text": "Step 1: Create an empty activity Android studio project"
},
{
"code": null,
"e": 25802,
"s": 25753,
"text": "Create an empty activity android studio project."
},
{
"code": null,
"e": 25874,
"s": 25802,
"text": "Refer to Android | How to Create/Start a New Project in Android Studio?"
},
{
"code": null,
"e": 25925,
"s": 25874,
"text": "Note that select Java as the programming language."
},
{
"code": null,
"e": 25968,
"s": 25925,
"text": "Step 2: Working with the activity_main.xml"
},
{
"code": null,
"e": 26035,
"s": 25968,
"text": "In this discussion, four different types of haptics are discussed."
},
{
"code": null,
"e": 26185,
"s": 26035,
"text": "So to generate that haptics there are four different buttons are included in the layout. Invoke the following code inside the activity_main.xml file."
},
{
"code": null,
"e": 26285,
"s": 26185,
"text": "Make sure to give appropriate IDs for all the buttons to handle them in the MainActivity.java file."
},
{
"code": null,
"e": 26289,
"s": 26285,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--Button to generate normal vibration--> <Button android:id=\"@+id/normalVibrationButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"64dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"NORMAL VIBRATION\" android:textColor=\"@android:color/white\" /> <!--Button to generate click vibration--> <Button android:id=\"@+id/clickVibrationButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/normalVibrationButton\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"8dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"CLICK VIBRATION\" android:textColor=\"@android:color/white\" /> <!--Button to generate double click vibration--> <Button android:id=\"@+id/doubleClickVibrationButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/clickVibrationButton\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"8dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"DOUBLE CLICK VIBRATION\" android:textColor=\"@android:color/white\" /> <!--Button to generate tick vibration--> <Button android:id=\"@+id/tickVibrationButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/doubleClickVibrationButton\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"8dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"TICK VIBRATION\" android:textColor=\"@android:color/white\" /> <!--Button to generate heavy click vibration--> <Button android:id=\"@+id/heavyClickVibrationButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/tickVibrationButton\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"8dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"HEAVY CLICK EFFECT VIBRATION\" android:textColor=\"@android:color/white\" /> </RelativeLayout>",
"e": 29060,
"s": 26289,
"text": null
},
{
"code": null,
"e": 29071,
"s": 29060,
"text": "Output UI:"
},
{
"code": null,
"e": 29131,
"s": 29071,
"text": "Step 3: Invoking Vibrate permission in AndroidManifest file"
},
{
"code": null,
"e": 29240,
"s": 29131,
"text": "The vibration of the device needs permissions. To invoke the following code inside the AndroidManifest file."
},
{
"code": null,
"e": 29244,
"s": 29240,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.adityamshidlyali.vibrationsinandroid\"> <!--vibrate permission which needs to be invoked as we hard accessing the vibrator hardware of the device--> <uses-permission android:name=\"android.permission.VIBRATE\" /> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>",
"e": 30152,
"s": 29244,
"text": null
},
{
"code": null,
"e": 30200,
"s": 30152,
"text": "Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 30350,
"s": 30200,
"text": "As it is said that there are five different kinds of vibrations. For those five kinds of vibrations, there are constants for each of them. Those are:"
},
{
"code": null,
"e": 30407,
"s": 30350,
"text": "DEFAULT_AMPLITUDE -> for default vibration of the device"
},
{
"code": null,
"e": 30447,
"s": 30407,
"text": "EFFECT_CLICK -> for single click haptic"
},
{
"code": null,
"e": 30499,
"s": 30447,
"text": "EFFECT_DOUBLE_CLICK -> for double click of the view"
},
{
"code": null,
"e": 30556,
"s": 30499,
"text": "EFFECT_HEAVY_CLICK -> for heavy click effect of the view"
},
{
"code": null,
"e": 30597,
"s": 30556,
"text": "EFFECT_TICK -> for tick effect vibration"
},
{
"code": null,
"e": 30732,
"s": 30597,
"text": "Invoke the following code inside the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 30737,
"s": 30732,
"text": "Java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import android.content.Context;import android.os.Bundle;import android.os.VibrationEffect;import android.os.Vibrator;import android.view.View;import android.widget.Button; public class MainActivity extends AppCompatActivity { // buttons for all the types of the vibration effects Button bNormalVibration, bClickVibration, bDoubleClickVibration, bTickVibration, bHeavyClickVibration; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // get the VIBRATOR_SERVICE system service final Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); // register all of the buttons with their IDs bNormalVibration = findViewById(R.id.normalVibrationButton); bClickVibration = findViewById(R.id.clickVibrationButton); bDoubleClickVibration = findViewById(R.id.doubleClickVibrationButton); bTickVibration = findViewById(R.id.tickVibrationButton); bHeavyClickVibration = findViewById(R.id.heavyClickVibrationButton); // handle normal vibration button bNormalVibration.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final VibrationEffect vibrationEffect1; // this is the only type of the vibration which requires system version Oreo (API 26) if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { // this effect creates the vibration of default amplitude for 1000ms(1 sec) vibrationEffect1 = VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE); // it is safe to cancel other vibrations currently taking place vibrator.cancel(); vibrator.vibrate(vibrationEffect1); } } }); // handle click vibration button bClickVibration.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // this type of vibration requires API 29 final VibrationEffect vibrationEffect2; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) { // create vibrator effect with the constant EFFECT_CLICK vibrationEffect2 = VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK); // it is safe to cancel other vibrations currently taking place vibrator.cancel(); vibrator.vibrate(vibrationEffect2); } } }); // handle double click vibration button bDoubleClickVibration.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final VibrationEffect vibrationEffect3; // this type of vibration requires API 29 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) { // create vibrator effect with the constant EFFECT_DOUBLE_CLICK vibrationEffect3 = VibrationEffect.createPredefined(VibrationEffect.EFFECT_DOUBLE_CLICK); // it is safe to cancel other vibrations currently taking place vibrator.cancel(); vibrator.vibrate(vibrationEffect3); } } }); // handle tick effect vibration button bTickVibration.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final VibrationEffect vibrationEffect4; // this type of vibration requires API 29 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) { // create vibrator effect with the constant EFFECT_TICK vibrationEffect4 = VibrationEffect.createPredefined(VibrationEffect.EFFECT_TICK); // it is safe to cancel other vibrations currently taking place vibrator.cancel(); vibrator.vibrate(vibrationEffect4); } } }); // handle heavy click vibration button bHeavyClickVibration.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final VibrationEffect vibrationEffect5; // this type of vibration requires API 29 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) { // create vibrator effect with the constant EFFECT_HEAVY_CLICK vibrationEffect5 = VibrationEffect.createPredefined(VibrationEffect.EFFECT_HEAVY_CLICK); // it is safe to cancel other vibrations currently taking place vibrator.cancel(); vibrator.vibrate(vibrationEffect5); } } }); }}",
"e": 35994,
"s": 30737,
"text": null
},
{
"code": null,
"e": 36156,
"s": 35994,
"text": "The output should be tested on the physical android device. To know how to set up a physical android studio refer to How to Run the Android App on a Real Device?"
},
{
"code": null,
"e": 36169,
"s": 36156,
"text": "Android-Misc"
},
{
"code": null,
"e": 36193,
"s": 36169,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 36201,
"s": 36193,
"text": "Android"
},
{
"code": null,
"e": 36206,
"s": 36201,
"text": "Java"
},
{
"code": null,
"e": 36225,
"s": 36206,
"text": "Technical Scripter"
},
{
"code": null,
"e": 36230,
"s": 36225,
"text": "Java"
},
{
"code": null,
"e": 36238,
"s": 36230,
"text": "Android"
},
{
"code": null,
"e": 36336,
"s": 36238,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36345,
"s": 36336,
"text": "Comments"
},
{
"code": null,
"e": 36358,
"s": 36345,
"text": "Old Comments"
},
{
"code": null,
"e": 36400,
"s": 36358,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 36439,
"s": 36400,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 36490,
"s": 36439,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 36540,
"s": 36490,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 36578,
"s": 36540,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 36593,
"s": 36578,
"text": "Arrays in Java"
},
{
"code": null,
"e": 36637,
"s": 36593,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 36659,
"s": 36637,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 36684,
"s": 36659,
"text": "Reverse a string in Java"
}
] |
Computer Vision on Edge. Object detection with AIoT: An edge... | by Anuradha Wickramarachchi | Towards Data Science
|
A few weeks back when I was window shopping at AliExpress I came across the wonderful Maixduino device. It was claimed to carry RISC V architecture along with a KPU (KPU is a general-purpose neural network processor). Contrasting specs of the board were as follows;
CPU: RISC-V Dual Core 64bit, with FPU
Image Recognition: QVGA@60fps/VGA@30fps
Power consumption of chip < 300mW
Truth be told, the unit is old and has only been taking attention lately. Well, given my interest in edge computing I thought of presenting a complete end to end guide for an object detection example. This example is based on knowledge taken from this article by Dimitry. However, Iβll have a comprehensive walkthrough on how to collect images and annotate them as well. If you want to know what edge computing is, feel free to read the following article.
medium.com
Letβs try to build an image detection program that will be able to border out apples and bananas. You can be creative with your detector. We will discuss required tools and libraries as we move along.
Transfer learning is the idea that we use a pre-trained model for further specialization. In simple terms, you replace the last prediction layer of the trained model with your own classification layer (or more layers). Then you freeze the layers except for yours (or a few of the pre-trained ones too). Then you train the network so that the features of the pre-trained model will be used to fine-tune your layer to predict the classes that you want.
Unfortunately, at the moment the network weβll be training does not have any pre-trained models. Hence, we will be mostly training ground up. But itβll be an interesting experiment!
We need to prepare the data in the following format. First, we need images with apples and bananas. At the same time, we need them annotated as to where each fruit might be inside the image. This is where the difference between object classification and detection comes. We need to say where the object is. For this, you need the following tool.
github.com
Or you can use my tool to generate annotated images using your backgrounds and object images (eg: Images from Fruit 360 at Kaggle). Read more here;
anuradhawick.medium.com
In my example, I am using the following program as I capture from the webcam. Pick the easy method. The following program comes compiled with Nvidia jetson nano get started container.
github.com
We want to train our models so that they could run on the MaixDuino device. For this, we can use the following repository. It has all the necessary modifications to the model layers to suit the architecture of the K210 processor. Clone and install the required dependencies. All instructions are available at the following link;
github.com
We need to organize our training data as follows;
path-to/data---anns # store the training annotations---imgs # relevant images for the training---anns_val # validation annotations---imgs_val # validation images
Now we need to create a config.json to set the training options. For our case it should look like below;
{ "model" : { "type": "Detector", "architecture": "MobileNet7_5", "input_size": [224,224], "anchors": [0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828], "labels": ["Apple", "Banana"], "coord_scale" : 1.0, "class_scale" : 1.0, "object_scale" : 5.0, "no_object_scale" : 1.0 }, "weights" : { "full": "", "backend": "imagenet" }, "train" : { "actual_epoch": 50, "train_image_folder": "data/imgs", "train_annot_folder": "data/anns", "train_times": 2, "valid_image_folder": "data/imgs_val", "valid_annot_folder": "data/anns_val", "valid_times": 2, "valid_metric": "mAP", "batch_size": 4, "learning_rate": 1e-4, "saved_folder": "obj_detector", "first_trainable_layer": "", "augumentation": true, "is_only_detect" : false }, "converter" : { "type": ["k210"] }}
Note: use absolute paths to avoid unwanted errors.
Next, we can train using the following command;
python3 aXelerate/axelerate/traing.py -c config.json
Now the training is complete. We are interested in the kmodel file generated within the project folder. We can move it to a microSD card and connect it to the MaixDuino device.
Following is the sketch I will be using in the maixPy IDE.
import sensor,image,lcdimport KPU as kpulcd.init()sensor.reset()sensor.set_pixformat(sensor.RGB565)sensor.set_framesize(sensor.QVGA)sensor.set_windowing((224, 224))sensor.set_vflip(1)sensor.run(1)classes = ["Apple", "Banana"]task = kpu.load("/sd/name_of_the_model_file.kmodel")a = kpu.set_outputs(task, 0, 7, 7, 35)anchor = (0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828)a = kpu.init_yolo2(task, 0.3, 0.3, 5, anchor) while(True): img = sensor.snapshot().rotation_corr(z_rotation=90.0) a = img.pix_to_ai() code = kpu.run_yolo2(task, img) if code: for i in code: a = img.draw_rectangle(i.rect(),color = (0, 255, 0)) a = img.draw_string(i.x(),i.y(), classes[i.classid()], color=(255,0,0), scale=3) a = lcd.display(img) else: a = lcd.display(img)a = kpu.deinit(task)
Be sure to change the output parameters to fit that in the trained neural network in kpu.set_outputs(task, 0, 7, 7, 35). Now youβre ready to run the program. It is quite easy. Check out the following screenshots.
Note that the quality is very low. This is because maixPy IDE allows us to stream the LCD display to the computer. So the quality is less.
This image detection program can run under 300mA of current. Moreover, it has GPIO pins similar to an Arduino nano board. So the possibilities are numerous. Yet having to program that in python is a big relief too.
I hope this article opens your awareness to a new level of data science. Happy reading!
|
[
{
"code": null,
"e": 438,
"s": 172,
"text": "A few weeks back when I was window shopping at AliExpress I came across the wonderful Maixduino device. It was claimed to carry RISC V architecture along with a KPU (KPU is a general-purpose neural network processor). Contrasting specs of the board were as follows;"
},
{
"code": null,
"e": 476,
"s": 438,
"text": "CPU: RISC-V Dual Core 64bit, with FPU"
},
{
"code": null,
"e": 516,
"s": 476,
"text": "Image Recognition: QVGA@60fps/VGA@30fps"
},
{
"code": null,
"e": 550,
"s": 516,
"text": "Power consumption of chip < 300mW"
},
{
"code": null,
"e": 1006,
"s": 550,
"text": "Truth be told, the unit is old and has only been taking attention lately. Well, given my interest in edge computing I thought of presenting a complete end to end guide for an object detection example. This example is based on knowledge taken from this article by Dimitry. However, Iβll have a comprehensive walkthrough on how to collect images and annotate them as well. If you want to know what edge computing is, feel free to read the following article."
},
{
"code": null,
"e": 1017,
"s": 1006,
"text": "medium.com"
},
{
"code": null,
"e": 1218,
"s": 1017,
"text": "Letβs try to build an image detection program that will be able to border out apples and bananas. You can be creative with your detector. We will discuss required tools and libraries as we move along."
},
{
"code": null,
"e": 1669,
"s": 1218,
"text": "Transfer learning is the idea that we use a pre-trained model for further specialization. In simple terms, you replace the last prediction layer of the trained model with your own classification layer (or more layers). Then you freeze the layers except for yours (or a few of the pre-trained ones too). Then you train the network so that the features of the pre-trained model will be used to fine-tune your layer to predict the classes that you want."
},
{
"code": null,
"e": 1851,
"s": 1669,
"text": "Unfortunately, at the moment the network weβll be training does not have any pre-trained models. Hence, we will be mostly training ground up. But itβll be an interesting experiment!"
},
{
"code": null,
"e": 2197,
"s": 1851,
"text": "We need to prepare the data in the following format. First, we need images with apples and bananas. At the same time, we need them annotated as to where each fruit might be inside the image. This is where the difference between object classification and detection comes. We need to say where the object is. For this, you need the following tool."
},
{
"code": null,
"e": 2208,
"s": 2197,
"text": "github.com"
},
{
"code": null,
"e": 2356,
"s": 2208,
"text": "Or you can use my tool to generate annotated images using your backgrounds and object images (eg: Images from Fruit 360 at Kaggle). Read more here;"
},
{
"code": null,
"e": 2380,
"s": 2356,
"text": "anuradhawick.medium.com"
},
{
"code": null,
"e": 2564,
"s": 2380,
"text": "In my example, I am using the following program as I capture from the webcam. Pick the easy method. The following program comes compiled with Nvidia jetson nano get started container."
},
{
"code": null,
"e": 2575,
"s": 2564,
"text": "github.com"
},
{
"code": null,
"e": 2904,
"s": 2575,
"text": "We want to train our models so that they could run on the MaixDuino device. For this, we can use the following repository. It has all the necessary modifications to the model layers to suit the architecture of the K210 processor. Clone and install the required dependencies. All instructions are available at the following link;"
},
{
"code": null,
"e": 2915,
"s": 2904,
"text": "github.com"
},
{
"code": null,
"e": 2965,
"s": 2915,
"text": "We need to organize our training data as follows;"
},
{
"code": null,
"e": 3139,
"s": 2965,
"text": "path-to/data---anns # store the training annotations---imgs # relevant images for the training---anns_val # validation annotations---imgs_val # validation images"
},
{
"code": null,
"e": 3244,
"s": 3139,
"text": "Now we need to create a config.json to set the training options. For our case it should look like below;"
},
{
"code": null,
"e": 4399,
"s": 3244,
"text": "{ \"model\" : { \"type\": \"Detector\", \"architecture\": \"MobileNet7_5\", \"input_size\": [224,224], \"anchors\": [0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828], \"labels\": [\"Apple\", \"Banana\"], \"coord_scale\" : 1.0, \"class_scale\" : 1.0, \"object_scale\" : 5.0, \"no_object_scale\" : 1.0 }, \"weights\" : { \"full\": \"\", \"backend\": \"imagenet\" }, \"train\" : { \"actual_epoch\": 50, \"train_image_folder\": \"data/imgs\", \"train_annot_folder\": \"data/anns\", \"train_times\": 2, \"valid_image_folder\": \"data/imgs_val\", \"valid_annot_folder\": \"data/anns_val\", \"valid_times\": 2, \"valid_metric\": \"mAP\", \"batch_size\": 4, \"learning_rate\": 1e-4, \"saved_folder\": \"obj_detector\", \"first_trainable_layer\": \"\", \"augumentation\": true, \"is_only_detect\" : false }, \"converter\" : { \"type\": [\"k210\"] }}"
},
{
"code": null,
"e": 4450,
"s": 4399,
"text": "Note: use absolute paths to avoid unwanted errors."
},
{
"code": null,
"e": 4498,
"s": 4450,
"text": "Next, we can train using the following command;"
},
{
"code": null,
"e": 4551,
"s": 4498,
"text": "python3 aXelerate/axelerate/traing.py -c config.json"
},
{
"code": null,
"e": 4728,
"s": 4551,
"text": "Now the training is complete. We are interested in the kmodel file generated within the project folder. We can move it to a microSD card and connect it to the MaixDuino device."
},
{
"code": null,
"e": 4787,
"s": 4728,
"text": "Following is the sketch I will be using in the maixPy IDE."
},
{
"code": null,
"e": 5675,
"s": 4787,
"text": "import sensor,image,lcdimport KPU as kpulcd.init()sensor.reset()sensor.set_pixformat(sensor.RGB565)sensor.set_framesize(sensor.QVGA)sensor.set_windowing((224, 224))sensor.set_vflip(1)sensor.run(1)classes = [\"Apple\", \"Banana\"]task = kpu.load(\"/sd/name_of_the_model_file.kmodel\")a = kpu.set_outputs(task, 0, 7, 7, 35)anchor = (0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828)a = kpu.init_yolo2(task, 0.3, 0.3, 5, anchor) while(True): img = sensor.snapshot().rotation_corr(z_rotation=90.0) a = img.pix_to_ai() code = kpu.run_yolo2(task, img) if code: for i in code: a = img.draw_rectangle(i.rect(),color = (0, 255, 0)) a = img.draw_string(i.x(),i.y(), classes[i.classid()], color=(255,0,0), scale=3) a = lcd.display(img) else: a = lcd.display(img)a = kpu.deinit(task)"
},
{
"code": null,
"e": 5888,
"s": 5675,
"text": "Be sure to change the output parameters to fit that in the trained neural network in kpu.set_outputs(task, 0, 7, 7, 35). Now youβre ready to run the program. It is quite easy. Check out the following screenshots."
},
{
"code": null,
"e": 6027,
"s": 5888,
"text": "Note that the quality is very low. This is because maixPy IDE allows us to stream the LCD display to the computer. So the quality is less."
},
{
"code": null,
"e": 6242,
"s": 6027,
"text": "This image detection program can run under 300mA of current. Moreover, it has GPIO pins similar to an Arduino nano board. So the possibilities are numerous. Yet having to program that in python is a big relief too."
}
] |
MVVM aΜΒΒ Hooking Up ViewModel
|
In this chapter, we will cover how to hook up ViewModel. It is a continuation of the last chapter in which we discussed the View first construction. Now, the next form of the first construction is a meta-pattern which is known as ViewModelLocator. It is a pseudo pattern and is layered on top of the MVVM pattern.
In MVVM each View needs to be hooked up to its ViewModel.
In MVVM each View needs to be hooked up to its ViewModel.
The ViewModelLocator is a simple approach to centralize the code and decoupling the view more.
The ViewModelLocator is a simple approach to centralize the code and decoupling the view more.
It means that it does not have to explicitly know about ViewModel type and how to construct it.
It means that it does not have to explicitly know about ViewModel type and how to construct it.
There are a number of different approaches to use ViewModelLocator, but here we use the most similar to the one that's part of the PRISM framework.
There are a number of different approaches to use ViewModelLocator, but here we use the most similar to the one that's part of the PRISM framework.
ViewModelLocator provides a standard, consistent, declarative and loosely coupled way to do view first construction which automates the process of getting ViewModel hooked up to the View. The following figure represents the high level process of ViewModelLocator.
Step 1 β Figure out which View type is being constructed.
Step 2 β Identify the ViewModel for that particular View type.
Step 3 β Construct that ViewModel.
Step 4 β Set the Views DataContext to the ViewModel.
To understand the basic concept, let's have a look at the simple example of ViewModelLocator by continuing the same example from the last chapter. If you look at the StudentView.xaml file, you will see that we have statically hooked up the ViewModel.
Now as shown in the following program, comment these XAML code also remove the code from Code-behind.
<UserControl x:Class = "MVVMDemo.Views.StudentView"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:local = "clr-namespace:MVVMDemo.Views"
xmlns:viewModel = "clr-namespace:MVVMDemo.ViewModel"
mc:Ignorable = "d" d:DesignHeight = "300" d:DesignWidth = "300">
<!--<UserControl.DataContext>
<viewModel:StudentViewModel/>
</UserControl.DataContext>-->
<Grid>
<StackPanel HorizontalAlignment = "Left">
<ItemsControl ItemsSource = "{Binding Path = Students}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation = "Horizontal">
<TextBox Text = "{Binding Path = FirstName, Mode = TwoWay}"
Width = "100" Margin = "3 5 3 5"/>
<TextBox Text = "{Binding Path = LastName, Mode = TwoWay}"
Width = "100" Margin = "0 5 3 5"/>
<TextBlock Text = "{Binding Path = FullName, Mode = OneWay}"
Margin = "0 5 3 5"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Grid>
</UserControl>
Now letβs create a new folder VML and add a new public class ViewModelLocator which will contain a single attached property (dependency property) AutoHookedUpViewModel as shown in the following code.
public static bool GetAutoHookedUpViewModel(DependencyObject obj) {
return (bool)obj.GetValue(AutoHookedUpViewModelProperty);
}
public static void SetAutoHookedUpViewModel(DependencyObject obj, bool value) {
obj.SetValue(AutoHookedUpViewModelProperty, value);
}
// Using a DependencyProperty as the backing store for AutoHookedUpViewModel.
//This enables animation, styling, binding, etc...
public static readonly DependencyProperty AutoHookedUpViewModelProperty =
DependencyProperty.RegisterAttached("AutoHookedUpViewModel",
typeof(bool), typeof(ViewModelLocator), new PropertyMetadata(false,
AutoHookedUpViewModelChanged));
And now you can see a basic attach property definition. To add behavior to the property, we need to add a changed event handler for this property which contains the automatic process of hooking up the ViewModel for View. The code to do this is as follows β
private static void AutoHookedUpViewModelChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e) {
if (DesignerProperties.GetIsInDesignMode(d)) return;
var viewType = d.GetType();
string str = viewType.FullName;
str = str.Replace(".Views.", ".ViewModel.");
var viewTypeName = str;
var viewModelTypeName = viewTypeName + "Model";
var viewModelType = Type.GetType(viewModelTypeName);
var viewModel = Activator.CreateInstance(viewModelType);
((FrameworkElement)d).DataContext = viewModel;
}
Following is the complete implementation of ViewModelLocator class.
using System;
using System.ComponentModel;
using System.Windows;
namespace MVVMDemo.VML {
public static class ViewModelLocator {
public static bool GetAutoHookedUpViewModel(DependencyObject obj) {
return (bool)obj.GetValue(AutoHookedUpViewModelProperty);
}
public static void SetAutoHookedUpViewModel(DependencyObject obj, bool value) {
obj.SetValue(AutoHookedUpViewModelProperty, value);
}
// Using a DependencyProperty as the backing store for AutoHookedUpViewModel.
//This enables animation, styling, binding, etc...
public static readonly DependencyProperty AutoHookedUpViewModelProperty =
DependencyProperty.RegisterAttached("AutoHookedUpViewModel",
typeof(bool), typeof(ViewModelLocator), new
PropertyMetadata(false, AutoHookedUpViewModelChanged));
private static void AutoHookedUpViewModelChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e) {
if (DesignerProperties.GetIsInDesignMode(d)) return;
var viewType = d.GetType();
string str = viewType.FullName;
str = str.Replace(".Views.", ".ViewModel.");
var viewTypeName = str;
var viewModelTypeName = viewTypeName + "Model";
var viewModelType = Type.GetType(viewModelTypeName);
var viewModel = Activator.CreateInstance(viewModelType);
((FrameworkElement)d).DataContext = viewModel;
}
}
}
First thing to do is to add a namespace so that we can get to that ViewModelLocator type in the root of our project. Then on route element which is a view type, add AutoHookedUpViewModel property and set it to true.
xmlns:vml = "clr-namespace:MVVMDemo.VML"
vml:ViewModelLocator.AutoHookedUpViewModel = "True"
Here is the complete implementation of StudentView.xaml file.
<UserControl x:Class = "MVVMDemo.Views.StudentView"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:local = "clr-namespace:MVVMDemo.Views"
xmlns:viewModel = "clr-namespace:MVVMDemo.ViewModel"
xmlns:vml = "clr-namespace:MVVMDemo.VML"
vml:ViewModelLocator.AutoHookedUpViewModel = "True"
mc:Ignorable = "d" d:DesignHeight = "300" d:DesignWidth = "300">
<!--<UserControl.DataContext>
<viewModel:StudentViewModel/>
</UserControl.DataContext>-->
<Grid>
<StackPanel HorizontalAlignment = "Left">
<ItemsControl ItemsSource = "{Binding Path = Students}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation = "Horizontal">
<TextBox Text = "{Binding Path = FirstName, Mode = TwoWay}"
Width = "100" Margin = "3 5 3 5"/>
<TextBox Text = "{Binding Path = LastName, Mode = TwoWay}"
Width = "100" Margin = "0 5 3 5"/>
<TextBlock Text = "{Binding Path = FullName, Mode = OneWay}"
Margin = "0 5 3 5"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Grid>
</UserControl>
When the above code is compiled and executed, you will see that ViewModelLocator is hooking up the ViewModel for that particular View.
A key thing to notice about this is the view is no longer coupled in a way to what the type of its ViewModel is or how it gets constructed. Thatβs all been moved out to the central location inside the ViewModelLocator.
38 Lectures
2 hours
Skillbakerystudios
22 Lectures
1 hours
CLEMENT OCHIENG
14 Lectures
2 hours
DevTechie
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2256,
"s": 1942,
"text": "In this chapter, we will cover how to hook up ViewModel. It is a continuation of the last chapter in which we discussed the View first construction. Now, the next form of the first construction is a meta-pattern which is known as ViewModelLocator. It is a pseudo pattern and is layered on top of the MVVM pattern."
},
{
"code": null,
"e": 2314,
"s": 2256,
"text": "In MVVM each View needs to be hooked up to its ViewModel."
},
{
"code": null,
"e": 2372,
"s": 2314,
"text": "In MVVM each View needs to be hooked up to its ViewModel."
},
{
"code": null,
"e": 2467,
"s": 2372,
"text": "The ViewModelLocator is a simple approach to centralize the code and decoupling the view more."
},
{
"code": null,
"e": 2562,
"s": 2467,
"text": "The ViewModelLocator is a simple approach to centralize the code and decoupling the view more."
},
{
"code": null,
"e": 2658,
"s": 2562,
"text": "It means that it does not have to explicitly know about ViewModel type and how to construct it."
},
{
"code": null,
"e": 2754,
"s": 2658,
"text": "It means that it does not have to explicitly know about ViewModel type and how to construct it."
},
{
"code": null,
"e": 2902,
"s": 2754,
"text": "There are a number of different approaches to use ViewModelLocator, but here we use the most similar to the one that's part of the PRISM framework."
},
{
"code": null,
"e": 3050,
"s": 2902,
"text": "There are a number of different approaches to use ViewModelLocator, but here we use the most similar to the one that's part of the PRISM framework."
},
{
"code": null,
"e": 3314,
"s": 3050,
"text": "ViewModelLocator provides a standard, consistent, declarative and loosely coupled way to do view first construction which automates the process of getting ViewModel hooked up to the View. The following figure represents the high level process of ViewModelLocator."
},
{
"code": null,
"e": 3372,
"s": 3314,
"text": "Step 1 β Figure out which View type is being constructed."
},
{
"code": null,
"e": 3435,
"s": 3372,
"text": "Step 2 β Identify the ViewModel for that particular View type."
},
{
"code": null,
"e": 3470,
"s": 3435,
"text": "Step 3 β Construct that ViewModel."
},
{
"code": null,
"e": 3523,
"s": 3470,
"text": "Step 4 β Set the Views DataContext to the ViewModel."
},
{
"code": null,
"e": 3774,
"s": 3523,
"text": "To understand the basic concept, let's have a look at the simple example of ViewModelLocator by continuing the same example from the last chapter. If you look at the StudentView.xaml file, you will see that we have statically hooked up the ViewModel."
},
{
"code": null,
"e": 3876,
"s": 3774,
"text": "Now as shown in the following program, comment these XAML code also remove the code from Code-behind."
},
{
"code": null,
"e": 5378,
"s": 3876,
"text": "<UserControl x:Class = \"MVVMDemo.Views.StudentView\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:local = \"clr-namespace:MVVMDemo.Views\" \n xmlns:viewModel = \"clr-namespace:MVVMDemo.ViewModel\" \n mc:Ignorable = \"d\" d:DesignHeight = \"300\" d:DesignWidth = \"300\">\n\t\n <!--<UserControl.DataContext> \n <viewModel:StudentViewModel/> \n </UserControl.DataContext>-->\n\t\n <Grid> \n <StackPanel HorizontalAlignment = \"Left\"> \n <ItemsControl ItemsSource = \"{Binding Path = Students}\">\n <ItemsControl.ItemTemplate> \n <DataTemplate> \n\t\t\t\t\t\n <StackPanel Orientation = \"Horizontal\">\n <TextBox Text = \"{Binding Path = FirstName, Mode = TwoWay}\" \n Width = \"100\" Margin = \"3 5 3 5\"/> \n\t\t\t\t\t\t\t\t\n <TextBox Text = \"{Binding Path = LastName, Mode = TwoWay}\" \n Width = \"100\" Margin = \"0 5 3 5\"/> \n\t\t\t\t\t\t\t\t\n <TextBlock Text = \"{Binding Path = FullName, Mode = OneWay}\" \n Margin = \"0 5 3 5\"/> \n\t\t\t\t\t\t\t\t\n </StackPanel> \n\t\t\t\t\t\t\n </DataTemplate> \n </ItemsControl.ItemTemplate> \n </ItemsControl> \n </StackPanel> \n </Grid>\n\t\n</UserControl>"
},
{
"code": null,
"e": 5578,
"s": 5378,
"text": "Now letβs create a new folder VML and add a new public class ViewModelLocator which will contain a single attached property (dependency property) AutoHookedUpViewModel as shown in the following code."
},
{
"code": null,
"e": 6228,
"s": 5578,
"text": "public static bool GetAutoHookedUpViewModel(DependencyObject obj) { \n return (bool)obj.GetValue(AutoHookedUpViewModelProperty); \n}\n\npublic static void SetAutoHookedUpViewModel(DependencyObject obj, bool value) { \n obj.SetValue(AutoHookedUpViewModelProperty, value); \n}\n\n// Using a DependencyProperty as the backing store for AutoHookedUpViewModel. \n//This enables animation, styling, binding, etc...\n \npublic static readonly DependencyProperty AutoHookedUpViewModelProperty =\n DependencyProperty.RegisterAttached(\"AutoHookedUpViewModel\",\n typeof(bool), typeof(ViewModelLocator), new PropertyMetadata(false,\n AutoHookedUpViewModelChanged));"
},
{
"code": null,
"e": 6485,
"s": 6228,
"text": "And now you can see a basic attach property definition. To add behavior to the property, we need to add a changed event handler for this property which contains the automatic process of hooking up the ViewModel for View. The code to do this is as follows β"
},
{
"code": null,
"e": 7025,
"s": 6485,
"text": "private static void AutoHookedUpViewModelChanged(DependencyObject d, \n DependencyPropertyChangedEventArgs e) { \n if (DesignerProperties.GetIsInDesignMode(d)) return; \n var viewType = d.GetType(); \n string str = viewType.FullName; \n str = str.Replace(\".Views.\", \".ViewModel.\"); \n\t\n var viewTypeName = str; \n var viewModelTypeName = viewTypeName + \"Model\"; \n var viewModelType = Type.GetType(viewModelTypeName); \n var viewModel = Activator.CreateInstance(viewModelType);\n ((FrameworkElement)d).DataContext = viewModel; \n}"
},
{
"code": null,
"e": 7093,
"s": 7025,
"text": "Following is the complete implementation of ViewModelLocator class."
},
{
"code": null,
"e": 8591,
"s": 7093,
"text": "using System; \nusing System.ComponentModel; \nusing System.Windows;\n\nnamespace MVVMDemo.VML { \n\n public static class ViewModelLocator { \n\t\n public static bool GetAutoHookedUpViewModel(DependencyObject obj) {\n return (bool)obj.GetValue(AutoHookedUpViewModelProperty); \n }\n\t\t\n public static void SetAutoHookedUpViewModel(DependencyObject obj, bool value) { \n obj.SetValue(AutoHookedUpViewModelProperty, value); \n }\n\t\t\n // Using a DependencyProperty as the backing store for AutoHookedUpViewModel. \n\t\t\n //This enables animation, styling, binding, etc...\n public static readonly DependencyProperty AutoHookedUpViewModelProperty =\n DependencyProperty.RegisterAttached(\"AutoHookedUpViewModel\", \n typeof(bool), typeof(ViewModelLocator), new\n PropertyMetadata(false, AutoHookedUpViewModelChanged));\n\t\t\n private static void AutoHookedUpViewModelChanged(DependencyObject d,\n DependencyPropertyChangedEventArgs e) { \n if (DesignerProperties.GetIsInDesignMode(d)) return; \n var viewType = d.GetType(); \n\t\t\t\n string str = viewType.FullName; \n str = str.Replace(\".Views.\", \".ViewModel.\"); \n\t\t\t\n var viewTypeName = str; \n var viewModelTypeName = viewTypeName + \"Model\";\n var viewModelType = Type.GetType(viewModelTypeName); \n var viewModel = Activator.CreateInstance(viewModelType);\n\t\t\t\n ((FrameworkElement)d).DataContext = viewModel; \n } \n } \n}"
},
{
"code": null,
"e": 8807,
"s": 8591,
"text": "First thing to do is to add a namespace so that we can get to that ViewModelLocator type in the root of our project. Then on route element which is a view type, add AutoHookedUpViewModel property and set it to true."
},
{
"code": null,
"e": 8900,
"s": 8807,
"text": "xmlns:vml = \"clr-namespace:MVVMDemo.VML\"\nvml:ViewModelLocator.AutoHookedUpViewModel = \"True\""
},
{
"code": null,
"e": 8962,
"s": 8900,
"text": "Here is the complete implementation of StudentView.xaml file."
},
{
"code": null,
"e": 10567,
"s": 8962,
"text": "<UserControl x:Class = \"MVVMDemo.Views.StudentView\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:local = \"clr-namespace:MVVMDemo.Views\" \n xmlns:viewModel = \"clr-namespace:MVVMDemo.ViewModel\" \n xmlns:vml = \"clr-namespace:MVVMDemo.VML\" \n vml:ViewModelLocator.AutoHookedUpViewModel = \"True\" \n mc:Ignorable = \"d\" d:DesignHeight = \"300\" d:DesignWidth = \"300\">\n \n <!--<UserControl.DataContext> \n <viewModel:StudentViewModel/> \n </UserControl.DataContext>-->\n\n <Grid> \n <StackPanel HorizontalAlignment = \"Left\"> \n <ItemsControl ItemsSource = \"{Binding Path = Students}\"> \n <ItemsControl.ItemTemplate> \n <DataTemplate> \n\t\t\t\t\t\n <StackPanel Orientation = \"Horizontal\"> \n <TextBox Text = \"{Binding Path = FirstName, Mode = TwoWay}\" \n Width = \"100\" Margin = \"3 5 3 5\"/> \n\t\t\t\t\t\t\t\t\n <TextBox Text = \"{Binding Path = LastName, Mode = TwoWay}\" \n Width = \"100\" Margin = \"0 5 3 5\"/>\n\t\t\t\t\t\t\t\t\n <TextBlock Text = \"{Binding Path = FullName, Mode = OneWay}\" \n Margin = \"0 5 3 5\"/> \n\t\t\t\t\t\t\t\t\n </StackPanel> \n\t\t\t\t\t\t\n </DataTemplate> \n </ItemsControl.ItemTemplate> \n </ItemsControl> \n </StackPanel>\n </Grid> \n\t\n</UserControl>"
},
{
"code": null,
"e": 10702,
"s": 10567,
"text": "When the above code is compiled and executed, you will see that ViewModelLocator is hooking up the ViewModel for that particular View."
},
{
"code": null,
"e": 10921,
"s": 10702,
"text": "A key thing to notice about this is the view is no longer coupled in a way to what the type of its ViewModel is or how it gets constructed. Thatβs all been moved out to the central location inside the ViewModelLocator."
},
{
"code": null,
"e": 10954,
"s": 10921,
"text": "\n 38 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 10974,
"s": 10954,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 11007,
"s": 10974,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 11024,
"s": 11007,
"text": " CLEMENT OCHIENG"
},
{
"code": null,
"e": 11057,
"s": 11024,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 11068,
"s": 11057,
"text": " DevTechie"
},
{
"code": null,
"e": 11075,
"s": 11068,
"text": " Print"
},
{
"code": null,
"e": 11086,
"s": 11075,
"text": " Add Notes"
}
] |
strpbrk() in C
|
The function strpbrk() is used to find the first character of first string and matches it to any character of second string. It returns NULL, if no matches are found otherwise, it returns a pointer to the character of first string that matches to the character of second string.
Here is the syntax of strpbrk() in C language,
char *strpbrk(const char *string1, const char *string2)
Here is an example of strpbrk() in C language,
Live Demo
#include <stdio.h>
#include <string.h>
int main () {
const char s1[] = "Helloworld";
const char s2[] = "Blank";
char *result;
result = strpbrk(s1, s2);
printf("The matching character : %c\n", *result);
return(0);
}
The matching character : l
|
[
{
"code": null,
"e": 1341,
"s": 1062,
"text": "The function strpbrk() is used to find the first character of first string and matches it to any character of second string. It returns NULL, if no matches are found otherwise, it returns a pointer to the character of first string that matches to the character of second string."
},
{
"code": null,
"e": 1388,
"s": 1341,
"text": "Here is the syntax of strpbrk() in C language,"
},
{
"code": null,
"e": 1444,
"s": 1388,
"text": "char *strpbrk(const char *string1, const char *string2)"
},
{
"code": null,
"e": 1491,
"s": 1444,
"text": "Here is an example of strpbrk() in C language,"
},
{
"code": null,
"e": 1502,
"s": 1491,
"text": " Live Demo"
},
{
"code": null,
"e": 1735,
"s": 1502,
"text": "#include <stdio.h>\n#include <string.h>\nint main () {\n const char s1[] = \"Helloworld\";\n const char s2[] = \"Blank\";\n char *result;\n result = strpbrk(s1, s2);\n printf(\"The matching character : %c\\n\", *result);\n return(0);\n}"
},
{
"code": null,
"e": 1762,
"s": 1735,
"text": "The matching character : l"
}
] |
GPT-3: Creative Potential of NLP. New ML milestone by OpenAI β in action | by Merzmensch | Towards Data Science
|
Updated: 18th of November 2021: βaccess without waitlistβ
It was last year in February, as OpenAI published results on their training of unsupervised language model GPT-2. Trained in 40Gb texts (8 Mio websites) and was able to predict words in proximity. GPT-2, a transformer-based language applied to self-attention, allowed us to generated very convincing and coherent texts. The quality was that good, so the main model with 1.5 billion parameters wasnβt initially publicly accessible, to prevent uncontrolled fake news. Luckily, the complete model was later published and could be even used with Colab Notebooks.
This year OpenAI strikes back with new language model GPT-3. With 175 billion parameters (read also: GPT-3 Paper).Unnecessary spoiler: itβs incredibly good.
There are already some profound articles on TDS examining features and paper of GPT-3:
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
OpenAI is building an API, currently accessible via waiting list:
beta.openai.com
Fortunately, I could get access and experiment with GPT-3 directly. Here are some of my initial outcomes.
Update (18.11.2021): OpenAIβs API is now available with no waitlist.
The AI Playground interface looks simple, but it bears the power within. For the first, here is a setting dialog, which lets you configure text length, temperature (from low/boring to standard to chaotic/creative), and other features.
You also can define where the generated text has to start and to stop, these are some of the control functions that have a direct impact on textual results.
The simple interface provides also some GPT-3 presets. The amazing thing about transformer-driven GPT-models is among others the ability to recognize a specific style, text character, or structure. In case you begin with lists, GPT-3 continues generating lists. In case your prompt has a Q&A structure, it will be kept coherently. If you ask for a poem, it writes a poem.
You can do your own presets, or use the existing, which are:
Chat.
A typical setting for a chatbot. You ask - AI answers. Itβs possible to change the βcharactersβ or setting also. As you can see, the chat situation was accomplished perfectly (even if my, Humanβs, third question was kind of unfair).
To demonstrate the contextual impact, letβs change the AI character from βhelpfulβ and βvery friendlyβ to βbrutal, stupid and very unfriendlyβ. You will see how the whole dialogue will be influenced:
I think, we re-invented Marvin the Paranoid Android.
Q&A
This preset consists of a clear dual structure: Question and Answer. You need some training before it starts to answer the question (and get the rules), but then it works perfectly. I asked some random questions from various areas and here you go:
Iβd say, perfect!
Parsing unstructured data
This one is fascinating and shows a good comprehension of the unstructured text β extracting structured data from the full text.
Summarizing for a 2nd grader
This preset shows another level of comprehension β including rephrasing of difficult concepts and sentences in clear words.
I tried Wittgenstein:
The simple proverb can be paraphrased convincingly:
Or look at this pretty well and clear transition of Sigmund Freudβs time distancing concept:
As you see, compression of text and its coherent βtranslationβ is one of the strengths of GPT-3.
GPT-2 was already a great language model when it was about English. You could generate amazing texts, especially with 1.5 billion parameters. I used GPT-2 for a screenplay of this short movie β and its absurdity could be rather understood as a good tradition of David Lynch and Beckett:
Clip ID: 424315654
Delivery:application/vnd.vimeo.dash+json
Embed Size:692Γ389
Separate AV:true
Dropped Frames:0 / 0 - 0
Playhead / Buffer:0 / 0 / 0
Bandwidth:0(0 Kbps0 Kbps)
The dialogues were logical, even if spontaneous. But it was regarding English. If youβve tried with inputs in other languages, you would face the barrier of understanding. GPT-2 tried to imitate languages, but you needed to fine-tune it on text corpus in a specific language to get good results.
GPT-3 is different.
Its processing in other languages is phenomenal.
I tried German, Russian, and Japanese.
German.
It was rather my daughter, who tried to let GPT-3 write a fairy tale. She began with βEine Katze mit FluΜgeln ging im Park spazierenβ (βA cat with wings took a walk in a parkβ).
The emerged story was astonishingly well written. With irony, vivid characters, and some leitmotifs. This is not just a collection of topoi or connected sentences. This is... a story!
Russian.
I trained once GPT-2 on Pushkinβs poetry and have got some interesting neologisms, but it was a grammar mess. Here I input some lines of Pushkinβs poem β and the result Iβve got was... interesting. It hadnβt rhymes, but stylistically intense power. It was not Pushkin style, though. But almost without any mistakes or weird grammar. And... it works as poetry (especially if you are ready to interpret it).
Japanese.
This was something special. I entered just a random sentence:
δ»ζ₯γ―ζ₯½γγδΈζ₯γ«γͺγγΎγγγγ«!γ¨θ¨γγΎγγγ// Today was funny and entertaining day, I said.
And the result was a small story about prayer, happiness, wisdom, and financial investment. In well written Japanese (neutral politeness form, like the input).
It does mean: GPT-3 is ready for multilingual text processing.
My first try was, of course, to write a Shakespearean sonnet. So the prompt was just:
here is a poem by Shakespeare
The result was this:
Perfect iambic verse, great style, nice rhymes... If not one thing:
The first two lines are actually from Alexander Pope, The Rape of the Lock. And here we have a reason to be cautious: GPT-3 produces unique and unrepeatable texts, but it can reuse the whole quotes of existing texts it was trained on.
Re-examination of results is inevitable if you want to guarantee a singularity of a text.
I wonder, if there are some possibilities for βProjectionβ like StyleGAN2 feature, just in opposite to StyleGAN2 (where it compares the image with latent space), in GPT-3 it would compare with the dataset it was trained on? To prevent accidental plagiarism.
But the thing is: GPT-3 can write poems on demand, in particular styles.
Here is another example:
As I still hadnβt accessed, I asked a friend to let GPT-3 write an essay on Kurt Schwitters, a German artist, and Dadaist:
The outcome is: GPT-3 has already a rich knowledge, which can be recollected. It is not always reliable (you have to fine-tune it to have a perfect meaning match), but itβs still very close to the discourse.
Another mindblowing possibility is using GPT-3 is quite different cases than just text generation:
You can get support by CSS:
And calling it General Intelligence is already a thing:
We are still at the beginning, but the experiments with GPT-3 made by the AI community show its power, potential, and impact. We just have to use it with reason and good intention. But thatβs the human factor. Which is not always the best one.
For more wonderful text experiments I highly recommend you to read Gwern:
|
[
{
"code": null,
"e": 230,
"s": 172,
"text": "Updated: 18th of November 2021: βaccess without waitlistβ"
},
{
"code": null,
"e": 789,
"s": 230,
"text": "It was last year in February, as OpenAI published results on their training of unsupervised language model GPT-2. Trained in 40Gb texts (8 Mio websites) and was able to predict words in proximity. GPT-2, a transformer-based language applied to self-attention, allowed us to generated very convincing and coherent texts. The quality was that good, so the main model with 1.5 billion parameters wasnβt initially publicly accessible, to prevent uncontrolled fake news. Luckily, the complete model was later published and could be even used with Colab Notebooks."
},
{
"code": null,
"e": 946,
"s": 789,
"text": "This year OpenAI strikes back with new language model GPT-3. With 175 billion parameters (read also: GPT-3 Paper).Unnecessary spoiler: itβs incredibly good."
},
{
"code": null,
"e": 1033,
"s": 946,
"text": "There are already some profound articles on TDS examining features and paper of GPT-3:"
},
{
"code": null,
"e": 1056,
"s": 1033,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1079,
"s": 1056,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1102,
"s": 1079,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1168,
"s": 1102,
"text": "OpenAI is building an API, currently accessible via waiting list:"
},
{
"code": null,
"e": 1184,
"s": 1168,
"text": "beta.openai.com"
},
{
"code": null,
"e": 1290,
"s": 1184,
"text": "Fortunately, I could get access and experiment with GPT-3 directly. Here are some of my initial outcomes."
},
{
"code": null,
"e": 1359,
"s": 1290,
"text": "Update (18.11.2021): OpenAIβs API is now available with no waitlist."
},
{
"code": null,
"e": 1594,
"s": 1359,
"text": "The AI Playground interface looks simple, but it bears the power within. For the first, here is a setting dialog, which lets you configure text length, temperature (from low/boring to standard to chaotic/creative), and other features."
},
{
"code": null,
"e": 1751,
"s": 1594,
"text": "You also can define where the generated text has to start and to stop, these are some of the control functions that have a direct impact on textual results."
},
{
"code": null,
"e": 2123,
"s": 1751,
"text": "The simple interface provides also some GPT-3 presets. The amazing thing about transformer-driven GPT-models is among others the ability to recognize a specific style, text character, or structure. In case you begin with lists, GPT-3 continues generating lists. In case your prompt has a Q&A structure, it will be kept coherently. If you ask for a poem, it writes a poem."
},
{
"code": null,
"e": 2184,
"s": 2123,
"text": "You can do your own presets, or use the existing, which are:"
},
{
"code": null,
"e": 2190,
"s": 2184,
"text": "Chat."
},
{
"code": null,
"e": 2423,
"s": 2190,
"text": "A typical setting for a chatbot. You ask - AI answers. Itβs possible to change the βcharactersβ or setting also. As you can see, the chat situation was accomplished perfectly (even if my, Humanβs, third question was kind of unfair)."
},
{
"code": null,
"e": 2623,
"s": 2423,
"text": "To demonstrate the contextual impact, letβs change the AI character from βhelpfulβ and βvery friendlyβ to βbrutal, stupid and very unfriendlyβ. You will see how the whole dialogue will be influenced:"
},
{
"code": null,
"e": 2676,
"s": 2623,
"text": "I think, we re-invented Marvin the Paranoid Android."
},
{
"code": null,
"e": 2680,
"s": 2676,
"text": "Q&A"
},
{
"code": null,
"e": 2928,
"s": 2680,
"text": "This preset consists of a clear dual structure: Question and Answer. You need some training before it starts to answer the question (and get the rules), but then it works perfectly. I asked some random questions from various areas and here you go:"
},
{
"code": null,
"e": 2946,
"s": 2928,
"text": "Iβd say, perfect!"
},
{
"code": null,
"e": 2972,
"s": 2946,
"text": "Parsing unstructured data"
},
{
"code": null,
"e": 3101,
"s": 2972,
"text": "This one is fascinating and shows a good comprehension of the unstructured text β extracting structured data from the full text."
},
{
"code": null,
"e": 3130,
"s": 3101,
"text": "Summarizing for a 2nd grader"
},
{
"code": null,
"e": 3254,
"s": 3130,
"text": "This preset shows another level of comprehension β including rephrasing of difficult concepts and sentences in clear words."
},
{
"code": null,
"e": 3276,
"s": 3254,
"text": "I tried Wittgenstein:"
},
{
"code": null,
"e": 3328,
"s": 3276,
"text": "The simple proverb can be paraphrased convincingly:"
},
{
"code": null,
"e": 3421,
"s": 3328,
"text": "Or look at this pretty well and clear transition of Sigmund Freudβs time distancing concept:"
},
{
"code": null,
"e": 3518,
"s": 3421,
"text": "As you see, compression of text and its coherent βtranslationβ is one of the strengths of GPT-3."
},
{
"code": null,
"e": 3805,
"s": 3518,
"text": "GPT-2 was already a great language model when it was about English. You could generate amazing texts, especially with 1.5 billion parameters. I used GPT-2 for a screenplay of this short movie β and its absurdity could be rather understood as a good tradition of David Lynch and Beckett:"
},
{
"code": null,
"e": 3824,
"s": 3805,
"text": "Clip ID: 424315654"
},
{
"code": null,
"e": 3865,
"s": 3824,
"text": "Delivery:application/vnd.vimeo.dash+json"
},
{
"code": null,
"e": 3885,
"s": 3865,
"text": "Embed Size:692Γ389 "
},
{
"code": null,
"e": 3902,
"s": 3885,
"text": "Separate AV:true"
},
{
"code": null,
"e": 3927,
"s": 3902,
"text": "Dropped Frames:0 / 0 - 0"
},
{
"code": null,
"e": 3955,
"s": 3927,
"text": "Playhead / Buffer:0 / 0 / 0"
},
{
"code": null,
"e": 3981,
"s": 3955,
"text": "Bandwidth:0(0 Kbps0 Kbps)"
},
{
"code": null,
"e": 4277,
"s": 3981,
"text": "The dialogues were logical, even if spontaneous. But it was regarding English. If youβve tried with inputs in other languages, you would face the barrier of understanding. GPT-2 tried to imitate languages, but you needed to fine-tune it on text corpus in a specific language to get good results."
},
{
"code": null,
"e": 4297,
"s": 4277,
"text": "GPT-3 is different."
},
{
"code": null,
"e": 4346,
"s": 4297,
"text": "Its processing in other languages is phenomenal."
},
{
"code": null,
"e": 4385,
"s": 4346,
"text": "I tried German, Russian, and Japanese."
},
{
"code": null,
"e": 4393,
"s": 4385,
"text": "German."
},
{
"code": null,
"e": 4571,
"s": 4393,
"text": "It was rather my daughter, who tried to let GPT-3 write a fairy tale. She began with βEine Katze mit FluΜgeln ging im Park spazierenβ (βA cat with wings took a walk in a parkβ)."
},
{
"code": null,
"e": 4755,
"s": 4571,
"text": "The emerged story was astonishingly well written. With irony, vivid characters, and some leitmotifs. This is not just a collection of topoi or connected sentences. This is... a story!"
},
{
"code": null,
"e": 4764,
"s": 4755,
"text": "Russian."
},
{
"code": null,
"e": 5170,
"s": 4764,
"text": "I trained once GPT-2 on Pushkinβs poetry and have got some interesting neologisms, but it was a grammar mess. Here I input some lines of Pushkinβs poem β and the result Iβve got was... interesting. It hadnβt rhymes, but stylistically intense power. It was not Pushkin style, though. But almost without any mistakes or weird grammar. And... it works as poetry (especially if you are ready to interpret it)."
},
{
"code": null,
"e": 5180,
"s": 5170,
"text": "Japanese."
},
{
"code": null,
"e": 5242,
"s": 5180,
"text": "This was something special. I entered just a random sentence:"
},
{
"code": null,
"e": 5315,
"s": 5242,
"text": "δ»ζ₯γ―ζ₯½γγδΈζ₯γ«γͺγγΎγγγγ«!γ¨θ¨γγΎγγγ// Today was funny and entertaining day, I said."
},
{
"code": null,
"e": 5475,
"s": 5315,
"text": "And the result was a small story about prayer, happiness, wisdom, and financial investment. In well written Japanese (neutral politeness form, like the input)."
},
{
"code": null,
"e": 5538,
"s": 5475,
"text": "It does mean: GPT-3 is ready for multilingual text processing."
},
{
"code": null,
"e": 5624,
"s": 5538,
"text": "My first try was, of course, to write a Shakespearean sonnet. So the prompt was just:"
},
{
"code": null,
"e": 5654,
"s": 5624,
"text": "here is a poem by Shakespeare"
},
{
"code": null,
"e": 5675,
"s": 5654,
"text": "The result was this:"
},
{
"code": null,
"e": 5743,
"s": 5675,
"text": "Perfect iambic verse, great style, nice rhymes... If not one thing:"
},
{
"code": null,
"e": 5978,
"s": 5743,
"text": "The first two lines are actually from Alexander Pope, The Rape of the Lock. And here we have a reason to be cautious: GPT-3 produces unique and unrepeatable texts, but it can reuse the whole quotes of existing texts it was trained on."
},
{
"code": null,
"e": 6068,
"s": 5978,
"text": "Re-examination of results is inevitable if you want to guarantee a singularity of a text."
},
{
"code": null,
"e": 6326,
"s": 6068,
"text": "I wonder, if there are some possibilities for βProjectionβ like StyleGAN2 feature, just in opposite to StyleGAN2 (where it compares the image with latent space), in GPT-3 it would compare with the dataset it was trained on? To prevent accidental plagiarism."
},
{
"code": null,
"e": 6399,
"s": 6326,
"text": "But the thing is: GPT-3 can write poems on demand, in particular styles."
},
{
"code": null,
"e": 6424,
"s": 6399,
"text": "Here is another example:"
},
{
"code": null,
"e": 6547,
"s": 6424,
"text": "As I still hadnβt accessed, I asked a friend to let GPT-3 write an essay on Kurt Schwitters, a German artist, and Dadaist:"
},
{
"code": null,
"e": 6755,
"s": 6547,
"text": "The outcome is: GPT-3 has already a rich knowledge, which can be recollected. It is not always reliable (you have to fine-tune it to have a perfect meaning match), but itβs still very close to the discourse."
},
{
"code": null,
"e": 6854,
"s": 6755,
"text": "Another mindblowing possibility is using GPT-3 is quite different cases than just text generation:"
},
{
"code": null,
"e": 6882,
"s": 6854,
"text": "You can get support by CSS:"
},
{
"code": null,
"e": 6938,
"s": 6882,
"text": "And calling it General Intelligence is already a thing:"
},
{
"code": null,
"e": 7182,
"s": 6938,
"text": "We are still at the beginning, but the experiments with GPT-3 made by the AI community show its power, potential, and impact. We just have to use it with reason and good intention. But thatβs the human factor. Which is not always the best one."
}
] |
How to get all CSS styles associated with an element using jQuery ?
|
12 Dec, 2021
In this article, we will know how to get the applied CSS properties associated with the elements using jQuery, & will also understand its implementation through the example. Given an HTML document containing some CSS properties and we need to retrieve all the CSS styles of a particular element by using jQuery. The two approaches are as follows.
Approach 1: In this approach, we will use the document.defaultView.getComputedStyle() method to get all the cascading styles associated with that particular element. After that, append the style to a string one by one by traversing the object.
Please refer to the HTML DOM defaultView Property & getComputedStyle() method for further details.
Example: This example implements the document.defaultView.getComputedStyle() method to retrieve the various applied styling properties associated with the particular element.
HTML
<!DOCTYPE HTML><html> <head> <title> Getting all the CSS styles of an element using jQuery </title></head> <body style="text-align:center;"> <h1>GeeksforGeeks</h1> <p id="GFG_UP"></p> <button onclick="GFG_Fun();"> Click Here </button> <p id="GFG_DOWN"></p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on the button " + "to get the all CSS styles " + "associated with the element."; function GFG_Fun() { var ar = document.defaultView.getComputedStyle(up, null); var str = ""; for(var key in ar) { str = str + key + ': ' + ar[key] + "-"; } down.innerHTML = str; } </script></body> </html>
Output:
Approach 2: In this approach, only specific styles are getting extracted. We can pass the name of the styles. The method cssSpecific is defined that performing the string operations on the passed string and getting the properties from the object, and returning them as a string.
Example: This example is implemented to retrieve only the specific styling properties associated with an element.
HTML
<!DOCTYPE HTML><html> <head> <title> Getting all the CSS styles of an element using jQuery </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1>GeeksforGeeks</h1> <p id="GFG_UP"></p> <button onclick="GFG_Fun();"> Click Here </button> <p id="GFG_DOWN"></p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on the button to get" + " only specific CSS styles associated " + "with the element."; (function($) { $.fn.cssSpecific = function(str) { var ob = {}; if(this.length) { var css = str.split(', '); var prms = []; for(var i = 0, ii = css.length; i < ii; i++) { prms = css[i].split(':'); ob[$.trim(prms[0])] = $(this).css($.trim(prms[1] || prms[0])); } } return ob; }; })(jQuery); function GFG_Fun() { var styles = $('#GFG_UP').cssSpecific('color, backgroundColor, opacity, height, lineHeight:height'); down.innerHTML = JSON.stringify(styles); } </script></body> </html>
Output:
bhaskargeeksforgeeks
varshagumber28
CSS-Misc
HTML-Misc
jQuery-Misc
Picked
CSS
HTML
JQuery
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Dec, 2021"
},
{
"code": null,
"e": 375,
"s": 28,
"text": "In this article, we will know how to get the applied CSS properties associated with the elements using jQuery, & will also understand its implementation through the example. Given an HTML document containing some CSS properties and we need to retrieve all the CSS styles of a particular element by using jQuery. The two approaches are as follows."
},
{
"code": null,
"e": 619,
"s": 375,
"text": "Approach 1: In this approach, we will use the document.defaultView.getComputedStyle() method to get all the cascading styles associated with that particular element. After that, append the style to a string one by one by traversing the object."
},
{
"code": null,
"e": 718,
"s": 619,
"text": "Please refer to the HTML DOM defaultView Property & getComputedStyle() method for further details."
},
{
"code": null,
"e": 893,
"s": 718,
"text": "Example: This example implements the document.defaultView.getComputedStyle() method to retrieve the various applied styling properties associated with the particular element."
},
{
"code": null,
"e": 898,
"s": 893,
"text": "HTML"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Getting all the CSS styles of an element using jQuery </title></head> <body style=\"text-align:center;\"> <h1>GeeksforGeeks</h1> <p id=\"GFG_UP\"></p> <button onclick=\"GFG_Fun();\"> Click Here </button> <p id=\"GFG_DOWN\"></p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = \"Click on the button \" + \"to get the all CSS styles \" + \"associated with the element.\"; function GFG_Fun() { var ar = document.defaultView.getComputedStyle(up, null); var str = \"\"; for(var key in ar) { str = str + key + ': ' + ar[key] + \"-\"; } down.innerHTML = str; } </script></body> </html>",
"e": 1680,
"s": 898,
"text": null
},
{
"code": null,
"e": 1688,
"s": 1680,
"text": "Output:"
},
{
"code": null,
"e": 1967,
"s": 1688,
"text": "Approach 2: In this approach, only specific styles are getting extracted. We can pass the name of the styles. The method cssSpecific is defined that performing the string operations on the passed string and getting the properties from the object, and returning them as a string."
},
{
"code": null,
"e": 2081,
"s": 1967,
"text": "Example: This example is implemented to retrieve only the specific styling properties associated with an element."
},
{
"code": null,
"e": 2086,
"s": 2081,
"text": "HTML"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Getting all the CSS styles of an element using jQuery </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1>GeeksforGeeks</h1> <p id=\"GFG_UP\"></p> <button onclick=\"GFG_Fun();\"> Click Here </button> <p id=\"GFG_DOWN\"></p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = \"Click on the button to get\" + \" only specific CSS styles associated \" + \"with the element.\"; (function($) { $.fn.cssSpecific = function(str) { var ob = {}; if(this.length) { var css = str.split(', '); var prms = []; for(var i = 0, ii = css.length; i < ii; i++) { prms = css[i].split(':'); ob[$.trim(prms[0])] = $(this).css($.trim(prms[1] || prms[0])); } } return ob; }; })(jQuery); function GFG_Fun() { var styles = $('#GFG_UP').cssSpecific('color, backgroundColor, opacity, height, lineHeight:height'); down.innerHTML = JSON.stringify(styles); } </script></body> </html>",
"e": 3384,
"s": 2086,
"text": null
},
{
"code": null,
"e": 3392,
"s": 3384,
"text": "Output:"
},
{
"code": null,
"e": 3413,
"s": 3392,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 3428,
"s": 3413,
"text": "varshagumber28"
},
{
"code": null,
"e": 3437,
"s": 3428,
"text": "CSS-Misc"
},
{
"code": null,
"e": 3447,
"s": 3437,
"text": "HTML-Misc"
},
{
"code": null,
"e": 3459,
"s": 3447,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 3466,
"s": 3459,
"text": "Picked"
},
{
"code": null,
"e": 3470,
"s": 3466,
"text": "CSS"
},
{
"code": null,
"e": 3475,
"s": 3470,
"text": "HTML"
},
{
"code": null,
"e": 3482,
"s": 3475,
"text": "JQuery"
},
{
"code": null,
"e": 3499,
"s": 3482,
"text": "Web Technologies"
},
{
"code": null,
"e": 3526,
"s": 3499,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3531,
"s": 3526,
"text": "HTML"
}
] |
Print all leaf nodes of a binary tree from right to left
|
06 Aug, 2021
Given a binary tree, the task is to print all the leaf nodes of the binary tree from right to left.
Examples:
Input :
1
/ \
2 3
/ \ / \
4 5 6 7
Output : 7 6 5 4
Input :
1
/ \
2 3
/ \ \
4 5 6
/ / \
7 8 9
Output : 9 8 7 4
Recursive Approach: Traverse the tree in Preorder fashion, by first processing the root, then right subtree and then left subtree and do the following:
Check if the root is null then return from the function.
If it is a leaf node then print it.
If not then check if it has right child, if yes then call function for right child of the node recursively.
Check if it has left child, if yes then call function for left child of the node recursively.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to print leaf nodes from right to left #include <iostream>using namespace std; // A Binary Tree Nodestruct Node { int data; struct Node *left, *right;}; // Utility function to create a new tree nodeNode* newNode(int data){ Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Function to print leaf// nodes from right to leftvoid printLeafNodes(Node* root){ // If node is null, return if (!root) return; // If node is leaf node, print its data if (!root->left && !root->right) { cout << root->data << " "; return; } // If right child exists, check for leaf // recursively if (root->right) printLeafNodes(root->right); // If left child exists, check for leaf // recursively if (root->left) printLeafNodes(root->left);} // Driver codeint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->right->right->left = newNode(9); root->left->left->left->right = newNode(10); printLeafNodes(root); return 0;}
// Java program to print leaf nodes from right to leftimport java.util.*; class GFG{ // A Binary Tree Nodestatic class Node{ int data; Node left, right;}; // Utility function to create a new tree nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function to print leaf// nodes from right to leftstatic void printLeafNodes(Node root){ // If node is null, return if (root == null) return; // If node is leaf node, print its data if (root.left == null && root.right == null) { System.out.print( root.data +" "); return; } // If right child exists, check for leaf // recursively if (root.right != null) printLeafNodes(root.right); // If left child exists, check for leaf // recursively if (root.left != null) printLeafNodes(root.left);} // Driver codepublic static void main(String args[]){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); root.left.left.left = newNode(8); root.right.right.left = newNode(9); root.left.left.left.right = newNode(10); printLeafNodes(root);}} // This code is contributed by Arnab Kundu
# Python3 program to print# leaf nodes from right to left # Binary tree nodeclass newNode: def __init__(self, data): self.data = data self.left = None self.right = None # Function to print leaf# nodes from right to leftdef printLeafNodes(root): # If node is null, return if root == None: return # If node is leaf node, # print its data if (root.left == None and root.right == None): print(root.data, end = " ") return # If right child exists, # check for leaf recursively if root.right: printLeafNodes(root.right) # If left child exists, # check for leaf recursively if root.left: printLeafNodes(root.left) # Driver coderoot = newNode(1)root.left = newNode(2)root.right = newNode(3)root.left.left = newNode(4)root.left.right = newNode(5)root.right.left = newNode(6)root.right.right = newNode(7)root.left.left.left = newNode(8)root.right.right.left = newNode(9)root.left.left.left.right = newNode(10) printLeafNodes(root) # This code is contributed by SHUBHAMSINGH10
using System; // C# program to print leaf nodes from right to leftclass GFG{ // A Binary Tree Nodepublic class Node{ public int data; public Node left, right;} // Utility function to create a new tree nodepublic static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function to print leaf// nodes from right to leftpublic static void printLeafNodes(Node root){ // If node is null, return if (root == null) { return; } // If node is leaf node, print its data if (root.left == null && root.right == null) { Console.Write(root.data + " "); return; } // If right child exists, check for leaf // recursively if (root.right != null) { printLeafNodes(root.right); } // If left child exists, check for leaf // recursively if (root.left != null) { printLeafNodes(root.left); }} // Driver codepublic static void Main(string[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); root.left.left.left = newNode(8); root.right.right.left = newNode(9); root.left.left.left.right = newNode(10); printLeafNodes(root);}} // This code is contributed by shrikanth13
<script> // JavaScript program to print leaf nodes from right to left // A Binary Tree Nodeclass Node{ constructor() { this.data = 0; this.right = null; this.left = null; }} // Utility function to create a new tree nodefunction newNode(data){ var temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function to print leaf// nodes from right to leftfunction printLeafNodes(root){ // If node is null, return if (root == null) { return; } // If node is leaf node, print its data if (root.left == null && root.right == null) { document.write(root.data + " "); return; } // If right child exists, check for leaf // recursively if (root.right != null) { printLeafNodes(root.right); } // If left child exists, check for leaf // recursively if (root.left != null) { printLeafNodes(root.left); }} // Driver codevar root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(4);root.left.right = newNode(5);root.right.left = newNode(6);root.right.right = newNode(7);root.left.left.left = newNode(8);root.right.right.left = newNode(9);root.left.left.left.right = newNode(10);printLeafNodes(root); </script>
9 6 5 10
Iterative Approach: The idea is to perform iterative postorder traversal using one stack, but in a modified manner, first, we will visit the right subtree and then the left subtree and finally the root node and print the leaf nodes.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to print leaf nodes from// right to left using one stack #include<bits/stdc++.h>using namespace std; // Structure of binary treestruct Node { Node* left; Node* right; int data;}; // Function to create a new nodeNode* newNode(int key){ Node* node = new Node(); node->left = node->right = NULL; node->data = key; return node;} // Function to Print all the leaf nodes// of Binary tree using one stackvoid printLeafRightToLeft(Node* p){ // stack to store the nodes stack<Node*> s; while (1) { // If p is not null then push // it on the stack if (p) { s.push(p); p = p->right; } else { // If stack is empty then come out // of the loop if (s.empty()) break; else { // If the node on top of the stack has its // left subtree as null then pop that node and // print the node only if its right // subtree is also null if (s.top()->left == NULL) { p = s.top(); s.pop(); // Print the leaf node if (p->right == NULL) printf("%d ", p->data); } while (p == s.top()->left) { p = s.top(); s.pop(); if (s.empty()) break; } // If stack is not empty then assign p as // the stack's top node's left child if (!s.empty()) p = s.top()->left; else p = NULL; } } }} // Driver Codeint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); printLeafRightToLeft(root); return 0;}
// Java program to print leaf nodes from// right to left using one stackimport java.util.Stack; class GFG{ // Structure of binary tree static class Node { Node left; Node right; int data; }; // Function to create a new node static Node newNode(int key) { Node node = new Node(); node.left = node.right = null; node.data = key; return node; } // Function to Print all the leaf nodes // of Binary tree using one stack static void printLeafRightToLeft(Node p) { // stack to store the nodes Stack<Node> s = new Stack<>(); while (true) { // If p is not null then push // it on the stack if (p != null) { s.push(p); p = p.right; } else { // If stack is empty then come out // of the loop if (s.empty()) break; else { // If the node on top of the stack has its // left subtree as null then pop that node and // print the node only if its right // subtree is also null if (s.peek().left == null) { p = s.peek(); s.pop(); // Print the leaf node if (p.right == null) System.out.print( p.data+" "); } while (p == s.peek().left) { p = s.peek(); s.pop(); if (s.empty()) break; } // If stack is not empty then assign p as // the stack's top node's left child if (!s.empty()) p = s.peek().left; else p = null; } } } } // Driver Code public static void main(String[] args) { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); printLeafRightToLeft(root); }} // This code is contributed by 29AjayKumar
# Python3 program to print leaf nodes # from right to left using one stack # Tree nodeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Function to create a new nodedef newNode(key) : node = Node(0) node.left = node.right = None node.data = key return node # Function to Print all the leaf nodes# of Binary tree using one stackdef printLeafRightToLeft(p) : # stack to store the nodes s = [] while (True) : # If p is not None then append # it on the stack if (p != None) : s.append(p) p = p.right else: # If stack is len then come out # of the loop if (len(s) == 0) : break else: # If the node on top of the stack has # its left subtree as None then pop # that node and print the node only # if its right subtree is also None if (s[-1].left == None) : p = s[-1] s.pop() # Print the leaf node if (p.right == None) : print( p.data, end = " ") while (p == s[-1].left) : p = s[-1] s.pop() if (len(s) == 0) : break # If stack is not len then assign p as # the stack's top node's left child if (len(s) > 0) : p = s[-1].left else: p = None # Driver Coderoot = newNode(1)root.left = newNode(2)root.right = newNode(3)root.left.left = newNode(4)root.left.right = newNode(5)root.right.left = newNode(6)root.right.right = newNode(7) printLeafRightToLeft(root) # This code is contributed by Arnab Kundu
// C# program to print leaf nodes from// right to left using one stackusing System;using System.Collections.Generic; class GFG{ // Structure of binary tree public class Node { public Node left; public Node right; public int data; }; // Function to create a new node static Node newNode(int key) { Node node = new Node(); node.left = node.right = null; node.data = key; return node; } // Function to Print all the leaf nodes // of Binary tree using one stack static void printLeafRightToLeft(Node p) { // stack to store the nodes Stack<Node> s = new Stack<Node>(); while (true) { // If p is not null then push // it on the stack if (p != null) { s.Push(p); p = p.right; } else { // If stack is empty then come out // of the loop if (s.Count == 0) break; else { // If the node on top of the stack has its // left subtree as null then pop that node and // print the node only if its right // subtree is also null if (s.Peek().left == null) { p = s.Peek(); s.Pop(); // Print the leaf node if (p.right == null) Console.Write(p.data + " "); } while (p == s.Peek().left) { p = s.Peek(); s.Pop(); if (s.Count == 0) break; } // If stack is not empty then assign p as // the stack's top node's left child if (s.Count != 0) p = s.Peek().left; else p = null; } } } } // Driver Code public static void Main(String[] args) { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); printLeafRightToLeft(root); }} // This code contributed by Rajput-Ji
<script> // Javascript program to print leaf nodes from// right to left using one stack // Structure of binary treeclass Node{ constructor() { this.left = null; this.right = null; this.data = 0; }}; // Function to create a new nodefunction newNode(key){ var node = new Node(); node.left = node.right = null; node.data = key; return node;} // Function to Print all the leaf nodes// of Binary tree using one stackfunction printLeafRightToLeft(p){ // Stack to store the nodes var s = []; while (true) { // If p is not null then push // it on the stack if (p != null) { s.push(p); p = p.right; } else { // If stack is empty then come out // of the loop if (s.length == 0) break; else { // If the node on top of the stack has // its left subtree as null then pop // that node and print the node only // if its right subtree is also null if (s[s.length - 1].left == null) { p = s[s.length - 1]; s.pop(); // Print the leaf node if (p.right == null) document.write(p.data + " "); } while (p == s[s.length - 1].left) { p = s[s.length - 1]; s.pop(); if (s.length == 0) break; } // If stack is not empty then assign p as // the stack's top node's left child if (s.length != 0) p = s[s.length - 1].left; else p = null; } } }} // Driver Codevar root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(4);root.left.right = newNode(5);root.right.left = newNode(6);root.right.right = newNode(7); printLeafRightToLeft(root); // This code is contributed by rrrtnx </script>
7 6 5 4
Time Complexity: O(N), where N is the total number of nodes in the binary tree. Auxiliary Space: O(N)
andrew1234
shrikanth13
29AjayKumar
Rajput-Ji
SHUBHAMSINGH10
rutvik_56
rrrtnx
pankajsharmagfg
Binary Tree
Data Structures
Tree
Data Structures
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n06 Aug, 2021"
},
{
"code": null,
"e": 153,
"s": 53,
"text": "Given a binary tree, the task is to print all the leaf nodes of the binary tree from right to left."
},
{
"code": null,
"e": 164,
"s": 153,
"text": "Examples: "
},
{
"code": null,
"e": 372,
"s": 164,
"text": "Input : \n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\nOutput : 7 6 5 4\n\nInput :\n 1\n / \\\n 2 3\n / \\ \\\n 4 5 6\n / / \\\n 7 8 9\nOutput : 9 8 7 4"
},
{
"code": null,
"e": 526,
"s": 372,
"text": "Recursive Approach: Traverse the tree in Preorder fashion, by first processing the root, then right subtree and then left subtree and do the following: "
},
{
"code": null,
"e": 583,
"s": 526,
"text": "Check if the root is null then return from the function."
},
{
"code": null,
"e": 619,
"s": 583,
"text": "If it is a leaf node then print it."
},
{
"code": null,
"e": 727,
"s": 619,
"text": "If not then check if it has right child, if yes then call function for right child of the node recursively."
},
{
"code": null,
"e": 821,
"s": 727,
"text": "Check if it has left child, if yes then call function for left child of the node recursively."
},
{
"code": null,
"e": 873,
"s": 821,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 877,
"s": 873,
"text": "C++"
},
{
"code": null,
"e": 882,
"s": 877,
"text": "Java"
},
{
"code": null,
"e": 890,
"s": 882,
"text": "Python3"
},
{
"code": null,
"e": 893,
"s": 890,
"text": "C#"
},
{
"code": null,
"e": 904,
"s": 893,
"text": "Javascript"
},
{
"code": "// C++ program to print leaf nodes from right to left #include <iostream>using namespace std; // A Binary Tree Nodestruct Node { int data; struct Node *left, *right;}; // Utility function to create a new tree nodeNode* newNode(int data){ Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Function to print leaf// nodes from right to leftvoid printLeafNodes(Node* root){ // If node is null, return if (!root) return; // If node is leaf node, print its data if (!root->left && !root->right) { cout << root->data << \" \"; return; } // If right child exists, check for leaf // recursively if (root->right) printLeafNodes(root->right); // If left child exists, check for leaf // recursively if (root->left) printLeafNodes(root->left);} // Driver codeint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->right->right->left = newNode(9); root->left->left->left->right = newNode(10); printLeafNodes(root); return 0;}",
"e": 2187,
"s": 904,
"text": null
},
{
"code": "// Java program to print leaf nodes from right to leftimport java.util.*; class GFG{ // A Binary Tree Nodestatic class Node{ int data; Node left, right;}; // Utility function to create a new tree nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function to print leaf// nodes from right to leftstatic void printLeafNodes(Node root){ // If node is null, return if (root == null) return; // If node is leaf node, print its data if (root.left == null && root.right == null) { System.out.print( root.data +\" \"); return; } // If right child exists, check for leaf // recursively if (root.right != null) printLeafNodes(root.right); // If left child exists, check for leaf // recursively if (root.left != null) printLeafNodes(root.left);} // Driver codepublic static void main(String args[]){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); root.left.left.left = newNode(8); root.right.right.left = newNode(9); root.left.left.left.right = newNode(10); printLeafNodes(root);}} // This code is contributed by Arnab Kundu",
"e": 3550,
"s": 2187,
"text": null
},
{
"code": "# Python3 program to print# leaf nodes from right to left # Binary tree nodeclass newNode: def __init__(self, data): self.data = data self.left = None self.right = None # Function to print leaf# nodes from right to leftdef printLeafNodes(root): # If node is null, return if root == None: return # If node is leaf node, # print its data if (root.left == None and root.right == None): print(root.data, end = \" \") return # If right child exists, # check for leaf recursively if root.right: printLeafNodes(root.right) # If left child exists, # check for leaf recursively if root.left: printLeafNodes(root.left) # Driver coderoot = newNode(1)root.left = newNode(2)root.right = newNode(3)root.left.left = newNode(4)root.left.right = newNode(5)root.right.left = newNode(6)root.right.right = newNode(7)root.left.left.left = newNode(8)root.right.right.left = newNode(9)root.left.left.left.right = newNode(10) printLeafNodes(root) # This code is contributed by SHUBHAMSINGH10",
"e": 4640,
"s": 3550,
"text": null
},
{
"code": "using System; // C# program to print leaf nodes from right to leftclass GFG{ // A Binary Tree Nodepublic class Node{ public int data; public Node left, right;} // Utility function to create a new tree nodepublic static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function to print leaf// nodes from right to leftpublic static void printLeafNodes(Node root){ // If node is null, return if (root == null) { return; } // If node is leaf node, print its data if (root.left == null && root.right == null) { Console.Write(root.data + \" \"); return; } // If right child exists, check for leaf // recursively if (root.right != null) { printLeafNodes(root.right); } // If left child exists, check for leaf // recursively if (root.left != null) { printLeafNodes(root.left); }} // Driver codepublic static void Main(string[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); root.left.left.left = newNode(8); root.right.right.left = newNode(9); root.left.left.left.right = newNode(10); printLeafNodes(root);}} // This code is contributed by shrikanth13",
"e": 6045,
"s": 4640,
"text": null
},
{
"code": "<script> // JavaScript program to print leaf nodes from right to left // A Binary Tree Nodeclass Node{ constructor() { this.data = 0; this.right = null; this.left = null; }} // Utility function to create a new tree nodefunction newNode(data){ var temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function to print leaf// nodes from right to leftfunction printLeafNodes(root){ // If node is null, return if (root == null) { return; } // If node is leaf node, print its data if (root.left == null && root.right == null) { document.write(root.data + \" \"); return; } // If right child exists, check for leaf // recursively if (root.right != null) { printLeafNodes(root.right); } // If left child exists, check for leaf // recursively if (root.left != null) { printLeafNodes(root.left); }} // Driver codevar root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(4);root.left.right = newNode(5);root.right.left = newNode(6);root.right.right = newNode(7);root.left.left.left = newNode(8);root.right.right.left = newNode(9);root.left.left.left.right = newNode(10);printLeafNodes(root); </script>",
"e": 7339,
"s": 6045,
"text": null
},
{
"code": null,
"e": 7348,
"s": 7339,
"text": "9 6 5 10"
},
{
"code": null,
"e": 7583,
"s": 7350,
"text": "Iterative Approach: The idea is to perform iterative postorder traversal using one stack, but in a modified manner, first, we will visit the right subtree and then the left subtree and finally the root node and print the leaf nodes."
},
{
"code": null,
"e": 7635,
"s": 7583,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 7639,
"s": 7635,
"text": "C++"
},
{
"code": null,
"e": 7644,
"s": 7639,
"text": "Java"
},
{
"code": null,
"e": 7652,
"s": 7644,
"text": "Python3"
},
{
"code": null,
"e": 7655,
"s": 7652,
"text": "C#"
},
{
"code": null,
"e": 7666,
"s": 7655,
"text": "Javascript"
},
{
"code": "// C++ program to print leaf nodes from// right to left using one stack #include<bits/stdc++.h>using namespace std; // Structure of binary treestruct Node { Node* left; Node* right; int data;}; // Function to create a new nodeNode* newNode(int key){ Node* node = new Node(); node->left = node->right = NULL; node->data = key; return node;} // Function to Print all the leaf nodes// of Binary tree using one stackvoid printLeafRightToLeft(Node* p){ // stack to store the nodes stack<Node*> s; while (1) { // If p is not null then push // it on the stack if (p) { s.push(p); p = p->right; } else { // If stack is empty then come out // of the loop if (s.empty()) break; else { // If the node on top of the stack has its // left subtree as null then pop that node and // print the node only if its right // subtree is also null if (s.top()->left == NULL) { p = s.top(); s.pop(); // Print the leaf node if (p->right == NULL) printf(\"%d \", p->data); } while (p == s.top()->left) { p = s.top(); s.pop(); if (s.empty()) break; } // If stack is not empty then assign p as // the stack's top node's left child if (!s.empty()) p = s.top()->left; else p = NULL; } } }} // Driver Codeint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); printLeafRightToLeft(root); return 0;}",
"e": 9716,
"s": 7666,
"text": null
},
{
"code": "// Java program to print leaf nodes from// right to left using one stackimport java.util.Stack; class GFG{ // Structure of binary tree static class Node { Node left; Node right; int data; }; // Function to create a new node static Node newNode(int key) { Node node = new Node(); node.left = node.right = null; node.data = key; return node; } // Function to Print all the leaf nodes // of Binary tree using one stack static void printLeafRightToLeft(Node p) { // stack to store the nodes Stack<Node> s = new Stack<>(); while (true) { // If p is not null then push // it on the stack if (p != null) { s.push(p); p = p.right; } else { // If stack is empty then come out // of the loop if (s.empty()) break; else { // If the node on top of the stack has its // left subtree as null then pop that node and // print the node only if its right // subtree is also null if (s.peek().left == null) { p = s.peek(); s.pop(); // Print the leaf node if (p.right == null) System.out.print( p.data+\" \"); } while (p == s.peek().left) { p = s.peek(); s.pop(); if (s.empty()) break; } // If stack is not empty then assign p as // the stack's top node's left child if (!s.empty()) p = s.peek().left; else p = null; } } } } // Driver Code public static void main(String[] args) { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); printLeafRightToLeft(root); }} // This code is contributed by 29AjayKumar",
"e": 12199,
"s": 9716,
"text": null
},
{
"code": "# Python3 program to print leaf nodes # from right to left using one stack # Tree nodeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Function to create a new nodedef newNode(key) : node = Node(0) node.left = node.right = None node.data = key return node # Function to Print all the leaf nodes# of Binary tree using one stackdef printLeafRightToLeft(p) : # stack to store the nodes s = [] while (True) : # If p is not None then append # it on the stack if (p != None) : s.append(p) p = p.right else: # If stack is len then come out # of the loop if (len(s) == 0) : break else: # If the node on top of the stack has # its left subtree as None then pop # that node and print the node only # if its right subtree is also None if (s[-1].left == None) : p = s[-1] s.pop() # Print the leaf node if (p.right == None) : print( p.data, end = \" \") while (p == s[-1].left) : p = s[-1] s.pop() if (len(s) == 0) : break # If stack is not len then assign p as # the stack's top node's left child if (len(s) > 0) : p = s[-1].left else: p = None # Driver Coderoot = newNode(1)root.left = newNode(2)root.right = newNode(3)root.left.left = newNode(4)root.left.right = newNode(5)root.right.left = newNode(6)root.right.right = newNode(7) printLeafRightToLeft(root) # This code is contributed by Arnab Kundu",
"e": 14201,
"s": 12199,
"text": null
},
{
"code": "// C# program to print leaf nodes from// right to left using one stackusing System;using System.Collections.Generic; class GFG{ // Structure of binary tree public class Node { public Node left; public Node right; public int data; }; // Function to create a new node static Node newNode(int key) { Node node = new Node(); node.left = node.right = null; node.data = key; return node; } // Function to Print all the leaf nodes // of Binary tree using one stack static void printLeafRightToLeft(Node p) { // stack to store the nodes Stack<Node> s = new Stack<Node>(); while (true) { // If p is not null then push // it on the stack if (p != null) { s.Push(p); p = p.right; } else { // If stack is empty then come out // of the loop if (s.Count == 0) break; else { // If the node on top of the stack has its // left subtree as null then pop that node and // print the node only if its right // subtree is also null if (s.Peek().left == null) { p = s.Peek(); s.Pop(); // Print the leaf node if (p.right == null) Console.Write(p.data + \" \"); } while (p == s.Peek().left) { p = s.Peek(); s.Pop(); if (s.Count == 0) break; } // If stack is not empty then assign p as // the stack's top node's left child if (s.Count != 0) p = s.Peek().left; else p = null; } } } } // Driver Code public static void Main(String[] args) { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); printLeafRightToLeft(root); }} // This code contributed by Rajput-Ji",
"e": 16730,
"s": 14201,
"text": null
},
{
"code": "<script> // Javascript program to print leaf nodes from// right to left using one stack // Structure of binary treeclass Node{ constructor() { this.left = null; this.right = null; this.data = 0; }}; // Function to create a new nodefunction newNode(key){ var node = new Node(); node.left = node.right = null; node.data = key; return node;} // Function to Print all the leaf nodes// of Binary tree using one stackfunction printLeafRightToLeft(p){ // Stack to store the nodes var s = []; while (true) { // If p is not null then push // it on the stack if (p != null) { s.push(p); p = p.right; } else { // If stack is empty then come out // of the loop if (s.length == 0) break; else { // If the node on top of the stack has // its left subtree as null then pop // that node and print the node only // if its right subtree is also null if (s[s.length - 1].left == null) { p = s[s.length - 1]; s.pop(); // Print the leaf node if (p.right == null) document.write(p.data + \" \"); } while (p == s[s.length - 1].left) { p = s[s.length - 1]; s.pop(); if (s.length == 0) break; } // If stack is not empty then assign p as // the stack's top node's left child if (s.length != 0) p = s[s.length - 1].left; else p = null; } } }} // Driver Codevar root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(4);root.left.right = newNode(5);root.right.left = newNode(6);root.right.right = newNode(7); printLeafRightToLeft(root); // This code is contributed by rrrtnx </script>",
"e": 18971,
"s": 16730,
"text": null
},
{
"code": null,
"e": 18979,
"s": 18971,
"text": "7 6 5 4"
},
{
"code": null,
"e": 19083,
"s": 18981,
"text": "Time Complexity: O(N), where N is the total number of nodes in the binary tree. Auxiliary Space: O(N)"
},
{
"code": null,
"e": 19094,
"s": 19083,
"text": "andrew1234"
},
{
"code": null,
"e": 19106,
"s": 19094,
"text": "shrikanth13"
},
{
"code": null,
"e": 19118,
"s": 19106,
"text": "29AjayKumar"
},
{
"code": null,
"e": 19128,
"s": 19118,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 19143,
"s": 19128,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 19153,
"s": 19143,
"text": "rutvik_56"
},
{
"code": null,
"e": 19160,
"s": 19153,
"text": "rrrtnx"
},
{
"code": null,
"e": 19176,
"s": 19160,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 19188,
"s": 19176,
"text": "Binary Tree"
},
{
"code": null,
"e": 19204,
"s": 19188,
"text": "Data Structures"
},
{
"code": null,
"e": 19209,
"s": 19204,
"text": "Tree"
},
{
"code": null,
"e": 19225,
"s": 19209,
"text": "Data Structures"
},
{
"code": null,
"e": 19230,
"s": 19225,
"text": "Tree"
}
] |
Ruby | Regexp match() function
|
18 Dec, 2019
Regexp#match() : force_encoding?() is a Regexp class method which matches the regular expression with the string and specifies the position in the string to begin the search.
Syntax: Regexp.match()
Parameter: Regexp values
Return: regular expression with the string after matching it.
Example #1 :
# Ruby code for Regexp.match() method # declaring Regexp valuereg_a = /a/ # declaring Regexp valuereg_b = /geeks/ # declaring Regexp valuereg_c = /a/ # match methodputs "Regexp match form : #{reg_a.match("abcd")}\n\n" puts "Regexp match form : #{reg_b.match("geeksforgeeks")}\n\n" puts "Regexp match form : #{reg_c.match("playway")}\n\n"
Output :
Regexp match form : a
Regexp match form : geeks
Regexp match form : a
Example #2 :
# Ruby code for Regexp.match() method # declaring Regexp valuereg_a = /geeks/ # declaring Regexp valuereg_b = /problem/ # declaring Regexp valuereg_c = /code/ # match methodputs "Regexp match form : #{reg_a.match("geeksforgeeks")}\n\n" puts "Regexp match form : #{reg_b.match("geeksforgeeks")}\n\n" puts "Regexp match form : #{reg_c.match("codeer")}\n\n"
Output :
Regexp match form : geeks
Regexp match form :
Regexp match form : code
Ruby Regexp-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Dec, 2019"
},
{
"code": null,
"e": 229,
"s": 54,
"text": "Regexp#match() : force_encoding?() is a Regexp class method which matches the regular expression with the string and specifies the position in the string to begin the search."
},
{
"code": null,
"e": 252,
"s": 229,
"text": "Syntax: Regexp.match()"
},
{
"code": null,
"e": 277,
"s": 252,
"text": "Parameter: Regexp values"
},
{
"code": null,
"e": 339,
"s": 277,
"text": "Return: regular expression with the string after matching it."
},
{
"code": null,
"e": 352,
"s": 339,
"text": "Example #1 :"
},
{
"code": "# Ruby code for Regexp.match() method # declaring Regexp valuereg_a = /a/ # declaring Regexp valuereg_b = /geeks/ # declaring Regexp valuereg_c = /a/ # match methodputs \"Regexp match form : #{reg_a.match(\"abcd\")}\\n\\n\" puts \"Regexp match form : #{reg_b.match(\"geeksforgeeks\")}\\n\\n\" puts \"Regexp match form : #{reg_c.match(\"playway\")}\\n\\n\"",
"e": 699,
"s": 352,
"text": null
},
{
"code": null,
"e": 708,
"s": 699,
"text": "Output :"
},
{
"code": null,
"e": 782,
"s": 708,
"text": "Regexp match form : a\n\nRegexp match form : geeks\n\nRegexp match form : a\n\n"
},
{
"code": null,
"e": 795,
"s": 782,
"text": "Example #2 :"
},
{
"code": "# Ruby code for Regexp.match() method # declaring Regexp valuereg_a = /geeks/ # declaring Regexp valuereg_b = /problem/ # declaring Regexp valuereg_c = /code/ # match methodputs \"Regexp match form : #{reg_a.match(\"geeksforgeeks\")}\\n\\n\" puts \"Regexp match form : #{reg_b.match(\"geeksforgeeks\")}\\n\\n\" puts \"Regexp match form : #{reg_c.match(\"codeer\")}\\n\\n\"",
"e": 1159,
"s": 795,
"text": null
},
{
"code": null,
"e": 1168,
"s": 1159,
"text": "Output :"
},
{
"code": null,
"e": 1244,
"s": 1168,
"text": "Regexp match form : geeks\n\nRegexp match form : \n\nRegexp match form : code\n\n"
},
{
"code": null,
"e": 1262,
"s": 1244,
"text": "Ruby Regexp-class"
},
{
"code": null,
"e": 1275,
"s": 1262,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 1280,
"s": 1275,
"text": "Ruby"
}
] |
C# | Dictionary.Values Property
|
03 Apr, 2019
This property is used to get a collection containing the values in the Dictionary<TKey,TValue>.
Syntax:
public System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection Values{ get; }
Return Value: This property returns a collection containing the Values in the Dictionary.
Below are the programs to illustrate the use of Dictionary<TKey,TValue>.Values Property:
Example 1:
// C# code to get the Values// in the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary // of strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add("Australia", "Canberra"); myDict.Add("Belgium", "Brussels"); myDict.Add("Netherlands", "Amsterdam"); myDict.Add("China", "Beijing"); myDict.Add("Russia", "Moscow"); myDict.Add("India", "New Delhi"); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs"+ " in myDict are : " + myDict.Count); // To get the values alone, // use the Values property. Dictionary<string, string>.ValueCollection valueColl = myDict.Values; // The elements of the ValueCollection // are strongly typed with the type // that was specified for dictionary values. foreach(string s in valueColl) { Console.WriteLine("Value = {0}", s); } }}
Total key/value pairs in myDict are : 6
Value = Canberra
Value = Brussels
Value = Amsterdam
Value = Beijing
Value = Moscow
Value = New Delhi
Example 2:
// C# code to get the values// in the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<int, int> myDict = new Dictionary<int, int>(); // Adding key/value pairs in myDict myDict.Add(9, 8); myDict.Add(3, 4); myDict.Add(4, 7); myDict.Add(1, 7); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs "+ "in myDict are : " + myDict.Count); // To get the values alone, // use the Values property. Dictionary<int, int>.ValueCollection valueColl = myDict.Values; // The elements of the ValueCollection // are strongly typed with the type // that was specified for dictionary values. foreach(int s in valueColl) { Console.WriteLine("Values = {0}", s); } }}
Total key/value pairs in myDict are : 4
Values = 8
Values = 4
Values = 7
Values = 7
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.values?view=netframework-4.7.2
CSharp Dictionary Class
CSharp-Generic-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Apr, 2019"
},
{
"code": null,
"e": 124,
"s": 28,
"text": "This property is used to get a collection containing the values in the Dictionary<TKey,TValue>."
},
{
"code": null,
"e": 132,
"s": 124,
"text": "Syntax:"
},
{
"code": null,
"e": 220,
"s": 132,
"text": "public System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection Values{ get; }"
},
{
"code": null,
"e": 310,
"s": 220,
"text": "Return Value: This property returns a collection containing the Values in the Dictionary."
},
{
"code": null,
"e": 399,
"s": 310,
"text": "Below are the programs to illustrate the use of Dictionary<TKey,TValue>.Values Property:"
},
{
"code": null,
"e": 410,
"s": 399,
"text": "Example 1:"
},
{
"code": "// C# code to get the Values// in the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary // of strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add(\"Australia\", \"Canberra\"); myDict.Add(\"Belgium\", \"Brussels\"); myDict.Add(\"Netherlands\", \"Amsterdam\"); myDict.Add(\"China\", \"Beijing\"); myDict.Add(\"Russia\", \"Moscow\"); myDict.Add(\"India\", \"New Delhi\"); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs\"+ \" in myDict are : \" + myDict.Count); // To get the values alone, // use the Values property. Dictionary<string, string>.ValueCollection valueColl = myDict.Values; // The elements of the ValueCollection // are strongly typed with the type // that was specified for dictionary values. foreach(string s in valueColl) { Console.WriteLine(\"Value = {0}\", s); } }}",
"e": 1639,
"s": 410,
"text": null
},
{
"code": null,
"e": 1781,
"s": 1639,
"text": "Total key/value pairs in myDict are : 6\nValue = Canberra\nValue = Brussels\nValue = Amsterdam\nValue = Beijing\nValue = Moscow\nValue = New Delhi\n"
},
{
"code": null,
"e": 1792,
"s": 1781,
"text": "Example 2:"
},
{
"code": "// C# code to get the values// in the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<int, int> myDict = new Dictionary<int, int>(); // Adding key/value pairs in myDict myDict.Add(9, 8); myDict.Add(3, 4); myDict.Add(4, 7); myDict.Add(1, 7); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs \"+ \"in myDict are : \" + myDict.Count); // To get the values alone, // use the Values property. Dictionary<int, int>.ValueCollection valueColl = myDict.Values; // The elements of the ValueCollection // are strongly typed with the type // that was specified for dictionary values. foreach(int s in valueColl) { Console.WriteLine(\"Values = {0}\", s); } }}",
"e": 2847,
"s": 1792,
"text": null
},
{
"code": null,
"e": 2932,
"s": 2847,
"text": "Total key/value pairs in myDict are : 4\nValues = 8\nValues = 4\nValues = 7\nValues = 7\n"
},
{
"code": null,
"e": 2943,
"s": 2932,
"text": "Reference:"
},
{
"code": null,
"e": 3058,
"s": 2943,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.values?view=netframework-4.7.2"
},
{
"code": null,
"e": 3082,
"s": 3058,
"text": "CSharp Dictionary Class"
},
{
"code": null,
"e": 3107,
"s": 3082,
"text": "CSharp-Generic-Namespace"
},
{
"code": null,
"e": 3110,
"s": 3107,
"text": "C#"
}
] |
Suffix Array | Set 1 (Introduction)
|
13 Jul, 2022
We strongly recommend to read following post on suffix trees as a pre-requisite for this post.Pattern Searching | Set 8 (Suffix Tree Introduction)A suffix array is a sorted array of all suffixes of a given string. The definition is similar to Suffix Tree which is compressed trie of all suffixes of the given text. Any suffix tree based algorithm can be replaced with an algorithm that uses a suffix array enhanced with additional information and solves the same problem in the same time complexity (Source Wiki). A suffix array can be constructed from Suffix tree by doing a DFS traversal of the suffix tree. In fact Suffix array and suffix tree both can be constructed from each other in linear time. Advantages of suffix arrays over suffix trees include improved space requirements, simpler linear time construction algorithms (e.g., compared to Ukkonenβs algorithm) and improved cache locality (Source: Wiki)Example:
Let the given string be "banana".
0 banana 5 a
1 anana Sort the Suffixes 3 ana
2 nana ----------------> 1 anana
3 ana alphabetically 0 banana
4 na 4 na
5 a 2 nana
So the suffix array for "banana" is {5, 3, 1, 0, 4, 2}
Naive method to build Suffix Array A simple method to construct suffix array is to make an array of all suffixes and then sort the array. Following is implementation of simple method.
CPP
Java
// Naive algorithm for building suffix array of a given text#include <iostream>#include <cstring>#include <algorithm>using namespace std; // Structure to store information of a suffixstruct suffix{ int index; char *suff;}; // A comparison function used by sort() to compare two suffixesint cmp(struct suffix a, struct suffix b){ return strcmp(a.suff, b.suff) < 0? 1 : 0;} // This is the main function that takes a string 'txt' of size n as an// argument, builds and return the suffix array for the given stringint *buildSuffixArray(char *txt, int n){ // A structure to store suffixes and their indexes struct suffix suffixes[n]; // Store suffixes and their indexes in an array of structures. // The structure is needed to sort the suffixes alphabetically // and maintain their old indexes while sorting for (int i = 0; i < n; i++) { suffixes[i].index = i; suffixes[i].suff = (txt+i); } // Sort the suffixes using the comparison function // defined above. sort(suffixes, suffixes+n, cmp); // Store indexes of all sorted suffixes in the suffix array int *suffixArr = new int[n]; for (int i = 0; i < n; i++) suffixArr[i] = suffixes[i].index; // Return the suffix array return suffixArr;} // A utility function to print an array of given sizevoid printArr(int arr[], int n){ for(int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl;} // Driver program to test above functionsint main(){ char txt[] = "banana"; int n = strlen(txt); int *suffixArr = buildSuffixArray(txt, n); cout << "Following is suffix array for " << txt << endl; printArr(suffixArr, n); return 0;}
//importing the required packagesimport java.util.ArrayList;import java.util.Arrays; class suffix_array { public static void main(String[] args) throws Exception { String word = "banana"; String arr1[] = new String[word.length()]; String arr2[] = new String[word.length()]; ArrayList<Integer> suffix_index = new ArrayList<Integer>(); int suffix_array[] = new int[word.length()]; for (int i = 0; i < word.length(); i++) { arr1[i] = word.substring(i); } arr2 = arr1.clone(); Arrays.sort(arr1); for (String i : arr1) { String piece = i; int index = new suffix_array().index(arr2, piece); suffix_index.add(index); } for (int i = 0; i < suffix_array.length; i++) { suffix_array[i] = suffix_index.get(i); } System.out.println( "following is the suffix array for banana"); for (int i : suffix_array) { System.out.print(i + " "); } } //simple function to return the index of item from array arr[] int index(String arr[], String item) { for (int i = 0; i < arr.length; i++) { if (item == arr[i]) return i; } return -1; }}
Output:
Following is suffix array for banana
5 3 1 0 4 2
Time Complexity: O(n*k*Logn). if we consider a O(nLogn)) algorithm used for sorting. The sorting step itself takes O(n*k*Logn) time as every comparison is a comparison of two strings and the comparison takes O(K) time where K is max length of string in given array.
Auxiliary Space: O(n)
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
There are many efficient algorithms to build suffix array. We will soon be covering them as separate posts.Search a pattern using the built Suffix Array To search a pattern in a text, we preprocess the text and build a suffix array of the text. Since we have a sorted array of all suffixes, Binary Search can be used to search. Following is the search function. Note that the function doesnβt report all occurrences of pattern, it only report one of them.
CPP
// This code only contains search() and main. To make it a complete running// above code or see https://ide.geeksforgeeks.org/oY7OkD // A suffix array based search function to search a given pattern// 'pat' in given text 'txt' using suffix array suffArr[]void search(char *pat, char *txt, int *suffArr, int n){ int m = strlen(pat); // get length of pattern, needed for strncmp() // Do simple binary search for the pat in txt using the // built suffix array int l = 0, r = n-1; // Initialize left and right indexes while (l <= r) { // See if 'pat' is prefix of middle suffix in suffix array int mid = l + (r - l)/2; int res = strncmp(pat, txt+suffArr[mid], m); // If match found at the middle, print it and return if (res == 0) { cout << "Pattern found at index " << suffArr[mid]; return; } // Move to left half if pattern is alphabetically less than // the mid suffix if (res < 0) r = mid - 1; // Otherwise move to right half else l = mid + 1; } // We reach here if return statement in loop is not executed cout << "Pattern not found";} // Driver program to test above functionint main(){ char txt[] = "banana"; // text char pat[] = "nan"; // pattern to be searched in text // Build suffix array int n = strlen(txt); int *suffArr = buildSuffixArray(txt, n); // search pat in txt using the built suffix array search(pat, txt, suffArr, n); return 0;}
Output:
Pattern found at index 2
Time Complexity: O(mlogn)Auxiliary Space: O(m+n)
There are more efficient algorithms to search pattern once the suffix array is built. In fact there is a O(m) suffix array based algorithm to search a pattern. We will soon be discussing efficient algorithm for search.Applications of Suffix Array Suffix array is an extremely useful data structure, it can be used for a wide range of problems. Following are some famous problems where Suffix array can be used. 1) Pattern Searching 2) Finding the longest repeated substring 3) Finding the longest common substring 4) Finding the longest palindrome in a string
See this for more problems where Suffix arrays can be used.This post is a simple introduction. There is a lot to cover in Suffix arrays. We have discussed a O(nLogn) algorithm for Suffix Array construction here. We will soon be discussing more efficient suffix array algorithms.References: http://www.stanford.edu/class/cs97si/suffix-array.pdf http://en.wikipedia.org/wiki/Suffix_arrayPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above
sweetyty
devro3014
rajeev0719singh
ayush786113
vivekanand1108
Suffix-Array
Advanced Data Structure
Pattern Searching
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jul, 2022"
},
{
"code": null,
"e": 977,
"s": 54,
"text": "We strongly recommend to read following post on suffix trees as a pre-requisite for this post.Pattern Searching | Set 8 (Suffix Tree Introduction)A suffix array is a sorted array of all suffixes of a given string. The definition is similar to Suffix Tree which is compressed trie of all suffixes of the given text. Any suffix tree based algorithm can be replaced with an algorithm that uses a suffix array enhanced with additional information and solves the same problem in the same time complexity (Source Wiki). A suffix array can be constructed from Suffix tree by doing a DFS traversal of the suffix tree. In fact Suffix array and suffix tree both can be constructed from each other in linear time. Advantages of suffix arrays over suffix trees include improved space requirements, simpler linear time construction algorithms (e.g., compared to Ukkonenβs algorithm) and improved cache locality (Source: Wiki)Example: "
},
{
"code": null,
"e": 1318,
"s": 977,
"text": "Let the given string be \"banana\".\n\n0 banana 5 a\n1 anana Sort the Suffixes 3 ana\n2 nana ----------------> 1 anana \n3 ana alphabetically 0 banana \n4 na 4 na \n5 a 2 nana\n\nSo the suffix array for \"banana\" is {5, 3, 1, 0, 4, 2}"
},
{
"code": null,
"e": 1503,
"s": 1318,
"text": "Naive method to build Suffix Array A simple method to construct suffix array is to make an array of all suffixes and then sort the array. Following is implementation of simple method. "
},
{
"code": null,
"e": 1507,
"s": 1503,
"text": "CPP"
},
{
"code": null,
"e": 1512,
"s": 1507,
"text": "Java"
},
{
"code": "// Naive algorithm for building suffix array of a given text#include <iostream>#include <cstring>#include <algorithm>using namespace std; // Structure to store information of a suffixstruct suffix{ int index; char *suff;}; // A comparison function used by sort() to compare two suffixesint cmp(struct suffix a, struct suffix b){ return strcmp(a.suff, b.suff) < 0? 1 : 0;} // This is the main function that takes a string 'txt' of size n as an// argument, builds and return the suffix array for the given stringint *buildSuffixArray(char *txt, int n){ // A structure to store suffixes and their indexes struct suffix suffixes[n]; // Store suffixes and their indexes in an array of structures. // The structure is needed to sort the suffixes alphabetically // and maintain their old indexes while sorting for (int i = 0; i < n; i++) { suffixes[i].index = i; suffixes[i].suff = (txt+i); } // Sort the suffixes using the comparison function // defined above. sort(suffixes, suffixes+n, cmp); // Store indexes of all sorted suffixes in the suffix array int *suffixArr = new int[n]; for (int i = 0; i < n; i++) suffixArr[i] = suffixes[i].index; // Return the suffix array return suffixArr;} // A utility function to print an array of given sizevoid printArr(int arr[], int n){ for(int i = 0; i < n; i++) cout << arr[i] << \" \"; cout << endl;} // Driver program to test above functionsint main(){ char txt[] = \"banana\"; int n = strlen(txt); int *suffixArr = buildSuffixArray(txt, n); cout << \"Following is suffix array for \" << txt << endl; printArr(suffixArr, n); return 0;}",
"e": 3204,
"s": 1512,
"text": null
},
{
"code": "//importing the required packagesimport java.util.ArrayList;import java.util.Arrays; class suffix_array { public static void main(String[] args) throws Exception { String word = \"banana\"; String arr1[] = new String[word.length()]; String arr2[] = new String[word.length()]; ArrayList<Integer> suffix_index = new ArrayList<Integer>(); int suffix_array[] = new int[word.length()]; for (int i = 0; i < word.length(); i++) { arr1[i] = word.substring(i); } arr2 = arr1.clone(); Arrays.sort(arr1); for (String i : arr1) { String piece = i; int index = new suffix_array().index(arr2, piece); suffix_index.add(index); } for (int i = 0; i < suffix_array.length; i++) { suffix_array[i] = suffix_index.get(i); } System.out.println( \"following is the suffix array for banana\"); for (int i : suffix_array) { System.out.print(i + \" \"); } } //simple function to return the index of item from array arr[] int index(String arr[], String item) { for (int i = 0; i < arr.length; i++) { if (item == arr[i]) return i; } return -1; }}",
"e": 4509,
"s": 3204,
"text": null
},
{
"code": null,
"e": 4519,
"s": 4509,
"text": "Output: "
},
{
"code": null,
"e": 4568,
"s": 4519,
"text": "Following is suffix array for banana\n5 3 1 0 4 2"
},
{
"code": null,
"e": 4835,
"s": 4568,
"text": "Time Complexity: O(n*k*Logn). if we consider a O(nLogn)) algorithm used for sorting. The sorting step itself takes O(n*k*Logn) time as every comparison is a comparison of two strings and the comparison takes O(K) time where K is max length of string in given array. "
},
{
"code": null,
"e": 4857,
"s": 4835,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 4866,
"s": 4857,
"text": "Chapters"
},
{
"code": null,
"e": 4893,
"s": 4866,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 4943,
"s": 4893,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 4966,
"s": 4943,
"text": "captions off, selected"
},
{
"code": null,
"e": 4974,
"s": 4966,
"text": "English"
},
{
"code": null,
"e": 4998,
"s": 4974,
"text": "This is a modal window."
},
{
"code": null,
"e": 5067,
"s": 4998,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 5089,
"s": 5067,
"text": "End of dialog window."
},
{
"code": null,
"e": 5546,
"s": 5089,
"text": "There are many efficient algorithms to build suffix array. We will soon be covering them as separate posts.Search a pattern using the built Suffix Array To search a pattern in a text, we preprocess the text and build a suffix array of the text. Since we have a sorted array of all suffixes, Binary Search can be used to search. Following is the search function. Note that the function doesnβt report all occurrences of pattern, it only report one of them. "
},
{
"code": null,
"e": 5550,
"s": 5546,
"text": "CPP"
},
{
"code": "// This code only contains search() and main. To make it a complete running// above code or see https://ide.geeksforgeeks.org/oY7OkD // A suffix array based search function to search a given pattern// 'pat' in given text 'txt' using suffix array suffArr[]void search(char *pat, char *txt, int *suffArr, int n){ int m = strlen(pat); // get length of pattern, needed for strncmp() // Do simple binary search for the pat in txt using the // built suffix array int l = 0, r = n-1; // Initialize left and right indexes while (l <= r) { // See if 'pat' is prefix of middle suffix in suffix array int mid = l + (r - l)/2; int res = strncmp(pat, txt+suffArr[mid], m); // If match found at the middle, print it and return if (res == 0) { cout << \"Pattern found at index \" << suffArr[mid]; return; } // Move to left half if pattern is alphabetically less than // the mid suffix if (res < 0) r = mid - 1; // Otherwise move to right half else l = mid + 1; } // We reach here if return statement in loop is not executed cout << \"Pattern not found\";} // Driver program to test above functionint main(){ char txt[] = \"banana\"; // text char pat[] = \"nan\"; // pattern to be searched in text // Build suffix array int n = strlen(txt); int *suffArr = buildSuffixArray(txt, n); // search pat in txt using the built suffix array search(pat, txt, suffArr, n); return 0;}",
"e": 7079,
"s": 5550,
"text": null
},
{
"code": null,
"e": 7089,
"s": 7079,
"text": "Output: "
},
{
"code": null,
"e": 7114,
"s": 7089,
"text": "Pattern found at index 2"
},
{
"code": null,
"e": 7164,
"s": 7114,
"text": "Time Complexity: O(mlogn)Auxiliary Space: O(m+n) "
},
{
"code": null,
"e": 7726,
"s": 7164,
"text": " There are more efficient algorithms to search pattern once the suffix array is built. In fact there is a O(m) suffix array based algorithm to search a pattern. We will soon be discussing efficient algorithm for search.Applications of Suffix Array Suffix array is an extremely useful data structure, it can be used for a wide range of problems. Following are some famous problems where Suffix array can be used. 1) Pattern Searching 2) Finding the longest repeated substring 3) Finding the longest common substring 4) Finding the longest palindrome in a string "
},
{
"code": null,
"e": 8236,
"s": 7726,
"text": "See this for more problems where Suffix arrays can be used.This post is a simple introduction. There is a lot to cover in Suffix arrays. We have discussed a O(nLogn) algorithm for Suffix Array construction here. We will soon be discussing more efficient suffix array algorithms.References: http://www.stanford.edu/class/cs97si/suffix-array.pdf http://en.wikipedia.org/wiki/Suffix_arrayPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 8245,
"s": 8236,
"text": "sweetyty"
},
{
"code": null,
"e": 8255,
"s": 8245,
"text": "devro3014"
},
{
"code": null,
"e": 8271,
"s": 8255,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 8283,
"s": 8271,
"text": "ayush786113"
},
{
"code": null,
"e": 8298,
"s": 8283,
"text": "vivekanand1108"
},
{
"code": null,
"e": 8311,
"s": 8298,
"text": "Suffix-Array"
},
{
"code": null,
"e": 8335,
"s": 8311,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 8353,
"s": 8335,
"text": "Pattern Searching"
},
{
"code": null,
"e": 8371,
"s": 8353,
"text": "Pattern Searching"
}
] |
Construct a Diagonal Matrix in R Programming β diag() Function
|
01 Sep, 2021
diag() function in R Language is used to construct a diagonal matrix.
Syntax: diag(x, nrow, ncol)Parameters: x: value present as the diagonal elements. nrow, ncol: number of rows and columns in which elements are represented.
Example 1:
Python3
# R program to illustrate# diag function # Calling the diag() function with# some number which will act as# rows as well as columns numberdiag(3)diag(5)
Output:
[, 1] [, 2] [, 3]
[1, ] 1 0 0
[2, ] 0 1 0
[3, ] 0 0 1
[, 1] [, 2] [, 3] [, 4] [, 5]
[1, ] 1 0 0 0 0
[2, ] 0 1 0 0 0
[3, ] 0 0 1 0 0
[4, ] 0 0 0 1 0
[5, ] 0 0 0 0 1
Example 2:
Python3
# R program to illustrate# diag function # Calling the diag() functiondiag(5, 2, 3)diag(10, 3, 3)
Output:
[, 1] [, 2] [, 3]
[1, ] 5 0 0
[2, ] 0 5 0
[, 1] [, 2] [, 3]
[1, ] 10 0 0
[2, ] 0 10 0
[3, ] 0 0 10
gulshankumarar231
R Matrix-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 99,
"s": 28,
"text": "diag() function in R Language is used to construct a diagonal matrix. "
},
{
"code": null,
"e": 257,
"s": 99,
"text": "Syntax: diag(x, nrow, ncol)Parameters: x: value present as the diagonal elements. nrow, ncol: number of rows and columns in which elements are represented. "
},
{
"code": null,
"e": 270,
"s": 257,
"text": "Example 1: "
},
{
"code": null,
"e": 278,
"s": 270,
"text": "Python3"
},
{
"code": "# R program to illustrate# diag function # Calling the diag() function with# some number which will act as# rows as well as columns numberdiag(3)diag(5)",
"e": 431,
"s": 278,
"text": null
},
{
"code": null,
"e": 441,
"s": 431,
"text": "Output: "
},
{
"code": null,
"e": 718,
"s": 441,
"text": " [, 1] [, 2] [, 3]\n[1, ] 1 0 0\n[2, ] 0 1 0\n[3, ] 0 0 1\n\n [, 1] [, 2] [, 3] [, 4] [, 5]\n[1, ] 1 0 0 0 0\n[2, ] 0 1 0 0 0\n[3, ] 0 0 1 0 0\n[4, ] 0 0 0 1 0\n[5, ] 0 0 0 0 1"
},
{
"code": null,
"e": 731,
"s": 718,
"text": "Example 2: "
},
{
"code": null,
"e": 739,
"s": 731,
"text": "Python3"
},
{
"code": "# R program to illustrate# diag function # Calling the diag() functiondiag(5, 2, 3)diag(10, 3, 3)",
"e": 837,
"s": 739,
"text": null
},
{
"code": null,
"e": 847,
"s": 837,
"text": "Output: "
},
{
"code": null,
"e": 999,
"s": 847,
"text": " [, 1] [, 2] [, 3]\n[1, ] 5 0 0\n[2, ] 0 5 0\n\n [, 1] [, 2] [, 3]\n[1, ] 10 0 0\n[2, ] 0 10 0\n[3, ] 0 0 10"
},
{
"code": null,
"e": 1019,
"s": 1001,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 1037,
"s": 1019,
"text": "R Matrix-Function"
},
{
"code": null,
"e": 1048,
"s": 1037,
"text": "R Language"
}
] |
Custom Django Management Commands
|
06 Aug, 2021
Prerequisites: Django Introduction and Installation
Manage.py in Django is a command-line utility that works similar to the django-admin command. The difference is that it points towards the projectβs settings.py file. This manage.py utility provides various commands that you must have while working with Django. Some of the most commonly used commands are β
python manage.py startapp
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
Interestingly we can create our own Custom Management Commands to fulfill a wide variety of requirements ranging from interacting with our application using the command line to serve as an interface to execute Cron Jobs. We are going to create a custom Management Command which gives us the stats or metrics of new articles published, comments on those articles on a particular day.
Follow Django Introduction and Installation to setup a virtual environment and install Django
Step 1: Initialize a project by following command
django-admin startproject geeks_site
Step 2: Create an app named blog
python manage.py startapp blog
Step 3: Add your app to the settings.py
In geeks_site/settings.py
Python3
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog',]
Step 4: Create Models named Article and Comment in the blog app
Model Article :
Fields :title: Stores the title of an articlebody: Content of that articlecreated_on: Date and Time on which that article was created
title: Stores the title of an article
body: Content of that article
created_on: Date and Time on which that article was created
Model Comment :
Fields :article: Article on which comment is createdtext: Actual commentcreated_on: Date and Time on which that article was created
article: Article on which comment is created
text: Actual comment
created_on: Date and Time on which that article was created
In blog/models.py
Python3
from django.db import models class Article(models.Model): title = models.CharField(max_length=200) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) text = models.CharField(max_length=200) created_on = models.DateTimeField(auto_now_add=True)
Step 5: Register your model in blog/admin.py so that it shows up in the admin panel.
In blog/admin.py
Python3
from django.contrib import admin from .models import Article, Comment admin.site.register(Article)admin.site.register(Comment)
Step 6: Now, To migrate all your changes and start the server, run the following commands in your terminal
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
Create a superuser account to log in to the admin panel
python manage.py createsuperuser
Now, Visit the admin panel at http://127.0.0.1:8000/admin/
Create some articles and then some comments :
Now, Letβs start working on the creation of Custom Django Management Commands
Add a management/commands directory to the blog app
Add __init__.py to blog/management and __init__.py + stats.py files to blog/management/commands directory
Note: Django will register a manage.py command for each Python module in that directory whose name doesnβt begin with an underscore
The folder structure of the blog app looks like this :
We will use python manage.py stats to run our custom management command. Now we will configure what actually this command will do.
In stats.py
Python3
from django.core.management.base import BaseCommandfrom django.db.models import Countfrom blog.models import Article, Commentfrom datetime import timedelta, datetimefrom django.utils.timezone import utc def now(): return datetime.utcnow().replace(tzinfo=utc) class Command(BaseCommand): help = 'Displays stats related to Article and Comment models' def handle(self, *args, **kwargs): From = now() - timedelta(hours=5) To = now() articles_published_in_last_5_hour = Article.objects.filter( created_on__gt=From, created_on__lte=To).count() comments_published_per_article = Comment.objects.filter( created_on__gt=From, created_on__lte=To).values( 'article').annotate(count=Count('article')).order_by() print("Articles Published in last 5 hours = ", articles_published_in_last_5_hour) print("Comments per Article in last 5 hours") for data in comments_published_per_article: print(data)
Understanding the stats.py file
Basically, a Django management command is built from a class named Command which inherits from BaseCommand.
1) help: It tells what actually the command does. Run the following command and see the help
python manage.py stats --help
2) handle(): It handles all the logic which needs to be executed when the command is executed. Letβs understand of code inside handle() method
Here we are concerned about the following two statsNumber of articles which were published in last 5 hoursNumber of comments created in last 5 hours per article
Number of articles which were published in last 5 hours
Number of comments created in last 5 hours per article
From: Current time β 5 hours
To: Current Time
articles_published_in_last_5_hour : an integer value
comments_published_per_article : queryset object or a list of dictionaries
print statements to output data on terminal
Now, Run the following command in your terminal :
python manage.py stats
Output :
Django uses the argparse module to handle the custom arguments. We need to define a function add_arguments under the command class to handle arguments.
Python3
from django.core.management.base import BaseCommandfrom django.db.models import Countfrom app.models import Article, Commentfrom datetime import timedelta, datetimefrom django.utils.timezone import utc def now(): return datetime.utcnow().replace(tzinfo=utc) class Command(BaseCommand): help = 'Displays stats related to Article and Comment models' def add_arguments(self, parser): parser.add_argument('-t', '--time', type=int, help='Articles published in last t hours') def handle(self, *args, **kwargs): t = kwargs['time'] if not t: t=5 From = now() - timedelta(hours=t) To = now() articles_published_in_last_t_hour = Article.objects.filter( created_on__gt=From, created_on__lte=To).count() comments_published_per_article = Comment.objects.filter( created_on__gt=From, created_on__lte=To).values( 'article').annotate(count=Count('article')).order_by() print(f"Articles Published in last {t} hours = ", articles_published_in_last_t_hour) print(f"Comments per Article in last {t} hours") for data in comments_published_per_article: print(data)
Output:
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n06 Aug, 2021"
},
{
"code": null,
"e": 106,
"s": 53,
"text": "Prerequisites: Django Introduction and Installation"
},
{
"code": null,
"e": 414,
"s": 106,
"text": "Manage.py in Django is a command-line utility that works similar to the django-admin command. The difference is that it points towards the projectβs settings.py file. This manage.py utility provides various commands that you must have while working with Django. Some of the most commonly used commands are β"
},
{
"code": null,
"e": 440,
"s": 414,
"text": "python manage.py startapp"
},
{
"code": null,
"e": 472,
"s": 440,
"text": "python manage.py makemigrations"
},
{
"code": null,
"e": 497,
"s": 472,
"text": "python manage.py migrate"
},
{
"code": null,
"e": 524,
"s": 497,
"text": "python manage.py runserver"
},
{
"code": null,
"e": 907,
"s": 524,
"text": "Interestingly we can create our own Custom Management Commands to fulfill a wide variety of requirements ranging from interacting with our application using the command line to serve as an interface to execute Cron Jobs. We are going to create a custom Management Command which gives us the stats or metrics of new articles published, comments on those articles on a particular day."
},
{
"code": null,
"e": 1001,
"s": 907,
"text": "Follow Django Introduction and Installation to setup a virtual environment and install Django"
},
{
"code": null,
"e": 1051,
"s": 1001,
"text": "Step 1: Initialize a project by following command"
},
{
"code": null,
"e": 1088,
"s": 1051,
"text": "django-admin startproject geeks_site"
},
{
"code": null,
"e": 1121,
"s": 1088,
"text": "Step 2: Create an app named blog"
},
{
"code": null,
"e": 1152,
"s": 1121,
"text": "python manage.py startapp blog"
},
{
"code": null,
"e": 1192,
"s": 1152,
"text": "Step 3: Add your app to the settings.py"
},
{
"code": null,
"e": 1218,
"s": 1192,
"text": "In geeks_site/settings.py"
},
{
"code": null,
"e": 1226,
"s": 1218,
"text": "Python3"
},
{
"code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog',]",
"e": 1465,
"s": 1226,
"text": null
},
{
"code": null,
"e": 1529,
"s": 1465,
"text": "Step 4: Create Models named Article and Comment in the blog app"
},
{
"code": null,
"e": 1545,
"s": 1529,
"text": "Model Article :"
},
{
"code": null,
"e": 1679,
"s": 1545,
"text": "Fields :title: Stores the title of an articlebody: Content of that articlecreated_on: Date and Time on which that article was created"
},
{
"code": null,
"e": 1717,
"s": 1679,
"text": "title: Stores the title of an article"
},
{
"code": null,
"e": 1747,
"s": 1717,
"text": "body: Content of that article"
},
{
"code": null,
"e": 1807,
"s": 1747,
"text": "created_on: Date and Time on which that article was created"
},
{
"code": null,
"e": 1823,
"s": 1807,
"text": "Model Comment :"
},
{
"code": null,
"e": 1956,
"s": 1823,
"text": "Fields :article: Article on which comment is createdtext: Actual commentcreated_on: Date and Time on which that article was created"
},
{
"code": null,
"e": 2002,
"s": 1956,
"text": "article: Article on which comment is created"
},
{
"code": null,
"e": 2023,
"s": 2002,
"text": "text: Actual comment"
},
{
"code": null,
"e": 2083,
"s": 2023,
"text": "created_on: Date and Time on which that article was created"
},
{
"code": null,
"e": 2101,
"s": 2083,
"text": "In blog/models.py"
},
{
"code": null,
"e": 2109,
"s": 2101,
"text": "Python3"
},
{
"code": "from django.db import models class Article(models.Model): title = models.CharField(max_length=200) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) text = models.CharField(max_length=200) created_on = models.DateTimeField(auto_now_add=True)",
"e": 2496,
"s": 2109,
"text": null
},
{
"code": null,
"e": 2581,
"s": 2496,
"text": "Step 5: Register your model in blog/admin.py so that it shows up in the admin panel."
},
{
"code": null,
"e": 2598,
"s": 2581,
"text": "In blog/admin.py"
},
{
"code": null,
"e": 2606,
"s": 2598,
"text": "Python3"
},
{
"code": "from django.contrib import admin from .models import Article, Comment admin.site.register(Article)admin.site.register(Comment)",
"e": 2736,
"s": 2606,
"text": null
},
{
"code": null,
"e": 2843,
"s": 2736,
"text": "Step 6: Now, To migrate all your changes and start the server, run the following commands in your terminal"
},
{
"code": null,
"e": 2927,
"s": 2843,
"text": "python manage.py makemigrations\npython manage.py migrate\npython manage.py runserver"
},
{
"code": null,
"e": 2983,
"s": 2927,
"text": "Create a superuser account to log in to the admin panel"
},
{
"code": null,
"e": 3016,
"s": 2983,
"text": "python manage.py createsuperuser"
},
{
"code": null,
"e": 3075,
"s": 3016,
"text": "Now, Visit the admin panel at http://127.0.0.1:8000/admin/"
},
{
"code": null,
"e": 3121,
"s": 3075,
"text": "Create some articles and then some comments :"
},
{
"code": null,
"e": 3199,
"s": 3121,
"text": "Now, Letβs start working on the creation of Custom Django Management Commands"
},
{
"code": null,
"e": 3251,
"s": 3199,
"text": "Add a management/commands directory to the blog app"
},
{
"code": null,
"e": 3357,
"s": 3251,
"text": "Add __init__.py to blog/management and __init__.py + stats.py files to blog/management/commands directory"
},
{
"code": null,
"e": 3489,
"s": 3357,
"text": "Note: Django will register a manage.py command for each Python module in that directory whose name doesnβt begin with an underscore"
},
{
"code": null,
"e": 3544,
"s": 3489,
"text": "The folder structure of the blog app looks like this :"
},
{
"code": null,
"e": 3675,
"s": 3544,
"text": "We will use python manage.py stats to run our custom management command. Now we will configure what actually this command will do."
},
{
"code": null,
"e": 3687,
"s": 3675,
"text": "In stats.py"
},
{
"code": null,
"e": 3695,
"s": 3687,
"text": "Python3"
},
{
"code": "from django.core.management.base import BaseCommandfrom django.db.models import Countfrom blog.models import Article, Commentfrom datetime import timedelta, datetimefrom django.utils.timezone import utc def now(): return datetime.utcnow().replace(tzinfo=utc) class Command(BaseCommand): help = 'Displays stats related to Article and Comment models' def handle(self, *args, **kwargs): From = now() - timedelta(hours=5) To = now() articles_published_in_last_5_hour = Article.objects.filter( created_on__gt=From, created_on__lte=To).count() comments_published_per_article = Comment.objects.filter( created_on__gt=From, created_on__lte=To).values( 'article').annotate(count=Count('article')).order_by() print(\"Articles Published in last 5 hours = \", articles_published_in_last_5_hour) print(\"Comments per Article in last 5 hours\") for data in comments_published_per_article: print(data)",
"e": 4713,
"s": 3695,
"text": null
},
{
"code": null,
"e": 4745,
"s": 4713,
"text": "Understanding the stats.py file"
},
{
"code": null,
"e": 4853,
"s": 4745,
"text": "Basically, a Django management command is built from a class named Command which inherits from BaseCommand."
},
{
"code": null,
"e": 4946,
"s": 4853,
"text": "1) help: It tells what actually the command does. Run the following command and see the help"
},
{
"code": null,
"e": 4976,
"s": 4946,
"text": "python manage.py stats --help"
},
{
"code": null,
"e": 5119,
"s": 4976,
"text": "2) handle(): It handles all the logic which needs to be executed when the command is executed. Letβs understand of code inside handle() method"
},
{
"code": null,
"e": 5281,
"s": 5119,
"text": "Here we are concerned about the following two statsNumber of articles which were published in last 5 hoursNumber of comments created in last 5 hours per article"
},
{
"code": null,
"e": 5337,
"s": 5281,
"text": "Number of articles which were published in last 5 hours"
},
{
"code": null,
"e": 5393,
"s": 5337,
"text": "Number of comments created in last 5 hours per article"
},
{
"code": null,
"e": 5422,
"s": 5393,
"text": "From: Current time β 5 hours"
},
{
"code": null,
"e": 5439,
"s": 5422,
"text": "To: Current Time"
},
{
"code": null,
"e": 5492,
"s": 5439,
"text": "articles_published_in_last_5_hour : an integer value"
},
{
"code": null,
"e": 5568,
"s": 5492,
"text": "comments_published_per_article : queryset object or a list of dictionaries"
},
{
"code": null,
"e": 5612,
"s": 5568,
"text": "print statements to output data on terminal"
},
{
"code": null,
"e": 5662,
"s": 5612,
"text": "Now, Run the following command in your terminal :"
},
{
"code": null,
"e": 5685,
"s": 5662,
"text": "python manage.py stats"
},
{
"code": null,
"e": 5695,
"s": 5685,
"text": "Output : "
},
{
"code": null,
"e": 5847,
"s": 5695,
"text": "Django uses the argparse module to handle the custom arguments. We need to define a function add_arguments under the command class to handle arguments."
},
{
"code": null,
"e": 5855,
"s": 5847,
"text": "Python3"
},
{
"code": "from django.core.management.base import BaseCommandfrom django.db.models import Countfrom app.models import Article, Commentfrom datetime import timedelta, datetimefrom django.utils.timezone import utc def now(): return datetime.utcnow().replace(tzinfo=utc) class Command(BaseCommand): help = 'Displays stats related to Article and Comment models' def add_arguments(self, parser): parser.add_argument('-t', '--time', type=int, help='Articles published in last t hours') def handle(self, *args, **kwargs): t = kwargs['time'] if not t: t=5 From = now() - timedelta(hours=t) To = now() articles_published_in_last_t_hour = Article.objects.filter( created_on__gt=From, created_on__lte=To).count() comments_published_per_article = Comment.objects.filter( created_on__gt=From, created_on__lte=To).values( 'article').annotate(count=Count('article')).order_by() print(f\"Articles Published in last {t} hours = \", articles_published_in_last_t_hour) print(f\"Comments per Article in last {t} hours\") for data in comments_published_per_article: print(data)",
"e": 7072,
"s": 5855,
"text": null
},
{
"code": null,
"e": 7080,
"s": 7072,
"text": "Output:"
},
{
"code": null,
"e": 7094,
"s": 7080,
"text": "Python Django"
},
{
"code": null,
"e": 7101,
"s": 7094,
"text": "Python"
}
] |
LocalDateTime toLocalDate() method in Java with Examples
|
30 Nov, 2018
The toLocalDate() method of LocalDateTime class is used to get the LocalDate representation of this LocalDateTime. This method is derived from the Object Class and behaves in the similar way.
Syntax:
public LocalDate toLocalDate()
Parameter: This method takes no parameters.
Returns: This method returns a LocalDate value which is the LocalDate representation of this LocalDateTime.
Below programs illustrate the LocalDateTime.toLocalDate() method:
Program 1:
// Program to illustrate the toLocalDate() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Get the LocalDateTime instance LocalDateTime dt = LocalDateTime.now(); // Get the LocalDate representation of this LocalDateTime // using toLocalDate() method System.out.println(dt.toLocalDate()); }}
2018-11-30
Program 2:
// Program to illustrate the toLocalDate() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Get the LocalDateTime instance LocalDateTime dt = LocalDateTime .parse("2018-11-03T12:45:30"); // Get the LocalDate representation of this LocalDateTime // using toLocalDate() method System.out.println(dt.toLocalDate()); }}
2018-11-03
Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#toLocalDate()
Java-Functions
Java-LocalDateTime
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Nov, 2018"
},
{
"code": null,
"e": 220,
"s": 28,
"text": "The toLocalDate() method of LocalDateTime class is used to get the LocalDate representation of this LocalDateTime. This method is derived from the Object Class and behaves in the similar way."
},
{
"code": null,
"e": 228,
"s": 220,
"text": "Syntax:"
},
{
"code": null,
"e": 259,
"s": 228,
"text": "public LocalDate toLocalDate()"
},
{
"code": null,
"e": 303,
"s": 259,
"text": "Parameter: This method takes no parameters."
},
{
"code": null,
"e": 411,
"s": 303,
"text": "Returns: This method returns a LocalDate value which is the LocalDate representation of this LocalDateTime."
},
{
"code": null,
"e": 477,
"s": 411,
"text": "Below programs illustrate the LocalDateTime.toLocalDate() method:"
},
{
"code": null,
"e": 488,
"s": 477,
"text": "Program 1:"
},
{
"code": "// Program to illustrate the toLocalDate() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Get the LocalDateTime instance LocalDateTime dt = LocalDateTime.now(); // Get the LocalDate representation of this LocalDateTime // using toLocalDate() method System.out.println(dt.toLocalDate()); }}",
"e": 890,
"s": 488,
"text": null
},
{
"code": null,
"e": 902,
"s": 890,
"text": "2018-11-30\n"
},
{
"code": null,
"e": 913,
"s": 902,
"text": "Program 2:"
},
{
"code": "// Program to illustrate the toLocalDate() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Get the LocalDateTime instance LocalDateTime dt = LocalDateTime .parse(\"2018-11-03T12:45:30\"); // Get the LocalDate representation of this LocalDateTime // using toLocalDate() method System.out.println(dt.toLocalDate()); }}",
"e": 1367,
"s": 913,
"text": null
},
{
"code": null,
"e": 1379,
"s": 1367,
"text": "2018-11-03\n"
},
{
"code": null,
"e": 1476,
"s": 1379,
"text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#toLocalDate()"
},
{
"code": null,
"e": 1491,
"s": 1476,
"text": "Java-Functions"
},
{
"code": null,
"e": 1510,
"s": 1491,
"text": "Java-LocalDateTime"
},
{
"code": null,
"e": 1528,
"s": 1510,
"text": "Java-time package"
},
{
"code": null,
"e": 1533,
"s": 1528,
"text": "Java"
},
{
"code": null,
"e": 1538,
"s": 1533,
"text": "Java"
}
] |
Basic Code Optimizations in C - GeeksforGeeks
|
28 Jun, 2019
Generally, resources are shared between different processes. Suppose your program takes more resources, then definitely it will affect the performance of other processes that need the same resources. So we have a need to write and optimize our program keeping in mind resources e.g. processorβs time and main memory.Following are some Optimization techniques
Optimizations in loopUnroll small loops: Most of the times Compiler does this automatically, but it is a good habit of writing optimized codes. Matrix updations using this is very advantageous.Program 1:#include <stdio.h>int main(void){ int fact[5]; fact[0] = 1; // Overhead of managing a counter // just for 4 iterations // is not a good idea for (int i = 1; i < 5; ++i) { fact[i] = fact[i - 1] * i; } return 0;}Program 2:#include <stdio.h>int main(void){ int fact[5] = { 1, 1, 2, 6, 24 }; // Here the same work is done // without counter overhead return 0;}Avoid calculations in loop: We should avoid any calculation which is more or less constant in value. Inner loops should have minimum possible calculations.Program 1:#include <stdio.h>int main(void){ int arr[1000]; int a = 1, b = 5, c = 25, d = 7; // Calculating a constant expression // for each iteration is not good. for (int i = 0; i < 1000; ++i) { arr[i] = (((c % d) * a / b) % d) * i; } return 0;}Program 2:#include <stdio.h> int main(void){ int arr[1000]; int a = 1, b = 5, c = 25, d = 7; // pre calculating the constant expression int temp = (((c % d) * a / b) % d); for (int i = 0; i < 1000; ++i) { arr[i] = temp * i; } return 0;}Avoid pointer Dereference in loop: Pointer dereferencing creates lots of trouble in memory. So better assign it to some temporary variable and then use that temporary variable in the loop.Program 1:#include <stdio.h>int main(void){ int a = 0; int* iptr = &a; // Dereferencing pointer inside loop // is costly for (int i = 1; i < 11; ++i) { *iptr = *iptr + i; } printf("Value of a : %d", a); return 0;}Output:Value of a : 55
Program 2:#include <stdio.h>int main(void){ int a = 0; int* iptr = &a; // Dereferencing pointer outside loop // and saving its value in a temp variable int temp = *iptr; for (int i = 1; i < 11; ++i) { // performing calculations on temp variable temp = temp + i; } // Updating pointer using final value of temp *iptr = temp; printf("Value of a : %d", a); return 0;}Output:Value of a : 55
Use Register variables as counters of inner loops: Variables stored in registers can be accessed much faster than variables stored in memory.Program:#include <stdio.h>int main(void){ register int i = 0; register int j = 0; int n = 5; // using register variables // as counters make the loop faster for (i = 0; i < n; ++i) { for (j = 0; j <= i; ++j) { printf("* "); } printf("\n"); } return 0;}Output:*
* *
* * *
* * * *
* * * * *
Fast MathematicsAvoid unnecessary Integer Division: Division operations are slow so we should minimize the division operations.Program:#include <stdio.h>int main(void){ int a = 100, b = 2, c = 5; // int d=a/b/c; two division operators int d = a / (b * c); // single division operator return 0;}Multiplication and division by power of 2: Use left shift(<<) for multiplication and right shift(>>) for division. The bit operations will be much faster than multiplication and division operations.For simple operations, the compiler may automatically optimize the code but in case of complex expressions it is always advised to use bit operations.Example :Multiply by 6 : a= a<<1 + a<<2;
Multiply by 7 : a= a<<3 - a;
Divide by 8 : a= a>>3; // division by power of 2
Simplifying Expressions: Sometimes we can reduce some operations by simplifying expressions.Example : a*b + a*b*c + a*b*c*d ---> (a*b)*(1 + c*(1 + d))
L.H.S can be Simplified to R.H.S
L.H.S : 6 multiplications and 2 additions
R.H.S : 3 multiplications and 2 additions
Optimization with Switch StatementCompilers translate switch statements in different ways. If case labels are small contiguous integer values, then it creates a jump table. This is very fast and doesnβt depend on the number of case labels also. If case labels are longer and not contiguous then it creates comparison tree i.e. if...else statements. So, in this case, we should keep the most frequent label first and the least frequent label should be at last.Sometimes we see a lot of repeated code written in all cases except one or two statementsExample :switch(expression)
{
case a:
........
........
break;
case b:
........
........
break;
case c:
common statements;
different statements;
common statements;
break;
case d:
common statements;
different statements;
common statements;
break; '
case e:
common statements;
different statements;
common statements;
break;
case f:
common statements;
different statements;
common statements;
break;
default:
break;
}
We can take all cases together and can write common statements only once and different statements in related cases using another switch. Here we will take cases c, d, e, f together and write common statements, then we can use another switch and write different statements in case c, d, e, f. Then after this switch, we can again write common statements.switch(expression)
{
case a:
........
........
break;
case b:
........
........
break;
case c:
case d:
case e:
case f:
common statements;
switch(expression);
{
case c:
different statements;
break;
case d:
different statements;
break;
case e:
different statements;
break;
case f:
different statements;
break;
} /*End of switch*/
common statements;
break;
default:
break;
}/*End of switch*/
Prefer int to char or shortWe should always prefer int to char because C performs all operations of char with an integer. In all operations like passing char to a function or an arithmetic operation, first char will be converted into integer and after compilation of operation, it will again be converted into char. For a single char, this may not affect the efficiency but suppose the same operation is performed 100 times in a loop then it can decrease the efficiency of the program.Prefer pre Increment/Decrement to post Increment/DecrementIn pre-increment, it first increments the value and just copies the value to variable location but in post-increment, it first copies the value to a temporary variable, increments it and then copies the value to the variable location. If post-increment is 1000 times in a loop it will decrement the efficiency.Order of Expression Evaluation A || B
Here first A will be evaluated, if itβs true then there is no need of evaluation of expression B. So We should prefer to have an expression which evaluates to true most of the times, at the Aβs place. A && B
Here first A will be evaluated, if itβs false then there is no need of evaluation of expression B. So We should prefer to have an expression which evaluates to false most of the times, at the Aβs place.
Optimizations in loopUnroll small loops: Most of the times Compiler does this automatically, but it is a good habit of writing optimized codes. Matrix updations using this is very advantageous.Program 1:#include <stdio.h>int main(void){ int fact[5]; fact[0] = 1; // Overhead of managing a counter // just for 4 iterations // is not a good idea for (int i = 1; i < 5; ++i) { fact[i] = fact[i - 1] * i; } return 0;}Program 2:#include <stdio.h>int main(void){ int fact[5] = { 1, 1, 2, 6, 24 }; // Here the same work is done // without counter overhead return 0;}Avoid calculations in loop: We should avoid any calculation which is more or less constant in value. Inner loops should have minimum possible calculations.Program 1:#include <stdio.h>int main(void){ int arr[1000]; int a = 1, b = 5, c = 25, d = 7; // Calculating a constant expression // for each iteration is not good. for (int i = 0; i < 1000; ++i) { arr[i] = (((c % d) * a / b) % d) * i; } return 0;}Program 2:#include <stdio.h> int main(void){ int arr[1000]; int a = 1, b = 5, c = 25, d = 7; // pre calculating the constant expression int temp = (((c % d) * a / b) % d); for (int i = 0; i < 1000; ++i) { arr[i] = temp * i; } return 0;}Avoid pointer Dereference in loop: Pointer dereferencing creates lots of trouble in memory. So better assign it to some temporary variable and then use that temporary variable in the loop.Program 1:#include <stdio.h>int main(void){ int a = 0; int* iptr = &a; // Dereferencing pointer inside loop // is costly for (int i = 1; i < 11; ++i) { *iptr = *iptr + i; } printf("Value of a : %d", a); return 0;}Output:Value of a : 55
Program 2:#include <stdio.h>int main(void){ int a = 0; int* iptr = &a; // Dereferencing pointer outside loop // and saving its value in a temp variable int temp = *iptr; for (int i = 1; i < 11; ++i) { // performing calculations on temp variable temp = temp + i; } // Updating pointer using final value of temp *iptr = temp; printf("Value of a : %d", a); return 0;}Output:Value of a : 55
Use Register variables as counters of inner loops: Variables stored in registers can be accessed much faster than variables stored in memory.Program:#include <stdio.h>int main(void){ register int i = 0; register int j = 0; int n = 5; // using register variables // as counters make the loop faster for (i = 0; i < n; ++i) { for (j = 0; j <= i; ++j) { printf("* "); } printf("\n"); } return 0;}Output:*
* *
* * *
* * * *
* * * * *
Unroll small loops: Most of the times Compiler does this automatically, but it is a good habit of writing optimized codes. Matrix updations using this is very advantageous.Program 1:#include <stdio.h>int main(void){ int fact[5]; fact[0] = 1; // Overhead of managing a counter // just for 4 iterations // is not a good idea for (int i = 1; i < 5; ++i) { fact[i] = fact[i - 1] * i; } return 0;}Program 2:#include <stdio.h>int main(void){ int fact[5] = { 1, 1, 2, 6, 24 }; // Here the same work is done // without counter overhead return 0;}
Program 1:
#include <stdio.h>int main(void){ int fact[5]; fact[0] = 1; // Overhead of managing a counter // just for 4 iterations // is not a good idea for (int i = 1; i < 5; ++i) { fact[i] = fact[i - 1] * i; } return 0;}
Program 2:
#include <stdio.h>int main(void){ int fact[5] = { 1, 1, 2, 6, 24 }; // Here the same work is done // without counter overhead return 0;}
Avoid calculations in loop: We should avoid any calculation which is more or less constant in value. Inner loops should have minimum possible calculations.Program 1:#include <stdio.h>int main(void){ int arr[1000]; int a = 1, b = 5, c = 25, d = 7; // Calculating a constant expression // for each iteration is not good. for (int i = 0; i < 1000; ++i) { arr[i] = (((c % d) * a / b) % d) * i; } return 0;}Program 2:#include <stdio.h> int main(void){ int arr[1000]; int a = 1, b = 5, c = 25, d = 7; // pre calculating the constant expression int temp = (((c % d) * a / b) % d); for (int i = 0; i < 1000; ++i) { arr[i] = temp * i; } return 0;}
#include <stdio.h>int main(void){ int arr[1000]; int a = 1, b = 5, c = 25, d = 7; // Calculating a constant expression // for each iteration is not good. for (int i = 0; i < 1000; ++i) { arr[i] = (((c % d) * a / b) % d) * i; } return 0;}
Program 2:
#include <stdio.h> int main(void){ int arr[1000]; int a = 1, b = 5, c = 25, d = 7; // pre calculating the constant expression int temp = (((c % d) * a / b) % d); for (int i = 0; i < 1000; ++i) { arr[i] = temp * i; } return 0;}
Avoid pointer Dereference in loop: Pointer dereferencing creates lots of trouble in memory. So better assign it to some temporary variable and then use that temporary variable in the loop.Program 1:#include <stdio.h>int main(void){ int a = 0; int* iptr = &a; // Dereferencing pointer inside loop // is costly for (int i = 1; i < 11; ++i) { *iptr = *iptr + i; } printf("Value of a : %d", a); return 0;}Output:Value of a : 55
Program 2:#include <stdio.h>int main(void){ int a = 0; int* iptr = &a; // Dereferencing pointer outside loop // and saving its value in a temp variable int temp = *iptr; for (int i = 1; i < 11; ++i) { // performing calculations on temp variable temp = temp + i; } // Updating pointer using final value of temp *iptr = temp; printf("Value of a : %d", a); return 0;}Output:Value of a : 55
#include <stdio.h>int main(void){ int a = 0; int* iptr = &a; // Dereferencing pointer inside loop // is costly for (int i = 1; i < 11; ++i) { *iptr = *iptr + i; } printf("Value of a : %d", a); return 0;}
Value of a : 55
Program 2:
#include <stdio.h>int main(void){ int a = 0; int* iptr = &a; // Dereferencing pointer outside loop // and saving its value in a temp variable int temp = *iptr; for (int i = 1; i < 11; ++i) { // performing calculations on temp variable temp = temp + i; } // Updating pointer using final value of temp *iptr = temp; printf("Value of a : %d", a); return 0;}
Value of a : 55
Use Register variables as counters of inner loops: Variables stored in registers can be accessed much faster than variables stored in memory.Program:#include <stdio.h>int main(void){ register int i = 0; register int j = 0; int n = 5; // using register variables // as counters make the loop faster for (i = 0; i < n; ++i) { for (j = 0; j <= i; ++j) { printf("* "); } printf("\n"); } return 0;}Output:*
* *
* * *
* * * *
* * * * *
#include <stdio.h>int main(void){ register int i = 0; register int j = 0; int n = 5; // using register variables // as counters make the loop faster for (i = 0; i < n; ++i) { for (j = 0; j <= i; ++j) { printf("* "); } printf("\n"); } return 0;}
*
* *
* * *
* * * *
* * * * *
Fast MathematicsAvoid unnecessary Integer Division: Division operations are slow so we should minimize the division operations.Program:#include <stdio.h>int main(void){ int a = 100, b = 2, c = 5; // int d=a/b/c; two division operators int d = a / (b * c); // single division operator return 0;}Multiplication and division by power of 2: Use left shift(<<) for multiplication and right shift(>>) for division. The bit operations will be much faster than multiplication and division operations.For simple operations, the compiler may automatically optimize the code but in case of complex expressions it is always advised to use bit operations.Example :Multiply by 6 : a= a<<1 + a<<2;
Multiply by 7 : a= a<<3 - a;
Divide by 8 : a= a>>3; // division by power of 2
Simplifying Expressions: Sometimes we can reduce some operations by simplifying expressions.Example : a*b + a*b*c + a*b*c*d ---> (a*b)*(1 + c*(1 + d))
L.H.S can be Simplified to R.H.S
L.H.S : 6 multiplications and 2 additions
R.H.S : 3 multiplications and 2 additions
Avoid unnecessary Integer Division: Division operations are slow so we should minimize the division operations.Program:#include <stdio.h>int main(void){ int a = 100, b = 2, c = 5; // int d=a/b/c; two division operators int d = a / (b * c); // single division operator return 0;}
#include <stdio.h>int main(void){ int a = 100, b = 2, c = 5; // int d=a/b/c; two division operators int d = a / (b * c); // single division operator return 0;}
Multiplication and division by power of 2: Use left shift(<<) for multiplication and right shift(>>) for division. The bit operations will be much faster than multiplication and division operations.For simple operations, the compiler may automatically optimize the code but in case of complex expressions it is always advised to use bit operations.Example :Multiply by 6 : a= a<<1 + a<<2;
Multiply by 7 : a= a<<3 - a;
Divide by 8 : a= a>>3; // division by power of 2
Multiply by 6 : a= a<<1 + a<<2;
Multiply by 7 : a= a<<3 - a;
Divide by 8 : a= a>>3; // division by power of 2
Simplifying Expressions: Sometimes we can reduce some operations by simplifying expressions.Example : a*b + a*b*c + a*b*c*d ---> (a*b)*(1 + c*(1 + d))
L.H.S can be Simplified to R.H.S
L.H.S : 6 multiplications and 2 additions
R.H.S : 3 multiplications and 2 additions
a*b + a*b*c + a*b*c*d ---> (a*b)*(1 + c*(1 + d))
L.H.S can be Simplified to R.H.S
L.H.S : 6 multiplications and 2 additions
R.H.S : 3 multiplications and 2 additions
Optimization with Switch StatementCompilers translate switch statements in different ways. If case labels are small contiguous integer values, then it creates a jump table. This is very fast and doesnβt depend on the number of case labels also. If case labels are longer and not contiguous then it creates comparison tree i.e. if...else statements. So, in this case, we should keep the most frequent label first and the least frequent label should be at last.Sometimes we see a lot of repeated code written in all cases except one or two statementsExample :switch(expression)
{
case a:
........
........
break;
case b:
........
........
break;
case c:
common statements;
different statements;
common statements;
break;
case d:
common statements;
different statements;
common statements;
break; '
case e:
common statements;
different statements;
common statements;
break;
case f:
common statements;
different statements;
common statements;
break;
default:
break;
}
We can take all cases together and can write common statements only once and different statements in related cases using another switch. Here we will take cases c, d, e, f together and write common statements, then we can use another switch and write different statements in case c, d, e, f. Then after this switch, we can again write common statements.switch(expression)
{
case a:
........
........
break;
case b:
........
........
break;
case c:
case d:
case e:
case f:
common statements;
switch(expression);
{
case c:
different statements;
break;
case d:
different statements;
break;
case e:
different statements;
break;
case f:
different statements;
break;
} /*End of switch*/
common statements;
break;
default:
break;
}/*End of switch*/
Sometimes we see a lot of repeated code written in all cases except one or two statements
Example :
switch(expression)
{
case a:
........
........
break;
case b:
........
........
break;
case c:
common statements;
different statements;
common statements;
break;
case d:
common statements;
different statements;
common statements;
break; '
case e:
common statements;
different statements;
common statements;
break;
case f:
common statements;
different statements;
common statements;
break;
default:
break;
}
We can take all cases together and can write common statements only once and different statements in related cases using another switch. Here we will take cases c, d, e, f together and write common statements, then we can use another switch and write different statements in case c, d, e, f. Then after this switch, we can again write common statements.
switch(expression)
{
case a:
........
........
break;
case b:
........
........
break;
case c:
case d:
case e:
case f:
common statements;
switch(expression);
{
case c:
different statements;
break;
case d:
different statements;
break;
case e:
different statements;
break;
case f:
different statements;
break;
} /*End of switch*/
common statements;
break;
default:
break;
}/*End of switch*/
Prefer int to char or shortWe should always prefer int to char because C performs all operations of char with an integer. In all operations like passing char to a function or an arithmetic operation, first char will be converted into integer and after compilation of operation, it will again be converted into char. For a single char, this may not affect the efficiency but suppose the same operation is performed 100 times in a loop then it can decrease the efficiency of the program.
Prefer pre Increment/Decrement to post Increment/DecrementIn pre-increment, it first increments the value and just copies the value to variable location but in post-increment, it first copies the value to a temporary variable, increments it and then copies the value to the variable location. If post-increment is 1000 times in a loop it will decrement the efficiency.
Order of Expression Evaluation A || B
Here first A will be evaluated, if itβs true then there is no need of evaluation of expression B. So We should prefer to have an expression which evaluates to true most of the times, at the Aβs place. A && B
Here first A will be evaluated, if itβs false then there is no need of evaluation of expression B. So We should prefer to have an expression which evaluates to false most of the times, at the Aβs place.
A || B
Here first A will be evaluated, if itβs true then there is no need of evaluation of expression B. So We should prefer to have an expression which evaluates to true most of the times, at the Aβs place.
A || B
Here first A will be evaluated, if itβs true then there is no need of evaluation of expression B. So We should prefer to have an expression which evaluates to true most of the times, at the Aβs place.
A && B
Here first A will be evaluated, if itβs false then there is no need of evaluation of expression B. So We should prefer to have an expression which evaluates to false most of the times, at the Aβs place.
A && B
Here first A will be evaluated, if itβs false then there is no need of evaluation of expression B. So We should prefer to have an expression which evaluates to false most of the times, at the Aβs place.
C Basics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
'this' pointer in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
Multiple Inheritance in C++
Smart Pointers in C++ and How to Use Them
Understanding "extern" keyword in C
Ways to copy a vector in C++
Basics of File Handling in C
|
[
{
"code": null,
"e": 25587,
"s": 25559,
"text": "\n28 Jun, 2019"
},
{
"code": null,
"e": 25946,
"s": 25587,
"text": "Generally, resources are shared between different processes. Suppose your program takes more resources, then definitely it will affect the performance of other processes that need the same resources. So we have a need to write and optimize our program keeping in mind resources e.g. processorβs time and main memory.Following are some Optimization techniques"
},
{
"code": null,
"e": 33134,
"s": 25946,
"text": "Optimizations in loopUnroll small loops: Most of the times Compiler does this automatically, but it is a good habit of writing optimized codes. Matrix updations using this is very advantageous.Program 1:#include <stdio.h>int main(void){ int fact[5]; fact[0] = 1; // Overhead of managing a counter // just for 4 iterations // is not a good idea for (int i = 1; i < 5; ++i) { fact[i] = fact[i - 1] * i; } return 0;}Program 2:#include <stdio.h>int main(void){ int fact[5] = { 1, 1, 2, 6, 24 }; // Here the same work is done // without counter overhead return 0;}Avoid calculations in loop: We should avoid any calculation which is more or less constant in value. Inner loops should have minimum possible calculations.Program 1:#include <stdio.h>int main(void){ int arr[1000]; int a = 1, b = 5, c = 25, d = 7; // Calculating a constant expression // for each iteration is not good. for (int i = 0; i < 1000; ++i) { arr[i] = (((c % d) * a / b) % d) * i; } return 0;}Program 2:#include <stdio.h> int main(void){ int arr[1000]; int a = 1, b = 5, c = 25, d = 7; // pre calculating the constant expression int temp = (((c % d) * a / b) % d); for (int i = 0; i < 1000; ++i) { arr[i] = temp * i; } return 0;}Avoid pointer Dereference in loop: Pointer dereferencing creates lots of trouble in memory. So better assign it to some temporary variable and then use that temporary variable in the loop.Program 1:#include <stdio.h>int main(void){ int a = 0; int* iptr = &a; // Dereferencing pointer inside loop // is costly for (int i = 1; i < 11; ++i) { *iptr = *iptr + i; } printf(\"Value of a : %d\", a); return 0;}Output:Value of a : 55\nProgram 2:#include <stdio.h>int main(void){ int a = 0; int* iptr = &a; // Dereferencing pointer outside loop // and saving its value in a temp variable int temp = *iptr; for (int i = 1; i < 11; ++i) { // performing calculations on temp variable temp = temp + i; } // Updating pointer using final value of temp *iptr = temp; printf(\"Value of a : %d\", a); return 0;}Output:Value of a : 55\nUse Register variables as counters of inner loops: Variables stored in registers can be accessed much faster than variables stored in memory.Program:#include <stdio.h>int main(void){ register int i = 0; register int j = 0; int n = 5; // using register variables // as counters make the loop faster for (i = 0; i < n; ++i) { for (j = 0; j <= i; ++j) { printf(\"* \"); } printf(\"\\n\"); } return 0;}Output:* \n* * \n* * * \n* * * * \n* * * * *\nFast MathematicsAvoid unnecessary Integer Division: Division operations are slow so we should minimize the division operations.Program:#include <stdio.h>int main(void){ int a = 100, b = 2, c = 5; // int d=a/b/c; two division operators int d = a / (b * c); // single division operator return 0;}Multiplication and division by power of 2: Use left shift(<<) for multiplication and right shift(>>) for division. The bit operations will be much faster than multiplication and division operations.For simple operations, the compiler may automatically optimize the code but in case of complex expressions it is always advised to use bit operations.Example :Multiply by 6 : a= a<<1 + a<<2; \nMultiply by 7 : a= a<<3 - a;\nDivide by 8 : a= a>>3; // division by power of 2\nSimplifying Expressions: Sometimes we can reduce some operations by simplifying expressions.Example : a*b + a*b*c + a*b*c*d ---> (a*b)*(1 + c*(1 + d)) \n L.H.S can be Simplified to R.H.S\n L.H.S : 6 multiplications and 2 additions\n R.H.S : 3 multiplications and 2 additions\nOptimization with Switch StatementCompilers translate switch statements in different ways. If case labels are small contiguous integer values, then it creates a jump table. This is very fast and doesnβt depend on the number of case labels also. If case labels are longer and not contiguous then it creates comparison tree i.e. if...else statements. So, in this case, we should keep the most frequent label first and the least frequent label should be at last.Sometimes we see a lot of repeated code written in all cases except one or two statementsExample :switch(expression)\n{\ncase a:\n ........\n ........\n break;\ncase b:\n ........\n ........\n break;\ncase c:\n common statements;\n different statements;\n common statements;\n break;\ncase d:\n common statements;\n different statements;\n common statements;\n break; '\ncase e:\n common statements;\n different statements;\n common statements;\n break;\ncase f:\n common statements;\n different statements;\n common statements;\n break;\ndefault:\n break; \n}\nWe can take all cases together and can write common statements only once and different statements in related cases using another switch. Here we will take cases c, d, e, f together and write common statements, then we can use another switch and write different statements in case c, d, e, f. Then after this switch, we can again write common statements.switch(expression)\n{\ncase a:\n ........\n ........\n break;\ncase b:\n ........\n ........\n break;\ncase c: \ncase d: \ncase e: \ncase f:\n common statements;\n switch(expression);\n {\n case c:\n different statements;\n break;\n case d:\n different statements;\n break;\n case e:\n different statements;\n break;\n case f:\n different statements;\n break;\n } /*End of switch*/\n common statements;\n break; \n \ndefault:\n break; \n}/*End of switch*/\nPrefer int to char or shortWe should always prefer int to char because C performs all operations of char with an integer. In all operations like passing char to a function or an arithmetic operation, first char will be converted into integer and after compilation of operation, it will again be converted into char. For a single char, this may not affect the efficiency but suppose the same operation is performed 100 times in a loop then it can decrease the efficiency of the program.Prefer pre Increment/Decrement to post Increment/DecrementIn pre-increment, it first increments the value and just copies the value to variable location but in post-increment, it first copies the value to a temporary variable, increments it and then copies the value to the variable location. If post-increment is 1000 times in a loop it will decrement the efficiency.Order of Expression Evaluation A || B \nHere first A will be evaluated, if itβs true then there is no need of evaluation of expression B. So We should prefer to have an expression which evaluates to true most of the times, at the Aβs place. A && B \nHere first A will be evaluated, if itβs false then there is no need of evaluation of expression B. So We should prefer to have an expression which evaluates to false most of the times, at the Aβs place."
},
{
"code": null,
"e": 35835,
"s": 33134,
"text": "Optimizations in loopUnroll small loops: Most of the times Compiler does this automatically, but it is a good habit of writing optimized codes. Matrix updations using this is very advantageous.Program 1:#include <stdio.h>int main(void){ int fact[5]; fact[0] = 1; // Overhead of managing a counter // just for 4 iterations // is not a good idea for (int i = 1; i < 5; ++i) { fact[i] = fact[i - 1] * i; } return 0;}Program 2:#include <stdio.h>int main(void){ int fact[5] = { 1, 1, 2, 6, 24 }; // Here the same work is done // without counter overhead return 0;}Avoid calculations in loop: We should avoid any calculation which is more or less constant in value. Inner loops should have minimum possible calculations.Program 1:#include <stdio.h>int main(void){ int arr[1000]; int a = 1, b = 5, c = 25, d = 7; // Calculating a constant expression // for each iteration is not good. for (int i = 0; i < 1000; ++i) { arr[i] = (((c % d) * a / b) % d) * i; } return 0;}Program 2:#include <stdio.h> int main(void){ int arr[1000]; int a = 1, b = 5, c = 25, d = 7; // pre calculating the constant expression int temp = (((c % d) * a / b) % d); for (int i = 0; i < 1000; ++i) { arr[i] = temp * i; } return 0;}Avoid pointer Dereference in loop: Pointer dereferencing creates lots of trouble in memory. So better assign it to some temporary variable and then use that temporary variable in the loop.Program 1:#include <stdio.h>int main(void){ int a = 0; int* iptr = &a; // Dereferencing pointer inside loop // is costly for (int i = 1; i < 11; ++i) { *iptr = *iptr + i; } printf(\"Value of a : %d\", a); return 0;}Output:Value of a : 55\nProgram 2:#include <stdio.h>int main(void){ int a = 0; int* iptr = &a; // Dereferencing pointer outside loop // and saving its value in a temp variable int temp = *iptr; for (int i = 1; i < 11; ++i) { // performing calculations on temp variable temp = temp + i; } // Updating pointer using final value of temp *iptr = temp; printf(\"Value of a : %d\", a); return 0;}Output:Value of a : 55\nUse Register variables as counters of inner loops: Variables stored in registers can be accessed much faster than variables stored in memory.Program:#include <stdio.h>int main(void){ register int i = 0; register int j = 0; int n = 5; // using register variables // as counters make the loop faster for (i = 0; i < n; ++i) { for (j = 0; j <= i; ++j) { printf(\"* \"); } printf(\"\\n\"); } return 0;}Output:* \n* * \n* * * \n* * * * \n* * * * *\n"
},
{
"code": null,
"e": 36421,
"s": 35835,
"text": "Unroll small loops: Most of the times Compiler does this automatically, but it is a good habit of writing optimized codes. Matrix updations using this is very advantageous.Program 1:#include <stdio.h>int main(void){ int fact[5]; fact[0] = 1; // Overhead of managing a counter // just for 4 iterations // is not a good idea for (int i = 1; i < 5; ++i) { fact[i] = fact[i - 1] * i; } return 0;}Program 2:#include <stdio.h>int main(void){ int fact[5] = { 1, 1, 2, 6, 24 }; // Here the same work is done // without counter overhead return 0;}"
},
{
"code": null,
"e": 36432,
"s": 36421,
"text": "Program 1:"
},
{
"code": "#include <stdio.h>int main(void){ int fact[5]; fact[0] = 1; // Overhead of managing a counter // just for 4 iterations // is not a good idea for (int i = 1; i < 5; ++i) { fact[i] = fact[i - 1] * i; } return 0;}",
"e": 36676,
"s": 36432,
"text": null
},
{
"code": null,
"e": 36687,
"s": 36676,
"text": "Program 2:"
},
{
"code": "#include <stdio.h>int main(void){ int fact[5] = { 1, 1, 2, 6, 24 }; // Here the same work is done // without counter overhead return 0;}",
"e": 36838,
"s": 36687,
"text": null
},
{
"code": null,
"e": 37540,
"s": 36838,
"text": "Avoid calculations in loop: We should avoid any calculation which is more or less constant in value. Inner loops should have minimum possible calculations.Program 1:#include <stdio.h>int main(void){ int arr[1000]; int a = 1, b = 5, c = 25, d = 7; // Calculating a constant expression // for each iteration is not good. for (int i = 0; i < 1000; ++i) { arr[i] = (((c % d) * a / b) % d) * i; } return 0;}Program 2:#include <stdio.h> int main(void){ int arr[1000]; int a = 1, b = 5, c = 25, d = 7; // pre calculating the constant expression int temp = (((c % d) * a / b) % d); for (int i = 0; i < 1000; ++i) { arr[i] = temp * i; } return 0;}"
},
{
"code": "#include <stdio.h>int main(void){ int arr[1000]; int a = 1, b = 5, c = 25, d = 7; // Calculating a constant expression // for each iteration is not good. for (int i = 0; i < 1000; ++i) { arr[i] = (((c % d) * a / b) % d) * i; } return 0;}",
"e": 37808,
"s": 37540,
"text": null
},
{
"code": null,
"e": 37819,
"s": 37808,
"text": "Program 2:"
},
{
"code": "#include <stdio.h> int main(void){ int arr[1000]; int a = 1, b = 5, c = 25, d = 7; // pre calculating the constant expression int temp = (((c % d) * a / b) % d); for (int i = 0; i < 1000; ++i) { arr[i] = temp * i; } return 0;}",
"e": 38079,
"s": 37819,
"text": null
},
{
"code": null,
"e": 38981,
"s": 38079,
"text": "Avoid pointer Dereference in loop: Pointer dereferencing creates lots of trouble in memory. So better assign it to some temporary variable and then use that temporary variable in the loop.Program 1:#include <stdio.h>int main(void){ int a = 0; int* iptr = &a; // Dereferencing pointer inside loop // is costly for (int i = 1; i < 11; ++i) { *iptr = *iptr + i; } printf(\"Value of a : %d\", a); return 0;}Output:Value of a : 55\nProgram 2:#include <stdio.h>int main(void){ int a = 0; int* iptr = &a; // Dereferencing pointer outside loop // and saving its value in a temp variable int temp = *iptr; for (int i = 1; i < 11; ++i) { // performing calculations on temp variable temp = temp + i; } // Updating pointer using final value of temp *iptr = temp; printf(\"Value of a : %d\", a); return 0;}Output:Value of a : 55\n"
},
{
"code": "#include <stdio.h>int main(void){ int a = 0; int* iptr = &a; // Dereferencing pointer inside loop // is costly for (int i = 1; i < 11; ++i) { *iptr = *iptr + i; } printf(\"Value of a : %d\", a); return 0;}",
"e": 39218,
"s": 38981,
"text": null
},
{
"code": null,
"e": 39235,
"s": 39218,
"text": "Value of a : 55\n"
},
{
"code": null,
"e": 39246,
"s": 39235,
"text": "Program 2:"
},
{
"code": "#include <stdio.h>int main(void){ int a = 0; int* iptr = &a; // Dereferencing pointer outside loop // and saving its value in a temp variable int temp = *iptr; for (int i = 1; i < 11; ++i) { // performing calculations on temp variable temp = temp + i; } // Updating pointer using final value of temp *iptr = temp; printf(\"Value of a : %d\", a); return 0;}",
"e": 39658,
"s": 39246,
"text": null
},
{
"code": null,
"e": 39675,
"s": 39658,
"text": "Value of a : 55\n"
},
{
"code": null,
"e": 40168,
"s": 39675,
"text": "Use Register variables as counters of inner loops: Variables stored in registers can be accessed much faster than variables stored in memory.Program:#include <stdio.h>int main(void){ register int i = 0; register int j = 0; int n = 5; // using register variables // as counters make the loop faster for (i = 0; i < n; ++i) { for (j = 0; j <= i; ++j) { printf(\"* \"); } printf(\"\\n\"); } return 0;}Output:* \n* * \n* * * \n* * * * \n* * * * *\n"
},
{
"code": "#include <stdio.h>int main(void){ register int i = 0; register int j = 0; int n = 5; // using register variables // as counters make the loop faster for (i = 0; i < n; ++i) { for (j = 0; j <= i; ++j) { printf(\"* \"); } printf(\"\\n\"); } return 0;}",
"e": 40471,
"s": 40168,
"text": null
},
{
"code": null,
"e": 40506,
"s": 40471,
"text": "* \n* * \n* * * \n* * * * \n* * * * *\n"
},
{
"code": null,
"e": 41558,
"s": 40506,
"text": "Fast MathematicsAvoid unnecessary Integer Division: Division operations are slow so we should minimize the division operations.Program:#include <stdio.h>int main(void){ int a = 100, b = 2, c = 5; // int d=a/b/c; two division operators int d = a / (b * c); // single division operator return 0;}Multiplication and division by power of 2: Use left shift(<<) for multiplication and right shift(>>) for division. The bit operations will be much faster than multiplication and division operations.For simple operations, the compiler may automatically optimize the code but in case of complex expressions it is always advised to use bit operations.Example :Multiply by 6 : a= a<<1 + a<<2; \nMultiply by 7 : a= a<<3 - a;\nDivide by 8 : a= a>>3; // division by power of 2\nSimplifying Expressions: Sometimes we can reduce some operations by simplifying expressions.Example : a*b + a*b*c + a*b*c*d ---> (a*b)*(1 + c*(1 + d)) \n L.H.S can be Simplified to R.H.S\n L.H.S : 6 multiplications and 2 additions\n R.H.S : 3 multiplications and 2 additions\n"
},
{
"code": null,
"e": 41852,
"s": 41558,
"text": "Avoid unnecessary Integer Division: Division operations are slow so we should minimize the division operations.Program:#include <stdio.h>int main(void){ int a = 100, b = 2, c = 5; // int d=a/b/c; two division operators int d = a / (b * c); // single division operator return 0;}"
},
{
"code": "#include <stdio.h>int main(void){ int a = 100, b = 2, c = 5; // int d=a/b/c; two division operators int d = a / (b * c); // single division operator return 0;}",
"e": 42027,
"s": 41852,
"text": null
},
{
"code": null,
"e": 42496,
"s": 42027,
"text": "Multiplication and division by power of 2: Use left shift(<<) for multiplication and right shift(>>) for division. The bit operations will be much faster than multiplication and division operations.For simple operations, the compiler may automatically optimize the code but in case of complex expressions it is always advised to use bit operations.Example :Multiply by 6 : a= a<<1 + a<<2; \nMultiply by 7 : a= a<<3 - a;\nDivide by 8 : a= a>>3; // division by power of 2\n"
},
{
"code": null,
"e": 42608,
"s": 42496,
"text": "Multiply by 6 : a= a<<1 + a<<2; \nMultiply by 7 : a= a<<3 - a;\nDivide by 8 : a= a>>3; // division by power of 2\n"
},
{
"code": null,
"e": 42883,
"s": 42608,
"text": "Simplifying Expressions: Sometimes we can reduce some operations by simplifying expressions.Example : a*b + a*b*c + a*b*c*d ---> (a*b)*(1 + c*(1 + d)) \n L.H.S can be Simplified to R.H.S\n L.H.S : 6 multiplications and 2 additions\n R.H.S : 3 multiplications and 2 additions\n"
},
{
"code": null,
"e": 43057,
"s": 42883,
"text": " a*b + a*b*c + a*b*c*d ---> (a*b)*(1 + c*(1 + d)) \n L.H.S can be Simplified to R.H.S\n L.H.S : 6 multiplications and 2 additions\n R.H.S : 3 multiplications and 2 additions\n"
},
{
"code": null,
"e": 45189,
"s": 43057,
"text": "Optimization with Switch StatementCompilers translate switch statements in different ways. If case labels are small contiguous integer values, then it creates a jump table. This is very fast and doesnβt depend on the number of case labels also. If case labels are longer and not contiguous then it creates comparison tree i.e. if...else statements. So, in this case, we should keep the most frequent label first and the least frequent label should be at last.Sometimes we see a lot of repeated code written in all cases except one or two statementsExample :switch(expression)\n{\ncase a:\n ........\n ........\n break;\ncase b:\n ........\n ........\n break;\ncase c:\n common statements;\n different statements;\n common statements;\n break;\ncase d:\n common statements;\n different statements;\n common statements;\n break; '\ncase e:\n common statements;\n different statements;\n common statements;\n break;\ncase f:\n common statements;\n different statements;\n common statements;\n break;\ndefault:\n break; \n}\nWe can take all cases together and can write common statements only once and different statements in related cases using another switch. Here we will take cases c, d, e, f together and write common statements, then we can use another switch and write different statements in case c, d, e, f. Then after this switch, we can again write common statements.switch(expression)\n{\ncase a:\n ........\n ........\n break;\ncase b:\n ........\n ........\n break;\ncase c: \ncase d: \ncase e: \ncase f:\n common statements;\n switch(expression);\n {\n case c:\n different statements;\n break;\n case d:\n different statements;\n break;\n case e:\n different statements;\n break;\n case f:\n different statements;\n break;\n } /*End of switch*/\n common statements;\n break; \n \ndefault:\n break; \n}/*End of switch*/\n"
},
{
"code": null,
"e": 45279,
"s": 45189,
"text": "Sometimes we see a lot of repeated code written in all cases except one or two statements"
},
{
"code": null,
"e": 45289,
"s": 45279,
"text": "Example :"
},
{
"code": null,
"e": 45866,
"s": 45289,
"text": "switch(expression)\n{\ncase a:\n ........\n ........\n break;\ncase b:\n ........\n ........\n break;\ncase c:\n common statements;\n different statements;\n common statements;\n break;\ncase d:\n common statements;\n different statements;\n common statements;\n break; '\ncase e:\n common statements;\n different statements;\n common statements;\n break;\ncase f:\n common statements;\n different statements;\n common statements;\n break;\ndefault:\n break; \n}\n"
},
{
"code": null,
"e": 46220,
"s": 45866,
"text": "We can take all cases together and can write common statements only once and different statements in related cases using another switch. Here we will take cases c, d, e, f together and write common statements, then we can use another switch and write different statements in case c, d, e, f. Then after this switch, we can again write common statements."
},
{
"code": null,
"e": 46866,
"s": 46220,
"text": "switch(expression)\n{\ncase a:\n ........\n ........\n break;\ncase b:\n ........\n ........\n break;\ncase c: \ncase d: \ncase e: \ncase f:\n common statements;\n switch(expression);\n {\n case c:\n different statements;\n break;\n case d:\n different statements;\n break;\n case e:\n different statements;\n break;\n case f:\n different statements;\n break;\n } /*End of switch*/\n common statements;\n break; \n \ndefault:\n break; \n}/*End of switch*/\n"
},
{
"code": null,
"e": 47352,
"s": 46866,
"text": "Prefer int to char or shortWe should always prefer int to char because C performs all operations of char with an integer. In all operations like passing char to a function or an arithmetic operation, first char will be converted into integer and after compilation of operation, it will again be converted into char. For a single char, this may not affect the efficiency but suppose the same operation is performed 100 times in a loop then it can decrease the efficiency of the program."
},
{
"code": null,
"e": 47721,
"s": 47352,
"text": "Prefer pre Increment/Decrement to post Increment/DecrementIn pre-increment, it first increments the value and just copies the value to variable location but in post-increment, it first copies the value to a temporary variable, increments it and then copies the value to the variable location. If post-increment is 1000 times in a loop it will decrement the efficiency."
},
{
"code": null,
"e": 48174,
"s": 47721,
"text": "Order of Expression Evaluation A || B \nHere first A will be evaluated, if itβs true then there is no need of evaluation of expression B. So We should prefer to have an expression which evaluates to true most of the times, at the Aβs place. A && B \nHere first A will be evaluated, if itβs false then there is no need of evaluation of expression B. So We should prefer to have an expression which evaluates to false most of the times, at the Aβs place."
},
{
"code": null,
"e": 48385,
"s": 48174,
"text": " A || B \nHere first A will be evaluated, if itβs true then there is no need of evaluation of expression B. So We should prefer to have an expression which evaluates to true most of the times, at the Aβs place."
},
{
"code": null,
"e": 48396,
"s": 48385,
"text": " A || B \n"
},
{
"code": null,
"e": 48597,
"s": 48396,
"text": "Here first A will be evaluated, if itβs true then there is no need of evaluation of expression B. So We should prefer to have an expression which evaluates to true most of the times, at the Aβs place."
},
{
"code": null,
"e": 48810,
"s": 48597,
"text": " A && B \nHere first A will be evaluated, if itβs false then there is no need of evaluation of expression B. So We should prefer to have an expression which evaluates to false most of the times, at the Aβs place."
},
{
"code": null,
"e": 48821,
"s": 48810,
"text": " A && B \n"
},
{
"code": null,
"e": 49024,
"s": 48821,
"text": "Here first A will be evaluated, if itβs false then there is no need of evaluation of expression B. So We should prefer to have an expression which evaluates to false most of the times, at the Aβs place."
},
{
"code": null,
"e": 49033,
"s": 49024,
"text": "C Basics"
},
{
"code": null,
"e": 49044,
"s": 49033,
"text": "C Language"
},
{
"code": null,
"e": 49142,
"s": 49044,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 49180,
"s": 49142,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 49206,
"s": 49180,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 49228,
"s": 49206,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 49248,
"s": 49228,
"text": "Multithreading in C"
},
{
"code": null,
"e": 49289,
"s": 49248,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 49317,
"s": 49289,
"text": "Multiple Inheritance in C++"
},
{
"code": null,
"e": 49359,
"s": 49317,
"text": "Smart Pointers in C++ and How to Use Them"
},
{
"code": null,
"e": 49395,
"s": 49359,
"text": "Understanding \"extern\" keyword in C"
},
{
"code": null,
"e": 49424,
"s": 49395,
"text": "Ways to copy a vector in C++"
}
] |
When to Stop Training your Deep Learning Model | Towards Data Science
|
One of the first decisions to be made when training deep neural networks is to select the epoch in which to stop. And it is not an easy one.
If the training is stopped before the optimal time, the model will not have had time to learn the most important features from the training set and therefore provide poorly fitted solutions for both the training and the test sets.
On the other hand, if the training is stopped after the optimal epoch, high performance will be achieved in the training set, but when looking at the test results, the model would not generalize correctly, as it has over-adjusted to the training set.
Fortunately, there is an easy and widely used method to avoid these two issues. It is known as early stopping and most deep learning frameworks provide an out-of-the-box interface for using it.
Early stopping should be used almost universally.
β Ian Goodfellow et al., Deep Learning.
The idea behind this approach lies in the comparison between the training set and the test set or, for more reliable results, between the training set and the validation set.
By analyzing the error or loss graph in both the training and validation splits as the epochs pass, we will see that at first both decrease. However, the validation error will start to flatten out or increase at a certain time while the training error will continue to decrease.
The purpose of a validation set is to give us an idea of how our model behaves on data on which it has not been trained. Therefore, the epoch when the validation error starts to increase is precisely when the model is overfitting to the training set and does not generalize new data correctly. This is when we need to stop our training.
Although validation loss is a widely used metric when applying early stopping to your model, it is not always the most relevant.
Sometimes it may be better to select a metric that represents the performance of the model based on the use case. It can, for example, be accuracy, precision, recall, or a combination of metrics.
Now we know which metrics to observe and that we should stop when the validation metrics no longer improve along with the training metrics or start to perform worse.
However, it may happen that the observed metric has multiple ups and downs (due to the stochasticity of the neural networks), which means that stopping the first time the validation metric gets worse might not be the best solution (although it is the simplest one).
Some more complex triggers to stop training are as follows (note that they can also be applied in combination):
The observed metric has not improved over a given number of epochs (known as the early stopping patience).
The observed metric has not improved more than a given minimum change to be considered an improvement (known as the min_delta).
Note that when early stopping patience is used, the trigger will be executed when the monitored accuracy has not improved over the best result obtained in the last X epochs. If it improves but it does not exceed the best result, it would not count.
Keras API offers a callback to use on model.fit() to stop training when a monitored metric has stopped improving.
The metric argument receives the name of the metric you want to observe. In the case of referring to a validation metric (more realistic results as it approximates how your model would behave in production), the name must be preceded by the prefix βval_β. Note that the validation set must be passed to model.fit() in order to include validation metrics.
In addition, you can specify patience and min_delta as introduced in the previous section. Finally, the mode argument specifies whether the desired result should go from high to low (min mode) or from low to high (max mode). For instance, when monitoring accuracy the mode should be max.
callback = tf.keras.callbacks.EarlyStopping( monitor="val_loss", min_delta=0, patience=0, verbose=0, mode="auto", baseline=None, restore_best_weights=False,)
This callback also offers a parameter restore_best_weights to restore the resulting model with the model weights obtained at the best-performing epoch.
To use the early stopping callback, we just need to pass the object to the callbacks argument in model.fit(), as follows:
model.fit(train_images, train_labels, epochs=10, batch_size=1, callbacks=[callback], verbose=0)
Depending on your use case, the early stop callback may not be sufficient. For example, in the case of having a model with multiple outputs and wanting to monitor a set of metrics instead of just one. Or a combined metric such as F-beta score given precision and recall.
To solve this, you can find a custom callback that I developed based on the available implementation in the Keras documentation and a StackOverflow issue. It receives a metrics names argument where instead of a single metric you can specify a set of them. To combine the metrics, the harmonic mean is calculated as commonly used for ratios.
At the end of the code, you can find an example of how to create an early stopping callback with the validation f1-score as the monitored metric (i.e. harmonic mean between validation precision and recall).
As most of the time, the answer to this question depends highly on the model and dataset you are using.
From my experience, I would recommend first running a training stage with a high number of epochs and visually observing from the results when the monitored metric starts to decrease and at what rate. After that, I would run the following experiments with a few additional epochs until it started to saturate, along with the patience as the number of epochs where it decreased by a significant percentage, also keeping in mind that if the results are very stochastic the patience should be greater.
In this article, one of the most common challenges when developing machine learning models has been addressed: when to stop the training. The widely used solution known as early stopping has been presented in detail, explaining more advanced techniques such as complex early stopping triggers to obtain optimal results and how to monitor multiple metrics by implementing a custom callback.
If you want to discover more posts like this one, you can find me at:
|
[
{
"code": null,
"e": 313,
"s": 172,
"text": "One of the first decisions to be made when training deep neural networks is to select the epoch in which to stop. And it is not an easy one."
},
{
"code": null,
"e": 544,
"s": 313,
"text": "If the training is stopped before the optimal time, the model will not have had time to learn the most important features from the training set and therefore provide poorly fitted solutions for both the training and the test sets."
},
{
"code": null,
"e": 795,
"s": 544,
"text": "On the other hand, if the training is stopped after the optimal epoch, high performance will be achieved in the training set, but when looking at the test results, the model would not generalize correctly, as it has over-adjusted to the training set."
},
{
"code": null,
"e": 989,
"s": 795,
"text": "Fortunately, there is an easy and widely used method to avoid these two issues. It is known as early stopping and most deep learning frameworks provide an out-of-the-box interface for using it."
},
{
"code": null,
"e": 1039,
"s": 989,
"text": "Early stopping should be used almost universally."
},
{
"code": null,
"e": 1079,
"s": 1039,
"text": "β Ian Goodfellow et al., Deep Learning."
},
{
"code": null,
"e": 1254,
"s": 1079,
"text": "The idea behind this approach lies in the comparison between the training set and the test set or, for more reliable results, between the training set and the validation set."
},
{
"code": null,
"e": 1533,
"s": 1254,
"text": "By analyzing the error or loss graph in both the training and validation splits as the epochs pass, we will see that at first both decrease. However, the validation error will start to flatten out or increase at a certain time while the training error will continue to decrease."
},
{
"code": null,
"e": 1870,
"s": 1533,
"text": "The purpose of a validation set is to give us an idea of how our model behaves on data on which it has not been trained. Therefore, the epoch when the validation error starts to increase is precisely when the model is overfitting to the training set and does not generalize new data correctly. This is when we need to stop our training."
},
{
"code": null,
"e": 1999,
"s": 1870,
"text": "Although validation loss is a widely used metric when applying early stopping to your model, it is not always the most relevant."
},
{
"code": null,
"e": 2195,
"s": 1999,
"text": "Sometimes it may be better to select a metric that represents the performance of the model based on the use case. It can, for example, be accuracy, precision, recall, or a combination of metrics."
},
{
"code": null,
"e": 2361,
"s": 2195,
"text": "Now we know which metrics to observe and that we should stop when the validation metrics no longer improve along with the training metrics or start to perform worse."
},
{
"code": null,
"e": 2627,
"s": 2361,
"text": "However, it may happen that the observed metric has multiple ups and downs (due to the stochasticity of the neural networks), which means that stopping the first time the validation metric gets worse might not be the best solution (although it is the simplest one)."
},
{
"code": null,
"e": 2739,
"s": 2627,
"text": "Some more complex triggers to stop training are as follows (note that they can also be applied in combination):"
},
{
"code": null,
"e": 2846,
"s": 2739,
"text": "The observed metric has not improved over a given number of epochs (known as the early stopping patience)."
},
{
"code": null,
"e": 2974,
"s": 2846,
"text": "The observed metric has not improved more than a given minimum change to be considered an improvement (known as the min_delta)."
},
{
"code": null,
"e": 3223,
"s": 2974,
"text": "Note that when early stopping patience is used, the trigger will be executed when the monitored accuracy has not improved over the best result obtained in the last X epochs. If it improves but it does not exceed the best result, it would not count."
},
{
"code": null,
"e": 3337,
"s": 3223,
"text": "Keras API offers a callback to use on model.fit() to stop training when a monitored metric has stopped improving."
},
{
"code": null,
"e": 3692,
"s": 3337,
"text": "The metric argument receives the name of the metric you want to observe. In the case of referring to a validation metric (more realistic results as it approximates how your model would behave in production), the name must be preceded by the prefix βval_β. Note that the validation set must be passed to model.fit() in order to include validation metrics."
},
{
"code": null,
"e": 3980,
"s": 3692,
"text": "In addition, you can specify patience and min_delta as introduced in the previous section. Finally, the mode argument specifies whether the desired result should go from high to low (min mode) or from low to high (max mode). For instance, when monitoring accuracy the mode should be max."
},
{
"code": null,
"e": 4159,
"s": 3980,
"text": "callback = tf.keras.callbacks.EarlyStopping( monitor=\"val_loss\", min_delta=0, patience=0, verbose=0, mode=\"auto\", baseline=None, restore_best_weights=False,)"
},
{
"code": null,
"e": 4311,
"s": 4159,
"text": "This callback also offers a parameter restore_best_weights to restore the resulting model with the model weights obtained at the best-performing epoch."
},
{
"code": null,
"e": 4433,
"s": 4311,
"text": "To use the early stopping callback, we just need to pass the object to the callbacks argument in model.fit(), as follows:"
},
{
"code": null,
"e": 4529,
"s": 4433,
"text": "model.fit(train_images, train_labels, epochs=10, batch_size=1, callbacks=[callback], verbose=0)"
},
{
"code": null,
"e": 4800,
"s": 4529,
"text": "Depending on your use case, the early stop callback may not be sufficient. For example, in the case of having a model with multiple outputs and wanting to monitor a set of metrics instead of just one. Or a combined metric such as F-beta score given precision and recall."
},
{
"code": null,
"e": 5141,
"s": 4800,
"text": "To solve this, you can find a custom callback that I developed based on the available implementation in the Keras documentation and a StackOverflow issue. It receives a metrics names argument where instead of a single metric you can specify a set of them. To combine the metrics, the harmonic mean is calculated as commonly used for ratios."
},
{
"code": null,
"e": 5348,
"s": 5141,
"text": "At the end of the code, you can find an example of how to create an early stopping callback with the validation f1-score as the monitored metric (i.e. harmonic mean between validation precision and recall)."
},
{
"code": null,
"e": 5452,
"s": 5348,
"text": "As most of the time, the answer to this question depends highly on the model and dataset you are using."
},
{
"code": null,
"e": 5951,
"s": 5452,
"text": "From my experience, I would recommend first running a training stage with a high number of epochs and visually observing from the results when the monitored metric starts to decrease and at what rate. After that, I would run the following experiments with a few additional epochs until it started to saturate, along with the patience as the number of epochs where it decreased by a significant percentage, also keeping in mind that if the results are very stochastic the patience should be greater."
},
{
"code": null,
"e": 6341,
"s": 5951,
"text": "In this article, one of the most common challenges when developing machine learning models has been addressed: when to stop the training. The widely used solution known as early stopping has been presented in detail, explaining more advanced techniques such as complex early stopping triggers to obtain optimal results and how to monitor multiple metrics by implementing a custom callback."
}
] |
How to Put Count and Percentage in One Cell in Excel? - GeeksforGeeks
|
09 Dec, 2021
In the real world, sometimes the user would like to present two or more values in a single cell. For eg in the sales report, we might need sales and the respective %share in the same cell. So in this article, we will learn how to display count and percentage in the same cell with the help of an example. In the below, sample data, have given sales data in $ and market share in Percentages. We need to add a column to show both Sales $ (Share %) in a cell as in (Img2).
Sample Data:
Sample Data
Output:
Expected Output
So to do this task, we use the following methods:
1. CONCAT() Function: CONCAT function is an Excel built-in function and allows to join 2 or more text/strings. Or we can say it joins two or more cells in a single content. This function must contain at least one text as an argument and if any of the arguments in the function is invalid then it will return an error.
Syntax:
CONCAT(text1, [text2],...)
Example: When we execute CONCAT(βgeeksβ, β-β, βforβ, β-β, βgeeksβ) we get geeks-for-geeks as a output.
2. TEXT() function: The TEXT function is also an Excel built-in function and returns a text with a specified format. It is useful when you want to combine text or symbols or when you want to display numbers in a more readable form.
Syntax:
TEXT(value, format_text)
Here, the value parameter is used to convert to text, and the format_text parameter is used to format to apply the result.
Example: When we execute this TEXT(1000, β$0β) we get $1000 as an output.
Now follow the following steps to put count and percentage in one cell:
Step 1: Type column header β $ Sales ( % Share)β in cell E2.
Step 2: We use the Excel TEXT() function to retain excel format and the CONCAT() function to join four texts.
Text 1 β Sales $
Text 2 β Open bracket
Text 3 β Share %
Text 4 β Close bracket
Type the formula in cell βE3β
=CONCAT(TEXT(C3,"$ 0")," (", TEXT(D3,"0.0%"),")")
Step 3: Drag formula E3 to E8 to fill the same formula to all other cells
This is how we can easily put count and percentage in one cell.
Excel-functions
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Use Solver in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Sum Values Based on Criteria in Another Column in Excel?
Introduction to Excel Spreadsheet
Macros in Excel
How to Read Data From Text File in Excel VBA?
How to Show Percentages in Stacked Column Chart in Excel?
How to Get Length of Array in Excel VBA?
How to Remove Duplicates From Array Using VBA in Excel?
Excel Dynamic Chart Linked with a Drop-down List
|
[
{
"code": null,
"e": 24964,
"s": 24936,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 25435,
"s": 24964,
"text": "In the real world, sometimes the user would like to present two or more values in a single cell. For eg in the sales report, we might need sales and the respective %share in the same cell. So in this article, we will learn how to display count and percentage in the same cell with the help of an example. In the below, sample data, have given sales data in $ and market share in Percentages. We need to add a column to show both Sales $ (Share %) in a cell as in (Img2)."
},
{
"code": null,
"e": 25448,
"s": 25435,
"text": "Sample Data:"
},
{
"code": null,
"e": 25460,
"s": 25448,
"text": "Sample Data"
},
{
"code": null,
"e": 25468,
"s": 25460,
"text": "Output:"
},
{
"code": null,
"e": 25484,
"s": 25468,
"text": "Expected Output"
},
{
"code": null,
"e": 25534,
"s": 25484,
"text": "So to do this task, we use the following methods:"
},
{
"code": null,
"e": 25852,
"s": 25534,
"text": "1. CONCAT() Function: CONCAT function is an Excel built-in function and allows to join 2 or more text/strings. Or we can say it joins two or more cells in a single content. This function must contain at least one text as an argument and if any of the arguments in the function is invalid then it will return an error."
},
{
"code": null,
"e": 25860,
"s": 25852,
"text": "Syntax:"
},
{
"code": null,
"e": 25887,
"s": 25860,
"text": "CONCAT(text1, [text2],...)"
},
{
"code": null,
"e": 25990,
"s": 25887,
"text": "Example: When we execute CONCAT(βgeeksβ, β-β, βforβ, β-β, βgeeksβ) we get geeks-for-geeks as a output."
},
{
"code": null,
"e": 26222,
"s": 25990,
"text": "2. TEXT() function: The TEXT function is also an Excel built-in function and returns a text with a specified format. It is useful when you want to combine text or symbols or when you want to display numbers in a more readable form."
},
{
"code": null,
"e": 26230,
"s": 26222,
"text": "Syntax:"
},
{
"code": null,
"e": 26255,
"s": 26230,
"text": "TEXT(value, format_text)"
},
{
"code": null,
"e": 26378,
"s": 26255,
"text": "Here, the value parameter is used to convert to text, and the format_text parameter is used to format to apply the result."
},
{
"code": null,
"e": 26452,
"s": 26378,
"text": "Example: When we execute this TEXT(1000, β$0β) we get $1000 as an output."
},
{
"code": null,
"e": 26524,
"s": 26452,
"text": "Now follow the following steps to put count and percentage in one cell:"
},
{
"code": null,
"e": 26586,
"s": 26524,
"text": "Step 1: Type column header β $ Sales ( % Share)β in cell E2."
},
{
"code": null,
"e": 26696,
"s": 26586,
"text": "Step 2: We use the Excel TEXT() function to retain excel format and the CONCAT() function to join four texts."
},
{
"code": null,
"e": 26715,
"s": 26696,
"text": "Text 1 β Sales $ "
},
{
"code": null,
"e": 26737,
"s": 26715,
"text": "Text 2 β Open bracket"
},
{
"code": null,
"e": 26754,
"s": 26737,
"text": "Text 3 β Share %"
},
{
"code": null,
"e": 26777,
"s": 26754,
"text": "Text 4 β Close bracket"
},
{
"code": null,
"e": 26808,
"s": 26777,
"text": "Type the formula in cell βE3β "
},
{
"code": null,
"e": 26858,
"s": 26808,
"text": "=CONCAT(TEXT(C3,\"$ 0\"),\" (\", TEXT(D3,\"0.0%\"),\")\")"
},
{
"code": null,
"e": 26932,
"s": 26858,
"text": "Step 3: Drag formula E3 to E8 to fill the same formula to all other cells"
},
{
"code": null,
"e": 26996,
"s": 26932,
"text": "This is how we can easily put count and percentage in one cell."
},
{
"code": null,
"e": 27012,
"s": 26996,
"text": "Excel-functions"
},
{
"code": null,
"e": 27019,
"s": 27012,
"text": "Picked"
},
{
"code": null,
"e": 27025,
"s": 27019,
"text": "Excel"
},
{
"code": null,
"e": 27123,
"s": 27025,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27132,
"s": 27123,
"text": "Comments"
},
{
"code": null,
"e": 27145,
"s": 27132,
"text": "Old Comments"
},
{
"code": null,
"e": 27173,
"s": 27145,
"text": "How to Use Solver in Excel?"
},
{
"code": null,
"e": 27228,
"s": 27173,
"text": "How to Find the Last Used Row and Column in Excel VBA?"
},
{
"code": null,
"e": 27292,
"s": 27228,
"text": "How to Sum Values Based on Criteria in Another Column in Excel?"
},
{
"code": null,
"e": 27326,
"s": 27292,
"text": "Introduction to Excel Spreadsheet"
},
{
"code": null,
"e": 27342,
"s": 27326,
"text": "Macros in Excel"
},
{
"code": null,
"e": 27388,
"s": 27342,
"text": "How to Read Data From Text File in Excel VBA?"
},
{
"code": null,
"e": 27446,
"s": 27388,
"text": "How to Show Percentages in Stacked Column Chart in Excel?"
},
{
"code": null,
"e": 27487,
"s": 27446,
"text": "How to Get Length of Array in Excel VBA?"
},
{
"code": null,
"e": 27543,
"s": 27487,
"text": "How to Remove Duplicates From Array Using VBA in Excel?"
}
] |
How to compute numerical negative value for all elements in a given NumPy array? - GeeksforGeeks
|
07 Aug, 2021
In this article, we will see how to compute the negative value for all elements in a given NumPy array. So, The negative value is actually the number which when added to any number becomes 0.
Example:
If we take a number as 4 then -4 is its negative number because when we add -4 to 4 we get sum as 0. Now let us take another example, Suppose we take a number -6 Now when we add +6 to it then the sum becomes zero. hence +6 is the negative value of -6. Now suppose we have an array of numbers:
A = [1,2,3,-1,-2,-3,0]
So, the negative value of A is
A'=[-1,-2,-3,1,2,3,0].
So, for finding the numerical negative value of an element we have to use numpy.negative() function of NumPy library.
Syntax: numpy.negative(arr, /, out=None, *, where=True, casting=βsame_kindβ, order=βKβ, dtype=None, subok=True[, signature, extobj], ufunc βnegativeβ)
Return: [ndarray or scalar] Returned array or scalar = -(input arr or scalar )
Now, letβs see the examples:
Example 1:
Python3
# importing libraryimport numpy as np # creating a arrayx = np.array([-1, -2, -3, 1, 2, 3, 0]) print("Printing the Original array:", x) # converting array elements to# its corresponding negative valuer1 = np.negative(x) print("Printing the negative value of the given array:", r1)
Output:
Printing the Original array: [-1 -2 -3 1 2 3 0]
Printing the negative value of the given array: [ 1 2 3 -1 -2 -3 0]
Example 2:
Python3
# importing libraryimport numpy as np # creating a numpy 2D arrayx = np.array([[1, 2], [2, 3]]) print("Printing the Original array Content:\n", x) # converting array elements to# its corresponding negative valuer1 = np.negative(x) print("Printing the negative value of the given array:\n", r1)
Output:
Printing the Original array Content:
[[1 2]
[2 3]]
Printing the negative value of the given array:
[[-1 -2]
[-2 -3]]
surinderdawra388
sumitgumber28
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
|
[
{
"code": null,
"e": 26249,
"s": 26221,
"text": "\n07 Aug, 2021"
},
{
"code": null,
"e": 26442,
"s": 26249,
"text": "In this article, we will see how to compute the negative value for all elements in a given NumPy array. So, The negative value is actually the number which when added to any number becomes 0. "
},
{
"code": null,
"e": 26452,
"s": 26442,
"text": "Example: "
},
{
"code": null,
"e": 26747,
"s": 26452,
"text": "If we take a number as 4 then -4 is its negative number because when we add -4 to 4 we get sum as 0. Now let us take another example, Suppose we take a number -6 Now when we add +6 to it then the sum becomes zero. hence +6 is the negative value of -6. Now suppose we have an array of numbers: "
},
{
"code": null,
"e": 26825,
"s": 26747,
"text": "A = [1,2,3,-1,-2,-3,0]\nSo, the negative value of A is \nA'=[-1,-2,-3,1,2,3,0]."
},
{
"code": null,
"e": 26943,
"s": 26825,
"text": "So, for finding the numerical negative value of an element we have to use numpy.negative() function of NumPy library."
},
{
"code": null,
"e": 27094,
"s": 26943,
"text": "Syntax: numpy.negative(arr, /, out=None, *, where=True, casting=βsame_kindβ, order=βKβ, dtype=None, subok=True[, signature, extobj], ufunc βnegativeβ)"
},
{
"code": null,
"e": 27173,
"s": 27094,
"text": "Return: [ndarray or scalar] Returned array or scalar = -(input arr or scalar )"
},
{
"code": null,
"e": 27202,
"s": 27173,
"text": "Now, letβs see the examples:"
},
{
"code": null,
"e": 27213,
"s": 27202,
"text": "Example 1:"
},
{
"code": null,
"e": 27221,
"s": 27213,
"text": "Python3"
},
{
"code": "# importing libraryimport numpy as np # creating a arrayx = np.array([-1, -2, -3, 1, 2, 3, 0]) print(\"Printing the Original array:\", x) # converting array elements to# its corresponding negative valuer1 = np.negative(x) print(\"Printing the negative value of the given array:\", r1)",
"e": 27525,
"s": 27221,
"text": null
},
{
"code": null,
"e": 27534,
"s": 27525,
"text": " Output:"
},
{
"code": null,
"e": 27661,
"s": 27534,
"text": "Printing the Original array: [-1 -2 -3 1 2 3 0] \nPrinting the negative value of the given array: [ 1 2 3 -1 -2 -3 0] \n "
},
{
"code": null,
"e": 27672,
"s": 27661,
"text": "Example 2:"
},
{
"code": null,
"e": 27680,
"s": 27672,
"text": "Python3"
},
{
"code": "# importing libraryimport numpy as np # creating a numpy 2D arrayx = np.array([[1, 2], [2, 3]]) print(\"Printing the Original array Content:\\n\", x) # converting array elements to# its corresponding negative valuer1 = np.negative(x) print(\"Printing the negative value of the given array:\\n\", r1)",
"e": 27997,
"s": 27680,
"text": null
},
{
"code": null,
"e": 28007,
"s": 27997,
"text": " Output: "
},
{
"code": null,
"e": 28124,
"s": 28007,
"text": "Printing the Original array Content:\n[[1 2]\n[2 3]]\nPrinting the negative value of the given array:\n[[-1 -2]\n[-2 -3]]"
},
{
"code": null,
"e": 28143,
"s": 28126,
"text": "surinderdawra388"
},
{
"code": null,
"e": 28157,
"s": 28143,
"text": "sumitgumber28"
},
{
"code": null,
"e": 28192,
"s": 28157,
"text": "Python numpy-Mathematical Function"
},
{
"code": null,
"e": 28205,
"s": 28192,
"text": "Python-numpy"
},
{
"code": null,
"e": 28212,
"s": 28205,
"text": "Python"
},
{
"code": null,
"e": 28310,
"s": 28212,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28328,
"s": 28310,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28363,
"s": 28328,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28395,
"s": 28363,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28417,
"s": 28395,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28459,
"s": 28417,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28489,
"s": 28459,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28518,
"s": 28489,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28562,
"s": 28518,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28599,
"s": 28562,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Intro to Window Functions in SQL. How to use Window functions to perform... | by Jason Lee | Towards Data Science
|
Window functions can help you run operations on a selection of rows and return a value from that original query.
The term window describes the set of rows on which the function operates. A window function uses values from the rows in a window to calculate the returned values.
Some common uses of window function include calculating cumulative sums, moving average, ranking, and more. (Chartio)
Window functions are initiated with the OVER clause, and are configured using three concepts:
window partition (PARTITION BY) - groups rows into partitions
window ordering (ORDER BY) - defines the order or sequence of rows within each window
window frame (ROWS) - defines the window by use of an offset from the specified row
For this tutorial, we will cover PARTITIONand ORDER BY. I will assume you have basic to intermediate SQL experience. If you donβt, here are some great resources to get started.
Datacamp
Weekender Crash Course
Learn MS SQL Server + PostgreSQL
Window functions donβt reduce the number of rows in the output.
Window functions can retrieve values from other rows, whereas GROUP BY functions cannot.
Window functions can calculate running totals and moving averages, whereas GROUP BY functions cannot.
I will be working with an Olympic Medalist table called summer_medal from Datacamp. (If you are a student with an edu email, and want to get three months of free Datacamp visit β GitHub Student Developer Pack).
Here is an overview of the table.
The table represents the Olympic games from 1896 to 2010, containing every medal winner from each country, sport, event, gender, and discipline.
As mentioned earlier, using OVER() identifies the window function. The first function in this tutorial is ROW_NUMBER(). This function assigns a number to each record in the row.
SELECT athlete, event, ROW_NUMBER() OVER() AS Row_NumberFROM Summer_MedalsORDER BY Row_Number ASC;
We can see that we use the ROW_NUMBER() to create and assign a row number to selected variables. We alias the window function as Row_Number and sort it so we can get the first-row number on the top.
We can combine ORDER BY and ROW_NUMBER to determine which column should be used for the row number assignment. Letβs find the DISTINCT sports, and assign them row numbers based on alphabetical order.
SELECT sport, ROW_NUMBER() OVER(ORDER BY sport ASC) AS Row_NFROM ( SELECT DISTINCT sport FROM Summer_Medals) AS sportsORDER BY sport ASC;
Using PARTITION BY you can split a table based on a unique value from a column. It is useful when we have to perform a calculation on individual rows of a group using other rows of that group. This clause works on windows functions only, like- LAG(), LEAD(), RANK(), etc.
SQL LAG() is a window function that outputs a row that comes before the current row.
Here is an excellent example of how it relates to our data. Letβs find the players separated by gender, who won the gold medal in singles for tennis and who won the year before from 2004 onwards.
There are several steps to this problem. First, we would want to create a CTE, which allows you to define a temporary named result set that available temporarily in the execution scope of a statement β if youβre stuck here, visit my other post to learn more.
Since we would want our results to have the winner from the year before we can use LAG().
-- CTE for isolating gold medal tennis winnersWITH Tennis_Gold AS ( SELECT Athlete, Gender, Year, Country FROM Summer_Medals WHERE Year >= 2004 AND Sport = 'Tennis' AND event = 'Singles' AND Medal = 'Gold')-- Window Function to find the lag and partition by genderSELECT Athlete as Champion, Gender, Year, LAG(Athlete) OVER (PARTITION BY gender ORDER BY Year ASC) AS Last_ChampionFROM Tennis_GoldORDER BY Gender ASC, Year ASC;
We can see that the results for both males and females are outputted in a single column β this is how partition helped. We recognize there are 3 winners for males and 3 for females. The first winner for both genders was in 2004, and if we look at the right, we see a NULL, because there is no winner before this since we started in 2004. Using LAG and PARTITION BYhelps achieve this.
Letβs try using LEAD().
SQL LEAD() is a window function that outputs a row that comes after the current row β essentially the opposite to LAG().
Letβs use the same question from the tennis example, but instead, find the future champion, not the past champion.
-- CTE isolating tennis sport, gold medalists from the year 2004+WITH Tennis_Gold AS ( SELECT Athlete, Gender, Year, Country FROM Summer_Medals WHERE Year >= 2004 AND Sport = 'Tennis' AND event = 'Singles' AND Medal = 'Gold')-- Window function, using LEAD to find the NEXT championSELECT Athlete as Champion, Gender, Year, LEAD(Athlete) OVER (PARTITION BY gender ORDER BY Year ASC) AS Future_ChampionFROM Tennis_GoldORDER BY Gender ASC, Year ASC;
We only changed LAG to LEAD and altered the alias to future champion, and we can achieve the opposite result.
SQL RANK is similar to ROW_NUMBER except it will assign the same number to rows with identical values, skipping over the following number. There is also DENSE_RANK which assigns a number to a row with equal values but doesnβt skip over a number. If this all seems confusing, donβt worry. See below for a side by side comparison of what that would look like.
Row_number β nothing new here, we are merely adding value for each row in the query.
Rank_number β Here, we give a ranking based on the values but notice we do not have the rank 3. Instead, we have two 2s, and we skip to rank 4.
Dense_rank β Similar to rank_number but instead of skipping the rank 3, we include it.
That is the main difference between RANK and DENSE_RANK. One includes a rank preceding a jointly ranked number, and one doesnβt.
Here is the code I used to get the table above.
-- CTE to get countries and number year particpated in selected countries.WITH countries AS ( SELECT Country, COUNT(DISTINCT year) AS participated FROM Summer_Medals WHERE Country in ('GBR', 'DEN', 'FRA', 'ITA','AUT') GROUP BY Country)-- Window functions to show different ranking choices.SELECT Country, participated, ROW_NUMBER() OVER(ORDER BY participated DESC) AS Row_Number, RANK() OVER(ORDER BY participated DESC) AS Rank_Number, DENSE_RANK() OVER(ORDER BY participated DESC) AS Dense_RankFROM countriesORDER BY participated DESC;
And that concludes this introduction to window functions. There are many more functionalities to windows functions including a ROWS , NTILE, as well as aggregate functions (SUM, MAX, MIN, etc.). I will be posting tutorials on how to utilize window functions more in SQL, so be sure to stay tuned for my latest posts.
Connect with me on Linkedin or Github
|
[
{
"code": null,
"e": 160,
"s": 47,
"text": "Window functions can help you run operations on a selection of rows and return a value from that original query."
},
{
"code": null,
"e": 324,
"s": 160,
"text": "The term window describes the set of rows on which the function operates. A window function uses values from the rows in a window to calculate the returned values."
},
{
"code": null,
"e": 442,
"s": 324,
"text": "Some common uses of window function include calculating cumulative sums, moving average, ranking, and more. (Chartio)"
},
{
"code": null,
"e": 536,
"s": 442,
"text": "Window functions are initiated with the OVER clause, and are configured using three concepts:"
},
{
"code": null,
"e": 598,
"s": 536,
"text": "window partition (PARTITION BY) - groups rows into partitions"
},
{
"code": null,
"e": 684,
"s": 598,
"text": "window ordering (ORDER BY) - defines the order or sequence of rows within each window"
},
{
"code": null,
"e": 768,
"s": 684,
"text": "window frame (ROWS) - defines the window by use of an offset from the specified row"
},
{
"code": null,
"e": 945,
"s": 768,
"text": "For this tutorial, we will cover PARTITIONand ORDER BY. I will assume you have basic to intermediate SQL experience. If you donβt, here are some great resources to get started."
},
{
"code": null,
"e": 954,
"s": 945,
"text": "Datacamp"
},
{
"code": null,
"e": 977,
"s": 954,
"text": "Weekender Crash Course"
},
{
"code": null,
"e": 1010,
"s": 977,
"text": "Learn MS SQL Server + PostgreSQL"
},
{
"code": null,
"e": 1074,
"s": 1010,
"text": "Window functions donβt reduce the number of rows in the output."
},
{
"code": null,
"e": 1163,
"s": 1074,
"text": "Window functions can retrieve values from other rows, whereas GROUP BY functions cannot."
},
{
"code": null,
"e": 1265,
"s": 1163,
"text": "Window functions can calculate running totals and moving averages, whereas GROUP BY functions cannot."
},
{
"code": null,
"e": 1476,
"s": 1265,
"text": "I will be working with an Olympic Medalist table called summer_medal from Datacamp. (If you are a student with an edu email, and want to get three months of free Datacamp visit β GitHub Student Developer Pack)."
},
{
"code": null,
"e": 1510,
"s": 1476,
"text": "Here is an overview of the table."
},
{
"code": null,
"e": 1655,
"s": 1510,
"text": "The table represents the Olympic games from 1896 to 2010, containing every medal winner from each country, sport, event, gender, and discipline."
},
{
"code": null,
"e": 1833,
"s": 1655,
"text": "As mentioned earlier, using OVER() identifies the window function. The first function in this tutorial is ROW_NUMBER(). This function assigns a number to each record in the row."
},
{
"code": null,
"e": 1935,
"s": 1833,
"text": "SELECT athlete, event, ROW_NUMBER() OVER() AS Row_NumberFROM Summer_MedalsORDER BY Row_Number ASC;"
},
{
"code": null,
"e": 2134,
"s": 1935,
"text": "We can see that we use the ROW_NUMBER() to create and assign a row number to selected variables. We alias the window function as Row_Number and sort it so we can get the first-row number on the top."
},
{
"code": null,
"e": 2334,
"s": 2134,
"text": "We can combine ORDER BY and ROW_NUMBER to determine which column should be used for the row number assignment. Letβs find the DISTINCT sports, and assign them row numbers based on alphabetical order."
},
{
"code": null,
"e": 2476,
"s": 2334,
"text": "SELECT sport, ROW_NUMBER() OVER(ORDER BY sport ASC) AS Row_NFROM ( SELECT DISTINCT sport FROM Summer_Medals) AS sportsORDER BY sport ASC;"
},
{
"code": null,
"e": 2748,
"s": 2476,
"text": "Using PARTITION BY you can split a table based on a unique value from a column. It is useful when we have to perform a calculation on individual rows of a group using other rows of that group. This clause works on windows functions only, like- LAG(), LEAD(), RANK(), etc."
},
{
"code": null,
"e": 2833,
"s": 2748,
"text": "SQL LAG() is a window function that outputs a row that comes before the current row."
},
{
"code": null,
"e": 3029,
"s": 2833,
"text": "Here is an excellent example of how it relates to our data. Letβs find the players separated by gender, who won the gold medal in singles for tennis and who won the year before from 2004 onwards."
},
{
"code": null,
"e": 3288,
"s": 3029,
"text": "There are several steps to this problem. First, we would want to create a CTE, which allows you to define a temporary named result set that available temporarily in the execution scope of a statement β if youβre stuck here, visit my other post to learn more."
},
{
"code": null,
"e": 3378,
"s": 3288,
"text": "Since we would want our results to have the winner from the year before we can use LAG()."
},
{
"code": null,
"e": 3872,
"s": 3378,
"text": "-- CTE for isolating gold medal tennis winnersWITH Tennis_Gold AS ( SELECT Athlete, Gender, Year, Country FROM Summer_Medals WHERE Year >= 2004 AND Sport = 'Tennis' AND event = 'Singles' AND Medal = 'Gold')-- Window Function to find the lag and partition by genderSELECT Athlete as Champion, Gender, Year, LAG(Athlete) OVER (PARTITION BY gender ORDER BY Year ASC) AS Last_ChampionFROM Tennis_GoldORDER BY Gender ASC, Year ASC;"
},
{
"code": null,
"e": 4256,
"s": 3872,
"text": "We can see that the results for both males and females are outputted in a single column β this is how partition helped. We recognize there are 3 winners for males and 3 for females. The first winner for both genders was in 2004, and if we look at the right, we see a NULL, because there is no winner before this since we started in 2004. Using LAG and PARTITION BYhelps achieve this."
},
{
"code": null,
"e": 4280,
"s": 4256,
"text": "Letβs try using LEAD()."
},
{
"code": null,
"e": 4401,
"s": 4280,
"text": "SQL LEAD() is a window function that outputs a row that comes after the current row β essentially the opposite to LAG()."
},
{
"code": null,
"e": 4516,
"s": 4401,
"text": "Letβs use the same question from the tennis example, but instead, find the future champion, not the past champion."
},
{
"code": null,
"e": 5030,
"s": 4516,
"text": "-- CTE isolating tennis sport, gold medalists from the year 2004+WITH Tennis_Gold AS ( SELECT Athlete, Gender, Year, Country FROM Summer_Medals WHERE Year >= 2004 AND Sport = 'Tennis' AND event = 'Singles' AND Medal = 'Gold')-- Window function, using LEAD to find the NEXT championSELECT Athlete as Champion, Gender, Year, LEAD(Athlete) OVER (PARTITION BY gender ORDER BY Year ASC) AS Future_ChampionFROM Tennis_GoldORDER BY Gender ASC, Year ASC;"
},
{
"code": null,
"e": 5140,
"s": 5030,
"text": "We only changed LAG to LEAD and altered the alias to future champion, and we can achieve the opposite result."
},
{
"code": null,
"e": 5498,
"s": 5140,
"text": "SQL RANK is similar to ROW_NUMBER except it will assign the same number to rows with identical values, skipping over the following number. There is also DENSE_RANK which assigns a number to a row with equal values but doesnβt skip over a number. If this all seems confusing, donβt worry. See below for a side by side comparison of what that would look like."
},
{
"code": null,
"e": 5583,
"s": 5498,
"text": "Row_number β nothing new here, we are merely adding value for each row in the query."
},
{
"code": null,
"e": 5727,
"s": 5583,
"text": "Rank_number β Here, we give a ranking based on the values but notice we do not have the rank 3. Instead, we have two 2s, and we skip to rank 4."
},
{
"code": null,
"e": 5814,
"s": 5727,
"text": "Dense_rank β Similar to rank_number but instead of skipping the rank 3, we include it."
},
{
"code": null,
"e": 5943,
"s": 5814,
"text": "That is the main difference between RANK and DENSE_RANK. One includes a rank preceding a jointly ranked number, and one doesnβt."
},
{
"code": null,
"e": 5991,
"s": 5943,
"text": "Here is the code I used to get the table above."
},
{
"code": null,
"e": 6583,
"s": 5991,
"text": "-- CTE to get countries and number year particpated in selected countries.WITH countries AS ( SELECT Country, COUNT(DISTINCT year) AS participated FROM Summer_Medals WHERE Country in ('GBR', 'DEN', 'FRA', 'ITA','AUT') GROUP BY Country)-- Window functions to show different ranking choices.SELECT Country, participated, ROW_NUMBER() OVER(ORDER BY participated DESC) AS Row_Number, RANK() OVER(ORDER BY participated DESC) AS Rank_Number, DENSE_RANK() OVER(ORDER BY participated DESC) AS Dense_RankFROM countriesORDER BY participated DESC;"
},
{
"code": null,
"e": 6900,
"s": 6583,
"text": "And that concludes this introduction to window functions. There are many more functionalities to windows functions including a ROWS , NTILE, as well as aggregate functions (SUM, MAX, MIN, etc.). I will be posting tutorials on how to utilize window functions more in SQL, so be sure to stay tuned for my latest posts."
}
] |
Maximize score by multiplying elements of given Array with given multipliers - GeeksforGeeks
|
29 Dec, 2021
Given two arrays array[] and multipliers[] of size N and M where N is always greater than equal to M. There are M operations to be performed. In each operation, choose multiplier[i] and an element from the array arr[] either from the start or the end letβs say K then add multiplier[i]*K to the total score say ans and remove K from the array arr[]. The task is to find the maximum value of the final score ans.
Examples:
Input: array[] = {1, 2, 3}, multipliers[] = {3, 2, 1}, N=3, M=3Output: 14Explanation: An optimal solution is as follows:β Choose from the end, [1, 2, 3], adding 3 * 3 = 9 to the score.β Choose from the end, [1, 2], adding 2 * 2 = 4 to the score.β Choose from the end, [1], adding 1 * 1 = 1 to the score.The total score is 9 + 4 + 1 = 14.
Input: array[] = {2, 1}, multipliers[] = {0}, N=2, M=1Output: 0Explanation: No matter 2 or 1 is chosen, the answer will be 0 because multiplier[0] equals 0.
Naive Approach: The brute force solution is to check each and every pair recursively and find the optimal solution.
Below is the implementation of the above approach
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum score// using dynamic programming and// memoizationint getMaxScore(vector<int>& array, vector<int>& multipliers){ // M is the number of elements needed to pick int M = multipliers.size(), N = array.size(); int remain = N - M; vector<int> dp(M + 1, 0); for (int i = 0; i < M; ++i) { int mm = multipliers[M - i - 1]; for (int j = 0; j < M - i; ++j) { dp[j] = max(mm * array[j] + dp[j + 1], mm * array[j + remain] + dp[j]); } remain += 1; } return dp[0];} // Driver Codeint main(){ vector<int> array = { 1, 2, 3 }; vector<int> multipliers = { 3, 2, 1 }; cout << getMaxScore(array, multipliers); return 0;} // This code is contributed by rakeshsahni
// Java program for the above approachpublic class GFG { // Function to find the maximum score // using dynamic programming and // memoization static int getMaxScore(int []array,int []multipliers) { // M is the number of elements needed to pick int M = multipliers.length; int N = array.length; int remain = N - M; int dp[] = new int[M + 1]; for (int i = 0; i < M; ++i) { int mm = multipliers[M - i - 1]; for (int j = 0; j < M - i; ++j) { dp[j] = Math.max(mm * array[j] + dp[j + 1], mm * array[j + remain] + dp[j]); } remain += 1; } return dp[0]; } // Driver Code public static void main (String[] args) { int []array = { 1, 2, 3 }; int []multipliers = { 3, 2, 1 }; System.out.println(getMaxScore(array, multipliers)); } } // This code is contributed by AnkThon
# Python program for the above approach # Function to find the maximum score# recursively def getMaxScore(array, multipliers): # Depth first search def dfs(start, end, index): if index == len(multipliers): return 0 # Pick left left = multipliers[index] * array[start] + \ dfs(start + 1, end, index + 1) # Pick right right = multipliers[index] * array[end] + \ dfs(start, end - 1, index + 1) return max(right, left) return dfs(0, len(array) - 1, 0) # Driver Codeif __name__ == "__main__": array = [1, 2, 3] multipliers = [3, 2, 1] print(getMaxScore(array, multipliers))
// C# program for the above approachusing System;public class GFG{ // Function to find the maximum score // using dynamic programming and // memoization static int getMaxScore(int[] array, int[] multipliers) { // M is the number of elements needed to pick int M = multipliers.Length; int N = array.Length; int remain = N - M; int[] dp = new int[M + 1]; for (int i = 0; i < M; ++i) { int mm = multipliers[M - i - 1]; for (int j = 0; j < M - i; ++j) { dp[j] = Math.Max(mm * array[j] + dp[j + 1], mm * array[j + remain] + dp[j]); } remain += 1; } return dp[0]; } // Driver Code public static void Main(String[] args) { int[] array = { 1, 2, 3 }; int[] multipliers = { 3, 2, 1 }; Console.Write(getMaxScore(array, multipliers)); }} // This code is contributed by gfgking.
<script>// Javascript program for the above approach // Function to find the maximum score// using dynamic programming and// memoizationfunction getMaxScore(array, multipliers) { // M is the number of elements needed to pick let M = multipliers.length, N = array.length; let remain = N - M; let dp = new Array(M + 1).fill(0); for (let i = 0; i < M; ++i) { let mm = multipliers[M - i - 1]; for (let j = 0; j < M - i; ++j) { dp[j] = Math.max(mm * array[j] + dp[j + 1], mm * array[j + remain] + dp[j]); } remain += 1; } return dp[0];} // Driver Code let array = [1, 2, 3];let multipliers = [3, 2, 1]; document.write(getMaxScore(array, multipliers)); // This code is contributed by gfgking</script>
14
Time Complexity: O(2M)Auxiliary Space: O(1)
Efficient Approach: The solution is based on dynamic programming as it contains both the properties β optimal substructure and overlapping subproblems. Assume dp[i][j] is the current maximum result that can get from a subarray, where i is the start index and j is the end. At any stage, there are two choices:
pick the first: dp[i + 1][j] + curr_weight * array[i]
pick the last: dp[i][j β 1] + curr_weight * array[j]
The result will be the maximum of both. Follow the steps below to solve the problem using depth-first search and memorization:
Initialize a variable remain as N-M.
Initialize an array dp[] of size M+1 with values 0.
Iterate over the range [0, M) using the variable i and perform the following steps:Initialize a variable mm as multipliers[-i-1].Iterate over the range [0, M-i) using the variable j and perform the following steps:Set the value of dp[j] as the maximum of mm*array[j] + dp[j+1] or mm*array[j+remain] + dp[j].Increase the value of remain by 1.
Initialize a variable mm as multipliers[-i-1].
Iterate over the range [0, M-i) using the variable j and perform the following steps:Set the value of dp[j] as the maximum of mm*array[j] + dp[j+1] or mm*array[j+remain] + dp[j].Increase the value of remain by 1.
Set the value of dp[j] as the maximum of mm*array[j] + dp[j+1] or mm*array[j+remain] + dp[j].
Increase the value of remain by 1.
After performing the above steps, print the value of dp[0] as the answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// Java program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum score // using dynamic programming and // memoizationint getMaxScore(vector<int>& array, vector<int>& multipliers){ // M is the number of elements needed to pick int M = multipliers.size(), N = array.size(); int remain = N - M; vector<int> dp(M + 1, 0); for (int i = 0; i < M; ++i) { int mm = multipliers[M - i - 1]; for (int j = 0; j < M - i; ++j) { dp[j] = max(mm * array[j] + dp[j + 1], mm * array[j + remain] + dp[j]); } remain += 1; } return dp[0]; } // Driver Code int main () { vector<int> array = { 1, 2, 3 }; vector<int> multipliers = { 3, 2, 1 }; cout << getMaxScore(array, multipliers); } // This code is contributed by shikhasingrajput
// Java program for the above approachimport java.util.*;public class GFG { // Function to find the maximum score // using dynamic programming and // memoization static int getMaxScore(int []array,int []multipliers) { // M is the number of elements needed to pick int M = multipliers.length; int N = array.length; int remain = N - M; int dp[] = new int[M + 1]; for (int i = 0; i < M; ++i) { int mm = multipliers[M - i - 1]; for (int j = 0; j < M - i; ++j) { dp[j] = Math.max(mm * array[j] + dp[j + 1], mm * array[j + remain] + dp[j]); } remain += 1; } return dp[0]; } // Driver Code public static void main (String[] args) { int []array = { 1, 2, 3 }; int []multipliers = { 3, 2, 1 }; System.out.println(getMaxScore(array, multipliers)); } } // This code is contributed by Samim Hossain Mondal.
# Python program for the above approach # Function to find the maximum score# using dynamic programming and# memoizationdef getMaxScore(array, multipliers): # M is the number of elements needed to pick M, N = len(multipliers), len(array) remain = N - M dp = [0] * (M + 1) for i in range(M): mm = multipliers[-i - 1] for j in range(M - i): dp[j] = max(mm * array[j] + dp[j + 1], mm * array[j + remain] + dp[j]) remain += 1 return dp[0] # Driver Codeif __name__ == "__main__": array = [1, 2, 3] multipliers = [3, 2, 1] print(getMaxScore(array, multipliers))
// C# program for the above approachusing System;public class GFG { // Function to find the maximum score // using dynamic programming and // memoization static int getMaxScore(int[] array, int[] multipliers) { // M is the number of elements needed to pick int M = multipliers.Length; int N = array.Length; int remain = N - M; int[] dp = new int[M + 1]; for (int i = 0; i < M; ++i) { int mm = multipliers[M - i - 1]; for (int j = 0; j < M - i; ++j) { dp[j] = Math.Max(mm * array[j] + dp[j + 1], mm * array[j + remain] + dp[j]); } remain += 1; } return dp[0]; } // Driver Code public static void Main(string[] args) { int[] array = { 1, 2, 3 }; int[] multipliers = { 3, 2, 1 }; Console.WriteLine(getMaxScore(array, multipliers)); }} // This code is contributed by ukasp.
<script> // JavaScript Program to implement // the above approach //Function to find the maximum score //using dynamic programming and //memoization function getMaxScore(array, multipliers) { //M is the number of elements needed to pick M = multipliers.length N = array.length remain = N - M dp = new Array(M + 1).fill(0) for (let i = 0; i < M; i++) { mm = multipliers[M - i - 1] for (j = 0; j < M - i; j++) dp[j] = Math.max(mm * array[j] + dp[j + 1], mm * array[j + remain] + dp[j]) remain += 1 } return dp[0] } array = [1, 2, 3] multipliers = [3, 2, 1] document.write(getMaxScore(array, multipliers)) // This code is contributed by Potta Lokesh </script>
14
Time Complexity: O(M*M)Auxiliary Space: O(M)
rakeshsahni
ankthon
gfgking
lokeshpotta20
samim2000
ukasp
shikhasingrajput
surinderdawra388
Memoization
Arrays
Dynamic Programming
Mathematical
Arrays
Dynamic Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Find duplicates in O(n) time and O(1) extra space | Set 1
Reversal algorithm for array rotation
Next Greater Element
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
BellmanβFord Algorithm | DP-23
Longest Common Subsequence | DP-4
Floyd Warshall Algorithm | DP-16
|
[
{
"code": null,
"e": 24820,
"s": 24792,
"text": "\n29 Dec, 2021"
},
{
"code": null,
"e": 25232,
"s": 24820,
"text": "Given two arrays array[] and multipliers[] of size N and M where N is always greater than equal to M. There are M operations to be performed. In each operation, choose multiplier[i] and an element from the array arr[] either from the start or the end letβs say K then add multiplier[i]*K to the total score say ans and remove K from the array arr[]. The task is to find the maximum value of the final score ans."
},
{
"code": null,
"e": 25242,
"s": 25232,
"text": "Examples:"
},
{
"code": null,
"e": 25580,
"s": 25242,
"text": "Input: array[] = {1, 2, 3}, multipliers[] = {3, 2, 1}, N=3, M=3Output: 14Explanation: An optimal solution is as follows:β Choose from the end, [1, 2, 3], adding 3 * 3 = 9 to the score.β Choose from the end, [1, 2], adding 2 * 2 = 4 to the score.β Choose from the end, [1], adding 1 * 1 = 1 to the score.The total score is 9 + 4 + 1 = 14."
},
{
"code": null,
"e": 25737,
"s": 25580,
"text": "Input: array[] = {2, 1}, multipliers[] = {0}, N=2, M=1Output: 0Explanation: No matter 2 or 1 is chosen, the answer will be 0 because multiplier[0] equals 0."
},
{
"code": null,
"e": 25853,
"s": 25737,
"text": "Naive Approach: The brute force solution is to check each and every pair recursively and find the optimal solution."
},
{
"code": null,
"e": 25903,
"s": 25853,
"text": "Below is the implementation of the above approach"
},
{
"code": null,
"e": 25907,
"s": 25903,
"text": "C++"
},
{
"code": null,
"e": 25912,
"s": 25907,
"text": "Java"
},
{
"code": null,
"e": 25920,
"s": 25912,
"text": "Python3"
},
{
"code": null,
"e": 25923,
"s": 25920,
"text": "C#"
},
{
"code": null,
"e": 25934,
"s": 25923,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum score// using dynamic programming and// memoizationint getMaxScore(vector<int>& array, vector<int>& multipliers){ // M is the number of elements needed to pick int M = multipliers.size(), N = array.size(); int remain = N - M; vector<int> dp(M + 1, 0); for (int i = 0; i < M; ++i) { int mm = multipliers[M - i - 1]; for (int j = 0; j < M - i; ++j) { dp[j] = max(mm * array[j] + dp[j + 1], mm * array[j + remain] + dp[j]); } remain += 1; } return dp[0];} // Driver Codeint main(){ vector<int> array = { 1, 2, 3 }; vector<int> multipliers = { 3, 2, 1 }; cout << getMaxScore(array, multipliers); return 0;} // This code is contributed by rakeshsahni",
"e": 26762,
"s": 25934,
"text": null
},
{
"code": "// Java program for the above approachpublic class GFG { // Function to find the maximum score // using dynamic programming and // memoization static int getMaxScore(int []array,int []multipliers) { // M is the number of elements needed to pick int M = multipliers.length; int N = array.length; int remain = N - M; int dp[] = new int[M + 1]; for (int i = 0; i < M; ++i) { int mm = multipliers[M - i - 1]; for (int j = 0; j < M - i; ++j) { dp[j] = Math.max(mm * array[j] + dp[j + 1], mm * array[j + remain] + dp[j]); } remain += 1; } return dp[0]; } // Driver Code public static void main (String[] args) { int []array = { 1, 2, 3 }; int []multipliers = { 3, 2, 1 }; System.out.println(getMaxScore(array, multipliers)); } } // This code is contributed by AnkThon",
"e": 27628,
"s": 26762,
"text": null
},
{
"code": "# Python program for the above approach # Function to find the maximum score# recursively def getMaxScore(array, multipliers): # Depth first search def dfs(start, end, index): if index == len(multipliers): return 0 # Pick left left = multipliers[index] * array[start] + \\ dfs(start + 1, end, index + 1) # Pick right right = multipliers[index] * array[end] + \\ dfs(start, end - 1, index + 1) return max(right, left) return dfs(0, len(array) - 1, 0) # Driver Codeif __name__ == \"__main__\": array = [1, 2, 3] multipliers = [3, 2, 1] print(getMaxScore(array, multipliers))",
"e": 28299,
"s": 27628,
"text": null
},
{
"code": "// C# program for the above approachusing System;public class GFG{ // Function to find the maximum score // using dynamic programming and // memoization static int getMaxScore(int[] array, int[] multipliers) { // M is the number of elements needed to pick int M = multipliers.Length; int N = array.Length; int remain = N - M; int[] dp = new int[M + 1]; for (int i = 0; i < M; ++i) { int mm = multipliers[M - i - 1]; for (int j = 0; j < M - i; ++j) { dp[j] = Math.Max(mm * array[j] + dp[j + 1], mm * array[j + remain] + dp[j]); } remain += 1; } return dp[0]; } // Driver Code public static void Main(String[] args) { int[] array = { 1, 2, 3 }; int[] multipliers = { 3, 2, 1 }; Console.Write(getMaxScore(array, multipliers)); }} // This code is contributed by gfgking.",
"e": 29292,
"s": 28299,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to find the maximum score// using dynamic programming and// memoizationfunction getMaxScore(array, multipliers) { // M is the number of elements needed to pick let M = multipliers.length, N = array.length; let remain = N - M; let dp = new Array(M + 1).fill(0); for (let i = 0; i < M; ++i) { let mm = multipliers[M - i - 1]; for (let j = 0; j < M - i; ++j) { dp[j] = Math.max(mm * array[j] + dp[j + 1], mm * array[j + remain] + dp[j]); } remain += 1; } return dp[0];} // Driver Code let array = [1, 2, 3];let multipliers = [3, 2, 1]; document.write(getMaxScore(array, multipliers)); // This code is contributed by gfgking</script>",
"e": 30026,
"s": 29292,
"text": null
},
{
"code": null,
"e": 30029,
"s": 30026,
"text": "14"
},
{
"code": null,
"e": 30073,
"s": 30029,
"text": "Time Complexity: O(2M)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30383,
"s": 30073,
"text": "Efficient Approach: The solution is based on dynamic programming as it contains both the properties β optimal substructure and overlapping subproblems. Assume dp[i][j] is the current maximum result that can get from a subarray, where i is the start index and j is the end. At any stage, there are two choices:"
},
{
"code": null,
"e": 30437,
"s": 30383,
"text": "pick the first: dp[i + 1][j] + curr_weight * array[i]"
},
{
"code": null,
"e": 30490,
"s": 30437,
"text": "pick the last: dp[i][j β 1] + curr_weight * array[j]"
},
{
"code": null,
"e": 30617,
"s": 30490,
"text": "The result will be the maximum of both. Follow the steps below to solve the problem using depth-first search and memorization:"
},
{
"code": null,
"e": 30654,
"s": 30617,
"text": "Initialize a variable remain as N-M."
},
{
"code": null,
"e": 30706,
"s": 30654,
"text": "Initialize an array dp[] of size M+1 with values 0."
},
{
"code": null,
"e": 31048,
"s": 30706,
"text": "Iterate over the range [0, M) using the variable i and perform the following steps:Initialize a variable mm as multipliers[-i-1].Iterate over the range [0, M-i) using the variable j and perform the following steps:Set the value of dp[j] as the maximum of mm*array[j] + dp[j+1] or mm*array[j+remain] + dp[j].Increase the value of remain by 1."
},
{
"code": null,
"e": 31095,
"s": 31048,
"text": "Initialize a variable mm as multipliers[-i-1]."
},
{
"code": null,
"e": 31308,
"s": 31095,
"text": "Iterate over the range [0, M-i) using the variable j and perform the following steps:Set the value of dp[j] as the maximum of mm*array[j] + dp[j+1] or mm*array[j+remain] + dp[j].Increase the value of remain by 1."
},
{
"code": null,
"e": 31402,
"s": 31308,
"text": "Set the value of dp[j] as the maximum of mm*array[j] + dp[j+1] or mm*array[j+remain] + dp[j]."
},
{
"code": null,
"e": 31437,
"s": 31402,
"text": "Increase the value of remain by 1."
},
{
"code": null,
"e": 31511,
"s": 31437,
"text": "After performing the above steps, print the value of dp[0] as the answer."
},
{
"code": null,
"e": 31562,
"s": 31511,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 31566,
"s": 31562,
"text": "C++"
},
{
"code": null,
"e": 31571,
"s": 31566,
"text": "Java"
},
{
"code": null,
"e": 31579,
"s": 31571,
"text": "Python3"
},
{
"code": null,
"e": 31582,
"s": 31579,
"text": "C#"
},
{
"code": null,
"e": 31593,
"s": 31582,
"text": "Javascript"
},
{
"code": "// Java program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum score // using dynamic programming and // memoizationint getMaxScore(vector<int>& array, vector<int>& multipliers){ // M is the number of elements needed to pick int M = multipliers.size(), N = array.size(); int remain = N - M; vector<int> dp(M + 1, 0); for (int i = 0; i < M; ++i) { int mm = multipliers[M - i - 1]; for (int j = 0; j < M - i; ++j) { dp[j] = max(mm * array[j] + dp[j + 1], mm * array[j + remain] + dp[j]); } remain += 1; } return dp[0]; } // Driver Code int main () { vector<int> array = { 1, 2, 3 }; vector<int> multipliers = { 3, 2, 1 }; cout << getMaxScore(array, multipliers); } // This code is contributed by shikhasingrajput",
"e": 32470,
"s": 31593,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;public class GFG { // Function to find the maximum score // using dynamic programming and // memoization static int getMaxScore(int []array,int []multipliers) { // M is the number of elements needed to pick int M = multipliers.length; int N = array.length; int remain = N - M; int dp[] = new int[M + 1]; for (int i = 0; i < M; ++i) { int mm = multipliers[M - i - 1]; for (int j = 0; j < M - i; ++j) { dp[j] = Math.max(mm * array[j] + dp[j + 1], mm * array[j + remain] + dp[j]); } remain += 1; } return dp[0]; } // Driver Code public static void main (String[] args) { int []array = { 1, 2, 3 }; int []multipliers = { 3, 2, 1 }; System.out.println(getMaxScore(array, multipliers)); } } // This code is contributed by Samim Hossain Mondal.",
"e": 33369,
"s": 32470,
"text": null
},
{
"code": "# Python program for the above approach # Function to find the maximum score# using dynamic programming and# memoizationdef getMaxScore(array, multipliers): # M is the number of elements needed to pick M, N = len(multipliers), len(array) remain = N - M dp = [0] * (M + 1) for i in range(M): mm = multipliers[-i - 1] for j in range(M - i): dp[j] = max(mm * array[j] + dp[j + 1], mm * array[j + remain] + dp[j]) remain += 1 return dp[0] # Driver Codeif __name__ == \"__main__\": array = [1, 2, 3] multipliers = [3, 2, 1] print(getMaxScore(array, multipliers))",
"e": 34011,
"s": 33369,
"text": null
},
{
"code": "// C# program for the above approachusing System;public class GFG { // Function to find the maximum score // using dynamic programming and // memoization static int getMaxScore(int[] array, int[] multipliers) { // M is the number of elements needed to pick int M = multipliers.Length; int N = array.Length; int remain = N - M; int[] dp = new int[M + 1]; for (int i = 0; i < M; ++i) { int mm = multipliers[M - i - 1]; for (int j = 0; j < M - i; ++j) { dp[j] = Math.Max(mm * array[j] + dp[j + 1], mm * array[j + remain] + dp[j]); } remain += 1; } return dp[0]; } // Driver Code public static void Main(string[] args) { int[] array = { 1, 2, 3 }; int[] multipliers = { 3, 2, 1 }; Console.WriteLine(getMaxScore(array, multipliers)); }} // This code is contributed by ukasp.",
"e": 35024,
"s": 34011,
"text": null
},
{
"code": "<script> // JavaScript Program to implement // the above approach //Function to find the maximum score //using dynamic programming and //memoization function getMaxScore(array, multipliers) { //M is the number of elements needed to pick M = multipliers.length N = array.length remain = N - M dp = new Array(M + 1).fill(0) for (let i = 0; i < M; i++) { mm = multipliers[M - i - 1] for (j = 0; j < M - i; j++) dp[j] = Math.max(mm * array[j] + dp[j + 1], mm * array[j + remain] + dp[j]) remain += 1 } return dp[0] } array = [1, 2, 3] multipliers = [3, 2, 1] document.write(getMaxScore(array, multipliers)) // This code is contributed by Potta Lokesh </script>",
"e": 35916,
"s": 35024,
"text": null
},
{
"code": null,
"e": 35919,
"s": 35916,
"text": "14"
},
{
"code": null,
"e": 35964,
"s": 35919,
"text": "Time Complexity: O(M*M)Auxiliary Space: O(M)"
},
{
"code": null,
"e": 35976,
"s": 35964,
"text": "rakeshsahni"
},
{
"code": null,
"e": 35984,
"s": 35976,
"text": "ankthon"
},
{
"code": null,
"e": 35992,
"s": 35984,
"text": "gfgking"
},
{
"code": null,
"e": 36006,
"s": 35992,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 36016,
"s": 36006,
"text": "samim2000"
},
{
"code": null,
"e": 36022,
"s": 36016,
"text": "ukasp"
},
{
"code": null,
"e": 36039,
"s": 36022,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 36056,
"s": 36039,
"text": "surinderdawra388"
},
{
"code": null,
"e": 36068,
"s": 36056,
"text": "Memoization"
},
{
"code": null,
"e": 36075,
"s": 36068,
"text": "Arrays"
},
{
"code": null,
"e": 36095,
"s": 36075,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 36108,
"s": 36095,
"text": "Mathematical"
},
{
"code": null,
"e": 36115,
"s": 36108,
"text": "Arrays"
},
{
"code": null,
"e": 36135,
"s": 36115,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 36148,
"s": 36135,
"text": "Mathematical"
},
{
"code": null,
"e": 36246,
"s": 36148,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36255,
"s": 36246,
"text": "Comments"
},
{
"code": null,
"e": 36268,
"s": 36255,
"text": "Old Comments"
},
{
"code": null,
"e": 36293,
"s": 36268,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 36342,
"s": 36293,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 36400,
"s": 36342,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 36438,
"s": 36400,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 36459,
"s": 36438,
"text": "Next Greater Element"
},
{
"code": null,
"e": 36488,
"s": 36459,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 36518,
"s": 36488,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 36549,
"s": 36518,
"text": "BellmanβFord Algorithm | DP-23"
},
{
"code": null,
"e": 36583,
"s": 36549,
"text": "Longest Common Subsequence | DP-4"
}
] |
Calculating the balance factor in a Javascript AVL Tree
|
AVL tree checks the height of the left and the right sub-trees and assures that the difference is not more than 1. This difference is called the Balance Factor.
For example, in the following trees, the first tree is balanced and the next two trees are not balanced β
In the second tree, the left subtree of C has height 2 and the right subtree has height 0, so the difference is 2. In the third tree, the right subtree of A has height 2 and the left is missing, so it is 0, and the difference is 2 again. AVL tree permits difference (balance factor) to be only 1.
BalanceFactor = height(left-sutree) β height(right-sutree)
If the difference in the height of left and right sub-trees is more than 1, the tree is balanced using some rotation techniques.
Let us define this method and initialize the class as well β
class AVLTree {
constructor() {
// Initialize a root element to null.
this.root = null;
}
getBalanceFactor(root) {
return this.getHeight(root.left) - this.getHeight(root.right);
}
getHeight(root) {
let height = 0;
if (root === null) {
height = -1;
} else {
height = Math.max(this.getHeight(root.left), this.getHeight(root.right)) + 1;
}
return height;
}
}
AVLTree.prototype.Node = class {
constructor(data, left = null, right = null) {
this.data = data;
this.left = left;
this.right = right;
}
};
|
[
{
"code": null,
"e": 1223,
"s": 1062,
"text": "AVL tree checks the height of the left and the right sub-trees and assures that the difference is not more than 1. This difference is called the Balance Factor."
},
{
"code": null,
"e": 1329,
"s": 1223,
"text": "For example, in the following trees, the first tree is balanced and the next two trees are not balanced β"
},
{
"code": null,
"e": 1626,
"s": 1329,
"text": "In the second tree, the left subtree of C has height 2 and the right subtree has height 0, so the difference is 2. In the third tree, the right subtree of A has height 2 and the left is missing, so it is 0, and the difference is 2 again. AVL tree permits difference (balance factor) to be only 1."
},
{
"code": null,
"e": 1685,
"s": 1626,
"text": "BalanceFactor = height(left-sutree) β height(right-sutree)"
},
{
"code": null,
"e": 1814,
"s": 1685,
"text": "If the difference in the height of left and right sub-trees is more than 1, the tree is balanced using some rotation techniques."
},
{
"code": null,
"e": 1876,
"s": 1814,
"text": "Let us define this method and initialize the class as well β "
},
{
"code": null,
"e": 2481,
"s": 1876,
"text": "class AVLTree {\n constructor() {\n // Initialize a root element to null.\n this.root = null;\n }\n getBalanceFactor(root) {\n return this.getHeight(root.left) - this.getHeight(root.right);\n }\n getHeight(root) {\n let height = 0;\n if (root === null) {\n height = -1;\n } else {\n height = Math.max(this.getHeight(root.left), this.getHeight(root.right)) + 1;\n }\n return height;\n }\n}\nAVLTree.prototype.Node = class {\n constructor(data, left = null, right = null) {\n this.data = data;\n this.left = left;\n this.right = right;\n }\n};"
}
] |
Apply Function to each Row in R DataFrame - GeeksforGeeks
|
15 Aug, 2021
In this article, we will discuss how to apply a function to each row in a data frame in R Programming Language. Letβs take an example for a better understanding.
Example:
Suppose we have a dummy dataset with A, B, C as column names and some numeric value as rows.
A
B
C
1.
5
6
1
2.
6
4
2
3.
7
3
3
4.
5
4
7
5.
6
2
8
6.
9
6
9
And we want to apply a function that will return the product of each row value, then the resultant data frame should look like this:
A
B
C
product
1.
5
6
1
60
2.
6
4
2
48
3.
7
3
3
63
4.
5
4
7
140
5.
6
2
8
96
6.
9
6
9
486
Approach: Using apply function
apply() is used to compute a function on a data frame or matrix. The purpose of using apply() function is to avoid the use of looping. apply() function returns output as a vector.
Syntax: apply(x, margin, func)
Parameters:x: Array or matrixmargin: dimension on which operation is to be appliedfunc: operation to be applied
Stepwise implementation:
Step 1: Create a dummy dataset.
R
# Apply function to each row in r Dataframe # Creating dataset# creating firs columnx <- c(5, 6, 7, 5, 6, 9) # creating second columny <- c(6, 4, 3, 4, 2, 6) # creating third columnz <- c(1, 2, 3, 7, 8, 9) # creating dataframedf <- data.frame(A = x, B = y, C = z) display(df)
Output:
A B C
1 5 6 1
2 6 4 2
3 7 3 3
4 5 4 7
5 6 2 8
6 9 6 9
Step 2: Create a custom function for calculating products.
R
# creating function to computer productproduct = function(x, output){ # accessing elements from first column A = x[1] # accessing elements from second column B=x[2] # accessing elements from third column C= x[3] # return product return(A*B*C)}
Note: Here we are just defining the function for computing product and not calling, so there will be no output until we call this function.
Step 3: Use apply the function to compute the product of each row.
Syntax: (data_frame, 1, function,...)
Now we are calling the newly created product function and returns the product using apply function.
R
# apply(X,MARGIN,FUN,...)apply(df,1,product )
Output:
[1] 30 48 63 140 96 486
Note: apply() return product as a vector list. So we have to add it to the data frame using cbind (column bind).
Step 4: Append product list to the data frame.
R
# apply(X,MARGIN,FUN,...)single <- apply(df,1,product ) # adding product vector to dataframecbind(df,product = single)
Output:
Using apply()
Below is the full implementation:
R
# Apply function to each row in r Dataframe # Creating dataset# creating firs columnx <- c(5,6,7,5,6,9) # creating second columny <- c(6,4,3,4,2,6) # creating third columnz <- c(1,2,3,7,8,9) # creating dataframedf <- data.frame(A=x,B=y,C=z) # creating function to computer productproduct = function(x,output){ # accessing elements from first column A = x[1] # accessing elements from second column B=x[2] # accessing elements from third column C= x[3] # return product return(A*B*C)} # apply(X,MARGIN,FUN,...)apply(df,1,product ) # apply(X,MARGIN,FUN,...)single <- apply(df,1,product ) # adding product vector to dataframecbind(df,product = single)
Output:
Using apply()
clintra
amnindersingh1414
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Group by function in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R
|
[
{
"code": null,
"e": 25340,
"s": 25312,
"text": "\n15 Aug, 2021"
},
{
"code": null,
"e": 25502,
"s": 25340,
"text": "In this article, we will discuss how to apply a function to each row in a data frame in R Programming Language. Letβs take an example for a better understanding."
},
{
"code": null,
"e": 25511,
"s": 25502,
"text": "Example:"
},
{
"code": null,
"e": 25604,
"s": 25511,
"text": "Suppose we have a dummy dataset with A, B, C as column names and some numeric value as rows."
},
{
"code": null,
"e": 25626,
"s": 25616,
"text": " A "
},
{
"code": null,
"e": 25635,
"s": 25626,
"text": " B "
},
{
"code": null,
"e": 25645,
"s": 25635,
"text": " C "
},
{
"code": null,
"e": 25648,
"s": 25645,
"text": "1."
},
{
"code": null,
"e": 25650,
"s": 25648,
"text": "5"
},
{
"code": null,
"e": 25652,
"s": 25650,
"text": "6"
},
{
"code": null,
"e": 25654,
"s": 25652,
"text": "1"
},
{
"code": null,
"e": 25657,
"s": 25654,
"text": "2."
},
{
"code": null,
"e": 25659,
"s": 25657,
"text": "6"
},
{
"code": null,
"e": 25661,
"s": 25659,
"text": "4"
},
{
"code": null,
"e": 25663,
"s": 25661,
"text": "2"
},
{
"code": null,
"e": 25666,
"s": 25663,
"text": "3."
},
{
"code": null,
"e": 25668,
"s": 25666,
"text": "7"
},
{
"code": null,
"e": 25670,
"s": 25668,
"text": "3"
},
{
"code": null,
"e": 25672,
"s": 25670,
"text": "3"
},
{
"code": null,
"e": 25675,
"s": 25672,
"text": "4."
},
{
"code": null,
"e": 25677,
"s": 25675,
"text": "5"
},
{
"code": null,
"e": 25679,
"s": 25677,
"text": "4"
},
{
"code": null,
"e": 25681,
"s": 25679,
"text": "7"
},
{
"code": null,
"e": 25684,
"s": 25681,
"text": "5."
},
{
"code": null,
"e": 25686,
"s": 25684,
"text": "6"
},
{
"code": null,
"e": 25688,
"s": 25686,
"text": "2"
},
{
"code": null,
"e": 25690,
"s": 25688,
"text": "8"
},
{
"code": null,
"e": 25693,
"s": 25690,
"text": "6."
},
{
"code": null,
"e": 25695,
"s": 25693,
"text": "9"
},
{
"code": null,
"e": 25697,
"s": 25695,
"text": "6"
},
{
"code": null,
"e": 25699,
"s": 25697,
"text": "9"
},
{
"code": null,
"e": 25832,
"s": 25699,
"text": "And we want to apply a function that will return the product of each row value, then the resultant data frame should look like this:"
},
{
"code": null,
"e": 25836,
"s": 25834,
"text": "A"
},
{
"code": null,
"e": 25838,
"s": 25836,
"text": "B"
},
{
"code": null,
"e": 25840,
"s": 25838,
"text": "C"
},
{
"code": null,
"e": 25848,
"s": 25840,
"text": "product"
},
{
"code": null,
"e": 25851,
"s": 25848,
"text": "1."
},
{
"code": null,
"e": 25853,
"s": 25851,
"text": "5"
},
{
"code": null,
"e": 25855,
"s": 25853,
"text": "6"
},
{
"code": null,
"e": 25857,
"s": 25855,
"text": "1"
},
{
"code": null,
"e": 25860,
"s": 25857,
"text": "60"
},
{
"code": null,
"e": 25863,
"s": 25860,
"text": "2."
},
{
"code": null,
"e": 25865,
"s": 25863,
"text": "6"
},
{
"code": null,
"e": 25867,
"s": 25865,
"text": "4"
},
{
"code": null,
"e": 25869,
"s": 25867,
"text": "2"
},
{
"code": null,
"e": 25872,
"s": 25869,
"text": "48"
},
{
"code": null,
"e": 25875,
"s": 25872,
"text": "3."
},
{
"code": null,
"e": 25877,
"s": 25875,
"text": "7"
},
{
"code": null,
"e": 25879,
"s": 25877,
"text": "3"
},
{
"code": null,
"e": 25881,
"s": 25879,
"text": "3"
},
{
"code": null,
"e": 25884,
"s": 25881,
"text": "63"
},
{
"code": null,
"e": 25887,
"s": 25884,
"text": "4."
},
{
"code": null,
"e": 25889,
"s": 25887,
"text": "5"
},
{
"code": null,
"e": 25891,
"s": 25889,
"text": "4"
},
{
"code": null,
"e": 25893,
"s": 25891,
"text": "7"
},
{
"code": null,
"e": 25897,
"s": 25893,
"text": "140"
},
{
"code": null,
"e": 25900,
"s": 25897,
"text": "5."
},
{
"code": null,
"e": 25902,
"s": 25900,
"text": "6"
},
{
"code": null,
"e": 25904,
"s": 25902,
"text": "2"
},
{
"code": null,
"e": 25906,
"s": 25904,
"text": "8"
},
{
"code": null,
"e": 25909,
"s": 25906,
"text": "96"
},
{
"code": null,
"e": 25912,
"s": 25909,
"text": "6."
},
{
"code": null,
"e": 25914,
"s": 25912,
"text": "9"
},
{
"code": null,
"e": 25916,
"s": 25914,
"text": "6"
},
{
"code": null,
"e": 25918,
"s": 25916,
"text": "9"
},
{
"code": null,
"e": 25922,
"s": 25918,
"text": "486"
},
{
"code": null,
"e": 25953,
"s": 25922,
"text": "Approach: Using apply function"
},
{
"code": null,
"e": 26133,
"s": 25953,
"text": "apply() is used to compute a function on a data frame or matrix. The purpose of using apply() function is to avoid the use of looping. apply() function returns output as a vector."
},
{
"code": null,
"e": 26164,
"s": 26133,
"text": "Syntax: apply(x, margin, func)"
},
{
"code": null,
"e": 26276,
"s": 26164,
"text": "Parameters:x: Array or matrixmargin: dimension on which operation is to be appliedfunc: operation to be applied"
},
{
"code": null,
"e": 26301,
"s": 26276,
"text": "Stepwise implementation:"
},
{
"code": null,
"e": 26333,
"s": 26301,
"text": "Step 1: Create a dummy dataset."
},
{
"code": null,
"e": 26335,
"s": 26333,
"text": "R"
},
{
"code": "# Apply function to each row in r Dataframe # Creating dataset# creating firs columnx <- c(5, 6, 7, 5, 6, 9) # creating second columny <- c(6, 4, 3, 4, 2, 6) # creating third columnz <- c(1, 2, 3, 7, 8, 9) # creating dataframedf <- data.frame(A = x, B = y, C = z) display(df)",
"e": 26611,
"s": 26335,
"text": null
},
{
"code": null,
"e": 26619,
"s": 26611,
"text": "Output:"
},
{
"code": null,
"e": 26675,
"s": 26619,
"text": " A B C\n1 5 6 1\n2 6 4 2\n3 7 3 3\n4 5 4 7\n5 6 2 8\n6 9 6 9"
},
{
"code": null,
"e": 26735,
"s": 26675,
"text": "Step 2: Create a custom function for calculating products. "
},
{
"code": null,
"e": 26737,
"s": 26735,
"text": "R"
},
{
"code": "# creating function to computer productproduct = function(x, output){ # accessing elements from first column A = x[1] # accessing elements from second column B=x[2] # accessing elements from third column C= x[3] # return product return(A*B*C)}",
"e": 27001,
"s": 26737,
"text": null
},
{
"code": null,
"e": 27143,
"s": 27001,
"text": " Note: Here we are just defining the function for computing product and not calling, so there will be no output until we call this function. "
},
{
"code": null,
"e": 27211,
"s": 27143,
"text": "Step 3: Use apply the function to compute the product of each row. "
},
{
"code": null,
"e": 27249,
"s": 27211,
"text": "Syntax: (data_frame, 1, function,...)"
},
{
"code": null,
"e": 27350,
"s": 27249,
"text": "Now we are calling the newly created product function and returns the product using apply function. "
},
{
"code": null,
"e": 27352,
"s": 27350,
"text": "R"
},
{
"code": "# apply(X,MARGIN,FUN,...)apply(df,1,product )",
"e": 27399,
"s": 27352,
"text": null
},
{
"code": null,
"e": 27409,
"s": 27399,
"text": "Output: "
},
{
"code": null,
"e": 27437,
"s": 27409,
"text": "[1] 30 48 63 140 96 486"
},
{
"code": null,
"e": 27550,
"s": 27437,
"text": "Note: apply() return product as a vector list. So we have to add it to the data frame using cbind (column bind)."
},
{
"code": null,
"e": 27598,
"s": 27550,
"text": "Step 4: Append product list to the data frame. "
},
{
"code": null,
"e": 27600,
"s": 27598,
"text": "R"
},
{
"code": "# apply(X,MARGIN,FUN,...)single <- apply(df,1,product ) # adding product vector to dataframecbind(df,product = single)",
"e": 27720,
"s": 27600,
"text": null
},
{
"code": null,
"e": 27728,
"s": 27720,
"text": "Output:"
},
{
"code": null,
"e": 27742,
"s": 27728,
"text": "Using apply()"
},
{
"code": null,
"e": 27776,
"s": 27742,
"text": "Below is the full implementation:"
},
{
"code": null,
"e": 27778,
"s": 27776,
"text": "R"
},
{
"code": "# Apply function to each row in r Dataframe # Creating dataset# creating firs columnx <- c(5,6,7,5,6,9) # creating second columny <- c(6,4,3,4,2,6) # creating third columnz <- c(1,2,3,7,8,9) # creating dataframedf <- data.frame(A=x,B=y,C=z) # creating function to computer productproduct = function(x,output){ # accessing elements from first column A = x[1] # accessing elements from second column B=x[2] # accessing elements from third column C= x[3] # return product return(A*B*C)} # apply(X,MARGIN,FUN,...)apply(df,1,product ) # apply(X,MARGIN,FUN,...)single <- apply(df,1,product ) # adding product vector to dataframecbind(df,product = single)",
"e": 28449,
"s": 27778,
"text": null
},
{
"code": null,
"e": 28457,
"s": 28449,
"text": "Output:"
},
{
"code": null,
"e": 28471,
"s": 28457,
"text": "Using apply()"
},
{
"code": null,
"e": 28479,
"s": 28471,
"text": "clintra"
},
{
"code": null,
"e": 28497,
"s": 28479,
"text": "amnindersingh1414"
},
{
"code": null,
"e": 28504,
"s": 28497,
"text": "Picked"
},
{
"code": null,
"e": 28525,
"s": 28504,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 28537,
"s": 28525,
"text": "R-DataFrame"
},
{
"code": null,
"e": 28548,
"s": 28537,
"text": "R Language"
},
{
"code": null,
"e": 28559,
"s": 28548,
"text": "R Programs"
},
{
"code": null,
"e": 28657,
"s": 28559,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28692,
"s": 28657,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28744,
"s": 28692,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28802,
"s": 28744,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28840,
"s": 28802,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28883,
"s": 28840,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28941,
"s": 28883,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28984,
"s": 28941,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29033,
"s": 28984,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29083,
"s": 29033,
"text": "How to filter R dataframe by multiple conditions?"
}
] |
Python program to print duplicates from a list of integers?
|
Here we are trying to print all the duplicate numbers from a list of numbers. So, we are trying to print all the numbers which occur more than once in a list (not unique in the list).
Input: given_list = [ 3, 6, 9, 12, 3, 30, 15, 9, 45, 36, 12]
Output: desired_output = [3, 9, 12]
Input: given_list = [-27, 4, 29, -27, -2 , -99, 123, 499, -99]
Output: desired_output = [-27, -99]
Below is the code to find the duplicates elements from a given list β
Live Demo
lst = [ 3, 6, 9, 12, 3, 30, 15, 9, 45, 36, 12, 12]
dupItems = []
uniqItems = {}
for x in lst:
if x not in uniqItems:
uniqItems[x] = 1
else:
if uniqItems[x] == 1:
dupItems.append(x)
uniqItems[x] += 1
print(dupItems)
[3, 9, 12]
Above program will work not only for a list of integers but others too β
Input: given_list = ['abc','def','raj','zack','abc','raj']
Output: output_returned= ['abc', 'raj']
|
[
{
"code": null,
"e": 1246,
"s": 1062,
"text": "Here we are trying to print all the duplicate numbers from a list of numbers. So, we are trying to print all the numbers which occur more than once in a list (not unique in the list)."
},
{
"code": null,
"e": 1442,
"s": 1246,
"text": "Input: given_list = [ 3, 6, 9, 12, 3, 30, 15, 9, 45, 36, 12]\nOutput: desired_output = [3, 9, 12]\nInput: given_list = [-27, 4, 29, -27, -2 , -99, 123, 499, -99]\nOutput: desired_output = [-27, -99]"
},
{
"code": null,
"e": 1512,
"s": 1442,
"text": "Below is the code to find the duplicates elements from a given list β"
},
{
"code": null,
"e": 1523,
"s": 1512,
"text": " Live Demo"
},
{
"code": null,
"e": 1771,
"s": 1523,
"text": "lst = [ 3, 6, 9, 12, 3, 30, 15, 9, 45, 36, 12, 12]\ndupItems = []\nuniqItems = {}\nfor x in lst:\n if x not in uniqItems:\n uniqItems[x] = 1\n else:\n if uniqItems[x] == 1:\n dupItems.append(x)\n uniqItems[x] += 1\nprint(dupItems)"
},
{
"code": null,
"e": 1782,
"s": 1771,
"text": "[3, 9, 12]"
},
{
"code": null,
"e": 1855,
"s": 1782,
"text": "Above program will work not only for a list of integers but others too β"
},
{
"code": null,
"e": 1954,
"s": 1855,
"text": "Input: given_list = ['abc','def','raj','zack','abc','raj']\nOutput: output_returned= ['abc', 'raj']"
}
] |
Unpacking Operators in Python. Using the * and ** unpacking operators... | by Luay Matalka | Towards Data Science
|
In this tutorial, we will learn how to use the asterisk (*) operator to unpack iterable objects, and two asterisks (**) to unpack dictionaries. In addition, we will discuss how we can pack several values into one variable using the same operator. And lastly, we will discuss what *args and **kwargs are and when they can be used.
Letβs say we have a list:
num_list = [1,2,3,4,5]
And we define a function that takes in 5 arguments and returns their sum:
def num_sum(num1,num2,num3,num4,num5): return num1 + num2 + num3 + num4 + num5
And we want to find the sum of all the elements in num_list. Well, we can accomplish this by passing in all the elements of num_list to the function num_sum. Since num_list has five elements in it, the num_sum function contains five parameters, one for each element in num_list.
One way to do this would be to pass the elements by using their index as follows:
num_sum(num_list[0], num_list[1], num_list[2], num_list[3], num_list[4])# 15
However, there is a much easier way to do this, and thatβs by using the * operator. The * operator is an unpacking operator that will unpack the values from any iterable object, such as lists, tuples, strings, etc...
For example, if we want to unpack num_list and pass in the 5 elements as separate arguments for the num_sum function, we could do so as follows:
num_sum(*num_list)# 15
And thatβs it! The asterisk, *, or unpacking operator, unpacks num_list, and passes the values, or elements, of num_list as separate arguments to the num_sum function.
Note: For this to work, the number of elements in num_list must match the number of parameters in the num_sum function. If they donβt match, we would get a TypeError.
We can also use the asterisk, *, or unpacking operator, with built-in functions in python, such as print:
print(*num_list)# 1 2 3 4 5
Letβs say we have another list:
num_list_2 = [6,7,8,9,10]
And we want to print all the elements in both num_list and num_list_2. We can use the unpacking operator, *, to accomplish this as follows:
print(*num_list, *num_list_2)# 1 2 3 4 5 6 7 8 9 10
Both num_list and num_list_2 are unpacked. Then, all the elements are passed in to print as separate arguments.
We can also create a new list that contains all the elements from num_list and num_list_2:
new_list = [*num_list, *num_list_2]# [1,2,3,4,5,6,7,8,9,10]
num_list and num_list_2 are unpacked, resulting in their elements constituting the elements of the newly made list, new_list.
Note: We could have simply added num_list and num_list_2 to create new_list. However, this was just to portray the functionality of the unpacking operator.
towardsdatascience.com
Letβs say that we have a string assigned to the variable name:
name = βMichaelβ
And we want to break this name up into 3 parts, with the first letter being assigned to a variable, the last letter being assigned to another variable, and everything in the middle assigned to a third variable. We can do so as follows:
first, *middle, last = name
And thatβs it! Since name is a string, and strings are iterable objects, we can unpack them. The values on the right side of the assignment operator will be assigned to the variables on the left depending on their relative position in the iterable object. As such, the first letter of βMichaelβ is assigned to the variable first, which would be βMβ in this case. The last letter, βlβ, is assigned to the variable last. And the variable middle will contain all the letters between βMβ and βlβ in the form of a list: [βiβ, βcβ, βhβ, βaβ, βeβ].
Note: The first and last variables above are called mandatory variables, as they must be assigned concrete values. The middle variable, due to using the * or unpacking operator, can have any number of values, including zero. If there are not enough values to unpack for the mandatory variables, we will get a ValueError.
For example, if we used the following assignment instead:
first, *middle, last = βma'
Then the variable first will be assigned βmβ, the variable last will be assigned βaβ, and the variable middle will just be an empty list since there are no other values to assign to it.
towardsdatascience.com
We can also use the * operator to pack multiple values into a single variable. For example:
*names, = βMichaelβ, βJohnβ, βNancyβ# names ['Michael', 'John', 'Nancy']
The reason for using a trailing comma after *names is because the left side of the assignment must be a tuple or list. Therefore, the names variable now contains all the names on the right side in the form of a list.
Note: This is what we do when we define functions that can receive a varying number of arguments! That is the concept of *args and **kwargs!
For example, letβs say we have a function, names_tuple, that takes in names as arguments and returns them back. However, the number of names that we pass in to this function can vary. Well, we canβt just choose a number of parameters that this function would have since the number of positional arguments can change with each calling of the function. We can instead use the * operator to pack the arguments passed in into a tuple as follows:
def names_tuple(*args): return argsnames_tuple('Michael', 'John', 'Nancy')# ('Michael', 'John', 'Nancy')names_tuple('Jennifer', 'Nancy')# ('Jennifer', 'Nancy')
No matter what number of positional arguments we pass in when we call the names_tuple function, the *args argument will pack the positional arguments into a tuple, similar to the *names assignment above.
To pass in a varying number of keyword or named arguments, we use the ** operator when defining a function. The ** unpacking operator will pack the varying number of named arguments we pass in into a dictionary.
def names_dict(**kwargs): return kwargsnames_dict(Jane = 'Doe')# {'Jane': 'Doe'}names_dict(Jane = 'Doe', John = 'Smith')# {'Jane': 'Doe', 'John': 'Smith'}
Note: When using the * operator to create a parameter that receives a varying number of positional arguments when defining a function, it is common to use the parameter name args (and kwargs to receive a varying number of keyword or named arguments). However, any names can be chosen for these parameters.
towardsdatascience.com
What happens when we try to use the * operator with a dictionary?
num_dict = {βaβ: 1, βbβ: 2, βcβ: 3}print(*num_dict)# a b c
Notice how it printed the keys of the dictionary and not the values? To unpack a dictionary, we need to use the ** unpacking operator. However, since each value is associated with a specific key, the function that we pass these arguments to must have parameters with the same names as the keys of the dictionary being unpacked. For example:
def dict_sum(a,b,c): return a+b+c
This dict_sum function has three parameters: a, b, and c. These three parameters are named the same as the keys of num_dict. Therefore, once we pass in the unpacked dictionary using the ** operator, itβll assign in the values of the keys according to the corresponding parameter names:
dict_sum(**num_dict)# 6
Thus, the values, or arguments, for the a, b, and c parameters in dict_sum will be 1, 2, and 3, respectively. And the sum of these three values is 6.
Just like with lists, the ** operator can be used to merge two or more dictionaries:
num_dict = {βaβ: 1, βbβ: 2, βcβ: 3}num_dict_2 = {βdβ: 4, βeβ: 5, βfβ: 6}new_dict = {**num_dict, **num_dict_2}# {βaβ: 1, βbβ: 2, βcβ: 3, βdβ: 4, βeβ: 5, βfβ: 6}
towardsdatascience.com
In this tutorial, we learned how to use the * operator to unpack iterable objects and the ** operator to unpack dictionaries. We also learned many ways to utilize these operators to accomplish many different tasks. In addition, we briefly discussed the concept of packing with *args and **kwargs by using the * and ** operators when defining functions that receive a varying number of positional or named arguments.
|
[
{
"code": null,
"e": 502,
"s": 172,
"text": "In this tutorial, we will learn how to use the asterisk (*) operator to unpack iterable objects, and two asterisks (**) to unpack dictionaries. In addition, we will discuss how we can pack several values into one variable using the same operator. And lastly, we will discuss what *args and **kwargs are and when they can be used."
},
{
"code": null,
"e": 528,
"s": 502,
"text": "Letβs say we have a list:"
},
{
"code": null,
"e": 551,
"s": 528,
"text": "num_list = [1,2,3,4,5]"
},
{
"code": null,
"e": 625,
"s": 551,
"text": "And we define a function that takes in 5 arguments and returns their sum:"
},
{
"code": null,
"e": 707,
"s": 625,
"text": "def num_sum(num1,num2,num3,num4,num5): return num1 + num2 + num3 + num4 + num5"
},
{
"code": null,
"e": 986,
"s": 707,
"text": "And we want to find the sum of all the elements in num_list. Well, we can accomplish this by passing in all the elements of num_list to the function num_sum. Since num_list has five elements in it, the num_sum function contains five parameters, one for each element in num_list."
},
{
"code": null,
"e": 1068,
"s": 986,
"text": "One way to do this would be to pass the elements by using their index as follows:"
},
{
"code": null,
"e": 1145,
"s": 1068,
"text": "num_sum(num_list[0], num_list[1], num_list[2], num_list[3], num_list[4])# 15"
},
{
"code": null,
"e": 1362,
"s": 1145,
"text": "However, there is a much easier way to do this, and thatβs by using the * operator. The * operator is an unpacking operator that will unpack the values from any iterable object, such as lists, tuples, strings, etc..."
},
{
"code": null,
"e": 1507,
"s": 1362,
"text": "For example, if we want to unpack num_list and pass in the 5 elements as separate arguments for the num_sum function, we could do so as follows:"
},
{
"code": null,
"e": 1530,
"s": 1507,
"text": "num_sum(*num_list)# 15"
},
{
"code": null,
"e": 1698,
"s": 1530,
"text": "And thatβs it! The asterisk, *, or unpacking operator, unpacks num_list, and passes the values, or elements, of num_list as separate arguments to the num_sum function."
},
{
"code": null,
"e": 1865,
"s": 1698,
"text": "Note: For this to work, the number of elements in num_list must match the number of parameters in the num_sum function. If they donβt match, we would get a TypeError."
},
{
"code": null,
"e": 1971,
"s": 1865,
"text": "We can also use the asterisk, *, or unpacking operator, with built-in functions in python, such as print:"
},
{
"code": null,
"e": 1999,
"s": 1971,
"text": "print(*num_list)# 1 2 3 4 5"
},
{
"code": null,
"e": 2031,
"s": 1999,
"text": "Letβs say we have another list:"
},
{
"code": null,
"e": 2057,
"s": 2031,
"text": "num_list_2 = [6,7,8,9,10]"
},
{
"code": null,
"e": 2197,
"s": 2057,
"text": "And we want to print all the elements in both num_list and num_list_2. We can use the unpacking operator, *, to accomplish this as follows:"
},
{
"code": null,
"e": 2249,
"s": 2197,
"text": "print(*num_list, *num_list_2)# 1 2 3 4 5 6 7 8 9 10"
},
{
"code": null,
"e": 2361,
"s": 2249,
"text": "Both num_list and num_list_2 are unpacked. Then, all the elements are passed in to print as separate arguments."
},
{
"code": null,
"e": 2452,
"s": 2361,
"text": "We can also create a new list that contains all the elements from num_list and num_list_2:"
},
{
"code": null,
"e": 2512,
"s": 2452,
"text": "new_list = [*num_list, *num_list_2]# [1,2,3,4,5,6,7,8,9,10]"
},
{
"code": null,
"e": 2638,
"s": 2512,
"text": "num_list and num_list_2 are unpacked, resulting in their elements constituting the elements of the newly made list, new_list."
},
{
"code": null,
"e": 2794,
"s": 2638,
"text": "Note: We could have simply added num_list and num_list_2 to create new_list. However, this was just to portray the functionality of the unpacking operator."
},
{
"code": null,
"e": 2817,
"s": 2794,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2880,
"s": 2817,
"text": "Letβs say that we have a string assigned to the variable name:"
},
{
"code": null,
"e": 2897,
"s": 2880,
"text": "name = βMichaelβ"
},
{
"code": null,
"e": 3133,
"s": 2897,
"text": "And we want to break this name up into 3 parts, with the first letter being assigned to a variable, the last letter being assigned to another variable, and everything in the middle assigned to a third variable. We can do so as follows:"
},
{
"code": null,
"e": 3161,
"s": 3133,
"text": "first, *middle, last = name"
},
{
"code": null,
"e": 3703,
"s": 3161,
"text": "And thatβs it! Since name is a string, and strings are iterable objects, we can unpack them. The values on the right side of the assignment operator will be assigned to the variables on the left depending on their relative position in the iterable object. As such, the first letter of βMichaelβ is assigned to the variable first, which would be βMβ in this case. The last letter, βlβ, is assigned to the variable last. And the variable middle will contain all the letters between βMβ and βlβ in the form of a list: [βiβ, βcβ, βhβ, βaβ, βeβ]."
},
{
"code": null,
"e": 4024,
"s": 3703,
"text": "Note: The first and last variables above are called mandatory variables, as they must be assigned concrete values. The middle variable, due to using the * or unpacking operator, can have any number of values, including zero. If there are not enough values to unpack for the mandatory variables, we will get a ValueError."
},
{
"code": null,
"e": 4082,
"s": 4024,
"text": "For example, if we used the following assignment instead:"
},
{
"code": null,
"e": 4110,
"s": 4082,
"text": "first, *middle, last = βma'"
},
{
"code": null,
"e": 4296,
"s": 4110,
"text": "Then the variable first will be assigned βmβ, the variable last will be assigned βaβ, and the variable middle will just be an empty list since there are no other values to assign to it."
},
{
"code": null,
"e": 4319,
"s": 4296,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4411,
"s": 4319,
"text": "We can also use the * operator to pack multiple values into a single variable. For example:"
},
{
"code": null,
"e": 4484,
"s": 4411,
"text": "*names, = βMichaelβ, βJohnβ, βNancyβ# names ['Michael', 'John', 'Nancy']"
},
{
"code": null,
"e": 4701,
"s": 4484,
"text": "The reason for using a trailing comma after *names is because the left side of the assignment must be a tuple or list. Therefore, the names variable now contains all the names on the right side in the form of a list."
},
{
"code": null,
"e": 4842,
"s": 4701,
"text": "Note: This is what we do when we define functions that can receive a varying number of arguments! That is the concept of *args and **kwargs!"
},
{
"code": null,
"e": 5284,
"s": 4842,
"text": "For example, letβs say we have a function, names_tuple, that takes in names as arguments and returns them back. However, the number of names that we pass in to this function can vary. Well, we canβt just choose a number of parameters that this function would have since the number of positional arguments can change with each calling of the function. We can instead use the * operator to pack the arguments passed in into a tuple as follows:"
},
{
"code": null,
"e": 5447,
"s": 5284,
"text": "def names_tuple(*args): return argsnames_tuple('Michael', 'John', 'Nancy')# ('Michael', 'John', 'Nancy')names_tuple('Jennifer', 'Nancy')# ('Jennifer', 'Nancy')"
},
{
"code": null,
"e": 5651,
"s": 5447,
"text": "No matter what number of positional arguments we pass in when we call the names_tuple function, the *args argument will pack the positional arguments into a tuple, similar to the *names assignment above."
},
{
"code": null,
"e": 5863,
"s": 5651,
"text": "To pass in a varying number of keyword or named arguments, we use the ** operator when defining a function. The ** unpacking operator will pack the varying number of named arguments we pass in into a dictionary."
},
{
"code": null,
"e": 6021,
"s": 5863,
"text": "def names_dict(**kwargs): return kwargsnames_dict(Jane = 'Doe')# {'Jane': 'Doe'}names_dict(Jane = 'Doe', John = 'Smith')# {'Jane': 'Doe', 'John': 'Smith'}"
},
{
"code": null,
"e": 6327,
"s": 6021,
"text": "Note: When using the * operator to create a parameter that receives a varying number of positional arguments when defining a function, it is common to use the parameter name args (and kwargs to receive a varying number of keyword or named arguments). However, any names can be chosen for these parameters."
},
{
"code": null,
"e": 6350,
"s": 6327,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6416,
"s": 6350,
"text": "What happens when we try to use the * operator with a dictionary?"
},
{
"code": null,
"e": 6475,
"s": 6416,
"text": "num_dict = {βaβ: 1, βbβ: 2, βcβ: 3}print(*num_dict)# a b c"
},
{
"code": null,
"e": 6816,
"s": 6475,
"text": "Notice how it printed the keys of the dictionary and not the values? To unpack a dictionary, we need to use the ** unpacking operator. However, since each value is associated with a specific key, the function that we pass these arguments to must have parameters with the same names as the keys of the dictionary being unpacked. For example:"
},
{
"code": null,
"e": 6853,
"s": 6816,
"text": "def dict_sum(a,b,c): return a+b+c"
},
{
"code": null,
"e": 7139,
"s": 6853,
"text": "This dict_sum function has three parameters: a, b, and c. These three parameters are named the same as the keys of num_dict. Therefore, once we pass in the unpacked dictionary using the ** operator, itβll assign in the values of the keys according to the corresponding parameter names:"
},
{
"code": null,
"e": 7163,
"s": 7139,
"text": "dict_sum(**num_dict)# 6"
},
{
"code": null,
"e": 7313,
"s": 7163,
"text": "Thus, the values, or arguments, for the a, b, and c parameters in dict_sum will be 1, 2, and 3, respectively. And the sum of these three values is 6."
},
{
"code": null,
"e": 7398,
"s": 7313,
"text": "Just like with lists, the ** operator can be used to merge two or more dictionaries:"
},
{
"code": null,
"e": 7558,
"s": 7398,
"text": "num_dict = {βaβ: 1, βbβ: 2, βcβ: 3}num_dict_2 = {βdβ: 4, βeβ: 5, βfβ: 6}new_dict = {**num_dict, **num_dict_2}# {βaβ: 1, βbβ: 2, βcβ: 3, βdβ: 4, βeβ: 5, βfβ: 6}"
},
{
"code": null,
"e": 7581,
"s": 7558,
"text": "towardsdatascience.com"
}
] |
The import Statements in Python
|
You can use any Python source file as a module by executing an import statement in some other Python source file.
The import has the following syntax β
import module1[, module2[,... moduleN]
When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module. For example, to import the module support.py, you need to put the following command at the top of the script β
#!/usr/bin/python
# Import module support
import support
# Now you can call defined function that module as follows
support.print_func("Zara")
When the above code is executed, it produces the following result β
Hello : Zara
A module is loaded only once, regardless of the number of times it is imported. This prevents the module execution from happening over and over again if multiple imports occur.
Python's from statement lets you import specific attributes from a module into the current namespace. The from...import has the following syntax β
from modname import name1[, name2[, ... nameN]]
For example, to import the function fibonacci from the module fib, use the following statement β
from fib import fibonacci
This statement does not import the entire module fib into the current namespace; it just introduces the item fibonacci from the module fib into the global symbol table of the importing module.
It is also possible to import all names from a module into the current namespace by using the following import statement β
from modname import *
This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly.
|
[
{
"code": null,
"e": 1176,
"s": 1062,
"text": "You can use any Python source file as a module by executing an import statement in some other Python source file."
},
{
"code": null,
"e": 1214,
"s": 1176,
"text": "The import has the following syntax β"
},
{
"code": null,
"e": 1253,
"s": 1214,
"text": "import module1[, module2[,... moduleN]"
},
{
"code": null,
"e": 1580,
"s": 1253,
"text": "When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module. For example, to import the module support.py, you need to put the following command at the top of the script β"
},
{
"code": null,
"e": 1723,
"s": 1580,
"text": "#!/usr/bin/python\n# Import module support\nimport support\n# Now you can call defined function that module as follows\nsupport.print_func(\"Zara\")"
},
{
"code": null,
"e": 1791,
"s": 1723,
"text": "When the above code is executed, it produces the following result β"
},
{
"code": null,
"e": 1804,
"s": 1791,
"text": "Hello : Zara"
},
{
"code": null,
"e": 1981,
"s": 1804,
"text": "A module is loaded only once, regardless of the number of times it is imported. This prevents the module execution from happening over and over again if multiple imports occur."
},
{
"code": null,
"e": 2128,
"s": 1981,
"text": "Python's from statement lets you import specific attributes from a module into the current namespace. The from...import has the following syntax β"
},
{
"code": null,
"e": 2176,
"s": 2128,
"text": "from modname import name1[, name2[, ... nameN]]"
},
{
"code": null,
"e": 2273,
"s": 2176,
"text": "For example, to import the function fibonacci from the module fib, use the following statement β"
},
{
"code": null,
"e": 2299,
"s": 2273,
"text": "from fib import fibonacci"
},
{
"code": null,
"e": 2492,
"s": 2299,
"text": "This statement does not import the entire module fib into the current namespace; it just introduces the item fibonacci from the module fib into the global symbol table of the importing module."
},
{
"code": null,
"e": 2615,
"s": 2492,
"text": "It is also possible to import all names from a module into the current namespace by using the following import statement β"
},
{
"code": null,
"e": 2637,
"s": 2615,
"text": "from modname import *"
},
{
"code": null,
"e": 2779,
"s": 2637,
"text": "This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly."
}
] |
C++ Program to Implement Circular Doubly Linked List
|
In data structure Link List is a linear collection of data elements. Each element or node of a list is comprising of two items - the data and a reference to the next node. The last node has a reference to null. In a linked list the entry point is called the head of the list.
In Circular Doubly Linked List two consecutive elements are linked or connected by previous and next pointer and the last node points to first node by next pointer and the first node also points to last node by previous pointer.
Begin
We shall create a class circulardoublylist which have the following functions:
nod *create_node(int) = To memory allocated for node dynamically.
insert_begin() = To Insert elements at beginning of the list.
A) If the list is empty, then insert the node and set next and previous pointer as NULL.
B) If the list is not empty, insert the data and set next and previous pointer and update them.
insert_end() = To Insert elements at end of the list:
A) If the list is empty create a node as circular doubly list.
B) Find last node.
C) Create node dynamically.
D) Start going to be the next of new node.
E) Make new node as previous node.
F) Make last previous of new node.
G) Make new node next of old last.
insert_pos() = To insert elements at a specified position of the list:
A) Insert the data.
B) Enter the position at which element to be inserted.
C) If the list is empty insert node at first.
D) If list is not empty find node having position and next node.
E) Insert the node between them.
delete_pos() = To delete elements from specified position of the list:
A) If list is empty, then return.
B) Enter the position from which node needs to be deleted.
C) If list has one node delete it and update next and prev pointers.
D) If list has more than one nodes, then delete the node at particular position and update next and prev pointer.
search() = To search element in the list:
A) If the list is empty, then return.
B) Enter the value to be searched.
C) Print the position at which element to be found.
D) If the element is not found, print not found.
update() = To update value at a particular node:
A) If the list is empty, then return.
B) Enter the position of node to be updated.
C) Enter the new value.
D) Update the node.
display() = To display the list.
reverse() = To reverse the list.
End
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct nod {
int info;
struct nod *n;
struct nod *p;
}*start, *last;
int count = 0;
class circulardoublylist {
public:
nod *create_node(int);
void insert_begin();
void insert_end();
void insert_pos();
void delete_pos();
void search();
void update();
void display();
void reverse();
circulardoublylist() {
start = NULL;
last = NULL;
}
};
int main() {
int c;
circulardoublylist cdl;
while (1) //perform switch operation {
cout<<"1.Insert at Beginning"<<endl;
cout<<"2.Insert at End"<<endl;
cout<<"3.Insert at Position"<<endl;
cout<<"4.Delete at Position"<<endl;
cout<<"5.Update Node"<<endl;
cout<<"6.Search Element"<<endl;
cout<<"7.Display List"<<endl;
cout<<"8.Reverse List"<<endl;
cout<<"9.Exit"<<endl;
cout<<"Enter your choice : ";
cin>>c;
switch(c) {
case 1:
cdl.insert_begin();
break;
case 2:
cdl.insert_end();
break;
case 3:
cdl.insert_pos();
break;
case 4:
cdl.delete_pos();
break;
case 5:
cdl.update();
break;
case 6:
cdl.search();
break;
case 7:
cdl.display();
break;
case 8:
cdl.reverse();
break;
case 9:
exit(1);
default:
cout<<"Wrong choice"<<endl;
}
}
return 0;
}
nod* circulardoublylist::create_node(int v) {
count++;
struct nod *t;
t = new(struct nod);
t->info = v;
t->n = NULL;
t->p = NULL;
return t;
}
void circulardoublylist::insert_begin() {
int v;
cout<<endl<<"Enter the element to be inserted: ";
cin>>v;
struct nod *t;
t = create_node(v);
if (start == last && start == NULL) {
cout<<"Element inserted in empty list"<<endl;
start = last = t;
start->n = last->n = NULL;
start->p = last->p = NULL;
} else {
t->n = start;
start->p = t;
start = t;
start->p = last;
last->n = start;
cout<<"Element inserted"<<endl;
}
}
void circulardoublylist::insert_end() {
int v;
cout<<endl<<"Enter the element to be inserted: ";
cin>>v;
struct nod *t;
t = create_node(v);
if (start == last && start == NULL) {
cout<<"Element inserted in empty list"<<endl;
start = last = t;
start->n= last->n = NULL;
start->p = last->p= NULL;
} else {
last->n= t;
t->p= last;
last = t;
start->p = last;
last->n= start;
}
}
void circulardoublylist::insert_pos() {
int v, pos, i;
cout<<endl<<"Enter the element to be inserted: ";
cin>>v;
cout<<endl<<"Enter the position of element inserted: ";
cin>>pos;
struct nod *t, *s, *ptr;
t = create_node(v);
if (start == last && start == NULL) {
if (pos == 1) {
start = last = t;
start->n = last->n = NULL;
start->p = last->p = NULL;
} else {
cout<<"Position out of range"<<endl;
count--;
return;
}
} else {
if (count < pos) {
cout<<"Position out of range"<<endl;
count--;
return;
}
s = start;
for (i = 1;i <= count;i++) {
ptr = s;
s = s->n;
if (i == pos - 1) {
ptr->n = t;
t->p= ptr;
t->n= s;
s->p = t;
cout<<"Element inserted"<<endl;
break;
}
}
}
}
void circulardoublylist::delete_pos() {
int pos, i;
nod *ptr, *s;
if (start == last && start == NULL) {
cout<<"List is empty, nothing to delete"<<endl;
return;
}
cout<<endl<<"Enter the position of element to be deleted: ";
cin>>pos;
if (count < pos) {
cout<<"Position out of range"<<endl;
return;
}
s = start;
if(pos == 1) {
count--;
last->n = s->n;
s->n->p = last;
start = s->n;
free(s);
cout<<"Element Deleted"<<endl;
return;
}
for (i = 0;i < pos - 1;i++ ) {
s = s->n;
ptr = s->p;
}
ptr->n = s->n;
s->n->p = ptr;
if (pos == count) {
last = ptr;
}
count--;
free(s);
cout<<"Element Deleted"<<endl;
}
void circulardoublylist::update() {
int v, i, pos;
if (start == last && start == NULL) {
cout<<"The List is empty, nothing to update"<<endl;
return;
}
cout<<endl<<"Enter the position of node to be updated: ";
cin>>pos;
cout<<"Enter the new value: ";
cin>>v;
struct nod *s;
if (count < pos) {
cout<<"Position out of range"<<endl;
return;
}
s = start;
if (pos == 1) {
s->info = v;
cout<<"Node Updated"<<endl;
return;
}
for (i=0;i < pos - 1;i++) {
s = s->n;
}
s->info = v;
cout<<"Node Updated"<<endl;
}
void circulardoublylist::search() {
int pos = 0, v, i;
bool flag = false;
struct nod *s;
if (start == last && start == NULL) {
cout<<"The List is empty, nothing to search"<<endl;
return;
}
cout<<endl<<"Enter the value to be searched: ";
cin>>v;
s = start;
for (i = 0;i < count;i++) {
pos++;
if (s->info == v) {
cout<<"Element "<<v<<" found at position: "<<pos<<endl;
flag = true;
}
s = s->n;
}
if (!flag)
cout<<"Element not found in the list"<<endl;
}
void circulardoublylist::display() {
int i;
struct nod *s;
if (start == last && start == NULL) {
cout<<"The List is empty, nothing to display"<<endl;
return;
}
s = start;
for (i = 0;i < count-1;i++) {
cout<<s->info<<"<->";
s = s->n;
}
cout<<s->info<<endl;
}
void circulardoublylist::reverse() {
if (start == last && start == NULL) {
cout<<"The List is empty, nothing to reverse"<<endl;
return;
}
struct nod *p1, *p2;
p1 = start;
p2 = p1->n;
p1->n = NULL;
p1->p= p2;
while (p2 != start) {
p2->p = p2->n;
p2->n = p1;
p1 = p2;
p2 = p2->p;
}
last = start;
start = p1;
cout<<"List Reversed"<<endl;
}
1.Insert at Beginning
2.Insert at End
3.Insert at Position
4.Delete at Position
5.Update Node
6.Search Element
7.Display List
8.Reverse List
9.Exit
Enter your choice : 1
Enter the element to be inserted: 7
Element inserted in empty list
1.Insert at Beginning
2.Insert at End
3.Insert at Position
4.Delete at Position
5.Update Node
6.Search Element
7.Display List
8.Reverse List
9.Exit
Enter your choice : 1
Enter the element to be inserted: 6
Element inserted
1.Insert at Beginning
2.Insert at End
3.Insert at Position
4.Delete at Position
5.Update Node
6.Search Element
7.Display List
8.Reverse List
9.Exit
Enter your choice : 2
Enter the element to be inserted: 4
1.Insert at Beginning
2.Insert at End
3.Insert at Position
4.Delete at Position
5.Update Node
6.Search Element
7.Display List
8.Reverse List
9.Exit
Enter your choice : 2
Enter the element to be inserted: 5
1.Insert at Beginning
2.Insert at End
3.Insert at Position
4.Delete at Position
5.Update Node
6.Search Element
7.Display List
8.Reverse List
9.Exit
Enter your choice : 7
6<->7<->4<->5
1.Insert at Beginning
2.Insert at End
3.Insert at Position
4.Delete at Position
5.Update Node
6.Search Element
7.Display List
8.Reverse List
9.Exit
Enter your choice : 6
Enter the value to be searched: 7
Element 7 found at position: 2
1.Insert at Beginning
2.Insert at End
3.Insert at Position
4.Delete at Position
5.Update Node
6.Search Element
7.Display List
8.Reverse List
9.Exit
Enter your choice : 6
Enter the value to be searched: 2
Element not found in the list
1.Insert at Beginning
2.Insert at End
3.Insert at Position
4.Delete at Position
5.Update Node
6.Search Element
7.Display List
8.Reverse List
9.Exit
Enter your choice : 4
Enter the position of element to be deleted: 4
Element Deleted
1.Insert at Beginning
2.Insert at End
3.Insert at Position
4.Delete at Position
5.Update Node
6.Search Element
7.Display List
8.Reverse List
9.Exit
Enter your choice : 3
Enter the element to be inserted: 5
Enter the position of element inserted: 2
Element inserted
1.Insert at Beginning
2.Insert at End
3.Insert at Position
4.Delete at Position
5.Update Node
6.Search Element
7.Display List
8.Reverse List
9.Exit
Enter your choice : 7
6<->5<->7<->4
1.Insert at Beginning
2.Insert at End
3.Insert at Position
4.Delete at Position
5.Update Node
6.Search Element
7.Display List
8.Reverse List
9.Exit
Enter your choice : 8
List Reversed
1.Insert at Beginning
2.Insert at End
3.Insert at Position
4.Delete at Position
5.Update Node
6.Search Element
7.Display List
8.Reverse List
9.Exit
Enter your choice : 7
4<->7<->5<->6
1.Insert at Beginning
2.Insert at End
3.Insert at Position
4.Delete at Position
5.Update Node
6.Search Element
7.Display List
8.Reverse List
9.Exit
Enter your choice : 9
|
[
{
"code": null,
"e": 1338,
"s": 1062,
"text": "In data structure Link List is a linear collection of data elements. Each element or node of a list is comprising of two items - the data and a reference to the next node. The last node has a reference to null. In a linked list the entry point is called the head of the list."
},
{
"code": null,
"e": 1567,
"s": 1338,
"text": "In Circular Doubly Linked List two consecutive elements are linked or connected by previous and next pointer and the last node points to first node by next pointer and the first node also points to last node by previous pointer."
},
{
"code": null,
"e": 3579,
"s": 1567,
"text": "Begin\n We shall create a class circulardoublylist which have the following functions:\n nod *create_node(int) = To memory allocated for node dynamically.\n insert_begin() = To Insert elements at beginning of the list.\n A) If the list is empty, then insert the node and set next and previous pointer as NULL.\n B) If the list is not empty, insert the data and set next and previous pointer and update them.\n\n insert_end() = To Insert elements at end of the list:\n A) If the list is empty create a node as circular doubly list.\n B) Find last node.\n C) Create node dynamically.\n D) Start going to be the next of new node.\n E) Make new node as previous node.\n F) Make last previous of new node.\n G) Make new node next of old last.\n\n insert_pos() = To insert elements at a specified position of the list:\n A) Insert the data.\n B) Enter the position at which element to be inserted.\n C) If the list is empty insert node at first.\n D) If list is not empty find node having position and next node.\n E) Insert the node between them.\n\n delete_pos() = To delete elements from specified position of the list:\n A) If list is empty, then return.\n B) Enter the position from which node needs to be deleted.\n C) If list has one node delete it and update next and prev pointers.\n D) If list has more than one nodes, then delete the node at particular position and update next and prev pointer.\n\n search() = To search element in the list:\n A) If the list is empty, then return.\n B) Enter the value to be searched.\n C) Print the position at which element to be found.\n D) If the element is not found, print not found.\n\n update() = To update value at a particular node:\n A) If the list is empty, then return.\n B) Enter the position of node to be updated.\n C) Enter the new value.\n D) Update the node.\n display() = To display the list.\n reverse() = To reverse the list.\nEnd"
},
{
"code": null,
"e": 9852,
"s": 3579,
"text": "#include<iostream>\n#include<cstdio>\n#include<cstdlib>\nusing namespace std;\nstruct nod {\n int info;\n struct nod *n;\n struct nod *p;\n}*start, *last;\nint count = 0;\nclass circulardoublylist {\n public:\n nod *create_node(int);\n void insert_begin();\n void insert_end();\n void insert_pos();\n void delete_pos();\n void search();\n void update();\n void display();\n void reverse();\n circulardoublylist() {\n start = NULL;\n last = NULL;\n }\n};\nint main() {\n int c;\n circulardoublylist cdl;\n while (1) //perform switch operation {\n cout<<\"1.Insert at Beginning\"<<endl;\n cout<<\"2.Insert at End\"<<endl;\n cout<<\"3.Insert at Position\"<<endl;\n cout<<\"4.Delete at Position\"<<endl;\n cout<<\"5.Update Node\"<<endl;\n cout<<\"6.Search Element\"<<endl;\n cout<<\"7.Display List\"<<endl;\n cout<<\"8.Reverse List\"<<endl;\n cout<<\"9.Exit\"<<endl;\n cout<<\"Enter your choice : \";\n cin>>c;\n switch(c) {\n case 1:\n cdl.insert_begin();\n break;\n case 2:\n cdl.insert_end();\n break;\n case 3:\n cdl.insert_pos();\n break;\n case 4:\n cdl.delete_pos();\n break;\n case 5:\n cdl.update();\n break;\n case 6:\n cdl.search();\n break;\n case 7:\n cdl.display();\n break;\n case 8:\n cdl.reverse();\n break;\n case 9:\n exit(1);\n default:\n cout<<\"Wrong choice\"<<endl;\n }\n }\n return 0;\n}\nnod* circulardoublylist::create_node(int v) {\n count++;\n struct nod *t;\n t = new(struct nod);\n t->info = v;\n t->n = NULL;\n t->p = NULL;\n return t;\n}\nvoid circulardoublylist::insert_begin() {\n int v;\n cout<<endl<<\"Enter the element to be inserted: \";\n cin>>v;\n struct nod *t;\n t = create_node(v);\n if (start == last && start == NULL) {\n cout<<\"Element inserted in empty list\"<<endl;\n start = last = t;\n start->n = last->n = NULL;\n start->p = last->p = NULL;\n } else {\n t->n = start;\n start->p = t;\n start = t;\n start->p = last;\n last->n = start;\n cout<<\"Element inserted\"<<endl;\n }\n}\nvoid circulardoublylist::insert_end() {\n int v;\n cout<<endl<<\"Enter the element to be inserted: \";\n cin>>v;\n struct nod *t;\n t = create_node(v);\n if (start == last && start == NULL) {\n cout<<\"Element inserted in empty list\"<<endl;\n start = last = t;\n start->n= last->n = NULL;\n start->p = last->p= NULL;\n } else {\n last->n= t;\n t->p= last;\n last = t;\n start->p = last;\n last->n= start;\n }\n}\nvoid circulardoublylist::insert_pos() {\n int v, pos, i;\n cout<<endl<<\"Enter the element to be inserted: \";\n cin>>v;\n cout<<endl<<\"Enter the position of element inserted: \";\n cin>>pos;\n struct nod *t, *s, *ptr;\n t = create_node(v);\n if (start == last && start == NULL) {\n if (pos == 1) {\n start = last = t;\n start->n = last->n = NULL;\n start->p = last->p = NULL;\n } else {\n cout<<\"Position out of range\"<<endl;\n count--;\n return;\n }\n } else {\n if (count < pos) {\n cout<<\"Position out of range\"<<endl;\n count--;\n return;\n }\n s = start;\n for (i = 1;i <= count;i++) {\n ptr = s;\n s = s->n;\n if (i == pos - 1) {\n ptr->n = t;\n t->p= ptr;\n t->n= s;\n s->p = t;\n cout<<\"Element inserted\"<<endl;\n break;\n }\n }\n }\n}\nvoid circulardoublylist::delete_pos() {\n int pos, i;\n nod *ptr, *s;\n if (start == last && start == NULL) {\n cout<<\"List is empty, nothing to delete\"<<endl;\n return;\n }\n cout<<endl<<\"Enter the position of element to be deleted: \";\n cin>>pos;\n if (count < pos) {\n cout<<\"Position out of range\"<<endl;\n return;\n }\n s = start;\n if(pos == 1) {\n count--;\n last->n = s->n;\n s->n->p = last;\n start = s->n;\n free(s);\n cout<<\"Element Deleted\"<<endl;\n return;\n }\n for (i = 0;i < pos - 1;i++ ) {\n s = s->n;\n ptr = s->p;\n }\n ptr->n = s->n;\n s->n->p = ptr;\n if (pos == count) {\n last = ptr;\n }\n count--;\n free(s);\n cout<<\"Element Deleted\"<<endl;\n}\nvoid circulardoublylist::update() {\n int v, i, pos;\n if (start == last && start == NULL) {\n cout<<\"The List is empty, nothing to update\"<<endl;\n return;\n }\n cout<<endl<<\"Enter the position of node to be updated: \";\n cin>>pos;\n cout<<\"Enter the new value: \";\n cin>>v;\n struct nod *s;\n if (count < pos) {\n cout<<\"Position out of range\"<<endl;\n return;\n }\n s = start;\n if (pos == 1) {\n s->info = v;\n cout<<\"Node Updated\"<<endl;\n return;\n }\n for (i=0;i < pos - 1;i++) {\n s = s->n;\n }\n s->info = v;\n cout<<\"Node Updated\"<<endl;\n}\nvoid circulardoublylist::search() {\n int pos = 0, v, i;\n bool flag = false;\n struct nod *s;\n if (start == last && start == NULL) {\n cout<<\"The List is empty, nothing to search\"<<endl;\n return;\n }\n cout<<endl<<\"Enter the value to be searched: \";\n cin>>v;\n s = start;\n for (i = 0;i < count;i++) {\n pos++;\n if (s->info == v) {\n cout<<\"Element \"<<v<<\" found at position: \"<<pos<<endl;\n flag = true;\n }\n s = s->n;\n }\n if (!flag)\n cout<<\"Element not found in the list\"<<endl;\n}\nvoid circulardoublylist::display() {\n int i;\n struct nod *s;\n if (start == last && start == NULL) {\n cout<<\"The List is empty, nothing to display\"<<endl;\n return;\n }\n s = start;\n for (i = 0;i < count-1;i++) {\n cout<<s->info<<\"<->\";\n s = s->n;\n }\n cout<<s->info<<endl;\n}\nvoid circulardoublylist::reverse() {\n if (start == last && start == NULL) {\n cout<<\"The List is empty, nothing to reverse\"<<endl;\n return;\n }\n struct nod *p1, *p2;\n p1 = start;\n p2 = p1->n;\n p1->n = NULL;\n p1->p= p2;\n while (p2 != start) {\n p2->p = p2->n;\n p2->n = p1;\n p1 = p2;\n p2 = p2->p;\n }\n last = start;\n start = p1;\n cout<<\"List Reversed\"<<endl;\n}"
},
{
"code": null,
"e": 12606,
"s": 9852,
"text": "1.Insert at Beginning\n2.Insert at End\n3.Insert at Position\n4.Delete at Position\n5.Update Node\n6.Search Element\n7.Display List\n8.Reverse List\n9.Exit\nEnter your choice : 1\n\nEnter the element to be inserted: 7\nElement inserted in empty list\n1.Insert at Beginning\n2.Insert at End\n3.Insert at Position\n4.Delete at Position\n5.Update Node\n6.Search Element\n7.Display List\n8.Reverse List\n9.Exit\nEnter your choice : 1\n\nEnter the element to be inserted: 6\nElement inserted\n1.Insert at Beginning\n2.Insert at End\n3.Insert at Position\n4.Delete at Position\n5.Update Node\n6.Search Element\n7.Display List\n8.Reverse List\n9.Exit\nEnter your choice : 2\n\nEnter the element to be inserted: 4\n1.Insert at Beginning\n2.Insert at End\n3.Insert at Position\n4.Delete at Position\n5.Update Node\n6.Search Element\n7.Display List\n8.Reverse List\n9.Exit\nEnter your choice : 2\n\nEnter the element to be inserted: 5\n1.Insert at Beginning\n2.Insert at End\n3.Insert at Position\n4.Delete at Position\n5.Update Node\n6.Search Element\n7.Display List\n8.Reverse List\n9.Exit\nEnter your choice : 7\n6<->7<->4<->5\n1.Insert at Beginning\n2.Insert at End\n3.Insert at Position\n4.Delete at Position\n5.Update Node\n6.Search Element\n7.Display List\n8.Reverse List\n9.Exit\nEnter your choice : 6\n\nEnter the value to be searched: 7\nElement 7 found at position: 2\n1.Insert at Beginning\n2.Insert at End\n3.Insert at Position\n4.Delete at Position\n5.Update Node\n6.Search Element\n7.Display List\n8.Reverse List\n9.Exit\nEnter your choice : 6\n\nEnter the value to be searched: 2\nElement not found in the list\n1.Insert at Beginning\n2.Insert at End\n3.Insert at Position\n4.Delete at Position\n5.Update Node\n6.Search Element\n7.Display List\n8.Reverse List\n9.Exit\nEnter your choice : 4\n\nEnter the position of element to be deleted: 4\nElement Deleted\n1.Insert at Beginning\n2.Insert at End\n3.Insert at Position\n4.Delete at Position\n5.Update Node\n6.Search Element\n7.Display List\n8.Reverse List\n9.Exit\nEnter your choice : 3\n\nEnter the element to be inserted: 5\n\nEnter the position of element inserted: 2\nElement inserted\n1.Insert at Beginning\n2.Insert at End\n3.Insert at Position\n4.Delete at Position\n5.Update Node\n6.Search Element\n7.Display List\n8.Reverse List\n9.Exit\nEnter your choice : 7\n6<->5<->7<->4\n1.Insert at Beginning\n2.Insert at End\n3.Insert at Position\n4.Delete at Position\n5.Update Node\n6.Search Element\n7.Display List\n8.Reverse List\n9.Exit\nEnter your choice : 8\nList Reversed\n1.Insert at Beginning\n2.Insert at End\n3.Insert at Position\n4.Delete at Position\n5.Update Node\n6.Search Element\n7.Display List\n8.Reverse List\n9.Exit\nEnter your choice : 7\n4<->7<->5<->6\n1.Insert at Beginning\n2.Insert at End\n3.Insert at Position\n4.Delete at Position\n5.Update Node\n6.Search Element\n7.Display List\n8.Reverse List\n9.Exit\nEnter your choice : 9"
}
] |
Program to check whether two string arrays are equivalent or not in Python
|
Suppose we have two string type arrays word1 and word2, we have to check whether the two arrays represent the same string or not. We can say a string can be represented by an array if the elements in that array are concatenated in order forms the string.
So, if the input is like word1 = ["ko", "lka", "ta"] word2 = ["k", "olk", "at", "a"], then the output will be True as both are forming "kolkata".
To solve this, we will follow these steps β
s1:= blank string, s2:= blank string
s1:= blank string, s2:= blank string
for each string i in word1, dos1 := s1 concatenate i
for each string i in word1, do
s1 := s1 concatenate i
s1 := s1 concatenate i
for each string i in word2, dos2 := s2 + i
for each string i in word2, do
s2 := s2 + i
s2 := s2 + i
return true if s1 is same as s2, otherwise false
return true if s1 is same as s2, otherwise false
Let us see the following implementation to get better understanding β
Live Demo
def solve(word1, word2):
s1=''
s2=''
for i in word1:
s1+=i
for i in word2:
s2+=i
return (s1==s2)
word1 = ["ko", "lka", "ta"]
word2 = ["k", "olk", "at", "a"]
print(solve(word1, word2))
["ko", "lka", "ta"], ["k", "olk", "at", "a"]
True
|
[
{
"code": null,
"e": 1317,
"s": 1062,
"text": "Suppose we have two string type arrays word1 and word2, we have to check whether the two arrays represent the same string or not. We can say a string can be represented by an array if the elements in that array are concatenated in order forms the string."
},
{
"code": null,
"e": 1463,
"s": 1317,
"text": "So, if the input is like word1 = [\"ko\", \"lka\", \"ta\"] word2 = [\"k\", \"olk\", \"at\", \"a\"], then the output will be True as both are forming \"kolkata\"."
},
{
"code": null,
"e": 1507,
"s": 1463,
"text": "To solve this, we will follow these steps β"
},
{
"code": null,
"e": 1544,
"s": 1507,
"text": "s1:= blank string, s2:= blank string"
},
{
"code": null,
"e": 1581,
"s": 1544,
"text": "s1:= blank string, s2:= blank string"
},
{
"code": null,
"e": 1634,
"s": 1581,
"text": "for each string i in word1, dos1 := s1 concatenate i"
},
{
"code": null,
"e": 1665,
"s": 1634,
"text": "for each string i in word1, do"
},
{
"code": null,
"e": 1688,
"s": 1665,
"text": "s1 := s1 concatenate i"
},
{
"code": null,
"e": 1711,
"s": 1688,
"text": "s1 := s1 concatenate i"
},
{
"code": null,
"e": 1754,
"s": 1711,
"text": "for each string i in word2, dos2 := s2 + i"
},
{
"code": null,
"e": 1785,
"s": 1754,
"text": "for each string i in word2, do"
},
{
"code": null,
"e": 1798,
"s": 1785,
"text": "s2 := s2 + i"
},
{
"code": null,
"e": 1811,
"s": 1798,
"text": "s2 := s2 + i"
},
{
"code": null,
"e": 1860,
"s": 1811,
"text": "return true if s1 is same as s2, otherwise false"
},
{
"code": null,
"e": 1909,
"s": 1860,
"text": "return true if s1 is same as s2, otherwise false"
},
{
"code": null,
"e": 1979,
"s": 1909,
"text": "Let us see the following implementation to get better understanding β"
},
{
"code": null,
"e": 1990,
"s": 1979,
"text": " Live Demo"
},
{
"code": null,
"e": 2202,
"s": 1990,
"text": "def solve(word1, word2):\n s1=''\n s2=''\n for i in word1:\n s1+=i\n for i in word2:\n s2+=i\n return (s1==s2)\n\nword1 = [\"ko\", \"lka\", \"ta\"]\nword2 = [\"k\", \"olk\", \"at\", \"a\"]\nprint(solve(word1, word2))"
},
{
"code": null,
"e": 2247,
"s": 2202,
"text": "[\"ko\", \"lka\", \"ta\"], [\"k\", \"olk\", \"at\", \"a\"]"
},
{
"code": null,
"e": 2252,
"s": 2247,
"text": "True"
}
] |
How to get current Bluetooth name in android?
|
This example demonstrate about How to get current Bluetooth name in android.
Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project.
Step 2 β Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:gravity = "center"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/text"
android:textSize = "30sp"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken text view to show Bluetooth name.
Step 3 β Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.os.Build;
import android.os.Bundle;
import android.os.health.SystemHealthManager;
import android.provider.Telephony;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
final BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
textView.setText(manager.getAdapter().getName());
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onResume() {
super.onResume();
}
}
Step 4 β Add the following code to androidManifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.myapplication">
<uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name = "android.permission.BLUETOOTH" />
<uses-permission android:name = "android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:roundIcon = "@mipmap/ic_launcher_round"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">
<activity android:name = ".MainActivity">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<action android:name = "android.net.conn.CONNECTIVITY_CHANGE" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen β
Click here to download the project code
|
[
{
"code": null,
"e": 1139,
"s": 1062,
"text": "This example demonstrate about How to get current Bluetooth name in android."
},
{
"code": null,
"e": 1268,
"s": 1139,
"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": 1333,
"s": 1268,
"text": "Step 2 β Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1893,
"s": 1333,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout 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:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"30sp\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1960,
"s": 1893,
"text": "In the above code, we have taken text view to show Bluetooth name."
},
{
"code": null,
"e": 2017,
"s": 1960,
"text": "Step 3 β Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3173,
"s": 2017,
"text": "package com.example.myapplication;\nimport android.bluetooth.BluetoothManager;\nimport android.content.Context;\nimport android.net.ConnectivityManager;\nimport android.net.Network;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.health.SystemHealthManager;\nimport android.provider.Telephony;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.telephony.SmsManager;\nimport android.view.View;\nimport android.view.WindowManager;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n final BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);\n textView.setText(manager.getAdapter().getName());\n }\n @Override\n protected void onStop() {\n super.onStop();\n }\n @Override\n protected void onResume() {\n super.onResume();\n }\n}"
},
{
"code": null,
"e": 3228,
"s": 3173,
"text": "Step 4 β Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4239,
"s": 3228,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.ACCESS_NETWORK_STATE\" />\n <uses-permission android:name = \"android.permission.BLUETOOTH\" />\n <uses-permission android:name = \"android.permission.BLUETOOTH_ADMIN\" />\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <action android:name = \"android.net.conn.CONNECTIVITY_CHANGE\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4586,
"s": 4239,
"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": 4626,
"s": 4586,
"text": "Click here to download the project code"
}
] |
How to remove outliers from multiple boxplots created with the help of boxplot function for columns of a data frame using single line code in R?
|
A data frame can have multiple numerical columns and we can create boxplot for each of the columns just by using boxplot function with data frame name but if we want to exclude outliers then outline argument can be used. For example, if we have a data frame df with multiple numerical columns that contain outlying values then the boxplot without outliers can be created as boxplot(df,outline=FALSE).
Consider the below data frame:
Live Demo
set.seed(151)
x1<-c(-5,rnorm(18),5)
x2<-c(-6,rnorm(18,1,0.2),6)
x3<-c(-10,rnorm(18,1,0.5),10)
x4<-c(-12,rnorm(18,1,0.1),12)
x5<-c(-15,rnorm(18,1,0.8),15)
df<-data.frame(x1,x2,x3,x4,x5)
df
x1 x2 x3 x4 x5
1 -5.00000000 -6.0000000 -10.0000000 -12.0000000 -15.0000000
2 -0.05153895 1.1347052 1.7228397 1.0216649 0.5526645
3 0.76573738 1.0620079 1.1305064 1.0407813 1.2837024
4 -0.14673959 0.7255857 1.9645730 0.9528957 0.9981142
5 -0.11318581 0.6726474 0.7000570 0.9979680 1.4502265
6 -0.39551140 0.9280697 1.0449886 0.9596063 1.1528738
7 0.78227595 1.2402230 1.2416571 1.0422124 0.8461499
8 -1.39747811 0.8708252 2.0122390 0.8796052 0.7642688
9 -1.01883832 0.8978782 1.8157587 0.8944016 0.3106157
10 0.22947586 0.8801754 1.6851877 1.0137921 2.2427285
11 0.67217297 1.1091206 -0.2065685 0.9715086 0.7642430
12 -0.48455178 0.9017412 0.5728289 1.0170325 2.6194087
13 0.56060896 1.0383071 1.2811840 0.9864194 2.3656720
14 0.06615648 0.8882945 0.8173998 0.8232215 1.4163186
15 -1.34987612 1.1845399 0.8286647 0.7985602 1.0698010
16 -0.24291581 1.2307996 0.6122296 1.0941148 1.3163952
17 -1.23674102 0.7255179 0.9935761 0.9278766 1.8420136
18 -1.47467765 1.2580363 1.3498465 0.9826864 1.0976992
19 2.43715892 1.2309804 1.0159605 0.8997847 0.9828209
20 5.00000000 6.0000000 10.0000000 12.0000000 15.0000000
Creating boxplot for columns of df β
boxplot(df)
Creating boxplot for columns of df without outliers β
boxplot(df,outline=FALSE)
|
[
{
"code": null,
"e": 1463,
"s": 1062,
"text": "A data frame can have multiple numerical columns and we can create boxplot for each of the columns just by using boxplot function with data frame name but if we want to exclude outliers then outline argument can be used. For example, if we have a data frame df with multiple numerical columns that contain outlying values then the boxplot without outliers can be created as boxplot(df,outline=FALSE)."
},
{
"code": null,
"e": 1494,
"s": 1463,
"text": "Consider the below data frame:"
},
{
"code": null,
"e": 1505,
"s": 1494,
"text": " Live Demo"
},
{
"code": null,
"e": 1693,
"s": 1505,
"text": "set.seed(151)\nx1<-c(-5,rnorm(18),5)\nx2<-c(-6,rnorm(18,1,0.2),6)\nx3<-c(-10,rnorm(18,1,0.5),10)\nx4<-c(-12,rnorm(18,1,0.1),12)\nx5<-c(-15,rnorm(18,1,0.8),15)\ndf<-data.frame(x1,x2,x3,x4,x5)\ndf"
},
{
"code": null,
"e": 2970,
"s": 1693,
"text": " x1 x2 x3 x4 x5\n1 -5.00000000 -6.0000000 -10.0000000 -12.0000000 -15.0000000\n2 -0.05153895 1.1347052 1.7228397 1.0216649 0.5526645\n3 0.76573738 1.0620079 1.1305064 1.0407813 1.2837024\n4 -0.14673959 0.7255857 1.9645730 0.9528957 0.9981142\n5 -0.11318581 0.6726474 0.7000570 0.9979680 1.4502265\n6 -0.39551140 0.9280697 1.0449886 0.9596063 1.1528738\n7 0.78227595 1.2402230 1.2416571 1.0422124 0.8461499\n8 -1.39747811 0.8708252 2.0122390 0.8796052 0.7642688\n9 -1.01883832 0.8978782 1.8157587 0.8944016 0.3106157\n10 0.22947586 0.8801754 1.6851877 1.0137921 2.2427285\n11 0.67217297 1.1091206 -0.2065685 0.9715086 0.7642430\n12 -0.48455178 0.9017412 0.5728289 1.0170325 2.6194087\n13 0.56060896 1.0383071 1.2811840 0.9864194 2.3656720\n14 0.06615648 0.8882945 0.8173998 0.8232215 1.4163186\n15 -1.34987612 1.1845399 0.8286647 0.7985602 1.0698010\n16 -0.24291581 1.2307996 0.6122296 1.0941148 1.3163952\n17 -1.23674102 0.7255179 0.9935761 0.9278766 1.8420136\n18 -1.47467765 1.2580363 1.3498465 0.9826864 1.0976992\n19 2.43715892 1.2309804 1.0159605 0.8997847 0.9828209\n20 5.00000000 6.0000000 10.0000000 12.0000000 15.0000000"
},
{
"code": null,
"e": 3007,
"s": 2970,
"text": "Creating boxplot for columns of df β"
},
{
"code": null,
"e": 3019,
"s": 3007,
"text": "boxplot(df)"
},
{
"code": null,
"e": 3073,
"s": 3019,
"text": "Creating boxplot for columns of df without outliers β"
},
{
"code": null,
"e": 3099,
"s": 3073,
"text": "boxplot(df,outline=FALSE)"
}
] |
4 Bit Binary Decrementer - GeeksforGeeks
|
05 May, 2021
What is 4 Bit Binary Decrementer ?It subtracts 1 binary value from the existing binary value stored in the register or in other words we can simply say that it decreases the existing value stored in the register by 1. For any n- bit binary decrementer, βnβ refers to the storage capacity of the register which needs to be decremented by 1. So we require βnβ number of full adders. Thus, in case of 4 bit binary decrementer we require 4 full adders.
Working:
It consists of 4 full adders, connected one after the other. Each full adder has 3 inputs (carry input, 1, A) and 2 outputs (carry output and S)
A full adder basic consist of 2 half adders and an OR gate.
The carry(C) from previous full adder is propagated to the next full adder. So carry output from one full adder becomes one of the three input of the next full adder.
It follows the concept of 2βs complement, so we take 1 as input in all 4 full adder as seen from the above diagram.
So we add 1111 in order to subtract 1.
Reason for adding 1111:
This is because our main motive is to subtract 1 which in 4 bit representation is 0001
Representing it in 1βs complement will give: 1110
Representing it in 2βs complement (adding 1 to 1βs complement) will give: 1111
This is the reason why input 1111 is given to get a decremented output in 4 bit binary decrementer.
In 4 bit representation In 1's complement In 2's complement
1 -------------------------> 0001 ----------------------> 1110 ---------------------> 1111
Example:
(Refer to the circuit diagram from right to left for better understanding)
1. Input: 1010 ----> After using 4 bit binary decrementer ----> Output: 1001
1 0 1 0 (Comparing from the circuit 1 0 1 0 is A3, A2, A1, A0 respectively)
+ 1 1 1 1 (1 1 1 1 is added as seen in the diagram also, in each full adder 1 is taken as input)
________
1 0 1 1 ( 1 0 1 1 , in the diagram are S3, S2, S1, S0 respectively)
________
2. Input: 0010 ----> After using 4 bit binary decrementer ----> Output: 0001
1 0 1 0
+ 1 1 1 1
________
0 0 0 1
________
3. Input: 0011 ----> After using 4 bit binary decrementer ----> Output: 0001
0 0 1 1
+ 1 1 1 1
_________
0 0 1 0
_________
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Magnitude Comparator in Digital Logic
4-bit binary Adder-Subtractor
Encoders and Decoders in Digital Logic
Difference between Flip-flop and Latch
BCD to 7 Segment Decoder
Differences between Synchronous and Asynchronous Counter
Carry Look-Ahead Adder
Encoder in Digital Logic
Difference between Feedback and Feed Forward control systems
Latches in Digital Logic
|
[
{
"code": null,
"e": 24035,
"s": 24007,
"text": "\n05 May, 2021"
},
{
"code": null,
"e": 24485,
"s": 24035,
"text": "What is 4 Bit Binary Decrementer ?It subtracts 1 binary value from the existing binary value stored in the register or in other words we can simply say that it decreases the existing value stored in the register by 1. For any n- bit binary decrementer, βnβ refers to the storage capacity of the register which needs to be decremented by 1. So we require βnβ number of full adders. Thus, in case of 4 bit binary decrementer we require 4 full adders. "
},
{
"code": null,
"e": 24494,
"s": 24485,
"text": "Working:"
},
{
"code": null,
"e": 24639,
"s": 24494,
"text": "It consists of 4 full adders, connected one after the other. Each full adder has 3 inputs (carry input, 1, A) and 2 outputs (carry output and S)"
},
{
"code": null,
"e": 24699,
"s": 24639,
"text": "A full adder basic consist of 2 half adders and an OR gate."
},
{
"code": null,
"e": 24866,
"s": 24699,
"text": "The carry(C) from previous full adder is propagated to the next full adder. So carry output from one full adder becomes one of the three input of the next full adder."
},
{
"code": null,
"e": 24982,
"s": 24866,
"text": "It follows the concept of 2βs complement, so we take 1 as input in all 4 full adder as seen from the above diagram."
},
{
"code": null,
"e": 25021,
"s": 24982,
"text": "So we add 1111 in order to subtract 1."
},
{
"code": null,
"e": 25045,
"s": 25021,
"text": "Reason for adding 1111:"
},
{
"code": null,
"e": 25132,
"s": 25045,
"text": "This is because our main motive is to subtract 1 which in 4 bit representation is 0001"
},
{
"code": null,
"e": 25182,
"s": 25132,
"text": "Representing it in 1βs complement will give: 1110"
},
{
"code": null,
"e": 25261,
"s": 25182,
"text": "Representing it in 2βs complement (adding 1 to 1βs complement) will give: 1111"
},
{
"code": null,
"e": 25362,
"s": 25261,
"text": "This is the reason why input 1111 is given to get a decremented output in 4 bit binary decrementer. "
},
{
"code": null,
"e": 25653,
"s": 25362,
"text": " In 4 bit representation In 1's complement In 2's complement \n 1 -------------------------> 0001 ----------------------> 1110 ---------------------> 1111\n "
},
{
"code": null,
"e": 25662,
"s": 25653,
"text": "Example:"
},
{
"code": null,
"e": 26113,
"s": 25662,
"text": "(Refer to the circuit diagram from right to left for better understanding)\n\n1. Input: 1010 ----> After using 4 bit binary decrementer ----> Output: 1001\n \n 1 0 1 0 (Comparing from the circuit 1 0 1 0 is A3, A2, A1, A0 respectively)\n+ 1 1 1 1 (1 1 1 1 is added as seen in the diagram also, in each full adder 1 is taken as input)\n ________\n 1 0 1 1 ( 1 0 1 1 , in the diagram are S3, S2, S1, S0 respectively)\n ________\n "
},
{
"code": null,
"e": 26254,
"s": 26113,
"text": "2. Input: 0010 ----> After using 4 bit binary decrementer ----> Output: 0001\n\n 1 0 1 0 \n + 1 1 1 1\n ________\n 0 0 0 1\n ________\n "
},
{
"code": null,
"e": 26393,
"s": 26254,
"text": "3. Input: 0011 ----> After using 4 bit binary decrementer ----> Output: 0001\n\n 0 0 1 1\n + 1 1 1 1\n _________\n 0 0 1 0\n _________\n "
},
{
"code": null,
"e": 26428,
"s": 26393,
"text": "Digital Electronics & Logic Design"
},
{
"code": null,
"e": 26526,
"s": 26428,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26535,
"s": 26526,
"text": "Comments"
},
{
"code": null,
"e": 26548,
"s": 26535,
"text": "Old Comments"
},
{
"code": null,
"e": 26586,
"s": 26548,
"text": "Magnitude Comparator in Digital Logic"
},
{
"code": null,
"e": 26616,
"s": 26586,
"text": "4-bit binary Adder-Subtractor"
},
{
"code": null,
"e": 26655,
"s": 26616,
"text": "Encoders and Decoders in Digital Logic"
},
{
"code": null,
"e": 26694,
"s": 26655,
"text": "Difference between Flip-flop and Latch"
},
{
"code": null,
"e": 26719,
"s": 26694,
"text": "BCD to 7 Segment Decoder"
},
{
"code": null,
"e": 26776,
"s": 26719,
"text": "Differences between Synchronous and Asynchronous Counter"
},
{
"code": null,
"e": 26799,
"s": 26776,
"text": "Carry Look-Ahead Adder"
},
{
"code": null,
"e": 26824,
"s": 26799,
"text": "Encoder in Digital Logic"
},
{
"code": null,
"e": 26885,
"s": 26824,
"text": "Difference between Feedback and Feed Forward control systems"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.